import { relative, resolve } from 'node:path' import { getElapsedMs, isPathInside, toPosixPath } from '@internals/utils' import type { FileNode, InputNode } from '@kubb/ast' import { host } from './host.ts' import { type Diagnostic, Diagnostics } from './diagnostics.ts' import type { Storage } from './createStorage.ts' import { detectSharedSchemas, type SharedSchemas } from './detectSharedSchemas.ts' import { serializeConfig, hashInputs, type LockfileInputs } from './lockfileInputs.ts' import { Driver } from './driver.ts' import { createLockfile, type Lockfile } from './lockfile.ts' import { fsStorage } from './storages/fsStorage.ts' import type { BuildOutput, Config, KubbGenerationEndContext, KubbHooks, UserConfig } from './types.ts' import { Hookable } from './hookable.ts' import { runOutputPasses, type RunOutputPassesOptions } from './output/runOutputPasses.ts' function resolveConfig(userConfig: UserConfig): Config { return { ...userConfig, root: userConfig.root || host.cwd(), parsers: userConfig.parsers ?? [], output: { format: false, lint: false, defaultBanner: 'simple', ...userConfig.output, }, storage: userConfig.storage ?? fsStorage(), reporters: userConfig.reporters ?? [], plugins: userConfig.plugins ?? [], } } /** * Only the fs storage writes `output.path`, so only then do the passes have fresh files to run * over; a memory or custom storage would leave them formatting whatever an earlier run left there. */ function writesOutputDirectory(storage: Storage): boolean { return storage.name === 'fs' } // The output path sets unnamed configs apart. const lockfileKey = ({ name, root, output }: Pick): string => name ?? toPosixPath(relative(root, resolve(root, output.path))) // `null` when the adapter lists no files for a spec that is a file. function readSources({ adapter, input }: Pick): Array | null { if (!adapter) return [] if (!adapter.sources) return null if (!adapter.sources.length && typeof input === 'string') return null return adapter.sources } // `undefined` for a run without `kubb-lock.json`, or a storage that writes no output directory. async function openLockfile({ config, enabled = true }: { config: Config; enabled?: boolean }): Promise { if (!enabled || !writesOutputDirectory(config.storage)) return undefined return createLockfile({ storage: config.storage, root: config.root }) } async function satisfiesLockfile({ config, lockfile }: { config: Config; lockfile: Lockfile }): Promise { const recorded = lockfile.inputs(lockfileKey(config)) const configText = recorded && serializeConfig(config) if (!recorded || !configText) return false return (await hashInputs({ root: config.root, configText, sources: recorded.sources }))?.hash === recorded.hash } /** * Whether anything runs over the output directory after the files are written. Only then can the * bytes on disk stop matching what Kubb wrote, which is what the lockfile exists to track. */ export function hasOutputPasses({ output, storage }: Pick): boolean { return writesOutputDirectory(storage) && Boolean(output.format || output.lint || output.postGenerate?.length) } /** * Warns when output passes are configured but skipped because the storage does not write `output.path`. */ async function reportSkippedPasses({ config, hooks }: { config: Config; hooks: Hookable }): Promise> { const { format, lint, postGenerate } = config.output const skipped: Array = [] if (format) skipped.push('output.format') if (lint) skipped.push('output.lint') if (postGenerate?.length) skipped.push('output.postGenerate') const code = Diagnostics.code.outputPassesSkipped if (skipped.length === 0 || config.diagnostics?.ignore?.includes(code)) return [] const diagnostic: Diagnostic = { code, severity: 'warning', message: `Skipped ${skipped.join(', ')} because storage "${config.storage.name}" is not "fs".`, location: { kind: 'config' }, } await Diagnostics.emit(hooks, diagnostic) return [diagnostic] } export type KubbOptions = { /** * Receives Kubb lifecycle hooks for the run. */ hooks?: Hookable /** * Stops the build at the next safe checkpoint. */ signal?: AbortSignal /** * The only folders a `$ref` in the input may read local files from. Unset, a `$ref` reads any file. */ fileRefs?: Array } /** * @deprecated Use `KubbOptions` instead. */ export type CreateKubbOptions = KubbOptions export type GenerateConfigsOptions = Pick & GenerateOptions & { /** * Index of the one config to build. It is still compared with the others, but never empties the directory they share. */ only?: number } export type ConfigGenerateResult = GenerateResult & { kubb: Kubb /** * What the build threw outside its own diagnostics. `diagnostics` holds it too. */ error?: unknown } /** * Host hooks for a single {@link Kubb#generate} call. All optional. Progress narration rides the * `kubb:*` lifecycle hooks on `.hooks`, so hosts subscribe there rather than pass a callback. */ export type GenerateOptions = { /** * Replaces the output passes that run after an error-free build. The default, * {@link runOutputPasses}, formats, lints and runs `output.postGenerate` over the generated * output and returns the diagnostics they emitted. */ processOutput?: (context: RunOutputPassesOptions) => Promise> /** * Runs `output.format` and `output.lint` even when the build left every file as it was. */ force?: boolean /** * Set to `false` to generate without reading or writing `kubb-lock.json`. * * @default true */ lockfile?: boolean } /** * What a {@link Kubb#generate} call produced, for the host to map onto its own result shape. */ export type GenerateResult = { /** * `true` when the build and every output pass completed without an error-level diagnostic. */ success: boolean /** * All files generated during the build. */ files: Array /** * Build diagnostics plus any collected from the output passes. */ diagnostics: Array /** * The parsed spec the build generated from, `null` when the build failed before parsing. */ input: InputNode | null } /** * Kubb code-generation instance bound to a single config entry. Resolves the user * config in the constructor, so `config` is available right away, and shares `hooks`, * `storage`, and `driver` across the `setup → build` lifecycle. * * `createKubb` takes a plain config object (the shape `defineConfig` produces), * not a fluent builder. * * Attach hook listeners to `.hooks` before calling `setup()` or `build()`. * * @example * ```ts * const kubb = createKubb(userConfig) * kubb.hooks.hook('kubb:plugin:end', ({ plugin, duration }) => console.log(plugin.name, duration)) * const { files, diagnostics } = await kubb.safeBuild() * ``` */ export class Kubb { readonly hooks: Hookable readonly config: Config #driver: Driver | null = null #lockfile: Lockfile | null = null #cleanPaths: Array = [] readonly #signal: AbortSignal | undefined #sharedSchemas: SharedSchemas | undefined readonly #fileRefs: Array | undefined constructor(userConfig: UserConfig, options: KubbOptions = {}) { this.config = resolveConfig(userConfig) this.hooks = options.hooks ?? new Hookable() this.#signal = options.signal this.#fileRefs = options.fileRefs } /** * Whether a build of `userConfig` would leave the output as it is: its inputs match what * `kubb-lock.json` recorded, and every generated file still holds its recorded output. `false` * whenever that cannot be told, such as for a URL input. * * @example * ```ts * if (!(await Kubb.isUpToDate(config))) await createKubb(config).generate() * ``` */ static async isUpToDate(userConfig: UserConfig): Promise { const config = resolveConfig(userConfig) // `postGenerate` commands can do anything, so a run that skips them is not the same run. if (!writesOutputDirectory(config.storage) || config.output.postGenerate?.length) return false const lockfile = await createLockfile({ storage: config.storage, root: config.root }) if (!(await satisfiesLockfile({ config, lockfile }))) return false return lockfile.verify({ cleanDir: config.output.clean ? resolve(config.root, config.output.path) : undefined }) } /** * Generates every config of a `defineConfig([...])` array in order and yields each result as its config finishes, so * memory holds one config at a time. A config that fails does not stop the others. Only an aborted `signal` rejects. */ static async *generate( configs: Array, { hooks = new Hookable(), signal, fileRefs, only, processOutput, force, lockfile }: GenerateConfigsOptions = {}, ): AsyncGenerator { const sharedByConfig = await detectSharedSchemas({ configs, hooks, fileRefs }) for (const index of only === undefined ? configs.keys() : [only]) { const kubb = new Kubb(configs[index]!, { hooks, signal, fileRefs }) const detected = sharedByConfig[index] // A config built on its own must not empty the directory the others share. kubb.#sharedSchemas = only === undefined ? detected : detected && { ...detected, clean: false } try { yield { ...(await kubb.generate({ processOutput, force, lockfile })), kubb } } catch (error) { if (signal?.aborted) throw error yield { success: false, files: [], diagnostics: [Diagnostics.from(error)], input: null, kubb, error } } } } get storage(): Storage { return this.config.storage } get driver(): Driver { if (!this.#driver) throw new Diagnostics.Error({ code: Diagnostics.code.internalError, severity: 'error', message: '[kubb] setup() must be called before accessing driver' }) return this.#driver } /** * Initializes the driver and storage. `build()` calls this automatically. `lockfile: false` leaves `kubb-lock.json` unread. */ async setup({ lockfile: usesLockfile }: Pick = {}): Promise { const signal = this.#signal signal?.throwIfAborted() // A second setup replaces the driver, so the old one's plugin listeners must go first. this.dispose() const config = this.config const lockfile = await openLockfile({ config, enabled: usesLockfile }) const dirsToClean: Array<[option: string, dir: string]> = [] if (config.output.clean) dirsToClean.push(['output.path', resolve(config.root, config.output.path)]) if (config.shared && this.#sharedSchemas?.clean) dirsToClean.push(['shared.path', resolve(config.root, config.shared.path)]) // clean only removes generated code. Refuse when the output resolves to the project root or // an ancestor of it, otherwise the wipe would delete kubb.config and every source file. for (const [option, dir] of dirsToClean) { if (!isPathInside(config.root, dir)) continue throw new Diagnostics.Error({ code: Diagnostics.code.cleanRoot, severity: 'error', message: `output.clean cannot delete "${dir}" because it is the project root or a parent of it.`, help: `Point \`${option}\` at a subdirectory such as \`./src/gen\` so clean only removes generated code.`, location: { kind: 'config' }, }) } // The driver empties `cleanPaths` after the plugins run, right before it writes. A parse or plugin setup // failure leaves the previous output in place; a plugin error while generating still empties and writes. const driver = new Driver(config, { hooks: this.hooks, lockfile, signal, cleanPaths: dirsToClean.map(([, dir]) => dir), sharedSchemas: this.#sharedSchemas, fileRefs: this.#fileRefs, }) await driver.setup() this.#driver = driver this.#lockfile = lockfile ?? null this.#cleanPaths = dirsToClean.map(([, dir]) => dir) } /** * Runs the full pipeline and throws on any plugin error. * Automatically calls `setup()` if needed. */ async build(): Promise { const out = await this.safeBuild() if (Diagnostics.hasError(out.diagnostics)) { const errors = out.diagnostics .filter(Diagnostics.isProblem) .filter((diagnostic) => diagnostic.severity === 'error') .map((diagnostic) => diagnostic.cause ?? new Diagnostics.Error(diagnostic)) throw new AggregateError(errors, `Build failed with ${errors.length} ${errors.length === 1 ? 'error' : 'errors'}`) } return out } /** * Runs the full pipeline and captures errors in `BuildOutput` instead of throwing. * Automatically calls `setup()` if needed. This is the canonical call: it never throws on * plugin errors, so callers stay in control of how failures surface. */ async safeBuild(): Promise { this.#signal?.throwIfAborted() if (!this.#driver) await this.setup() using self = this const driver = self.driver const storage = self.storage const { diagnostics } = await driver.run() return { diagnostics, files: driver.fileManager.files, driver, storage, input: driver.inputNode } } /** * Run one build and its output passes end to end, emitting the surrounding `kubb:generation:*` * hooks. Never throws on a build error: the outcome comes back in {@link GenerateResult} so the * host decides how failures surface. Telemetry and progress narration stay with the host, which * reads the result and subscribes to the `kubb:*` hooks. * * @example * ```ts * const result = await createKubb(config, { hooks }).generate() * if (!result.success) process.exitCode = 1 * ``` */ async generate(options: GenerateOptions = {}): Promise { const signal = this.#signal signal?.throwIfAborted() const { hooks, config } = this const hrStart = process.hrtime() await hooks.callHook('kubb:generation:start', { config }) const startedAt = Date.now() // Serialized before the build, so the text equals what `isUpToDate` serializes on the next run. const configText = serializeConfig(config) // A setup failure, such as an invalid plugin entry, becomes a diagnostic like any build // problem, so reporters still get a failed `kubb:generation:end` for this config. let output: Pick try { await hooks.callHook('kubb:setup:start') await this.setup({ lockfile: options.lockfile }) await hooks.callHook('kubb:setup:end') output = await this.safeBuild() } catch (caughtError) { if (signal?.aborted) throw caughtError output = { files: [], diagnostics: [Diagnostics.from(caughtError)], input: null } } const { files, diagnostics, input } = output const storage = this.storage signal?.throwIfAborted() // Surface every problem on the hooks. `performance` diagnostics feed the summary, not the // log, so they are skipped. for (const diagnostic of diagnostics) { if (Diagnostics.isProblem(diagnostic)) await Diagnostics.emit(hooks, diagnostic) } if (Diagnostics.hasError(diagnostics)) { await this.#end({ config, storage, diagnostics, filesCreated: files.length, status: 'failed', hrStart }) return { success: false, files, diagnostics, input } } const processOutput = options.processOutput ?? runOutputPasses const inputs = await this.#hashInputs({ configText, since: startedAt }) const passesConfig = this.#passesConfig({ inputs, force: options.force }) const outputDiagnostics = writesOutputDirectory(config.storage) ? await processOutput({ config: passesConfig, outputPath: resolve(config.root, config.output.path), hooks, signal }) : await reportSkippedPasses({ config, hooks }) const finalDiagnostics = [...diagnostics, ...outputDiagnostics] const failed = Diagnostics.hasError(outputDiagnostics) // The formatter and linter have had their turn, so what sits on disk now is what the next run // has to recognize as unchanged. Only record it when they finished: a pass that failed halfway // leaves files Kubb has to stay free to regenerate. if (!failed) await this.#lockfile?.write({ name: lockfileKey(config), inputs, cleaned: this.#cleanPaths }) await this.#end({ config, storage, diagnostics: finalDiagnostics, filesCreated: files.length, status: failed ? 'failed' : 'success', hrStart, }) return { success: !failed, files, diagnostics: finalDiagnostics, input } } // `null` without a lockfile to record the inputs in, or when they cannot be compared. async #hashInputs({ configText, since }: { configText: string | null; since: number }): Promise { const { config } = this const sources = readSources(config) if (!this.#lockfile || !configText || !sources) return null return hashInputs({ root: config.root, configText, sources, since }) } // Drops the formatter and linter when the inputs and every file are unchanged. #passesConfig({ inputs, force }: { inputs: LockfileInputs | null; force?: boolean }): Config { const { config } = this const lockfile = this.#lockfile if (force || !inputs || !lockfile?.unchanged || inputs.hash !== lockfile.inputs(lockfileKey(config))?.hash) return config return { ...config, output: { ...config.output, format: false, lint: false } } } /** Ends a run: `kubb:generation:end`, then the totals on `kubb:generation:summary`. */ async #end(ctx: Required): Promise { await this.hooks.callHook('kubb:generation:end', ctx) await this.hooks.callHook('kubb:generation:summary', { duration: Math.round(getElapsedMs(ctx.hrStart)), fileCount: ctx.filesCreated, failedPlugins: Diagnostics.failedPlugins(ctx.diagnostics).length, status: ctx.status, }) } dispose(): void { this.#driver?.dispose() // The next build sets up a fresh driver: a released one has no spec and would build nothing. this.#driver = null } [Symbol.dispose](): void { this.dispose() } } /** * Constructs a {@link Kubb} build orchestrator from a user config. Equivalent * to `new Kubb(userConfig, options)` and the canonical public entry point. * * @example * ```ts * import { createKubb } from '@kubb/core' * import { adapterOas } from '@kubb/adapter-oas' * import { pluginTs } from '@kubb/plugin-ts' * * const kubb = createKubb({ * input: './petStore.yaml', * output: { path: './src/gen' }, * adapter: adapterOas(), * plugins: [pluginTs()], * }) * * await kubb.build() * ``` */ export function createKubb(userConfig: UserConfig, options: KubbOptions = {}): Kubb { return new Kubb(userConfig, options) }