@kubb/cli 5.3.5 → 5.3.6
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.
- package/dist/{generate-B8M-7Y_K.js → generate-BdwuamCx.js} +2 -2
- package/dist/{generate-B8M-7Y_K.js.map → generate-BdwuamCx.js.map} +1 -1
- package/dist/{generate-CUhqg3E9.cjs → generate-R1LDUO_F.cjs} +2 -2
- package/dist/{generate-CUhqg3E9.cjs.map → generate-R1LDUO_F.cjs.map} +1 -1
- package/dist/index.cjs +6 -6
- package/dist/index.js +6 -6
- package/dist/{init-aQ_HMWWB.cjs → init-DCApJ9KW.cjs} +2 -2
- package/dist/{init-aQ_HMWWB.cjs.map → init-DCApJ9KW.cjs.map} +1 -1
- package/dist/{init-TWYViDuY.js → init-sgZ9bKP6.js} +2 -2
- package/dist/{init-TWYViDuY.js.map → init-sgZ9bKP6.js.map} +1 -1
- package/dist/package-Can72ro6.js +6 -0
- package/dist/package-Can72ro6.js.map +1 -0
- package/dist/{package-dGnyXH8M.cjs → package-DF4lLkdS.cjs} +2 -2
- package/dist/package-DF4lLkdS.cjs.map +1 -0
- package/dist/{run-a4o7dHDF.js → run-BEnmnOrx.js} +2 -2
- package/dist/{run-a4o7dHDF.js.map → run-BEnmnOrx.js.map} +1 -1
- package/dist/{run-BGqRxk_b.js → run-BOhLX63y.js} +6 -6
- package/dist/run-BOhLX63y.js.map +1 -0
- package/dist/{run-95WWzCp7.cjs → run-D20DTdsd.cjs} +2 -2
- package/dist/{run-95WWzCp7.cjs.map → run-D20DTdsd.cjs.map} +1 -1
- package/dist/{run-DiZRs6tL.js → run-HrazdRxs.js} +2 -2
- package/dist/{run-DiZRs6tL.js.map → run-HrazdRxs.js.map} +1 -1
- package/dist/run-VK50TiB7.cjs.map +1 -1
- package/dist/{run-3dDRXSyB.js → run-X5jd8jAf.js} +2 -2
- package/dist/{run-3dDRXSyB.js.map → run-X5jd8jAf.js.map} +1 -1
- package/dist/{run-DzZA8ZTw.cjs → run-Y3pSO7EW.cjs} +2 -2
- package/dist/{run-DzZA8ZTw.cjs.map → run-Y3pSO7EW.cjs.map} +1 -1
- package/dist/{run-BwQ4w5se.cjs → run-YSoDwlKZ.cjs} +2 -2
- package/dist/{run-BwQ4w5se.cjs.map → run-YSoDwlKZ.cjs.map} +1 -1
- package/dist/run-kdxqOL8u.js.map +1 -1
- package/dist/{run-wMAAv1n7.cjs → run-zEtX5h_L.cjs} +6 -6
- package/dist/run-zEtX5h_L.cjs.map +1 -0
- package/package.json +8 -8
- package/dist/package-FUxfgCYj.js +0 -6
- package/dist/package-FUxfgCYj.js.map +0 -1
- package/dist/package-dGnyXH8M.cjs.map +0 -1
- package/dist/run-BGqRxk_b.js.map +0 -1
- package/dist/run-wMAAv1n7.cjs.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"run-
|
|
1
|
+
{"version":3,"file":"run-HrazdRxs.js","names":[],"sources":["../src/runners/validate/run.ts"],"sourcesContent":["import process from 'node:process'\nimport { styleText } from 'node:util'\nimport { toError } from '@internals/utils'\nimport type { CommandRunner } from 'gunshi'\nimport { buildTelemetryEvent, sendTelemetry } from '../../Telemetry.ts'\nimport { version } from '../../../package.json'\nimport type { definition } from '../../commands/validate.ts'\n\ntype ValidateOptions = {\n /**\n * Path or URL to the OpenAPI/Swagger file to validate.\n */\n input: string\n /**\n * Current `@kubb/cli` version string, used for the telemetry payload.\n */\n version: string\n}\n\n/**\n * Validates an OpenAPI/Swagger file at `input` using `@kubb/adapter-oas`.\n * Exits the process with code 1 on validation failure or missing dependency.\n */\nexport async function run({ input, version }: ValidateOptions): Promise<void> {\n const hrStart = process.hrtime()\n const report = (status: 'success' | 'failed') => sendTelemetry(buildTelemetryEvent({ command: 'validate', kubbVersion: version, hrStart, status }))\n\n try {\n const { adapterOas } = await import('@kubb/adapter-oas')\n\n const adapter = adapterOas()\n if (!adapter.validate) {\n throw new Error('The loaded adapter does not support validation.')\n }\n\n await adapter.validate(input, { throwOnError: true })\n await report('success')\n\n console.log('✅ Validation success')\n } catch (error) {\n await report('failed')\n if (error instanceof Error && /@kubb\\/adapter-oas/.test(error.message)) {\n console.error(styleText('red', 'The @kubb/adapter-oas package is not installed.'))\n console.error('')\n console.error('Install it with:')\n console.error(styleText('cyan', ' npm install @kubb/adapter-oas'))\n console.error(styleText('cyan', ' # or'))\n console.error(styleText('cyan', ' pnpm install @kubb/adapter-oas'))\n console.error('')\n }\n console.error('❌ Validation failed')\n console.error(toError(error).message)\n\n process.exit(1)\n }\n}\n\n/**\n * Loaded on demand by `index.ts`, so `@kubb/adapter-oas` stays out of the process for every other\n * command.\n */\nexport const runner: CommandRunner<{ args: typeof definition.args; extensions: {} }> = async ({ values }) => {\n await run({ input: values.input, version })\n}\n"],"mappings":";;;;;;;;;;;AAuBA,eAAsB,IAAI,EAAE,OAAO,WAA2C;CAC5E,MAAM,UAAU,QAAQ,OAAO;CAC/B,MAAM,UAAU,WAAiC,cAAc,oBAAoB;EAAE,SAAS;EAAY,aAAa;EAAS;EAAS;CAAO,CAAC,CAAC;CAElJ,IAAI;EACF,MAAM,EAAE,eAAe,MAAM,OAAO;EAEpC,MAAM,UAAU,WAAW;EAC3B,IAAI,CAAC,QAAQ,UACX,MAAM,IAAI,MAAM,iDAAiD;EAGnE,MAAM,QAAQ,SAAS,OAAO,EAAE,cAAc,KAAK,CAAC;EACpD,MAAM,OAAO,SAAS;EAEtB,QAAQ,IAAI,sBAAsB;CACpC,SAAS,OAAO;EACd,MAAM,OAAO,QAAQ;EACrB,IAAI,iBAAiB,SAAS,qBAAqB,KAAK,MAAM,OAAO,GAAG;GACtE,QAAQ,MAAM,UAAU,OAAO,iDAAiD,CAAC;GACjF,QAAQ,MAAM,EAAE;GAChB,QAAQ,MAAM,kBAAkB;GAChC,QAAQ,MAAM,UAAU,QAAQ,iCAAiC,CAAC;GAClE,QAAQ,MAAM,UAAU,QAAQ,QAAQ,CAAC;GACzC,QAAQ,MAAM,UAAU,QAAQ,kCAAkC,CAAC;GACnE,QAAQ,MAAM,EAAE;EAClB;EACA,QAAQ,MAAM,qBAAqB;EACnC,QAAQ,MAAM,QAAQ,KAAK,CAAC,CAAC,OAAO;EAEpC,QAAQ,KAAK,CAAC;CAChB;AACF;;;;;AAMA,MAAa,SAA0E,OAAO,EAAE,aAAa;CAC3G,MAAM,IAAI;EAAE,OAAO,OAAO;EAAO;CAAQ,CAAC;AAC5C"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"run-VK50TiB7.cjs","names":["availablePlugins","join","existsSync","readFileSync","process","fs","path","x","process","styleText","clack","createSpinner","initDefaults","availablePlugins","KUBB_PACKAGE_NAME","KUBB_CONFIG_FILENAME","path","fs"],"sources":["../../../internals/shared/src/init.ts","../src/tools.ts","../src/runners/init/utils.ts","../src/runners/init/run.ts"],"sourcesContent":["import { availablePlugins, KUBB_PACKAGE_NAME } from './constants.ts'\nimport type { PluginOption } from './types.ts'\n\n/**\n * Resolves a comma-separated plugin flag (e.g. `--plugins plugin-ts,plugin-zod`) into the\n * matching known plugin options. Unrecognized names are dropped, and a missing flag yields\n * an empty list.\n */\nexport function resolvePlugins(pluginsFlag: string | undefined): Array<PluginOption> {\n if (!pluginsFlag) {\n return []\n }\n const requested = pluginsFlag\n .split(',')\n .map((value) => value.trim())\n .filter(Boolean)\n return availablePlugins.filter((plugin) => requested.includes(plugin.value))\n}\n\nexport function generateConfigFile({\n selectedPlugins,\n inputPath,\n outputPath,\n}: {\n selectedPlugins: Array<PluginOption>\n inputPath: string\n outputPath: string\n}): string {\n const imports = selectedPlugins.map((plugin) => `import { ${plugin.importName} } from '${plugin.packageName}'`).join('\\n')\n\n const pluginConfigs = selectedPlugins.map((plugin) => ` ${plugin.importName}(),`).join('\\n')\n\n return `import { defineConfig } from 'kubb/config'\n${imports}\n\nexport default defineConfig({\n input: '${inputPath}',\n output: {\n path: '${outputPath}',\n clean: true,\n },\n plugins: [\n${pluginConfigs}\n ],\n})\n`\n}\n\n/**\n * Turns package names into install specifiers for the wizard.\n *\n * `kubb` is pinned to the exact version of the running CLI, since both ship from the same release\n * and resolving `kubb@beta` separately can land on a different version than the CLI doing the\n * scaffolding. Plugins release from their own repo on their own cadence, so they follow the\n * release channel of the CLI through its dist-tag.\n */\nexport function resolveInstallVersions({ packages, version }: { packages: Array<string>; version: string }): Array<string> {\n const prerelease = version.match(/-([a-z]+)/)?.[1]\n const tag = prerelease ?? 'latest'\n\n return packages.map((name) => (name === KUBB_PACKAGE_NAME ? `${name}@${version}` : `${name}@${tag}`))\n}\n","import { existsSync, readFileSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { formatters, linters } from '@internals/utils'\nimport type { Config } from '@kubb/core'\n\n/**\n * The configurable formatter names, mirrored from `Config['output'].format`. Excludes `'auto'`\n * (detection, not a tool) and `false` (skip). The `formatters`/`linters` tables below are pinned to\n * these so adding a tool to the config union without a descriptor fails to compile.\n */\ntype FormatterName = Exclude<NonNullable<Config['output']['format']>, 'auto' | false>\ntype LinterName = Exclude<NonNullable<Config['output']['lint']>, 'auto' | false>\n\n// Pinned to core's union here rather than in `@internals/utils`, which must not import `@kubb/core`:\n// adding a tool to the config union without a descriptor stays a compile error.\nformatters satisfies Record<FormatterName, unknown>\nlinters satisfies Record<LinterName, unknown>\n\nexport { detectTool, formatters, linters } from '@internals/utils'\n\nexport type PackageManagerName = 'npm' | 'pnpm' | 'yarn' | 'bun'\n\n/**\n * Metadata describing a package manager's lock file and install command.\n */\nexport interface PackageManagerInfo {\n /**\n * Identifier used in CLI commands, e.g. `pnpm`, `yarn`.\n */\n name: PackageManagerName\n /**\n * Lock file name that uniquely identifies this package manager in a project root.\n */\n lockFile: string\n /**\n * Subcommands passed to the package manager binary to install a dev dependency.\n */\n installCommand: ReadonlyArray<string>\n}\n\n/**\n * Metadata for each supported package manager, keyed by its short name.\n *\n * @example\n * ```ts\n * packageManagers.pnpm.installCommand // ['add', '-D']\n * packageManagers.npm.lockFile // 'package-lock.json'\n * ```\n */\nconst packageManagers: Record<PackageManagerName, PackageManagerInfo> = {\n pnpm: {\n name: 'pnpm',\n lockFile: 'pnpm-lock.yaml',\n installCommand: ['add', '-D'],\n },\n yarn: {\n name: 'yarn',\n lockFile: 'yarn.lock',\n installCommand: ['add', '-D'],\n },\n bun: {\n name: 'bun',\n lockFile: 'bun.lockb',\n installCommand: ['add', '-d'],\n },\n npm: {\n name: 'npm',\n lockFile: 'package-lock.json',\n installCommand: ['install', '--save-dev'],\n },\n}\n\n/**\n * Minimal shape of `package.json` fields read during detection.\n */\ntype PackageJson = {\n /**\n * The `packageManager` field from `package.json` (e.g. `\"pnpm@9.0.0\"`).\n */\n packageManager?: string\n}\n\n/**\n * Detects the active package manager for the given directory.\n * Resolution order: `packageManager` field in `package.json`, then presence of a lock file.\n * Falls back to `npm` when no signal is found.\n *\n * @example\n * ```ts\n * detectPackageManager('/my/project') // { name: 'pnpm', lockFile: 'pnpm-lock.yaml', ... }\n * detectPackageManager() // falls back to npm when no lock file is found\n * ```\n */\nexport function detectPackageManager(cwd: string = process.cwd()): PackageManagerInfo {\n const packageJsonPath = join(cwd, 'package.json')\n if (existsSync(packageJsonPath)) {\n try {\n const packageJson = JSON.parse(readFileSync(packageJsonPath, 'utf-8')) as PackageJson\n const pmField = packageJson.packageManager\n if (typeof pmField === 'string') {\n const name = pmField.split('@')[0]\n if (name && name in packageManagers) {\n return packageManagers[name as PackageManagerName]\n }\n }\n } catch {\n // Continue to lock file detection\n }\n }\n\n for (const pm of Object.values(packageManagers)) {\n if (existsSync(join(cwd, pm.lockFile))) {\n return pm\n }\n }\n\n return packageManagers.npm\n}\n","import fs from 'node:fs'\nimport path from 'node:path'\nimport process from 'node:process'\nimport { x } from 'tinyexec'\nimport type { PackageManagerInfo, PackageManagerName } from '../../tools.ts'\n\n/**\n * Returns `true` when a `package.json` exists at `cwd`.\n */\nexport function hasPackageJson(cwd: string = process.cwd()): boolean {\n return fs.existsSync(path.join(cwd, 'package.json'))\n}\n\n/**\n * Initializes a new `package.json` at `cwd` using the detected package manager.\n */\nexport async function initPackageJson(cwd: string, packageManager: PackageManagerInfo): Promise<void> {\n const commands: Record<PackageManagerName, Array<string>> = {\n npm: ['init', '-y'],\n pnpm: ['init'],\n yarn: ['init', '-y'],\n bun: ['init', '-y'],\n }\n\n await x(packageManager.name, commands[packageManager.name], {\n nodeOptions: { cwd, stdio: 'inherit' },\n throwOnError: true,\n })\n}\n\n/**\n * Installs the given packages at `cwd` using the detected package manager.\n */\nexport async function installPackages(packages: Array<string>, packageManager: PackageManagerInfo, cwd: string = process.cwd()): Promise<void> {\n await x(packageManager.name, [...packageManager.installCommand, ...packages], {\n nodeOptions: { cwd, stdio: 'inherit' },\n throwOnError: true,\n })\n}\n","import fs from 'node:fs'\nimport path from 'node:path'\nimport process from 'node:process'\nimport { styleText } from 'node:util'\nimport * as clack from '@clack/prompts'\nimport type { DryRunExtension } from '@gunshi/plugin-dryrun'\nimport {\n availablePlugins,\n generateConfigFile,\n initDefaults,\n KUBB_CONFIG_FILENAME,\n KUBB_PACKAGE_NAME,\n type PluginOption,\n resolveInstallVersions,\n resolvePlugins,\n} from '@internals/shared'\nimport { createSpinner, logError, logInfo, logIntro, logOutro, logWarn } from '../../loggers/output.ts'\nimport { hasPackageJson, initPackageJson, installPackages } from './utils.ts'\nimport { detectPackageManager } from '../../tools.ts'\n\nfunction cancelAndExit(message = 'Operation canceled.'): never {\n clack.cancel(message)\n process.exit(0)\n}\n\ntype InitOptions = {\n /**\n * When `true`, skips all interactive prompts and uses default values.\n */\n yes: boolean\n /**\n * Current `@kubb/cli` version string, shown in the closing outro.\n */\n version: string\n /**\n * Input path flag value from `--input`. When provided, skips the input prompt.\n */\n input?: string\n /**\n * Output directory flag value from `--output`. When provided, skips the output prompt.\n */\n output?: string\n /**\n * Comma-separated plugin list from `--plugins`, e.g. `'plugin-ts,plugin-zod'`. When provided, skips the plugin selection prompt.\n */\n plugins?: string\n /**\n * Dry-run extension from `@gunshi/plugin-dryrun`. When enabled, package installation and the\n * config file write are skipped.\n */\n dryRun: DryRunExtension\n}\n\n/**\n * Runs the interactive Kubb scaffolding wizard.\n * Detects the package manager, prompts for input/output paths and plugins, installs packages, and writes `kubb.config.ts`.\n * Pass `yes: true` to skip all prompts and use defaults.\n */\nexport async function run({ yes, version, input: inputFlag, output: outputFlag, plugins: pluginsFlag, dryRun }: InitOptions): Promise<void> {\n const cwd = process.cwd()\n\n logIntro({ title: styleText('bgCyan', styleText('black', ' Kubb Init ')) })\n\n /**\n * Returns `flag` when provided, the `defaultValue` when `yes` is set,\n * or calls `prompt()` for interactive input. Exits on cancellation.\n */\n async function resolveOrPrompt<T>(flag: T | undefined, defaultValue: T, logLabel: string, prompt: () => Promise<T | symbol>): Promise<T> {\n if (flag !== undefined) {\n logInfo(`${logLabel}: ${styleText('cyan', String(flag))}`)\n return flag\n }\n if (yes) {\n logInfo(`${logLabel}: ${styleText('cyan', String(defaultValue))}`)\n return defaultValue\n }\n const result = await prompt()\n if (clack.isCancel(result)) cancelAndExit()\n return result as T\n }\n\n try {\n // Check/create package.json, detect package manager once after the block\n if (!hasPackageJson(cwd)) {\n if (!yes) {\n const shouldInit = await clack.confirm({\n message: 'No package.json found. Would you like to create one?',\n initialValue: true,\n })\n\n if (clack.isCancel(shouldInit) || !shouldInit) {\n cancelAndExit()\n }\n }\n\n const packageManager = detectPackageManager(cwd)\n const spinner = createSpinner()\n spinner.start(`Initializing package.json with ${packageManager.name}`)\n await initPackageJson(cwd, packageManager)\n spinner.stop(`Created package.json with ${packageManager.name}`)\n }\n\n const packageManager = detectPackageManager(cwd)\n if (hasPackageJson(cwd)) {\n logInfo(`Detected package manager: ${styleText('cyan', packageManager.name)}`)\n }\n\n // Prompt for OpenAPI spec path\n const inputPath = await resolveOrPrompt(inputFlag, initDefaults.inputPath, 'Using input path', () =>\n clack.text({\n message: 'Where is your OpenAPI specification located?',\n placeholder: initDefaults.inputPath,\n defaultValue: initDefaults.inputPath,\n validate: (value) => {\n if (!value) return 'Input path is required'\n },\n }),\n )\n\n // Prompt for output directory\n const outputPath = await resolveOrPrompt(outputFlag, initDefaults.outputPath, 'Using output path', () =>\n clack.text({\n message: 'Where should the generated files be output?',\n placeholder: initDefaults.outputPath,\n defaultValue: initDefaults.outputPath,\n validate: (value) => {\n if (!value) return 'Output path is required'\n },\n }),\n )\n\n // Plugin selection\n const defaultPlugins = availablePlugins.filter((p) => (initDefaults.plugins as ReadonlyArray<string>).includes(p.value))\n const pluginLabel = (plugins: Array<PluginOption>) => styleText('cyan', plugins.map((p) => p.label).join(', '))\n\n const selectedPlugins: Array<PluginOption> = await (async () => {\n if (pluginsFlag) {\n const plugins = resolvePlugins(pluginsFlag)\n if (plugins.length === 0) {\n logWarn(`No valid plugins found in --plugins value; falling back to default: ${pluginLabel(defaultPlugins)}`)\n return defaultPlugins\n }\n logInfo(`Using plugins: ${pluginLabel(plugins)}`)\n return plugins\n }\n if (yes) {\n logInfo(`Using plugins: ${pluginLabel(defaultPlugins)}`)\n return defaultPlugins\n }\n const values = await clack.multiselect({\n message: 'Select plugins to use:',\n options: availablePlugins.map(({ value, label, hint }) => ({ value, label, hint })),\n initialValues: [...initDefaults.plugins],\n required: true,\n })\n if (clack.isCancel(values)) cancelAndExit()\n return availablePlugins.filter((p) => (values as Array<string>).includes(p.value))\n })()\n\n // Install packages, matching the release of the running CLI\n const packagesToInstall = resolveInstallVersions({ packages: [KUBB_PACKAGE_NAME, ...selectedPlugins.map((p) => p.packageName)], version })\n\n const spinner = createSpinner()\n spinner.start(`Installing ${packagesToInstall.length} packages with ${packageManager.name}`)\n\n try {\n await dryRun.run(() => installPackages(packagesToInstall, packageManager, cwd), {\n message: `install ${packagesToInstall.length} packages with ${packageManager.name}`,\n })\n spinner.stop(`Installed ${packagesToInstall.length} packages`)\n } catch (error) {\n spinner.stop('Installation failed')\n throw error\n }\n\n // Generate config file\n const configSpinner = createSpinner()\n configSpinner.start(`Creating ${KUBB_CONFIG_FILENAME}`)\n\n const configContent = generateConfigFile({ selectedPlugins, inputPath, outputPath })\n const configPath = path.join(cwd, KUBB_CONFIG_FILENAME)\n\n if (fs.existsSync(configPath)) {\n configSpinner.stop(`${KUBB_CONFIG_FILENAME} already exists`)\n\n if (!yes) {\n const shouldOverwrite = await clack.confirm({\n message: `${KUBB_CONFIG_FILENAME} already exists. Overwrite?`,\n initialValue: false,\n })\n\n if (clack.isCancel(shouldOverwrite) || !shouldOverwrite) {\n cancelAndExit('Keeping existing configuration. Packages have been installed.')\n }\n }\n\n configSpinner.start(`Overwriting ${KUBB_CONFIG_FILENAME}`)\n }\n\n await dryRun.run(() => fs.promises.writeFile(configPath, configContent, 'utf-8'), { message: `write ${KUBB_CONFIG_FILENAME}` })\n\n configSpinner.stop(`Created ${KUBB_CONFIG_FILENAME}`)\n\n logOutro(\n styleText('green', '✓ All set!') +\n '\\n\\n' +\n styleText('dim', 'Next steps:') +\n '\\n' +\n styleText('cyan', ` 1. Make sure your OpenAPI spec is at: ${inputPath}`) +\n '\\n' +\n styleText('cyan', ' 2. Generate code with: npx kubb generate') +\n '\\n' +\n styleText('cyan', ` 3. Find generated files in: ${outputPath}`) +\n '\\n\\n' +\n styleText('dim', `Using ${packageManager.name} • Kubb v${version}`),\n )\n } catch (error) {\n logError(styleText('red', 'An error occurred during initialization'))\n if (error instanceof Error) {\n logError(error.message)\n }\n process.exit(1)\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAQA,SAAgB,eAAe,aAAsD;CACnF,IAAI,CAAC,aACH,OAAO,CAAC;CAEV,MAAM,YAAY,YACf,MAAM,GAAG,CAAC,CACV,KAAK,UAAU,MAAM,KAAK,CAAC,CAAC,CAC5B,OAAO,OAAO;CACjB,OAAOA,kBAAAA,iBAAiB,QAAQ,WAAW,UAAU,SAAS,OAAO,KAAK,CAAC;AAC7E;AAEA,SAAgB,mBAAmB,EACjC,iBACA,WACA,cAKS;CAKT,OAAO;EAJS,gBAAgB,KAAK,WAAW,YAAY,OAA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OAAO;EACd,eAAA,UAAA,GAASA,UAAAA,UAAAA,CAAU,OAAO,yCAAyC,CAAC;EACpE,IAAI,iBAAiB,OACnB,eAAA,SAAS,MAAM,OAAO;EAExB,aAAA,QAAQ,KAAK,CAAC;CAChB;AACF"}
|
|
1
|
+
{"version":3,"file":"run-VK50TiB7.cjs","names":["availablePlugins","join","existsSync","readFileSync","process","fs","path","x","process","styleText","clack","createSpinner","initDefaults","availablePlugins","KUBB_PACKAGE_NAME","KUBB_CONFIG_FILENAME","path","fs"],"sources":["../../../internals/shared/src/init.ts","../src/tools.ts","../src/runners/init/utils.ts","../src/runners/init/run.ts"],"sourcesContent":["import { availablePlugins, KUBB_PACKAGE_NAME } from './constants.ts'\nimport type { PluginOption } from './types.ts'\n\n/**\n * Resolves a comma-separated plugin flag (e.g. `--plugins plugin-ts,plugin-zod`) into the\n * matching known plugin options. Unrecognized names are dropped, and a missing flag yields\n * an empty list.\n */\nexport function resolvePlugins(pluginsFlag: string | undefined): Array<PluginOption> {\n if (!pluginsFlag) {\n return []\n }\n const requested = pluginsFlag\n .split(',')\n .map((value) => value.trim())\n .filter(Boolean)\n return availablePlugins.filter((plugin) => requested.includes(plugin.value))\n}\n\nexport function generateConfigFile({\n selectedPlugins,\n inputPath,\n outputPath,\n}: {\n selectedPlugins: Array<PluginOption>\n inputPath: string\n outputPath: string\n}): string {\n const imports = selectedPlugins.map((plugin) => `import { ${plugin.importName} } from '${plugin.packageName}'`).join('\\n')\n\n const pluginConfigs = selectedPlugins.map((plugin) => ` ${plugin.importName}(),`).join('\\n')\n\n return `import { defineConfig } from 'kubb/config'\n${imports}\n\nexport default defineConfig({\n input: '${inputPath}',\n output: {\n path: '${outputPath}',\n clean: true,\n },\n plugins: [\n${pluginConfigs}\n ],\n})\n`\n}\n\n/**\n * Turns package names into install specifiers for the wizard.\n *\n * `kubb` is pinned to the exact version of the running CLI, since both ship from the same release\n * and resolving `kubb@beta` separately can land on a different version than the CLI doing the\n * scaffolding. Plugins release from their own repo on their own cadence, so they follow the\n * release channel of the CLI through its dist-tag.\n */\nexport function resolveInstallVersions({ packages, version }: { packages: Array<string>; version: string }): Array<string> {\n const prerelease = version.match(/-([a-z]+)/)?.[1]\n const tag = prerelease ?? 'latest'\n\n return packages.map((name) => (name === KUBB_PACKAGE_NAME ? `${name}@${version}` : `${name}@${tag}`))\n}\n","import { existsSync, readFileSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { formatters, linters } from '@internals/utils'\nimport type { Config } from '@kubb/core'\n\n/**\n * The configurable formatter names, mirrored from `Config['output'].format`. Excludes `'auto'`\n * (detection, not a tool) and `false` (skip). The `formatters`/`linters` tables below are pinned to\n * these so adding a tool to the config union without a descriptor fails to compile.\n */\ntype FormatterName = Exclude<NonNullable<Config['output']['format']>, 'auto' | false>\ntype LinterName = Exclude<NonNullable<Config['output']['lint']>, 'auto' | false>\n\n// Pinned to core's union here rather than in `@internals/utils`, which must not import `@kubb/core`:\n// adding a tool to the config union without a descriptor stays a compile error.\nformatters satisfies Record<FormatterName, unknown>\nlinters satisfies Record<LinterName, unknown>\n\nexport { detectTool, formatters, linters } from '@internals/utils'\n\nexport type PackageManagerName = 'npm' | 'pnpm' | 'yarn' | 'bun'\n\n/**\n * Metadata describing a package manager's lock file and install command.\n */\nexport interface PackageManagerInfo {\n /**\n * Identifier used in CLI commands, e.g. `pnpm`, `yarn`.\n */\n name: PackageManagerName\n /**\n * Lock file name that uniquely identifies this package manager in a project root.\n */\n lockFile: string\n /**\n * Subcommands passed to the package manager binary to install a dev dependency.\n */\n installCommand: ReadonlyArray<string>\n}\n\n/**\n * Metadata for each supported package manager, keyed by its short name.\n *\n * @example\n * ```ts\n * packageManagers.pnpm.installCommand // ['add', '-D']\n * packageManagers.npm.lockFile // 'package-lock.json'\n * ```\n */\nconst packageManagers: Record<PackageManagerName, PackageManagerInfo> = {\n pnpm: {\n name: 'pnpm',\n lockFile: 'pnpm-lock.yaml',\n installCommand: ['add', '-D'],\n },\n yarn: {\n name: 'yarn',\n lockFile: 'yarn.lock',\n installCommand: ['add', '-D'],\n },\n bun: {\n name: 'bun',\n lockFile: 'bun.lockb',\n installCommand: ['add', '-d'],\n },\n npm: {\n name: 'npm',\n lockFile: 'package-lock.json',\n installCommand: ['install', '--save-dev'],\n },\n}\n\n/**\n * Minimal shape of `package.json` fields read during detection.\n */\ntype PackageJson = {\n /**\n * The `packageManager` field from `package.json` (e.g. `\"pnpm@9.0.0\"`).\n */\n packageManager?: string\n}\n\n/**\n * Detects the active package manager for the given directory.\n * Resolution order: `packageManager` field in `package.json`, then presence of a lock file.\n * Falls back to `npm` when no signal is found.\n *\n * @example\n * ```ts\n * detectPackageManager('/my/project') // { name: 'pnpm', lockFile: 'pnpm-lock.yaml', ... }\n * detectPackageManager() // falls back to npm when no lock file is found\n * ```\n */\nexport function detectPackageManager(cwd: string = process.cwd()): PackageManagerInfo {\n const packageJsonPath = join(cwd, 'package.json')\n if (existsSync(packageJsonPath)) {\n try {\n const packageJson = JSON.parse(readFileSync(packageJsonPath, 'utf-8')) as PackageJson\n const pmField = packageJson.packageManager\n if (typeof pmField === 'string') {\n const name = pmField.split('@')[0]\n if (name && name in packageManagers) {\n return packageManagers[name as PackageManagerName]\n }\n }\n } catch {\n // Continue to lock file detection\n }\n }\n\n for (const pm of Object.values(packageManagers)) {\n if (existsSync(join(cwd, pm.lockFile))) {\n return pm\n }\n }\n\n return packageManagers.npm\n}\n","import fs from 'node:fs'\nimport path from 'node:path'\nimport process from 'node:process'\nimport { x } from 'tinyexec'\nimport type { PackageManagerInfo, PackageManagerName } from '../../tools.ts'\n\n/**\n * Returns `true` when a `package.json` exists at `cwd`.\n */\nexport function hasPackageJson(cwd: string = process.cwd()): boolean {\n return fs.existsSync(path.join(cwd, 'package.json'))\n}\n\n/**\n * Initializes a new `package.json` at `cwd` using the detected package manager.\n */\nexport async function initPackageJson(cwd: string, packageManager: PackageManagerInfo): Promise<void> {\n const commands: Record<PackageManagerName, Array<string>> = {\n npm: ['init', '-y'],\n pnpm: ['init'],\n yarn: ['init', '-y'],\n bun: ['init', '-y'],\n }\n\n await x(packageManager.name, commands[packageManager.name], {\n nodeOptions: { cwd, stdio: 'inherit' },\n throwOnError: true,\n })\n}\n\n/**\n * Installs the given packages at `cwd` using the detected package manager.\n */\nexport async function installPackages(packages: Array<string>, packageManager: PackageManagerInfo, cwd: string = process.cwd()): Promise<void> {\n await x(packageManager.name, [...packageManager.installCommand, ...packages], {\n nodeOptions: { cwd, stdio: 'inherit' },\n throwOnError: true,\n })\n}\n","import fs from 'node:fs'\nimport path from 'node:path'\nimport process from 'node:process'\nimport { styleText } from 'node:util'\nimport * as clack from '@clack/prompts'\nimport type { DryRunExtension } from '@gunshi/plugin-dryrun'\nimport {\n availablePlugins,\n generateConfigFile,\n initDefaults,\n KUBB_CONFIG_FILENAME,\n KUBB_PACKAGE_NAME,\n type PluginOption,\n resolveInstallVersions,\n resolvePlugins,\n} from '@internals/shared'\nimport { createSpinner, logError, logInfo, logIntro, logOutro, logWarn } from '../../loggers/output.ts'\nimport { hasPackageJson, initPackageJson, installPackages } from './utils.ts'\nimport { detectPackageManager } from '../../tools.ts'\n\nfunction cancelAndExit(message = 'Operation canceled.'): never {\n clack.cancel(message)\n process.exit(0)\n}\n\ntype InitOptions = {\n /**\n * When `true`, skips all interactive prompts and uses default values.\n */\n yes: boolean\n /**\n * Current `@kubb/cli` version string, shown in the closing outro.\n */\n version: string\n /**\n * Input path flag value from `--input`. When provided, skips the input prompt.\n */\n input?: string\n /**\n * Output directory flag value from `--output`. When provided, skips the output prompt.\n */\n output?: string\n /**\n * Comma-separated plugin list from `--plugins`, e.g. `'plugin-ts,plugin-zod'`. When provided, skips the plugin selection prompt.\n */\n plugins?: string\n /**\n * Dry-run extension from `@gunshi/plugin-dryrun`. When enabled, package installation and the\n * config file write are skipped.\n */\n dryRun: DryRunExtension\n}\n\n/**\n * Runs the interactive Kubb scaffolding wizard.\n * Detects the package manager, prompts for input/output paths and plugins, installs packages, and writes `kubb.config.ts`.\n * Pass `yes: true` to skip all prompts and use defaults.\n */\nexport async function run({ yes, version, input: inputFlag, output: outputFlag, plugins: pluginsFlag, dryRun }: InitOptions): Promise<void> {\n const cwd = process.cwd()\n\n logIntro({ title: styleText('bgCyan', styleText('black', ' Kubb Init ')) })\n\n /**\n * Returns `flag` when provided, the `defaultValue` when `yes` is set,\n * or calls `prompt()` for interactive input. Exits on cancellation.\n */\n async function resolveOrPrompt<T>(flag: T | undefined, defaultValue: T, logLabel: string, prompt: () => Promise<NoInfer<T> | symbol>): Promise<T> {\n if (flag !== undefined) {\n logInfo(`${logLabel}: ${styleText('cyan', String(flag))}`)\n return flag\n }\n if (yes) {\n logInfo(`${logLabel}: ${styleText('cyan', String(defaultValue))}`)\n return defaultValue\n }\n const result = await prompt()\n if (clack.isCancel(result)) cancelAndExit()\n return result as T\n }\n\n try {\n // Check/create package.json, detect package manager once after the block\n if (!hasPackageJson(cwd)) {\n if (!yes) {\n const shouldInit = await clack.confirm({\n message: 'No package.json found. Would you like to create one?',\n initialValue: true,\n })\n\n if (clack.isCancel(shouldInit) || !shouldInit) {\n cancelAndExit()\n }\n }\n\n const packageManager = detectPackageManager(cwd)\n const spinner = createSpinner()\n spinner.start(`Initializing package.json with ${packageManager.name}`)\n await initPackageJson(cwd, packageManager)\n spinner.stop(`Created package.json with ${packageManager.name}`)\n }\n\n const packageManager = detectPackageManager(cwd)\n if (hasPackageJson(cwd)) {\n logInfo(`Detected package manager: ${styleText('cyan', packageManager.name)}`)\n }\n\n // Prompt for OpenAPI spec path\n const inputPath = await resolveOrPrompt(inputFlag, initDefaults.inputPath, 'Using input path', () =>\n clack.text({\n message: 'Where is your OpenAPI specification located?',\n placeholder: initDefaults.inputPath,\n defaultValue: initDefaults.inputPath,\n validate: (value) => {\n if (!value) return 'Input path is required'\n },\n }),\n )\n\n // Prompt for output directory\n const outputPath = await resolveOrPrompt(outputFlag, initDefaults.outputPath, 'Using output path', () =>\n clack.text({\n message: 'Where should the generated files be output?',\n placeholder: initDefaults.outputPath,\n defaultValue: initDefaults.outputPath,\n validate: (value) => {\n if (!value) return 'Output path is required'\n },\n }),\n )\n\n // Plugin selection\n const defaultPlugins = availablePlugins.filter((p) => (initDefaults.plugins as ReadonlyArray<string>).includes(p.value))\n const pluginLabel = (plugins: Array<PluginOption>) => styleText('cyan', plugins.map((p) => p.label).join(', '))\n\n const selectedPlugins: Array<PluginOption> = await (async () => {\n if (pluginsFlag) {\n const plugins = resolvePlugins(pluginsFlag)\n if (plugins.length === 0) {\n logWarn(`No valid plugins found in --plugins value; falling back to default: ${pluginLabel(defaultPlugins)}`)\n return defaultPlugins\n }\n logInfo(`Using plugins: ${pluginLabel(plugins)}`)\n return plugins\n }\n if (yes) {\n logInfo(`Using plugins: ${pluginLabel(defaultPlugins)}`)\n return defaultPlugins\n }\n const values = await clack.multiselect({\n message: 'Select plugins to use:',\n options: availablePlugins.map(({ value, label, hint }) => ({ value, label, hint })),\n initialValues: [...initDefaults.plugins],\n required: true,\n })\n if (clack.isCancel(values)) cancelAndExit()\n return availablePlugins.filter((p) => (values as Array<string>).includes(p.value))\n })()\n\n // Install packages, matching the release of the running CLI\n const packagesToInstall = resolveInstallVersions({ packages: [KUBB_PACKAGE_NAME, ...selectedPlugins.map((p) => p.packageName)], version })\n\n const spinner = createSpinner()\n spinner.start(`Installing ${packagesToInstall.length} packages with ${packageManager.name}`)\n\n try {\n await dryRun.run(() => installPackages(packagesToInstall, packageManager, cwd), {\n message: `install ${packagesToInstall.length} packages with ${packageManager.name}`,\n })\n spinner.stop(`Installed ${packagesToInstall.length} packages`)\n } catch (error) {\n spinner.stop('Installation failed')\n throw error\n }\n\n // Generate config file\n const configSpinner = createSpinner()\n configSpinner.start(`Creating ${KUBB_CONFIG_FILENAME}`)\n\n const configContent = generateConfigFile({ selectedPlugins, inputPath, outputPath })\n const configPath = path.join(cwd, KUBB_CONFIG_FILENAME)\n\n if (fs.existsSync(configPath)) {\n configSpinner.stop(`${KUBB_CONFIG_FILENAME} already exists`)\n\n if (!yes) {\n const shouldOverwrite = await clack.confirm({\n message: `${KUBB_CONFIG_FILENAME} already exists. Overwrite?`,\n initialValue: false,\n })\n\n if (clack.isCancel(shouldOverwrite) || !shouldOverwrite) {\n cancelAndExit('Keeping existing configuration. Packages have been installed.')\n }\n }\n\n configSpinner.start(`Overwriting ${KUBB_CONFIG_FILENAME}`)\n }\n\n await dryRun.run(() => fs.promises.writeFile(configPath, configContent, 'utf-8'), { message: `write ${KUBB_CONFIG_FILENAME}` })\n\n configSpinner.stop(`Created ${KUBB_CONFIG_FILENAME}`)\n\n logOutro(\n styleText('green', '✓ All set!') +\n '\\n\\n' +\n styleText('dim', 'Next steps:') +\n '\\n' +\n styleText('cyan', ` 1. Make sure your OpenAPI spec is at: ${inputPath}`) +\n '\\n' +\n styleText('cyan', ' 2. Generate code with: npx kubb generate') +\n '\\n' +\n styleText('cyan', ` 3. Find generated files in: ${outputPath}`) +\n '\\n\\n' +\n styleText('dim', `Using ${packageManager.name} • Kubb v${version}`),\n )\n } catch (error) {\n logError(styleText('red', 'An error occurred during initialization'))\n if (error instanceof Error) {\n logError(error.message)\n }\n process.exit(1)\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAQA,SAAgB,eAAe,aAAsD;CACnF,IAAI,CAAC,aACH,OAAO,CAAC;CAEV,MAAM,YAAY,YACf,MAAM,GAAG,CAAC,CACV,KAAK,UAAU,MAAM,KAAK,CAAC,CAAC,CAC5B,OAAO,OAAO;CACjB,OAAOA,kBAAAA,iBAAiB,QAAQ,WAAW,UAAU,SAAS,OAAO,KAAK,CAAC;AAC7E;AAEA,SAAgB,mBAAmB,EACjC,iBACA,WACA,cAKS;CAKT,OAAO;EAJS,gBAAgB,KAAK,WAAW,YAAY,OAAO,WAAW,WAAW,OAAO,YAAY,EAAE,CAAC,CAAC,KAAK,IAK/G,EAAE;;;YAGE,UAAU;;aAET,WAAW;;;;EARA,gBAAgB,KAAK,WAAW,OAAO,OA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aAAA,QAAQ,KAAK,CAAC;CAChB;AACF"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import "./rolldown-runtime-C0LytTxp.js";
|
|
2
2
|
import { t as toError } from "./errors-C8yNfV7w.js";
|
|
3
3
|
import { r as sendTelemetry, t as buildTelemetryEvent } from "./Telemetry-CJcQkQOT.js";
|
|
4
|
-
import { t as version } from "./package-
|
|
4
|
+
import { t as version } from "./package-Can72ro6.js";
|
|
5
5
|
import { styleText } from "node:util";
|
|
6
6
|
import process from "node:process";
|
|
7
7
|
//#region src/runners/mcp/run.ts
|
|
@@ -37,4 +37,4 @@ const runner = async () => {
|
|
|
37
37
|
//#endregion
|
|
38
38
|
export { runner };
|
|
39
39
|
|
|
40
|
-
//# sourceMappingURL=run-
|
|
40
|
+
//# sourceMappingURL=run-X5jd8jAf.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"run-
|
|
1
|
+
{"version":3,"file":"run-X5jd8jAf.js","names":[],"sources":["../src/runners/mcp/run.ts"],"sourcesContent":["import process from 'node:process'\nimport { styleText } from 'node:util'\nimport { toError } from '@internals/utils'\nimport type * as McpModule from '@kubb/mcp'\nimport type { CommandRunner } from 'gunshi'\nimport { buildTelemetryEvent, sendTelemetry } from '../../Telemetry.ts'\nimport { version } from '../../../package.json'\nimport type { definition } from '../../commands/mcp.ts'\n\ntype McpOptions = {\n /**\n * Current `@kubb/cli` version string, used for the telemetry payload.\n */\n version: string\n}\n\n/**\n * Starts the `@kubb/mcp` server over stdio and reports the outcome to telemetry.\n */\nexport async function run({ version }: McpOptions): Promise<void> {\n const { run: startMcpServer } = (await import('@kubb/mcp')) as typeof McpModule\n\n const hrStart = process.hrtime()\n const report = (status: 'success' | 'failed') => sendTelemetry(buildTelemetryEvent({ command: 'mcp', kubbVersion: version, hrStart, status }))\n\n try {\n console.log(styleText('cyan', '⏳ Starting MCP server...'))\n console.warn(styleText('yellow', 'This feature is still under development, use with caution'))\n\n await startMcpServer()\n await report('success')\n } catch (error) {\n await report('failed')\n console.error(toError(error).message)\n process.exitCode = 1\n }\n}\n\n/**\n * Loaded on demand by `index.ts`, so `@kubb/mcp` stays out of the process for every other command.\n */\nexport const runner: CommandRunner<{ args: typeof definition.args; extensions: {} }> = async () => {\n await run({ version })\n}\n"],"mappings":";;;;;;;;;;AAmBA,eAAsB,IAAI,EAAE,WAAsC;CAChE,MAAM,EAAE,KAAK,mBAAoB,MAAM,OAAO;CAE9C,MAAM,UAAU,QAAQ,OAAO;CAC/B,MAAM,UAAU,WAAiC,cAAc,oBAAoB;EAAE,SAAS;EAAO,aAAa;EAAS;EAAS;CAAO,CAAC,CAAC;CAE7I,IAAI;EACF,QAAQ,IAAI,UAAU,QAAQ,0BAA0B,CAAC;EACzD,QAAQ,KAAK,UAAU,UAAU,2DAA2D,CAAC;EAE7F,MAAM,eAAe;EACrB,MAAM,OAAO,SAAS;CACxB,SAAS,OAAO;EACd,MAAM,OAAO,QAAQ;EACrB,QAAQ,MAAM,QAAQ,KAAK,CAAC,CAAC,OAAO;EACpC,QAAQ,WAAW;CACrB;AACF;;;;AAKA,MAAa,SAA0E,YAAY;CACjG,MAAM,IAAI,EAAE,QAAQ,CAAC;AACvB"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
const require_rolldown_runtime = require("./rolldown-runtime-qbf5tadS.cjs");
|
|
2
2
|
const require_errors = require("./errors-C-wEou02.cjs");
|
|
3
3
|
const require_Telemetry = require("./Telemetry-CvHQevSK.cjs");
|
|
4
|
-
const require_package = require("./package-
|
|
4
|
+
const require_package = require("./package-DF4lLkdS.cjs");
|
|
5
5
|
let node_util = require("node:util");
|
|
6
6
|
let node_process = require("node:process");
|
|
7
7
|
node_process = require_rolldown_runtime.__toESM(node_process, 1);
|
|
@@ -54,4 +54,4 @@ const runner = async ({ values }) => {
|
|
|
54
54
|
//#endregion
|
|
55
55
|
exports.runner = runner;
|
|
56
56
|
|
|
57
|
-
//# sourceMappingURL=run-
|
|
57
|
+
//# sourceMappingURL=run-Y3pSO7EW.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"run-
|
|
1
|
+
{"version":3,"file":"run-Y3pSO7EW.cjs","names":["process","sendTelemetry","buildTelemetryEvent","styleText","toError"],"sources":["../src/runners/validate/run.ts"],"sourcesContent":["import process from 'node:process'\nimport { styleText } from 'node:util'\nimport { toError } from '@internals/utils'\nimport type { CommandRunner } from 'gunshi'\nimport { buildTelemetryEvent, sendTelemetry } from '../../Telemetry.ts'\nimport { version } from '../../../package.json'\nimport type { definition } from '../../commands/validate.ts'\n\ntype ValidateOptions = {\n /**\n * Path or URL to the OpenAPI/Swagger file to validate.\n */\n input: string\n /**\n * Current `@kubb/cli` version string, used for the telemetry payload.\n */\n version: string\n}\n\n/**\n * Validates an OpenAPI/Swagger file at `input` using `@kubb/adapter-oas`.\n * Exits the process with code 1 on validation failure or missing dependency.\n */\nexport async function run({ input, version }: ValidateOptions): Promise<void> {\n const hrStart = process.hrtime()\n const report = (status: 'success' | 'failed') => sendTelemetry(buildTelemetryEvent({ command: 'validate', kubbVersion: version, hrStart, status }))\n\n try {\n const { adapterOas } = await import('@kubb/adapter-oas')\n\n const adapter = adapterOas()\n if (!adapter.validate) {\n throw new Error('The loaded adapter does not support validation.')\n }\n\n await adapter.validate(input, { throwOnError: true })\n await report('success')\n\n console.log('✅ Validation success')\n } catch (error) {\n await report('failed')\n if (error instanceof Error && /@kubb\\/adapter-oas/.test(error.message)) {\n console.error(styleText('red', 'The @kubb/adapter-oas package is not installed.'))\n console.error('')\n console.error('Install it with:')\n console.error(styleText('cyan', ' npm install @kubb/adapter-oas'))\n console.error(styleText('cyan', ' # or'))\n console.error(styleText('cyan', ' pnpm install @kubb/adapter-oas'))\n console.error('')\n }\n console.error('❌ Validation failed')\n console.error(toError(error).message)\n\n process.exit(1)\n }\n}\n\n/**\n * Loaded on demand by `index.ts`, so `@kubb/adapter-oas` stays out of the process for every other\n * command.\n */\nexport const runner: Command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|
@@ -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_Telemetry = require("./Telemetry-CvHQevSK.cjs");
|
|
4
4
|
const require_utils = require("./utils-CMU1rLfY.cjs");
|
|
5
|
-
const require_package = require("./package-
|
|
5
|
+
const require_package = require("./package-DF4lLkdS.cjs");
|
|
6
6
|
const require_output = require("./output-kmklyYIv.cjs");
|
|
7
7
|
let node_util = require("node:util");
|
|
8
8
|
let node_crypto = require("node:crypto");
|
|
@@ -288,4 +288,4 @@ async function run({ input, configPath, logLevel: logLevelKey, watch, reporters:
|
|
|
288
288
|
//#endregion
|
|
289
289
|
exports.run = run;
|
|
290
290
|
|
|
291
|
-
//# sourceMappingURL=run-
|
|
291
|
+
//# sourceMappingURL=run-YSoDwlKZ.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"run-BwQ4w5se.cjs","names":["styleText","existsSync","logLevelMap","randomUUID","runHook","toError","process","memoryStorage","Diagnostics","formatters","detectTool","FORMATTER_PREFERENCE","linters","LINTER_PREFERENCE","runPostGenerate","createKubb","sendTelemetry","buildTelemetryEvent","version","KUBB_NPM_PACKAGE_URL","UPDATE_CHECK_TIMEOUT_MS","isNewerVersion","Hookable","getConfigs","setupReporters","cliReporter","selectReporters","path","getInputKind","fetchUrlBody","logInfo","logError","startWatcher"],"sources":["../src/runners/generate/run.ts"],"sourcesContent":["import { randomUUID } from 'node:crypto'\nimport { existsSync } from 'node:fs'\nimport path from 'node:path'\nimport process from 'node:process'\nimport { styleText } from 'node:util'\nimport { toError } from '@internals/utils'\nimport {\n Hookable,\n type CLIOptions,\n cliReporter,\n type Config,\n createKubb,\n type Diagnostic,\n Diagnostics,\n getInputKind,\n type KubbHooks,\n logLevel as logLevelMap,\n memoryStorage,\n type ProblemDiagnostic,\n type ReporterName,\n} from '@kubb/core'\nimport { version } from '../../../package.json'\nimport { KUBB_NPM_PACKAGE_URL, UPDATE_CHECK_TIMEOUT_MS } from '../../constants.ts'\nimport { buildTelemetryEvent, sendTelemetry } from '../../Telemetry.ts'\nimport setupReporters, { selectReporters } from '../../loggers/utils.ts'\nimport { logError, logInfo, logStep } from '../../loggers/output.ts'\nimport { fetchUrlBody, getConfigs, isNewerVersion, runHook, runPostGenerate, startUrlWatcher, startWatcher } from './utils.ts'\nimport { FORMATTER_PREFERENCE, LINTER_PREFERENCE } from '@internals/utils'\nimport { detectTool, formatters, linters } from '../../tools.ts'\n\ntype GenerateProps = {\n input?: string\n config: Config\n hooks: Hookable<KubbHooks>\n logLevel: number\n /**\n * When `true`, generates in memory instead of writing to disk, and skips formatting, linting,\n * and post-generate commands.\n */\n dryRun?: boolean\n}\n\ntype ToolMap = typeof formatters | typeof linters\n\n/**\n * Static description of one output tool: its command table, the label and messages the pass logs,\n * and how to auto-detect it. Format and lint differ only in these values.\n */\ntype Tool = {\n label: string\n map: ToolMap\n detect: () => Promise<string | null>\n successPrefix: string\n noToolMessage: string\n}\n\ntype RunToolPassOptions = {\n toolValue: string\n tool: Tool\n outputPath: string\n logLevel: number\n hooks: Hookable<KubbHooks>\n onStart: () => Promise<void> | void\n onEnd: () => Promise<void> | void\n}\n\n/**\n * Runs one formatter or linter pass over the output directory. Returns the failure instead of\n * throwing, so the caller can turn it into a coded diagnostic. Failures never render here:\n * the caller emits them through `Diagnostics.emit`, like every other diagnostic.\n */\nasync function runToolPass({ toolValue, tool, outputPath, logLevel, hooks, onStart, onEnd }: RunToolPassOptions): Promise<Error | null> {\n await onStart()\n\n let resolvedTool = toolValue\n if (resolvedTool === 'auto') {\n const detected = await tool.detect()\n if (!detected) {\n await hooks.callHook('kubb:warn', { message: tool.noToolMessage })\n } else {\n resolvedTool = detected\n await hooks.callHook('kubb:info', { message: `Auto-detected ${tool.label}: ${styleText('dim', resolvedTool)}` })\n }\n }\n\n let toolError: Error | null = null\n\n // Nothing to lint or format when the output dir was never written. Skip so the tool\n // (e.g. oxlint with --no-ignore) doesn't fail with \"No files found to lint\".\n if (resolvedTool && resolvedTool !== 'auto' && resolvedTool in tool.map && existsSync(outputPath)) {\n const toolConfig = tool.map[resolvedTool as keyof ToolMap]\n\n const successMessage = [\n `${tool.successPrefix} with ${styleText('dim', resolvedTool)}`,\n logLevel >= logLevelMap.info ? `on ${styleText('dim', outputPath)}` : undefined,\n 'successfully',\n ]\n .filter(Boolean)\n .join(' ')\n\n try {\n const hookId = randomUUID()\n const hookArgs = toolConfig.args(outputPath)\n const commandWithArgs = [toolConfig.command, ...hookArgs].join(' ')\n\n await hooks.callHook('kubb:hook:start', { id: hookId, command: toolConfig.command, args: hookArgs })\n\n const result = await runHook({ id: hookId, command: toolConfig.command, args: hookArgs, commandWithArgs, hooks })\n\n if (result.success) {\n await hooks.callHook('kubb:success', { message: successMessage })\n } else {\n toolError = result.error ?? new Error(toolConfig.errorMessage)\n }\n } catch (caughtError) {\n toolError = toError(caughtError)\n }\n }\n\n await onEnd()\n\n return toolError\n}\n\nasync function generate(options: GenerateProps): Promise<boolean> {\n const { input, hooks, logLevel, dryRun = false } = options\n\n const hrStart = process.hrtime()\n const inputPath = input ?? (typeof options.config.input === 'string' ? options.config.input : undefined)\n\n const config: Config = {\n ...options.config,\n input: input ?? options.config.input,\n // Dry-run never touches disk, regardless of the config's own storage driver.\n storage: dryRun ? memoryStorage() : options.config.storage,\n // Also keeps core's `hasOutputPasses` false, so dry-run skips the output manifest write too.\n output: dryRun ? { ...options.config.output, format: false, lint: false, postGenerate: [] } : options.config.output,\n }\n\n // The formatter, linter, and post-generate commands run after a successful build. Collect their\n // failures as coded diagnostics so they reach the summary, the json report, and the exit code.\n const processOutput = async ({ config: resolvedConfig, outputPath }: { config: Config; outputPath: string }): Promise<Array<Diagnostic>> => {\n if (dryRun) return []\n\n const outputDiagnostics: Array<Diagnostic> = []\n const reportOutputFailure = async (code: ProblemDiagnostic['code'], label: string, error: Error) => {\n const diagnostic = outputDiagnostic(code, label, error)\n outputDiagnostics.push(diagnostic)\n await Diagnostics.emit(hooks, diagnostic)\n }\n\n // Format and lint are the same pass over the output directory, differing only in the tool\n // table and the hooks they announce themselves with, so run them from one descriptor list.\n const toolPasses = [\n {\n value: resolvedConfig.output.format,\n code: Diagnostics.code.formatFailed,\n tool: {\n label: 'formatter',\n map: formatters,\n detect: () => detectTool(FORMATTER_PREFERENCE),\n successPrefix: 'Formatting',\n noToolMessage: `No formatter found (${FORMATTER_PREFERENCE.join(', ')}). Skipping formatting.`,\n },\n onStart: () => hooks.callHook('kubb:format:start'),\n onEnd: () => hooks.callHook('kubb:format:end'),\n },\n {\n value: resolvedConfig.output.lint,\n code: Diagnostics.code.lintFailed,\n tool: {\n label: 'linter',\n map: linters,\n detect: () => detectTool(LINTER_PREFERENCE),\n successPrefix: 'Linting',\n noToolMessage: `No linter found (${LINTER_PREFERENCE.join(', ')}). Skipping linting.`,\n },\n onStart: () => hooks.callHook('kubb:lint:start'),\n onEnd: () => hooks.callHook('kubb:lint:end'),\n },\n ]\n\n for (const pass of toolPasses) {\n if (!pass.value) continue\n const error = await runToolPass({\n toolValue: pass.value,\n tool: pass.tool,\n onStart: pass.onStart,\n onEnd: pass.onEnd,\n outputPath,\n logLevel,\n hooks,\n })\n if (error) await reportOutputFailure(pass.code, pass.tool.label, error)\n }\n\n if (resolvedConfig.output.postGenerate?.length) {\n await hooks.callHook('kubb:hooks:start')\n const hookResults = await runPostGenerate({ commands: resolvedConfig.output.postGenerate, hooks })\n for (const hookResult of hookResults) {\n if (hookResult.success) continue\n await reportOutputFailure(Diagnostics.code.postGenerateFailed, 'Post-generate command', hookResult.error ?? new Error('Post-generate command failed'))\n }\n await hooks.callHook('kubb:hooks:end')\n }\n\n return outputDiagnostics\n }\n\n hooks.hook('kubb:generation:end', ({ status }) => {\n if (status === 'success') return hooks.callHook('kubb:success', { message: 'Generation succeeded', info: inputPath })\n })\n\n const kubb = createKubb(config, { hooks })\n const result = await kubb.generate({ processOutput })\n\n if (dryRun) {\n await hooks.callHook('kubb:info', { message: 'Dry run: no files were written', info: `${result.files.length} file(s) would be generated` })\n }\n\n const telemetryPlugins = Array.from(kubb.driver.plugins.values(), (p) => ({ name: p.name, options: p.options as Record<string, unknown> }))\n await sendTelemetry(\n buildTelemetryEvent({\n command: 'generate',\n kubbVersion: version,\n plugins: telemetryPlugins,\n hrStart,\n filesCreated: result.files.length,\n status: result.success ? 'success' : 'failed',\n }),\n )\n\n return result.success\n}\n\n/**\n * Builds a coded diagnostic for an output-phase failure (formatter, linter, or `done` hook).\n */\nfunction outputDiagnostic(code: ProblemDiagnostic['code'], label: string, caughtError: unknown): ProblemDiagnostic {\n const error = toError(caughtError)\n return {\n code,\n severity: 'error',\n message: `${label} failed: ${error.message}`,\n help: 'Check that the tool is installed and that the command and its config are correct.',\n location: { kind: 'config' },\n cause: error,\n }\n}\n\ntype GenerateCommandOptions = {\n input?: string\n configPath?: string\n logLevel: string\n watch: boolean\n reporters?: Array<ReporterName>\n dryRun?: boolean\n}\n\nasync function checkForUpdate(hooks: Hookable<KubbHooks>): Promise<void> {\n try {\n const res = await fetch(KUBB_NPM_PACKAGE_URL, { signal: AbortSignal.timeout(UPDATE_CHECK_TIMEOUT_MS) })\n const data = (await res.json()) as { version: string }\n if (data.version && isNewerVersion(version, data.version)) {\n await Diagnostics.emit(hooks, Diagnostics.update({ currentVersion: version, latestVersion: data.version }))\n }\n } catch {\n // Ignore network errors\n }\n}\n\n/**\n * Runs the full Kubb generation lifecycle for the given CLI options.\n * Loads configs, sets up the reporters (CLI `--reporter` picks which of `config.reporters` to trigger),\n * checks for a newer version, and calls `generate` for each config entry.\n */\nexport async function run({ input, configPath, logLevel: logLevelKey, watch, reporters: cliReporters, dryRun }: GenerateCommandOptions): Promise<void> {\n const logLevel = logLevelMap[logLevelKey as keyof typeof logLevelMap] ?? logLevelMap.info\n const hooks = new Hookable<KubbHooks>()\n\n // Load the config first so `config.reporters` can pick the reporters. A failure here has no\n // reporter installed yet, so fall back to the default `cli` reporter to surface it.\n let configs: Array<Config>\n let resolvedConfigPath: string\n try {\n const loaded = await getConfigs({\n configPath,\n input,\n watch,\n logLevel: logLevelKey as CLIOptions['logLevel'],\n })\n configs = loaded.configs\n resolvedConfigPath = loaded.configPath\n } catch (error) {\n await setupReporters(hooks, { logLevel, reporters: [cliReporter] })\n await hooks.callHook('kubb:error', { error: toError(error) })\n process.exit(1)\n }\n\n // CLI `--reporter` selects which reporters to trigger by name, defaulting to `cli`. The config\n // always carries the available reporters (defineConfig registers the built-ins).\n const requestedNames: Array<ReporterName> = cliReporters?.length ? cliReporters : ['cli']\n const reporters = selectReporters(configs[0]?.reporters ?? [], requestedNames)\n await setupReporters(hooks, { logLevel, reporters })\n\n await hooks.callHook('kubb:lifecycle:start', { version })\n\n await checkForUpdate(hooks)\n\n try {\n const relativeConfigPath = path.relative(process.cwd(), resolvedConfigPath)\n\n await hooks.callHook('kubb:info', { message: 'Config loaded', info: relativeConfigPath })\n await hooks.callHook('kubb:success', { message: 'Config loaded successfully', info: relativeConfigPath })\n\n let anyFailed = false\n for (const config of configs) {\n const effectiveInput = input ?? config.input\n const inputKind = typeof effectiveInput === 'string' ? getInputKind(effectiveInput) : undefined\n const watchPath = inputKind === 'file' || inputKind === 'url' ? (effectiveInput as string) : undefined\n if (watchPath && watch) {\n const watchedPaths = [watchPath]\n // Don't removeAll() between builds, that would also drop logger and lifecycle\n // listeners. Plugin listeners are already disposed by safeBuild's dispose()\n // in its finally block, so re-running generate() on the same hooks emitter is safe.\n const build = async (paths: Array<string>) => {\n await generate({ input, config, logLevel, hooks, dryRun })\n logStep(styleText('yellow', `Watching for changes in ${paths.join(' and ')}`))\n }\n\n // For a URL input, capture the document before the build: it becomes the watcher's\n // change-detection baseline, so an edit landing before the first poll still rebuilds.\n // When the server is down the baseline stays undefined and the watcher rebuilds on its\n // first successful poll, so recovery with an unchanged document still generates output.\n const initialBody = inputKind === 'url' ? await fetchUrlBody(watchPath) : undefined\n\n // The watchers ignore their startup state (chokidar's initial events, the baseline\n // above), so run the first build here. A failing first build keeps watching, since\n // the user can fix the input and save.\n try {\n await build(watchedPaths)\n } catch (buildError) {\n await hooks.callHook('kubb:error', { error: toError(buildError) })\n }\n\n if (inputKind === 'url') {\n startUrlWatcher(watchPath, build, { log: { info: logInfo, error: logError }, initialBody })\n } else {\n await startWatcher(watchedPaths, build, { info: logInfo, error: logError })\n }\n } else {\n try {\n const succeeded = await generate({ input, config, logLevel, hooks, dryRun })\n if (!succeeded) anyFailed = true\n } catch (configError) {\n await hooks.callHook('kubb:error', { error: toError(configError) })\n anyFailed = true\n }\n }\n }\n\n await hooks.callHook('kubb:lifecycle:end')\n\n if (anyFailed) {\n process.exit(1)\n }\n } catch (error) {\n await hooks.callHook('kubb:error', { error: toError(error) })\n process.exit(1)\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAuEA,eAAe,YAAY,EAAE,WAAW,MAAM,YAAY,UAAU,OAAO,SAAS,SAAoD;CACtI,MAAM,QAAQ;CAEd,IAAI,eAAe;CACnB,IAAI,iBAAiB,QAAQ;EAC3B,MAAM,WAAW,MAAM,KAAK,OAAO;EACnC,IAAI,CAAC,UACH,MAAM,MAAM,SAAS,aAAa,EAAE,SAAS,KAAK,cAAc,CAAC;OAC5D;GACL,eAAe;GACf,MAAM,MAAM,SAAS,aAAa,EAAE,SAAS,iBAAiB,KAAK,MAAM,KAAA,GAAIA,UAAAA,UAAAA,CAAU,OAAO,YAAY,IAAI,CAAC;EACjH;CACF;CAEA,IAAI,YAA0B;CAI9B,IAAI,gBAAgB,iBAAiB,UAAU,gBAAgB,KAAK,QAAA,GAAOC,QAAAA,WAAAA,CAAW,UAAU,GAAG;EACjG,MAAM,aAAa,KAAK,IAAI;EAE5B,MAAM,iBAAiB;GACrB,GAAG,KAAK,cAAc,SAAA,GAAQD,UAAAA,UAAAA,CAAU,OAAO,YAAY;GAC3D,YAAYE,WAAAA,SAAY,OAAO,OAAA,GAAMF,UAA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AI,WACF,aAAA,QAAQ,KAAK,CAAC;CAElB,SAAS,OAAO;EACd,MAAM,MAAM,SAAS,cAAc,EAAE,OAAOA,eAAAA,QAAQ,KAAK,EAAE,CAAC;EAC5D,aAAA,QAAQ,KAAK,CAAC;CAChB;AACF"}
|
|
1
|
+
{"version":3,"file":"run-YSoDwlKZ.cjs","names":["styleText","existsSync","logLevelMap","randomUUID","runHook","toError","process","memoryStorage","Diagnostics","formatters","detectTool","FORMATTER_PREFERENCE","linters","LINTER_PREFERENCE","runPostGenerate","createKubb","sendTelemetry","buildTelemetryEvent","version","KUBB_NPM_PACKAGE_URL","UPDATE_CHECK_TIMEOUT_MS","isNewerVersion","Hookable","getConfigs","setupReporters","cliReporter","selectReporters","path","getInputKind","fetchUrlBody","logInfo","logError","startWatcher"],"sources":["../src/runners/generate/run.ts"],"sourcesContent":["import { randomUUID } from 'node:crypto'\nimport { existsSync } from 'node:fs'\nimport path from 'node:path'\nimport process from 'node:process'\nimport { styleText } from 'node:util'\nimport { toError } from '@internals/utils'\nimport {\n Hookable,\n type CLIOptions,\n cliReporter,\n type Config,\n createKubb,\n type Diagnostic,\n Diagnostics,\n getInputKind,\n type KubbHooks,\n logLevel as logLevelMap,\n memoryStorage,\n type ProblemDiagnostic,\n type ReporterName,\n} from '@kubb/core'\nimport { version } from '../../../package.json'\nimport { KUBB_NPM_PACKAGE_URL, UPDATE_CHECK_TIMEOUT_MS } from '../../constants.ts'\nimport { buildTelemetryEvent, sendTelemetry } from '../../Telemetry.ts'\nimport setupReporters, { selectReporters } from '../../loggers/utils.ts'\nimport { logError, logInfo, logStep } from '../../loggers/output.ts'\nimport { fetchUrlBody, getConfigs, isNewerVersion, runHook, runPostGenerate, startUrlWatcher, startWatcher } from './utils.ts'\nimport { FORMATTER_PREFERENCE, LINTER_PREFERENCE } from '@internals/utils'\nimport { detectTool, formatters, linters } from '../../tools.ts'\n\ntype GenerateProps = {\n input?: string\n config: Config\n hooks: Hookable<KubbHooks>\n logLevel: number\n /**\n * When `true`, generates in memory instead of writing to disk, and skips formatting, linting,\n * and post-generate commands.\n */\n dryRun?: boolean\n}\n\ntype ToolMap = typeof formatters | typeof linters\n\n/**\n * Static description of one output tool: its command table, the label and messages the pass logs,\n * and how to auto-detect it. Format and lint differ only in these values.\n */\ntype Tool = {\n label: string\n map: ToolMap\n detect: () => Promise<string | null>\n successPrefix: string\n noToolMessage: string\n}\n\ntype RunToolPassOptions = {\n toolValue: string\n tool: Tool\n outputPath: string\n logLevel: number\n hooks: Hookable<KubbHooks>\n onStart: () => Promise<void> | void\n onEnd: () => Promise<void> | void\n}\n\n/**\n * Runs one formatter or linter pass over the output directory. Returns the failure instead of\n * throwing, so the caller can turn it into a coded diagnostic. Failures never render here:\n * the caller emits them through `Diagnostics.emit`, like every other diagnostic.\n */\nasync function runToolPass({ toolValue, tool, outputPath, logLevel, hooks, onStart, onEnd }: RunToolPassOptions): Promise<Error | null> {\n await onStart()\n\n let resolvedTool = toolValue\n if (resolvedTool === 'auto') {\n const detected = await tool.detect()\n if (!detected) {\n await hooks.callHook('kubb:warn', { message: tool.noToolMessage })\n } else {\n resolvedTool = detected\n await hooks.callHook('kubb:info', { message: `Auto-detected ${tool.label}: ${styleText('dim', resolvedTool)}` })\n }\n }\n\n let toolError: Error | null = null\n\n // Nothing to lint or format when the output dir was never written. Skip so the tool\n // (e.g. oxlint with --no-ignore) doesn't fail with \"No files found to lint\".\n if (resolvedTool && resolvedTool !== 'auto' && resolvedTool in tool.map && existsSync(outputPath)) {\n const toolConfig = tool.map[resolvedTool as keyof ToolMap]\n\n const successMessage = [\n `${tool.successPrefix} with ${styleText('dim', resolvedTool)}`,\n logLevel >= logLevelMap.info ? `on ${styleText('dim', outputPath)}` : undefined,\n 'successfully',\n ]\n .filter(Boolean)\n .join(' ')\n\n try {\n const hookId = randomUUID()\n const hookArgs = toolConfig.args(outputPath)\n const commandWithArgs = [toolConfig.command, ...hookArgs].join(' ')\n\n await hooks.callHook('kubb:hook:start', { id: hookId, command: toolConfig.command, args: hookArgs })\n\n const result = await runHook({ id: hookId, command: toolConfig.command, args: hookArgs, commandWithArgs, hooks })\n\n if (result.success) {\n await hooks.callHook('kubb:success', { message: successMessage })\n } else {\n toolError = result.error ?? new Error(toolConfig.errorMessage)\n }\n } catch (caughtError) {\n toolError = toError(caughtError)\n }\n }\n\n await onEnd()\n\n return toolError\n}\n\nasync function generate(options: GenerateProps): Promise<boolean> {\n const { input, hooks, logLevel, dryRun = false } = options\n\n const hrStart = process.hrtime()\n const inputPath = input ?? (typeof options.config.input === 'string' ? options.config.input : undefined)\n\n const config: Config = {\n ...options.config,\n input: input ?? options.config.input,\n // Dry-run never touches disk, regardless of the config's own storage driver.\n storage: dryRun ? memoryStorage() : options.config.storage,\n // Also keeps core's `hasOutputPasses` false, so dry-run skips the output manifest write too.\n output: dryRun ? { ...options.config.output, format: false, lint: false, postGenerate: [] } : options.config.output,\n }\n\n // The formatter, linter, and post-generate commands run after a successful build. Collect their\n // failures as coded diagnostics so they reach the summary, the json report, and the exit code.\n const processOutput = async ({ config: resolvedConfig, outputPath }: { config: Config; outputPath: string }): Promise<Array<Diagnostic>> => {\n if (dryRun) return []\n\n const outputDiagnostics: Array<Diagnostic> = []\n const reportOutputFailure = async (code: ProblemDiagnostic['code'], label: string, error: Error) => {\n const diagnostic = outputDiagnostic(code, label, error)\n outputDiagnostics.push(diagnostic)\n await Diagnostics.emit(hooks, diagnostic)\n }\n\n // Format and lint are the same pass over the output directory, differing only in the tool\n // table and the hooks they announce themselves with, so run them from one descriptor list.\n const toolPasses = [\n {\n value: resolvedConfig.output.format,\n code: Diagnostics.code.formatFailed,\n tool: {\n label: 'formatter',\n map: formatters,\n detect: () => detectTool(FORMATTER_PREFERENCE),\n successPrefix: 'Formatting',\n noToolMessage: `No formatter found (${FORMATTER_PREFERENCE.join(', ')}). Skipping formatting.`,\n },\n onStart: () => hooks.callHook('kubb:format:start'),\n onEnd: () => hooks.callHook('kubb:format:end'),\n },\n {\n value: resolvedConfig.output.lint,\n code: Diagnostics.code.lintFailed,\n tool: {\n label: 'linter',\n map: linters,\n detect: () => detectTool(LINTER_PREFERENCE),\n successPrefix: 'Linting',\n noToolMessage: `No linter found (${LINTER_PREFERENCE.join(', ')}). Skipping linting.`,\n },\n onStart: () => hooks.callHook('kubb:lint:start'),\n onEnd: () => hooks.callHook('kubb:lint:end'),\n },\n ]\n\n for (const pass of toolPasses) {\n if (!pass.value) continue\n const error = await runToolPass({\n toolValue: pass.value,\n tool: pass.tool,\n onStart: pass.onStart,\n onEnd: pass.onEnd,\n outputPath,\n logLevel,\n hooks,\n })\n if (error) await reportOutputFailure(pass.code, pass.tool.label, error)\n }\n\n if (resolvedConfig.output.postGenerate?.length) {\n await hooks.callHook('kubb:hooks:start')\n const hookResults = await runPostGenerate({ commands: resolvedConfig.output.postGenerate, hooks })\n for (const hookResult of hookResults) {\n if (hookResult.success) continue\n await reportOutputFailure(Diagnostics.code.postGenerateFailed, 'Post-generate command', hookResult.error ?? new Error('Post-generate command failed'))\n }\n await hooks.callHook('kubb:hooks:end')\n }\n\n return outputDiagnostics\n }\n\n hooks.hook('kubb:generation:end', ({ status }) => {\n if (status === 'success') return hooks.callHook('kubb:success', { message: 'Generation succeeded', info: inputPath })\n })\n\n const kubb = createKubb(config, { hooks })\n const result = await kubb.generate({ processOutput })\n\n if (dryRun) {\n await hooks.callHook('kubb:info', { message: 'Dry run: no files were written', info: `${result.files.length} file(s) would be generated` })\n }\n\n const telemetryPlugins = Array.from(kubb.driver.plugins.values(), (p) => ({ name: p.name, options: p.options as Record<string, unknown> }))\n await sendTelemetry(\n buildTelemetryEvent({\n command: 'generate',\n kubbVersion: version,\n plugins: telemetryPlugins,\n hrStart,\n filesCreated: result.files.length,\n status: result.success ? 'success' : 'failed',\n }),\n )\n\n return result.success\n}\n\n/**\n * Builds a coded diagnostic for an output-phase failure (formatter, linter, or `done` hook).\n */\nfunction outputDiagnostic(code: ProblemDiagnostic['code'], label: string, caughtError: unknown): ProblemDiagnostic {\n const error = toError(caughtError)\n return {\n code,\n severity: 'error',\n message: `${label} failed: ${error.message}`,\n help: 'Check that the tool is installed and that the command and its config are correct.',\n location: { kind: 'config' },\n cause: error,\n }\n}\n\ntype GenerateCommandOptions = {\n input?: string\n configPath?: string\n logLevel: string\n watch: boolean\n reporters?: Array<ReporterName>\n dryRun?: boolean\n}\n\nasync function checkForUpdate(hooks: Hookable<KubbHooks>): Promise<void> {\n try {\n const res = await fetch(KUBB_NPM_PACKAGE_URL, { signal: AbortSignal.timeout(UPDATE_CHECK_TIMEOUT_MS) })\n const data = (await res.json()) as { version: string }\n if (data.version && isNewerVersion(version, data.version)) {\n await Diagnostics.emit(hooks, Diagnostics.update({ currentVersion: version, latestVersion: data.version }))\n }\n } catch {\n // Ignore network errors\n }\n}\n\n/**\n * Runs the full Kubb generation lifecycle for the given CLI options.\n * Loads configs, sets up the reporters (CLI `--reporter` picks which of `config.reporters` to trigger),\n * checks for a newer version, and calls `generate` for each config entry.\n */\nexport async function run({ input, configPath, logLevel: logLevelKey, watch, reporters: cliReporters, dryRun }: GenerateCommandOptions): Promise<void> {\n const logLevel = logLevelMap[logLevelKey as keyof typeof logLevelMap] ?? logLevelMap.info\n const hooks = new Hookable<KubbHooks>()\n\n // Load the config first so `config.reporters` can pick the reporters. A failure here has no\n // reporter installed yet, so fall back to the default `cli` reporter to surface it.\n let configs: Array<Config>\n let resolvedConfigPath: string\n try {\n const loaded = await getConfigs({\n configPath,\n input,\n watch,\n logLevel: logLevelKey as CLIOptions['logLevel'],\n })\n configs = loaded.configs\n resolvedConfigPath = loaded.configPath\n } catch (error) {\n await setupReporters(hooks, { logLevel, reporters: [cliReporter] })\n await hooks.callHook('kubb:error', { error: toError(error) })\n process.exit(1)\n }\n\n // CLI `--reporter` selects which reporters to trigger by name, defaulting to `cli`. The config\n // always carries the available reporters (defineConfig registers the built-ins).\n const requestedNames: Array<ReporterName> = cliReporters?.length ? cliReporters : ['cli']\n const reporters = selectReporters(configs[0]?.reporters ?? [], requestedNames)\n await setupReporters(hooks, { logLevel, reporters })\n\n await hooks.callHook('kubb:lifecycle:start', { version })\n\n await checkForUpdate(hooks)\n\n try {\n const relativeConfigPath = path.relative(process.cwd(), resolvedConfigPath)\n\n await hooks.callHook('kubb:info', { message: 'Config loaded', info: relativeConfigPath })\n await hooks.callHook('kubb:success', { message: 'Config loaded successfully', info: relativeConfigPath })\n\n let anyFailed = false\n for (const config of configs) {\n const effectiveInput = input ?? config.input\n const inputKind = typeof effectiveInput === 'string' ? getInputKind(effectiveInput) : undefined\n const watchPath = inputKind === 'file' || inputKind === 'url' ? (effectiveInput as string) : undefined\n if (watchPath && watch) {\n const watchedPaths = [watchPath]\n // Don't removeAll() between builds, that would also drop logger and lifecycle\n // listeners. Plugin listeners are already disposed by safeBuild's dispose()\n // in its finally block, so re-running generate() on the same hooks emitter is safe.\n const build = async (paths: Array<string>) => {\n await generate({ input, config, logLevel, hooks, dryRun })\n logStep(styleText('yellow', `Watching for changes in ${paths.join(' and ')}`))\n }\n\n // For a URL input, capture the document before the build: it becomes the watcher's\n // change-detection baseline, so an edit landing before the first poll still rebuilds.\n // When the server is down the baseline stays undefined and the watcher rebuilds on its\n // first successful poll, so recovery with an unchanged document still generates output.\n const initialBody = inputKind === 'url' ? await fetchUrlBody(watchPath) : undefined\n\n // The watchers ignore their startup state (chokidar's initial events, the baseline\n // above), so run the first build here. A failing first build keeps watching, since\n // the user can fix the input and save.\n try {\n await build(watchedPaths)\n } catch (buildError) {\n await hooks.callHook('kubb:error', { error: toError(buildError) })\n }\n\n if (inputKind === 'url') {\n startUrlWatcher(watchPath, build, { log: { info: logInfo, error: logError }, initialBody })\n } else {\n await startWatcher(watchedPaths, build, { info: logInfo, error: logError })\n }\n } else {\n try {\n const succeeded = await generate({ input, config, logLevel, hooks, dryRun })\n if (!succeeded) anyFailed = true\n } catch (configError) {\n await hooks.callHook('kubb:error', { error: toError(configError) })\n anyFailed = true\n }\n }\n }\n\n await hooks.callHook('kubb:lifecycle:end')\n\n if (anyFailed) {\n process.exit(1)\n }\n } catch (error) {\n await hooks.callHook('kubb:error', { error: toError(error) })\n process.exit(1)\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAuEA,eAAe,YAAY,EAAE,WAAW,MAAM,YAAY,UAAU,OAAO,SAAS,SAAoD;CACtI,MAAM,QAAQ;CAEd,IAAI,eAAe;CACnB,IAAI,iBAAiB,QAAQ;EAC3B,MAAM,WAAW,MAAM,KAAK,OAAO;EACnC,IAAI,CAAC,UACH,MAAM,MAAM,SAAS,aAAa,EAAE,SAAS,KAAK,cAAc,CAAC;OAC5D;GACL,eAAe;GACf,MAAM,MAAM,SAAS,aAAa,EAAE,SAAS,iBAAiB,KAAK,MAAM,KAAA,GAAIA,UAAAA,UAAAA,CAAU,OAAO,YAAY,IAAI,CAAC;EACjH;CACF;CAEA,IAAI,YAA0B;CAI9B,IAAI,gBAAgB,iBAAiB,UAAU,gBAAgB,KAAK,QAAA,GAAOC,QAAAA,WAAAA,CAAW,UAAU,GAAG;EACjG,MAAM,aAAa,KAAK,IAAI;EAE5B,MAAM,iBAAiB;GACrB,GAAG,KAAK,cAAc,SAAA,GAAQD,UAAAA,UAAAA,CAAU,OAAO,YAAY;GAC3D,YAAYE,WAAAA,SAAY,OAAO,OAAA,GAAMF,UAAAA,UAAAA,CAAU,OAAO,UAAU,MAAM,KAAA;GACtE;EACF,CAAC,CACE,OAAO,OAAO,CAAC,CACf,KAAK,GAAG;EAEX,IAAI;GACF,MAAM,UAAA,GAASG,YAAAA,WAAAA,CAAW;GAC1B,MAAM,WAAW,WAAW,KAAK,UAAU;GAC3C,MAAM,kBAAkB,CAAC,WAAW,SAAS,GAAG,QAAQ,CAAC,CAAC,KAAK,GAAG;GAElE,MAAM,MAAM,SAAS,mBAAmB;IAAE,IAAI;IAAQ,SAAS,WAAW;IAAS,MAAM;GAAS,CAAC;GAEnG,MAAM,SAAS,MAAMC,cAAAA,QAAQ;IAAE,IAAI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Q;MAAU;MAAO;KAAO,CAAC;KACzD,eAAA,SAAA,GAAQ5B,UAAAA,UAAAA,CAAU,UAAU,2BAA2B,MAAM,KAAK,OAAO,GAAG,CAAC;IAC/E;IAMA,MAAM,cAAc,cAAc,QAAQ,MAAM6B,cAAAA,aAAa,SAAS,IAAI,KAAA;IAK1E,IAAI;KACF,MAAM,MAAM,YAAY;IAC1B,SAAS,YAAY;KACnB,MAAM,MAAM,SAAS,cAAc,EAAE,OAAOxB,eAAAA,QAAQ,UAAU,EAAE,CAAC;IACnE;IAEA,IAAI,cAAc,OAChB,cAAA,gBAAgB,WAAW,OAAO;KAAE,KAAK;MAAE,MAAMyB,eAAAA;MAAS,OAAOC,eAAAA;KAAS;KAAG;IAAY,CAAC;SAE1F,MAAMC,cAAAA,aAAa,cAAc,OAAO;KAAE,MAAMF,eAAAA;KAAS,OAAOC,eAAAA;IAAS,CAAC;GAE9E,OACE,IAAI;IAEF,IAAI,CAAC,MADmB,SAAS;KAAE;KAAO;KAAQ;KAAU;KAAO;IAAO,CAAC,GAC3D,YAAY;GAC9B,SAAS,aAAa;IACpB,MAAM,MAAM,SAAS,cAAc,EAAE,OAAO1B,eAAAA,QAAQ,WAAW,EAAE,CAAC;IAClE,YAAY;GACd;EAEJ;EAEA,MAAM,MAAM,SAAS,oBAAoB;EAEzC,IAAI,WACF,aAAA,QAAQ,KAAK,CAAC;CAElB,SAAS,OAAO;EACd,MAAM,MAAM,SAAS,cAAc,EAAE,OAAOA,eAAAA,QAAQ,KAAK,EAAE,CAAC;EAC5D,aAAA,QAAQ,KAAK,CAAC;CAChB;AACF"}
|
package/dist/run-kdxqOL8u.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"run-kdxqOL8u.js","names":["process","process"],"sources":["../../../internals/shared/src/init.ts","../src/tools.ts","../src/runners/init/utils.ts","../src/runners/init/run.ts"],"sourcesContent":["import { availablePlugins, KUBB_PACKAGE_NAME } from './constants.ts'\nimport type { PluginOption } from './types.ts'\n\n/**\n * Resolves a comma-separated plugin flag (e.g. `--plugins plugin-ts,plugin-zod`) into the\n * matching known plugin options. Unrecognized names are dropped, and a missing flag yields\n * an empty list.\n */\nexport function resolvePlugins(pluginsFlag: string | undefined): Array<PluginOption> {\n if (!pluginsFlag) {\n return []\n }\n const requested = pluginsFlag\n .split(',')\n .map((value) => value.trim())\n .filter(Boolean)\n return availablePlugins.filter((plugin) => requested.includes(plugin.value))\n}\n\nexport function generateConfigFile({\n selectedPlugins,\n inputPath,\n outputPath,\n}: {\n selectedPlugins: Array<PluginOption>\n inputPath: string\n outputPath: string\n}): string {\n const imports = selectedPlugins.map((plugin) => `import { ${plugin.importName} } from '${plugin.packageName}'`).join('\\n')\n\n const pluginConfigs = selectedPlugins.map((plugin) => ` ${plugin.importName}(),`).join('\\n')\n\n return `import { defineConfig } from 'kubb/config'\n${imports}\n\nexport default defineConfig({\n input: '${inputPath}',\n output: {\n path: '${outputPath}',\n clean: true,\n },\n plugins: [\n${pluginConfigs}\n ],\n})\n`\n}\n\n/**\n * Turns package names into install specifiers for the wizard.\n *\n * `kubb` is pinned to the exact version of the running CLI, since both ship from the same release\n * and resolving `kubb@beta` separately can land on a different version than the CLI doing the\n * scaffolding. Plugins release from their own repo on their own cadence, so they follow the\n * release channel of the CLI through its dist-tag.\n */\nexport function resolveInstallVersions({ packages, version }: { packages: Array<string>; version: string }): Array<string> {\n const prerelease = version.match(/-([a-z]+)/)?.[1]\n const tag = prerelease ?? 'latest'\n\n return packages.map((name) => (name === KUBB_PACKAGE_NAME ? `${name}@${version}` : `${name}@${tag}`))\n}\n","import { existsSync, readFileSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { formatters, linters } from '@internals/utils'\nimport type { Config } from '@kubb/core'\n\n/**\n * The configurable formatter names, mirrored from `Config['output'].format`. Excludes `'auto'`\n * (detection, not a tool) and `false` (skip). The `formatters`/`linters` tables below are pinned to\n * these so adding a tool to the config union without a descriptor fails to compile.\n */\ntype FormatterName = Exclude<NonNullable<Config['output']['format']>, 'auto' | false>\ntype LinterName = Exclude<NonNullable<Config['output']['lint']>, 'auto' | false>\n\n// Pinned to core's union here rather than in `@internals/utils`, which must not import `@kubb/core`:\n// adding a tool to the config union without a descriptor stays a compile error.\nformatters satisfies Record<FormatterName, unknown>\nlinters satisfies Record<LinterName, unknown>\n\nexport { detectTool, formatters, linters } from '@internals/utils'\n\nexport type PackageManagerName = 'npm' | 'pnpm' | 'yarn' | 'bun'\n\n/**\n * Metadata describing a package manager's lock file and install command.\n */\nexport interface PackageManagerInfo {\n /**\n * Identifier used in CLI commands, e.g. `pnpm`, `yarn`.\n */\n name: PackageManagerName\n /**\n * Lock file name that uniquely identifies this package manager in a project root.\n */\n lockFile: string\n /**\n * Subcommands passed to the package manager binary to install a dev dependency.\n */\n installCommand: ReadonlyArray<string>\n}\n\n/**\n * Metadata for each supported package manager, keyed by its short name.\n *\n * @example\n * ```ts\n * packageManagers.pnpm.installCommand // ['add', '-D']\n * packageManagers.npm.lockFile // 'package-lock.json'\n * ```\n */\nconst packageManagers: Record<PackageManagerName, PackageManagerInfo> = {\n pnpm: {\n name: 'pnpm',\n lockFile: 'pnpm-lock.yaml',\n installCommand: ['add', '-D'],\n },\n yarn: {\n name: 'yarn',\n lockFile: 'yarn.lock',\n installCommand: ['add', '-D'],\n },\n bun: {\n name: 'bun',\n lockFile: 'bun.lockb',\n installCommand: ['add', '-d'],\n },\n npm: {\n name: 'npm',\n lockFile: 'package-lock.json',\n installCommand: ['install', '--save-dev'],\n },\n}\n\n/**\n * Minimal shape of `package.json` fields read during detection.\n */\ntype PackageJson = {\n /**\n * The `packageManager` field from `package.json` (e.g. `\"pnpm@9.0.0\"`).\n */\n packageManager?: string\n}\n\n/**\n * Detects the active package manager for the given directory.\n * Resolution order: `packageManager` field in `package.json`, then presence of a lock file.\n * Falls back to `npm` when no signal is found.\n *\n * @example\n * ```ts\n * detectPackageManager('/my/project') // { name: 'pnpm', lockFile: 'pnpm-lock.yaml', ... }\n * detectPackageManager() // falls back to npm when no lock file is found\n * ```\n */\nexport function detectPackageManager(cwd: string = process.cwd()): PackageManagerInfo {\n const packageJsonPath = join(cwd, 'package.json')\n if (existsSync(packageJsonPath)) {\n try {\n const packageJson = JSON.parse(readFileSync(packageJsonPath, 'utf-8')) as PackageJson\n const pmField = packageJson.packageManager\n if (typeof pmField === 'string') {\n const name = pmField.split('@')[0]\n if (name && name in packageManagers) {\n return packageManagers[name as PackageManagerName]\n }\n }\n } catch {\n // Continue to lock file detection\n }\n }\n\n for (const pm of Object.values(packageManagers)) {\n if (existsSync(join(cwd, pm.lockFile))) {\n return pm\n }\n }\n\n return packageManagers.npm\n}\n","import fs from 'node:fs'\nimport path from 'node:path'\nimport process from 'node:process'\nimport { x } from 'tinyexec'\nimport type { PackageManagerInfo, PackageManagerName } from '../../tools.ts'\n\n/**\n * Returns `true` when a `package.json` exists at `cwd`.\n */\nexport function hasPackageJson(cwd: string = process.cwd()): boolean {\n return fs.existsSync(path.join(cwd, 'package.json'))\n}\n\n/**\n * Initializes a new `package.json` at `cwd` using the detected package manager.\n */\nexport async function initPackageJson(cwd: string, packageManager: PackageManagerInfo): Promise<void> {\n const commands: Record<PackageManagerName, Array<string>> = {\n npm: ['init', '-y'],\n pnpm: ['init'],\n yarn: ['init', '-y'],\n bun: ['init', '-y'],\n }\n\n await x(packageManager.name, commands[packageManager.name], {\n nodeOptions: { cwd, stdio: 'inherit' },\n throwOnError: true,\n })\n}\n\n/**\n * Installs the given packages at `cwd` using the detected package manager.\n */\nexport async function installPackages(packages: Array<string>, packageManager: PackageManagerInfo, cwd: string = process.cwd()): Promise<void> {\n await x(packageManager.name, [...packageManager.installCommand, ...packages], {\n nodeOptions: { cwd, stdio: 'inherit' },\n throwOnError: true,\n })\n}\n","import fs from 'node:fs'\nimport path from 'node:path'\nimport process from 'node:process'\nimport { styleText } from 'node:util'\nimport * as clack from '@clack/prompts'\nimport type { DryRunExtension } from '@gunshi/plugin-dryrun'\nimport {\n availablePlugins,\n generateConfigFile,\n initDefaults,\n KUBB_CONFIG_FILENAME,\n KUBB_PACKAGE_NAME,\n type PluginOption,\n resolveInstallVersions,\n resolvePlugins,\n} from '@internals/shared'\nimport { createSpinner, logError, logInfo, logIntro, logOutro, logWarn } from '../../loggers/output.ts'\nimport { hasPackageJson, initPackageJson, installPackages } from './utils.ts'\nimport { detectPackageManager } from '../../tools.ts'\n\nfunction cancelAndExit(message = 'Operation canceled.'): never {\n clack.cancel(message)\n process.exit(0)\n}\n\ntype InitOptions = {\n /**\n * When `true`, skips all interactive prompts and uses default values.\n */\n yes: boolean\n /**\n * Current `@kubb/cli` version string, shown in the closing outro.\n */\n version: string\n /**\n * Input path flag value from `--input`. When provided, skips the input prompt.\n */\n input?: string\n /**\n * Output directory flag value from `--output`. When provided, skips the output prompt.\n */\n output?: string\n /**\n * Comma-separated plugin list from `--plugins`, e.g. `'plugin-ts,plugin-zod'`. When provided, skips the plugin selection prompt.\n */\n plugins?: string\n /**\n * Dry-run extension from `@gunshi/plugin-dryrun`. When enabled, package installation and the\n * config file write are skipped.\n */\n dryRun: DryRunExtension\n}\n\n/**\n * Runs the interactive Kubb scaffolding wizard.\n * Detects the package manager, prompts for input/output paths and plugins, installs packages, and writes `kubb.config.ts`.\n * Pass `yes: true` to skip all prompts and use defaults.\n */\nexport async function run({ yes, version, input: inputFlag, output: outputFlag, plugins: pluginsFlag, dryRun }: InitOptions): Promise<void> {\n const cwd = process.cwd()\n\n logIntro({ title: styleText('bgCyan', styleText('black', ' Kubb Init ')) })\n\n /**\n * Returns `flag` when provided, the `defaultValue` when `yes` is set,\n * or calls `prompt()` for interactive input. Exits on cancellation.\n */\n async function resolveOrPrompt<T>(flag: T | undefined, defaultValue: T, logLabel: string, prompt: () => Promise<T | symbol>): Promise<T> {\n if (flag !== undefined) {\n logInfo(`${logLabel}: ${styleText('cyan', String(flag))}`)\n return flag\n }\n if (yes) {\n logInfo(`${logLabel}: ${styleText('cyan', String(defaultValue))}`)\n return defaultValue\n }\n const result = await prompt()\n if (clack.isCancel(result)) cancelAndExit()\n return result as T\n }\n\n try {\n // Check/create package.json, detect package manager once after the block\n if (!hasPackageJson(cwd)) {\n if (!yes) {\n const shouldInit = await clack.confirm({\n message: 'No package.json found. Would you like to create one?',\n initialValue: true,\n })\n\n if (clack.isCancel(shouldInit) || !shouldInit) {\n cancelAndExit()\n }\n }\n\n const packageManager = detectPackageManager(cwd)\n const spinner = createSpinner()\n spinner.start(`Initializing package.json with ${packageManager.name}`)\n await initPackageJson(cwd, packageManager)\n spinner.stop(`Created package.json with ${packageManager.name}`)\n }\n\n const packageManager = detectPackageManager(cwd)\n if (hasPackageJson(cwd)) {\n logInfo(`Detected package manager: ${styleText('cyan', packageManager.name)}`)\n }\n\n // Prompt for OpenAPI spec path\n const inputPath = await resolveOrPrompt(inputFlag, initDefaults.inputPath, 'Using input path', () =>\n clack.text({\n message: 'Where is your OpenAPI specification located?',\n placeholder: initDefaults.inputPath,\n defaultValue: initDefaults.inputPath,\n validate: (value) => {\n if (!value) return 'Input path is required'\n },\n }),\n )\n\n // Prompt for output directory\n const outputPath = await resolveOrPrompt(outputFlag, initDefaults.outputPath, 'Using output path', () =>\n clack.text({\n message: 'Where should the generated files be output?',\n placeholder: initDefaults.outputPath,\n defaultValue: initDefaults.outputPath,\n validate: (value) => {\n if (!value) return 'Output path is required'\n },\n }),\n )\n\n // Plugin selection\n const defaultPlugins = availablePlugins.filter((p) => (initDefaults.plugins as ReadonlyArray<string>).includes(p.value))\n const pluginLabel = (plugins: Array<PluginOption>) => styleText('cyan', plugins.map((p) => p.label).join(', '))\n\n const selectedPlugins: Array<PluginOption> = await (async () => {\n if (pluginsFlag) {\n const plugins = resolvePlugins(pluginsFlag)\n if (plugins.length === 0) {\n logWarn(`No valid plugins found in --plugins value; falling back to default: ${pluginLabel(defaultPlugins)}`)\n return defaultPlugins\n }\n logInfo(`Using plugins: ${pluginLabel(plugins)}`)\n return plugins\n }\n if (yes) {\n logInfo(`Using plugins: ${pluginLabel(defaultPlugins)}`)\n return defaultPlugins\n }\n const values = await clack.multiselect({\n message: 'Select plugins to use:',\n options: availablePlugins.map(({ value, label, hint }) => ({ value, label, hint })),\n initialValues: [...initDefaults.plugins],\n required: true,\n })\n if (clack.isCancel(values)) cancelAndExit()\n return availablePlugins.filter((p) => (values as Array<string>).includes(p.value))\n })()\n\n // Install packages, matching the release of the running CLI\n const packagesToInstall = resolveInstallVersions({ packages: [KUBB_PACKAGE_NAME, ...selectedPlugins.map((p) => p.packageName)], version })\n\n const spinner = createSpinner()\n spinner.start(`Installing ${packagesToInstall.length} packages with ${packageManager.name}`)\n\n try {\n await dryRun.run(() => installPackages(packagesToInstall, packageManager, cwd), {\n message: `install ${packagesToInstall.length} packages with ${packageManager.name}`,\n })\n spinner.stop(`Installed ${packagesToInstall.length} packages`)\n } catch (error) {\n spinner.stop('Installation failed')\n throw error\n }\n\n // Generate config file\n const configSpinner = createSpinner()\n configSpinner.start(`Creating ${KUBB_CONFIG_FILENAME}`)\n\n const configContent = generateConfigFile({ selectedPlugins, inputPath, outputPath })\n const configPath = path.join(cwd, KUBB_CONFIG_FILENAME)\n\n if (fs.existsSync(configPath)) {\n configSpinner.stop(`${KUBB_CONFIG_FILENAME} already exists`)\n\n if (!yes) {\n const shouldOverwrite = await clack.confirm({\n message: `${KUBB_CONFIG_FILENAME} already exists. Overwrite?`,\n initialValue: false,\n })\n\n if (clack.isCancel(shouldOverwrite) || !shouldOverwrite) {\n cancelAndExit('Keeping existing configuration. Packages have been installed.')\n }\n }\n\n configSpinner.start(`Overwriting ${KUBB_CONFIG_FILENAME}`)\n }\n\n await dryRun.run(() => fs.promises.writeFile(configPath, configContent, 'utf-8'), { message: `write ${KUBB_CONFIG_FILENAME}` })\n\n configSpinner.stop(`Created ${KUBB_CONFIG_FILENAME}`)\n\n logOutro(\n styleText('green', '✓ All set!') +\n '\\n\\n' +\n styleText('dim', 'Next steps:') +\n '\\n' +\n styleText('cyan', ` 1. Make sure your OpenAPI spec is at: ${inputPath}`) +\n '\\n' +\n styleText('cyan', ' 2. Generate code with: npx kubb generate') +\n '\\n' +\n styleText('cyan', ` 3. Find generated files in: ${outputPath}`) +\n '\\n\\n' +\n styleText('dim', `Using ${packageManager.name} • Kubb v${version}`),\n )\n } catch (error) {\n logError(styleText('red', 'An error occurred during initialization'))\n if (error instanceof Error) {\n logError(error.message)\n }\n process.exit(1)\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;AAQA,SAAgB,eAAe,aAAsD;CACnF,IAAI,CAAC,aACH,OAAO,CAAC;CAEV,MAAM,YAAY,YACf,MAAM,GAAG,CAAC,CACV,KAAK,UAAU,MAAM,KAAK,CAAC,CAAC,CAC5B,OAAO,OAAO;CACjB,OAAO,iBAAiB,QAAQ,WAAW,UAAU,SAAS,OAAO,KAAK,CAAC;AAC7E;AAEA,SAAgB,mBAAmB,EACjC,iBACA,WACA,cAKS;CAKT,OAAO;EAJS,gBAAgB,KAAK,WAAW,YAAY,OAAO,WAAW,WAAW,OAAO,YAAY,EAAE,CAAC,CAAC,KAAK,IAK/G,EAAE;;;YAGE,UAAU;;aAET,WAAW;;;;EARA,gBAAgB,KAAK,WAAW,OAAO,OAAO,WAAW,IAAI,CAAC,CAAC,KAAK,IAY9E,EAAE;;;;AAIhB;;;;;;;;;AAUA,SAAgB,uBAAuB,EAAE,UAAU,WAAwE;CAEzH,MAAM,MADa,QAAQ,MAAM,WAAW,CAAC,GAAG,MACtB;CAE1B,OAAO,SAAS,KAAK,SAAU,SAAA,SAA6B,GAAG,KAAK,GAAG,YAAY,GAAG,KAAK,GAAG,KAAM;AACtG;;;;;;;;;;;;ACZA,MAAM,kBAAkE;CACtE,MAAM;EACJ,MAAM;EACN,UAAU;EACV,gBAAgB,CAAC,OAAO,IAAI;CAC9B;CACA,MAAM;EACJ,MAAM;EACN,UAAU;EACV,gBAAgB,CAAC,OAAO,IAAI;CAC9B;CACA,KAAK;EACH,MAAM;EACN,UAAU;EACV,g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AACF"}
|
|
1
|
+
{"version":3,"file":"run-kdxqOL8u.js","names":["process","process"],"sources":["../../../internals/shared/src/init.ts","../src/tools.ts","../src/runners/init/utils.ts","../src/runners/init/run.ts"],"sourcesContent":["import { availablePlugins, KUBB_PACKAGE_NAME } from './constants.ts'\nimport type { PluginOption } from './types.ts'\n\n/**\n * Resolves a comma-separated plugin flag (e.g. `--plugins plugin-ts,plugin-zod`) into the\n * matching known plugin options. Unrecognized names are dropped, and a missing flag yields\n * an empty list.\n */\nexport function resolvePlugins(pluginsFlag: string | undefined): Array<PluginOption> {\n if (!pluginsFlag) {\n return []\n }\n const requested = pluginsFlag\n .split(',')\n .map((value) => value.trim())\n .filter(Boolean)\n return availablePlugins.filter((plugin) => requested.includes(plugin.value))\n}\n\nexport function generateConfigFile({\n selectedPlugins,\n inputPath,\n outputPath,\n}: {\n selectedPlugins: Array<PluginOption>\n inputPath: string\n outputPath: string\n}): string {\n const imports = selectedPlugins.map((plugin) => `import { ${plugin.importName} } from '${plugin.packageName}'`).join('\\n')\n\n const pluginConfigs = selectedPlugins.map((plugin) => ` ${plugin.importName}(),`).join('\\n')\n\n return `import { defineConfig } from 'kubb/config'\n${imports}\n\nexport default defineConfig({\n input: '${inputPath}',\n output: {\n path: '${outputPath}',\n clean: true,\n },\n plugins: [\n${pluginConfigs}\n ],\n})\n`\n}\n\n/**\n * Turns package names into install specifiers for the wizard.\n *\n * `kubb` is pinned to the exact version of the running CLI, since both ship from the same release\n * and resolving `kubb@beta` separately can land on a different version than the CLI doing the\n * scaffolding. Plugins release from their own repo on their own cadence, so they follow the\n * release channel of the CLI through its dist-tag.\n */\nexport function resolveInstallVersions({ packages, version }: { packages: Array<string>; version: string }): Array<string> {\n const prerelease = version.match(/-([a-z]+)/)?.[1]\n const tag = prerelease ?? 'latest'\n\n return packages.map((name) => (name === KUBB_PACKAGE_NAME ? `${name}@${version}` : `${name}@${tag}`))\n}\n","import { existsSync, readFileSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { formatters, linters } from '@internals/utils'\nimport type { Config } from '@kubb/core'\n\n/**\n * The configurable formatter names, mirrored from `Config['output'].format`. Excludes `'auto'`\n * (detection, not a tool) and `false` (skip). The `formatters`/`linters` tables below are pinned to\n * these so adding a tool to the config union without a descriptor fails to compile.\n */\ntype FormatterName = Exclude<NonNullable<Config['output']['format']>, 'auto' | false>\ntype LinterName = Exclude<NonNullable<Config['output']['lint']>, 'auto' | false>\n\n// Pinned to core's union here rather than in `@internals/utils`, which must not import `@kubb/core`:\n// adding a tool to the config union without a descriptor stays a compile error.\nformatters satisfies Record<FormatterName, unknown>\nlinters satisfies Record<LinterName, unknown>\n\nexport { detectTool, formatters, linters } from '@internals/utils'\n\nexport type PackageManagerName = 'npm' | 'pnpm' | 'yarn' | 'bun'\n\n/**\n * Metadata describing a package manager's lock file and install command.\n */\nexport interface PackageManagerInfo {\n /**\n * Identifier used in CLI commands, e.g. `pnpm`, `yarn`.\n */\n name: PackageManagerName\n /**\n * Lock file name that uniquely identifies this package manager in a project root.\n */\n lockFile: string\n /**\n * Subcommands passed to the package manager binary to install a dev dependency.\n */\n installCommand: ReadonlyArray<string>\n}\n\n/**\n * Metadata for each supported package manager, keyed by its short name.\n *\n * @example\n * ```ts\n * packageManagers.pnpm.installCommand // ['add', '-D']\n * packageManagers.npm.lockFile // 'package-lock.json'\n * ```\n */\nconst packageManagers: Record<PackageManagerName, PackageManagerInfo> = {\n pnpm: {\n name: 'pnpm',\n lockFile: 'pnpm-lock.yaml',\n installCommand: ['add', '-D'],\n },\n yarn: {\n name: 'yarn',\n lockFile: 'yarn.lock',\n installCommand: ['add', '-D'],\n },\n bun: {\n name: 'bun',\n lockFile: 'bun.lockb',\n installCommand: ['add', '-d'],\n },\n npm: {\n name: 'npm',\n lockFile: 'package-lock.json',\n installCommand: ['install', '--save-dev'],\n },\n}\n\n/**\n * Minimal shape of `package.json` fields read during detection.\n */\ntype PackageJson = {\n /**\n * The `packageManager` field from `package.json` (e.g. `\"pnpm@9.0.0\"`).\n */\n packageManager?: string\n}\n\n/**\n * Detects the active package manager for the given directory.\n * Resolution order: `packageManager` field in `package.json`, then presence of a lock file.\n * Falls back to `npm` when no signal is found.\n *\n * @example\n * ```ts\n * detectPackageManager('/my/project') // { name: 'pnpm', lockFile: 'pnpm-lock.yaml', ... }\n * detectPackageManager() // falls back to npm when no lock file is found\n * ```\n */\nexport function detectPackageManager(cwd: string = process.cwd()): PackageManagerInfo {\n const packageJsonPath = join(cwd, 'package.json')\n if (existsSync(packageJsonPath)) {\n try {\n const packageJson = JSON.parse(readFileSync(packageJsonPath, 'utf-8')) as PackageJson\n const pmField = packageJson.packageManager\n if (typeof pmField === 'string') {\n const name = pmField.split('@')[0]\n if (name && name in packageManagers) {\n return packageManagers[name as PackageManagerName]\n }\n }\n } catch {\n // Continue to lock file detection\n }\n }\n\n for (const pm of Object.values(packageManagers)) {\n if (existsSync(join(cwd, pm.lockFile))) {\n return pm\n }\n }\n\n return packageManagers.npm\n}\n","import fs from 'node:fs'\nimport path from 'node:path'\nimport process from 'node:process'\nimport { x } from 'tinyexec'\nimport type { PackageManagerInfo, PackageManagerName } from '../../tools.ts'\n\n/**\n * Returns `true` when a `package.json` exists at `cwd`.\n */\nexport function hasPackageJson(cwd: string = process.cwd()): boolean {\n return fs.existsSync(path.join(cwd, 'package.json'))\n}\n\n/**\n * Initializes a new `package.json` at `cwd` using the detected package manager.\n */\nexport async function initPackageJson(cwd: string, packageManager: PackageManagerInfo): Promise<void> {\n const commands: Record<PackageManagerName, Array<string>> = {\n npm: ['init', '-y'],\n pnpm: ['init'],\n yarn: ['init', '-y'],\n bun: ['init', '-y'],\n }\n\n await x(packageManager.name, commands[packageManager.name], {\n nodeOptions: { cwd, stdio: 'inherit' },\n throwOnError: true,\n })\n}\n\n/**\n * Installs the given packages at `cwd` using the detected package manager.\n */\nexport async function installPackages(packages: Array<string>, packageManager: PackageManagerInfo, cwd: string = process.cwd()): Promise<void> {\n await x(packageManager.name, [...packageManager.installCommand, ...packages], {\n nodeOptions: { cwd, stdio: 'inherit' },\n throwOnError: true,\n })\n}\n","import fs from 'node:fs'\nimport path from 'node:path'\nimport process from 'node:process'\nimport { styleText } from 'node:util'\nimport * as clack from '@clack/prompts'\nimport type { DryRunExtension } from '@gunshi/plugin-dryrun'\nimport {\n availablePlugins,\n generateConfigFile,\n initDefaults,\n KUBB_CONFIG_FILENAME,\n KUBB_PACKAGE_NAME,\n type PluginOption,\n resolveInstallVersions,\n resolvePlugins,\n} from '@internals/shared'\nimport { createSpinner, logError, logInfo, logIntro, logOutro, logWarn } from '../../loggers/output.ts'\nimport { hasPackageJson, initPackageJson, installPackages } from './utils.ts'\nimport { detectPackageManager } from '../../tools.ts'\n\nfunction cancelAndExit(message = 'Operation canceled.'): never {\n clack.cancel(message)\n process.exit(0)\n}\n\ntype InitOptions = {\n /**\n * When `true`, skips all interactive prompts and uses default values.\n */\n yes: boolean\n /**\n * Current `@kubb/cli` version string, shown in the closing outro.\n */\n version: string\n /**\n * Input path flag value from `--input`. When provided, skips the input prompt.\n */\n input?: string\n /**\n * Output directory flag value from `--output`. When provided, skips the output prompt.\n */\n output?: string\n /**\n * Comma-separated plugin list from `--plugins`, e.g. `'plugin-ts,plugin-zod'`. When provided, skips the plugin selection prompt.\n */\n plugins?: string\n /**\n * Dry-run extension from `@gunshi/plugin-dryrun`. When enabled, package installation and the\n * config file write are skipped.\n */\n dryRun: DryRunExtension\n}\n\n/**\n * Runs the interactive Kubb scaffolding wizard.\n * Detects the package manager, prompts for input/output paths and plugins, installs packages, and writes `kubb.config.ts`.\n * Pass `yes: true` to skip all prompts and use defaults.\n */\nexport async function run({ yes, version, input: inputFlag, output: outputFlag, plugins: pluginsFlag, dryRun }: InitOptions): Promise<void> {\n const cwd = process.cwd()\n\n logIntro({ title: styleText('bgCyan', styleText('black', ' Kubb Init ')) })\n\n /**\n * Returns `flag` when provided, the `defaultValue` when `yes` is set,\n * or calls `prompt()` for interactive input. Exits on cancellation.\n */\n async function resolveOrPrompt<T>(flag: T | undefined, defaultValue: T, logLabel: string, prompt: () => Promise<NoInfer<T> | symbol>): Promise<T> {\n if (flag !== undefined) {\n logInfo(`${logLabel}: ${styleText('cyan', String(flag))}`)\n return flag\n }\n if (yes) {\n logInfo(`${logLabel}: ${styleText('cyan', String(defaultValue))}`)\n return defaultValue\n }\n const result = await prompt()\n if (clack.isCancel(result)) cancelAndExit()\n return result as T\n }\n\n try {\n // Check/create package.json, detect package manager once after the block\n if (!hasPackageJson(cwd)) {\n if (!yes) {\n const shouldInit = await clack.confirm({\n message: 'No package.json found. Would you like to create one?',\n initialValue: true,\n })\n\n if (clack.isCancel(shouldInit) || !shouldInit) {\n cancelAndExit()\n }\n }\n\n const packageManager = detectPackageManager(cwd)\n const spinner = createSpinner()\n spinner.start(`Initializing package.json with ${packageManager.name}`)\n await initPackageJson(cwd, packageManager)\n spinner.stop(`Created package.json with ${packageManager.name}`)\n }\n\n const packageManager = detectPackageManager(cwd)\n if (hasPackageJson(cwd)) {\n logInfo(`Detected package manager: ${styleText('cyan', packageManager.name)}`)\n }\n\n // Prompt for OpenAPI spec path\n const inputPath = await resolveOrPrompt(inputFlag, initDefaults.inputPath, 'Using input path', () =>\n clack.text({\n message: 'Where is your OpenAPI specification located?',\n placeholder: initDefaults.inputPath,\n defaultValue: initDefaults.inputPath,\n validate: (value) => {\n if (!value) return 'Input path is required'\n },\n }),\n )\n\n // Prompt for output directory\n const outputPath = await resolveOrPrompt(outputFlag, initDefaults.outputPath, 'Using output path', () =>\n clack.text({\n message: 'Where should the generated files be output?',\n placeholder: initDefaults.outputPath,\n defaultValue: initDefaults.outputPath,\n validate: (value) => {\n if (!value) return 'Output path is required'\n },\n }),\n )\n\n // Plugin selection\n const defaultPlugins = availablePlugins.filter((p) => (initDefaults.plugins as ReadonlyArray<string>).includes(p.value))\n const pluginLabel = (plugins: Array<PluginOption>) => styleText('cyan', plugins.map((p) => p.label).join(', '))\n\n const selectedPlugins: Array<PluginOption> = await (async () => {\n if (pluginsFlag) {\n const plugins = resolvePlugins(pluginsFlag)\n if (plugins.length === 0) {\n logWarn(`No valid plugins found in --plugins value; falling back to default: ${pluginLabel(defaultPlugins)}`)\n return defaultPlugins\n }\n logInfo(`Using plugins: ${pluginLabel(plugins)}`)\n return plugins\n }\n if (yes) {\n logInfo(`Using plugins: ${pluginLabel(defaultPlugins)}`)\n return defaultPlugins\n }\n const values = await clack.multiselect({\n message: 'Select plugins to use:',\n options: availablePlugins.map(({ value, label, hint }) => ({ value, label, hint })),\n initialValues: [...initDefaults.plugins],\n required: true,\n })\n if (clack.isCancel(values)) cancelAndExit()\n return availablePlugins.filter((p) => (values as Array<string>).includes(p.value))\n })()\n\n // Install packages, matching the release of the running CLI\n const packagesToInstall = resolveInstallVersions({ packages: [KUBB_PACKAGE_NAME, ...selectedPlugins.map((p) => p.packageName)], version })\n\n const spinner = createSpinner()\n spinner.start(`Installing ${packagesToInstall.length} packages with ${packageManager.name}`)\n\n try {\n await dryRun.run(() => installPackages(packagesToInstall, packageManager, cwd), {\n message: `install ${packagesToInstall.length} packages with ${packageManager.name}`,\n })\n spinner.stop(`Installed ${packagesToInstall.length} packages`)\n } catch (error) {\n spinner.stop('Installation failed')\n throw error\n }\n\n // Generate config file\n const configSpinner = createSpinner()\n configSpinner.start(`Creating ${KUBB_CONFIG_FILENAME}`)\n\n const configContent = generateConfigFile({ selectedPlugins, inputPath, outputPath })\n const configPath = path.join(cwd, KUBB_CONFIG_FILENAME)\n\n if (fs.existsSync(configPath)) {\n configSpinner.stop(`${KUBB_CONFIG_FILENAME} already exists`)\n\n if (!yes) {\n const shouldOverwrite = await clack.confirm({\n message: `${KUBB_CONFIG_FILENAME} already exists. Overwrite?`,\n initialValue: false,\n })\n\n if (clack.isCancel(shouldOverwrite) || !shouldOverwrite) {\n cancelAndExit('Keeping existing configuration. Packages have been installed.')\n }\n }\n\n configSpinner.start(`Overwriting ${KUBB_CONFIG_FILENAME}`)\n }\n\n await dryRun.run(() => fs.promises.writeFile(configPath, configContent, 'utf-8'), { message: `write ${KUBB_CONFIG_FILENAME}` })\n\n configSpinner.stop(`Created ${KUBB_CONFIG_FILENAME}`)\n\n logOutro(\n styleText('green', '✓ All set!') +\n '\\n\\n' +\n styleText('dim', 'Next steps:') +\n '\\n' +\n styleText('cyan', ` 1. Make sure your OpenAPI spec is at: ${inputPath}`) +\n '\\n' +\n styleText('cyan', ' 2. Generate code with: npx kubb generate') +\n '\\n' +\n styleText('cyan', ` 3. Find generated files in: ${outputPath}`) +\n '\\n\\n' +\n styleText('dim', `Using ${packageManager.name} • Kubb v${version}`),\n )\n } catch (error) {\n logError(styleText('red', 'An error occurred during initialization'))\n if (error instanceof Error) {\n logError(error.message)\n }\n process.exit(1)\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;AAQA,SAAgB,eAAe,aAAsD;CACnF,IAAI,CAAC,aACH,OAAO,CAAC;CAEV,MAAM,YAAY,YACf,MAAM,GAAG,CAAC,CACV,KAAK,UAAU,MAAM,KAAK,CAAC,CAAC,CAC5B,OAAO,OAAO;CACjB,OAAO,iBAAiB,QAAQ,WAAW,UAAU,SAAS,OAAO,KAAK,CAAC;AAC7E;AAEA,SAAgB,mBAAmB,EACjC,iBACA,WACA,cAKS;CAKT,OAAO;EAJS,gBAAgB,KAAK,WAAW,YAAY,OAAO,WAAW,WAAW,OAAO,YAAY,EAAE,CAAC,CAAC,KAAK,IAK/G,EAAE;;;YAGE,UAAU;;aAET,WAAW;;;;EARA,gBAAgB,KAAK,WAAW,OAAO,OAAO,WAAW,IAAI,CAAC,CAAC,KAAK,IAY9E,EAAE;;;;AAIhB;;;;;;;;;AAUA,SAAgB,uBAAuB,EAAE,UAAU,WAAwE;CAEzH,MAAM,MADa,QAAQ,MAAM,WAAW,CAAC,GAAG,MACtB;CAE1B,OAAO,SAAS,KAAK,SAAU,SAAA,SAA6B,GAAG,KAAK,GAAG,YAAY,GAAG,KAAK,GAAG,KAAM;AACtG;;;;;;;;;;;;ACZA,M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C,YAAY,IAC/D,SACA,UAAU,OAAO,SAAS,eAAe,KAAK,WAAW,SAAS,CACtE;CACF,SAAS,OAAO;EACd,SAAS,UAAU,OAAO,yCAAyC,CAAC;EACpE,IAAI,iBAAiB,OACnB,SAAS,MAAM,OAAO;EAExB,UAAQ,KAAK,CAAC;CAChB;AACF"}
|
|
@@ -3,7 +3,7 @@ const require_errors = require("./errors-C-wEou02.cjs");
|
|
|
3
3
|
const require_agent = require("./agent-BPqs9VRj.cjs");
|
|
4
4
|
const require_Telemetry = require("./Telemetry-CvHQevSK.cjs");
|
|
5
5
|
const require_utils = require("./utils-CMU1rLfY.cjs");
|
|
6
|
-
const require_package = require("./package-
|
|
6
|
+
const require_package = require("./package-DF4lLkdS.cjs");
|
|
7
7
|
const require_output = require("./output-kmklyYIv.cjs");
|
|
8
8
|
const require_constants = require("./constants-CdxpgX3_.cjs");
|
|
9
9
|
let node_util = require("node:util");
|
|
@@ -303,7 +303,7 @@ async function snapshot(options) {
|
|
|
303
303
|
spinner?.message(message);
|
|
304
304
|
};
|
|
305
305
|
if (options.json) log("Creating Kubb Studio agent");
|
|
306
|
-
|
|
306
|
+
if (!options.json) spinner?.start("Creating Kubb Studio agent");
|
|
307
307
|
const agent = await (0, _kubb_studio.createAgent)({
|
|
308
308
|
studioUrl: options.studioUrl,
|
|
309
309
|
token,
|
|
@@ -361,12 +361,12 @@ async function snapshot(options) {
|
|
|
361
361
|
if (!finished.snapshot) throw new Error("Snapshot job succeeded without a snapshot");
|
|
362
362
|
const result = toResult(options.studioUrl, finished.snapshot, agent.slug);
|
|
363
363
|
if (options.json) log("Snapshot published");
|
|
364
|
-
|
|
364
|
+
if (!options.json) spinner?.stop("Snapshot published");
|
|
365
365
|
if (options.json) console.log(JSON.stringify(result));
|
|
366
|
-
|
|
366
|
+
if (!options.json) printSummary(result);
|
|
367
367
|
} catch (error) {
|
|
368
368
|
if (options.json) log("Snapshot failed");
|
|
369
|
-
|
|
369
|
+
if (!options.json) spinner?.stop("Snapshot failed");
|
|
370
370
|
throw error;
|
|
371
371
|
} finally {
|
|
372
372
|
if (options.json) log("Disconnecting from Kubb Studio");
|
|
@@ -778,4 +778,4 @@ const runner = async ({ values }) => {
|
|
|
778
778
|
//#endregion
|
|
779
779
|
exports.runner = runner;
|
|
780
780
|
|
|
781
|
-
//# sourceMappingURL=run-
|
|
781
|
+
//# sourceMappingURL=run-zEtX5h_L.cjs.map
|