import { resolve } from 'node:path' import { getElapsedMs, memo as storeMemo, toError } from '@internals/utils' import { ast, type FileNode, type InputMeta, type InputNode, type OperationNode, type SchemaNode } from '@kubb/ast' import { Diagnostics } from './diagnostics.ts' import type { Diagnostic, DiagnosticError, DiagnosticLocation, ProblemDiagnostic } from './diagnostics.ts' import type { PluginVisitContext } from './definePlugin.ts' import type { Parser } from './defineParser.ts' import type { KubbPluginSetupContext, Plugin, PluginName, ResolvePluginOptions, Group, NormalizedPlugin, Output, PluginType } from './definePlugin.ts' import { normalizeOutput } from './definePlugin.ts' import { checkCompatibility, checkDependencies, resolveMeta } from './defineExtension.ts' import { kubbContext, withContext } from './composables.ts' import { FileManager } from './fileManager.ts' import { createMemo, type Memo } from './memo.ts' import type { Lockfile } from './lockfile.ts' import type { SharedSchemas } from './detectSharedSchemas.ts' import { inputToAdapterSource, parseAdapterSource } from './input.ts' import type { Config, KubbHooks } from './types.ts' import type { Adapter, AdapterSource } from './createAdapter.ts' import type { Hookable } from './hookable.ts' export type DriverOptions = { hooks: Hookable signal?: AbortSignal fileRefs?: Array /** * Passed to `fileManager.write` so files the output passes already normalized are left alone. */ lockfile?: Lockfile /** * The directories `output.clean` empties: the output directory, and the shared one when this build cleans it. Emptied * right before the files are written, so a run that fails earlier leaves the previous output in place. */ cleanPaths?: Array /** * What `detectSharedSchemas` worked out for this config. */ sharedSchemas?: SharedSchemas } export type RequirePluginContext = { /** * Name of the plugin that declared the dependency, included in the error so users can * trace which plugin needs the missing one. */ requiredBy?: string } const VISIT_HOOKS = ['kubb:plugin:visit:start', 'kubb:plugin:visit:schema', 'kubb:plugin:visit:operation', 'kubb:plugin:visit:end'] as const function hasVisitHooks(plugin: NormalizedPlugin): boolean { return VISIT_HOOKS.some((name) => plugin.hooks?.[name]) } /** * The options bag a `NormalizedPlugin` starts with before a plugin refines it: a directory output * at the plugin root and empty filter lists. */ const defaultPluginOptions = (): NormalizedPlugin['options'] => ({ output: { path: '.', mode: 'directory' }, exclude: [], override: [] }) /** * Fills in the `output`, `exclude`, and `override` a `NormalizedPlugin` needs from a plugin's raw * options, running `output` through `normalizeOutput`. Idempotent, so the driver can apply it after * `setOptions` has already run without disturbing an already-normalized bag. */ function normalizePluginOptions(rawOptions: Plugin['options'], pluginName: string): NormalizedPlugin['options'] { const options: NormalizedPlugin['options'] = { ...defaultPluginOptions(), ...(rawOptions ?? {}) } const group = 'group' in options ? (options.group as Group | null | undefined) : undefined options.output = normalizeOutput({ output: options.output, group, pluginName }) // An override replaces `output` as a whole, so its `output` needs the same `mode` default. options.override = options.override?.map((entry) => { const { output } = entry.options as { output?: Output } if (!output) return entry const entryGroup = 'group' in entry.options ? (entry.options.group as Group | null | undefined) : group return { ...entry, options: { ...entry.options, output: normalizeOutput({ output, group: entryGroup, pluginName }) } } }) return options } /** * Throws `KUBB_INVALID_PLUGIN_OPTIONS` when a `plugins` entry is not a plugin object, such as a * factory passed without calling it. */ function assertPluginEntry(entry: unknown, index: number): asserts entry is Plugin { if (typeof entry === 'object' && entry !== null) return const name = typeof entry === 'function' ? entry.name || 'pluginName' : undefined throw new Diagnostics.Error({ code: Diagnostics.code.invalidPluginOptions, severity: 'error', message: name ? `plugins[${index}] is a function ("${name}"), not a plugin.` : `plugins[${index}] is ${entry === null ? 'null' : typeof entry}, not a plugin.`, help: name ? `Call it: ${name}()` : 'Pass the result of a plugin factory, for example `pluginTs()`, or remove the entry.', location: { kind: 'config' }, }) } type CrashSite = { label: string; location?: DiagnosticLocation } /** * Where a generator crashed: a label naming the node and, when the adapter set one, the node's * pointer into the input. */ function getCrashSite(node: SchemaNode | OperationNode): CrashSite { if (node.kind === ast.node.kinds.schema) { const label = node.name ? `schema "${node.name}"` : 'an inline schema' return { label, location: node.pointer ? { kind: 'schema', pointer: node.pointer } : undefined } } const label = node.method && node.path ? `operation "${node.operationId}" (${node.method.toUpperCase()} ${node.path})` : `operation "${node.operationId}"` return { label, location: node.pointer ? { kind: 'operation', pointer: node.pointer } : undefined } } export class Driver { readonly config: Config readonly options: DriverOptions /** * The `InputNode` produced by the adapter. Set after adapter setup. */ inputNode: InputNode | null = null adapter: Adapter | null = null /** * Raw adapter source so `adapter.parse()` can run lazily. * Intentionally outlives the build, cleared by `dispose()`. */ #adapterSource: AdapterSource | null = null /** * Central file store for all generated files. * Plugins should use `this.addFile()` / `this.upsertFile()` (via their context) to * add files. This property gives direct read/write access when needed. */ readonly fileManager = new FileManager() readonly plugins = new Map() readonly #memo = new Map() readonly memo: Memo = createMemo(this.#memo) readonly #contexts = new Map() /** * Removers for every listener the driver added (plugin, generator) so `dispose()` can detach * them in one pass. External `hooks.hook(...)` listeners are not tracked. */ readonly #unhooks: Array<() => void> = [] constructor(config: Config, options: DriverOptions) { this.config = config this.options = options this.adapter = config.adapter ?? null } get #shared(): { path: string; schemas: Array; written: Map } | undefined { const { root, shared } = this.config const { sharedSchemas } = this.options if (!shared || !sharedSchemas) return undefined return { path: resolve(root, shared.path), schemas: sharedSchemas.names, written: sharedSchemas.written } } /** * Checks the adapter's and parsers' `meta.compatibility`, then normalizes and checks every configured plugin, orders them, and registers their lifecycle handlers. * A plugin that another lists as a dependency runs first, then `enforce: 'pre'` before * `'post'`. When the config has an adapter, the adapter source is resolved from the input * so `run` can parse it later. */ async setup() { this.options.signal?.throwIfAborted() for (const extension of [this.config.adapter, ...this.config.parsers]) { if (extension?.meta) checkCompatibility(extension.meta) } // Plugins are keyed by name, so a second entry with the same name would silently replace the first. const names = new Set() const normalized = this.#sortPlugins( this.config.plugins.map((rawPlugin, index) => { assertPluginEntry(rawPlugin, index) if (rawPlugin.meta) checkCompatibility(rawPlugin.meta) const meta = resolveMeta(rawPlugin) if (names.has(meta.name)) { throw new Diagnostics.Error({ code: Diagnostics.code.invalidPluginOptions, severity: 'error', message: `Plugin "${meta.name}" appears twice in \`plugins\`.`, help: 'Remove the duplicate, or merge its options.', location: { kind: 'config' }, }) } names.add(meta.name) const normalizedPlugin: NormalizedPlugin = { name: meta.name, meta, dependencies: typeof rawPlugin.dependencies === 'function' ? rawPlugin.dependencies(rawPlugin.options ?? {}, { config: this.config }) : rawPlugin.dependencies, enforce: rawPlugin.enforce, hooks: rawPlugin.hooks, setup: rawPlugin.setup, // `rawPlugin.options` is the user-supplied shape. The normalized `output`/`exclude`/`override` // bag is filled in by the post-setup `normalizePluginOptions` pass, after `setOptions` runs. options: (rawPlugin.options ?? defaultPluginOptions()) as NormalizedPlugin['options'], } return normalizedPlugin }), ) const byName = new Map(normalized.map((plugin) => [plugin.name, plugin])) for (const plugin of normalized) { checkDependencies({ name: plugin.name, dependencies: plugin.dependencies, plugins: byName }) } // Resolved before any listener is added, so an invalid input cannot leave listeners on the shared hooks. if (this.config.adapter) { this.#adapterSource = inputToAdapterSource(this.config) } for (const plugin of normalized) { this.#registerPlugin(plugin) this.plugins.set(plugin.name, plugin) } } /** * Orders plugins so every dependency runs before its dependents (Kahn's algorithm), with * `enforce` (`'pre'` before normal before `'post'`) and declaration order as tiebreaks. * A pairwise `Array.sort` comparator cannot do this: dependency relations are not transitive * at the comparator level, so a chain where A depends on B and B depends on C could come out * wrong when A and C are never compared directly. Dependencies on plugins missing from the * config are ignored here and surface later through `requirePlugin`. */ #sortPlugins(plugins: Array): Array { const queue = [...plugins].sort((a, b) => ast.macro.compareOrder(a.enforce, b.enforce)) const names = new Set(queue.map((plugin) => plugin.name)) const blockedBy = new Map( queue.map((plugin) => { const dependencies = Array.isArray(plugin.dependencies) ? plugin.dependencies : Object.keys(plugin.dependencies ?? {}) return [plugin.name, new Set(dependencies.filter((name) => names.has(name) && name !== plugin.name))] }), ) // One plugin leaves `queue` per pass, so iterating once per plugin drains it. Each pass takes // the lowest-index plugin with no remaining blockers, preserving enforce and declaration order. const sorted: Array = [] for (const _ of plugins) { const index = queue.findIndex((plugin) => blockedBy.get(plugin.name)?.size === 0) if (index === -1) { throw new Diagnostics.Error({ code: Diagnostics.code.invalidPluginOptions, severity: 'error', message: `Plugin dependencies form a cycle: ${queue.map((plugin) => plugin.name).join(' → ')}.`, help: 'Remove one of the `dependencies` entries so the plugins can be ordered.', location: { kind: 'config' }, }) } const [plugin] = queue.splice(index, 1) if (!plugin) break sorted.push(plugin) for (const blockers of blockedBy.values()) blockers.delete(plugin.name) } return sorted } get hooks() { return this.options.hooks } /** * Parses the adapter source into `this.inputNode`. Idempotent, so repeated calls from * `run` do not re-parse. */ async #parseInput(): Promise { if (this.inputNode || !this.adapter || !this.#adapterSource) return this.options.signal?.throwIfAborted() this.inputNode = await parseAdapterSource({ adapter: this.adapter, source: this.#adapterSource, signal: this.options.signal, fileRefs: this.options.fileRefs, }) } /** * Registers a plugin's lifecycle hooks on the shared `Hookable` as pass-through listeners that * external tooling can observe via `hooks.hook(...)`. The returned remover is tracked for * `dispose`. `kubb:plugin:setup` is skipped here; `setupHooks` invokes it directly with a * plugin-scoped context. * * Each listener runs through `withContext`: an event fired inside a hook keeps that hook's context, * an event the driver fires gets the plugin's own visit context. A listener that throws is * attributed to its plugin, so the run counts it as that plugin's failure. * * @internal */ #registerPlugin(plugin: NormalizedPlugin): void { const { hooks } = plugin if (!hooks) return const { 'kubb:plugin:setup': _setup, 'kubb:plugin:visit:start': _start, 'kubb:plugin:visit:schema': _schema, 'kubb:plugin:visit:operation': _operation, 'kubb:plugin:visit:end': _end, ...configHooks } = hooks const ctx = this.getContext(plugin) const attribute = (error: unknown): never => { throw new Diagnostics.Error(Diagnostics.fromExtension(error, { kind: 'plugin', extension: plugin })) } const wrapped = Object.fromEntries( Object.entries(configHooks).map(([name, hook]) => [ name, hook && ((...args: Array) => { const current = kubbContext.getStore() ?? ctx try { const result = withContext(current, () => (hook as (...args: Array) => unknown).apply(current, args)) return result instanceof Promise ? result.catch(attribute) : result } catch (error) { return attribute(error) } }), ]), ) as typeof configHooks this.#unhooks.push(this.hooks.addHooks(wrapped)) } /** * Runs each plugin's `setup` and `kubb:plugin:setup` handler, in plugin order, with a context scoped to that * plugin so `setOptions` targets its `NormalizedPlugin` entry. Called once from `run` before the plugin execution loop begins, so * plugins can configure their options before `buildStart`. */ async setupHooks(): Promise { for (const plugin of this.plugins.values()) { const setupHook = plugin.hooks?.['kubb:plugin:setup'] if (!plugin.setup && !setupHook) continue const ctx: KubbPluginSetupContext = { config: this.config, plugin: { name: plugin.name, meta: plugin.meta }, options: plugin.options ?? {}, setOptions: (opts) => { plugin.options = normalizePluginOptions({ ...plugin.options, ...opts }, plugin.name) }, injectFile: (userFileNode) => { this.fileManager.add(ast.factory.createFile(userFileNode)) }, requirePlugin: ((name: string) => this.requirePlugin(name, { requiredBy: plugin.name })) as KubbPluginSetupContext['requirePlugin'], memo: this.memo, } try { // `this`, `ctx` and composables such as `setOptions()` read the same context, also after an `await` in setup. await withContext(ctx, async () => { if (plugin.setup) { plugin.options = normalizePluginOptions(await plugin.setup.call(ctx, ctx.options, ctx), plugin.name) } await setupHook?.call(ctx, ctx) }) } catch (caughtError) { // Attributed to the plugin, so the run summary counts it as a failed plugin. throw new Diagnostics.Error(Diagnostics.fromExtension(caughtError, { kind: 'plugin', extension: plugin })) } } } /** * Runs the full plugin pipeline. Returns the diagnostics collected so far even * when an outer hook throws, since the orchestrator preserves partial state by capturing * the failure as a {@link Diagnostic} instead of propagating. Each plugin also * contributes a `timing` diagnostic for the run summary. */ async run(): Promise<{ diagnostics: Array }> { const { hooks, config, fileManager } = this const diagnostics: Array = [] const parsersMap = new Map() for (const parser of config.parsers) { if (parser.extNames) { for (const ext of parser.extNames) parsersMap.set(ext, parser) } } // Make `diagnostics` the active sink so deep code (adapter parse, generators) can // report into this run via `Diagnostics.report`. return Diagnostics.scope( (diagnostic) => diagnostics.push(diagnostic), async () => { try { this.options.signal?.throwIfAborted() const outputRoot = resolve(config.root, config.output.path) // Parse the adapter source into `this.inputNode`. await this.#parseInput() // Kit's resolver reads the shared-schema data from memo, so it has to be there before setup. this.memo.set('kubb:sharedSchemas', this.#shared) await this.setupHooks() // Normalize each plugin's options once setup hooks have run, so the generate loop always // sees a filled-in bag whether or not the plugin called `setOptions`. for (const plugin of this.plugins.values()) { this.options.signal?.throwIfAborted() plugin.options = normalizePluginOptions(plugin.options, plugin.name) } if (this.adapter && this.inputNode) { const { meta, schemas, operations } = this.inputNode const buildStartContext = this.#withFiles({ config, adapter: this.adapter, meta, nodeCounts: { schemas: schemas.length, operations: operations.length }, getPlugin: this.getPlugin.bind(this), }) await hooks.callHook('kubb:build:start', buildStartContext) } const visitPlugins: Array<{ plugin: NormalizedPlugin context: PluginVisitContext hrStart: ReturnType }> = [] for (const plugin of this.plugins.values()) { const context = this.getContext(plugin) const hrStart = process.hrtime() try { await hooks.callHook('kubb:plugin:start', { plugin }) } catch (caughtError) { diagnostics.push(...(await this.#finishPlugin({ plugin, hrStart, error: toError(caughtError) }))) continue } if (hasVisitHooks(plugin)) { visitPlugins.push({ plugin, context, hrStart }) continue } diagnostics.push(...(await this.#finishPlugin({ plugin, hrStart }))) } // Walk every node through each plugin's visit hooks. diagnostics.push(...(await this.#walk(visitPlugins))) this.#inlineFiles(parsersMap) await hooks.callHook('kubb:plugins:end', this.#withFiles({ config })) // Write every generated file once, after post-processing (barrel etc.) has had its // chance to add more. Writing mid-generation measured no faster in practice, so a // single pass keeps the pipeline simpler. for (const cleanPath of this.options.cleanPaths ?? []) await config.storage.empty(cleanPath) await fileManager.write(fileManager.files, { storage: config.storage, parsers: parsersMap, lockfile: this.options.lockfile, signal: this.options.signal, cleaned: this.options.cleanPaths, shared: this.#shared, hooks, config, }) await this.adapter?.settle?.() await hooks.callHook('kubb:build:end', { files: this.fileManager.files, config, outputDir: outputRoot }) return { diagnostics: Diagnostics.dedupe(this.#withoutIgnored(diagnostics)) } } catch (caughtError) { await this.adapter?.settle?.() diagnostics.push(Diagnostics.from(caughtError)) return { diagnostics: Diagnostics.dedupe(this.#withoutIgnored(diagnostics)) } } }, ) } /** * Moves inline sources into the files that import them and drops the virtual files, before barrels * (`kubb:plugins:end`) and the write see them. */ #inlineFiles(parsers: ReadonlyMap): void { const { files, virtualPaths, problems } = ast.file.inline(this.fileManager.files, { language: (file) => parsers.get(file.extname)?.inline }) if (virtualPaths.length === 0) return this.fileManager.add(...files) this.fileManager.delete(...virtualPaths) // One diagnostic lists every problem, so the summary shows them together. if (problems.length > 0) { Diagnostics.report({ code: Diagnostics.code.inlineFailed, severity: 'error', message: problems.map(({ path, message }) => `${path}: ${message}`).join('\n'), help: 'Give every name the file imports an inline definition, register a parser with inline support for its extension, or stop marking the source as inline.', }) } } /** * Widens `extra` with the files present at emit time and a bound `upsertFile`, the shape every * file-carrying hook context shares. Building it here in one place keeps the `files` and * `upsertFile` keys from being dropped by a stray spread at the call site. */ #withFiles(extra: T): T & { files: Array; upsertFile: (...files: Array) => Array } { return { ...extra, files: this.fileManager.files, upsertFile: (...files: Array) => this.fileManager.upsert(...files), } } async #finishPlugin({ plugin, hrStart, error, crashSite, }: { plugin: NormalizedPlugin hrStart: ReturnType error?: Error crashSite?: CrashSite }): Promise> { const duration = getElapsedMs(hrStart) await this.hooks.callHook('kubb:plugin:end', this.#withFiles({ plugin, duration, success: !error, ...(error ? { error } : {}), config: this.config })) const timing = Diagnostics.performance({ plugin: plugin.name, duration }) if (!error) return [timing] const diagnostic = Diagnostics.fromExtension(error, { kind: 'plugin', extension: plugin }) const site = diagnostic.code === Diagnostics.code.pluginFailed && !diagnostic.location ? crashSite : undefined return [ site ? { ...diagnostic, message: `While generating ${site.label}: ${diagnostic.message}`, ...(site.location ? { location: site.location } : {}) } : diagnostic, timing, ] } /** * Walks schemas and operations through every plugin's visit hooks. The walk is node-outer: each * node goes to every plugin in dependency order, schemas before operations, so file output stays * deterministic across runs. * * A failing plugin is dropped from the remaining walk and contributes an error diagnostic, without * aborting the other plugins. `kubb:plugin:end` and each plugin's `timing` diagnostic fire in * dependency order once the walk finishes, driving the CLI's `Plugins N/M` counter. * * When `this.inputNode` is `null`, every entry still gets a `kubb:plugin:end` so post-plugin * listeners (the barrel writer and friends) complete. */ async #walk( entries: Array<{ plugin: NormalizedPlugin; context: PluginVisitContext; hrStart: ReturnType }>, ): Promise> { const diagnostics: Array = [] if (entries.length === 0) return diagnostics if (!this.inputNode) { for (const { plugin, hrStart } of entries) diagnostics.push(...(await this.#finishPlugin({ plugin, hrStart }))) return diagnostics } const { schemas, operations } = this.inputNode const states = entries.map(({ plugin, context, hrStart }) => ({ plugin, context, hrStart, hooks: plugin.hooks ?? {}, error: null as Error | null, // The node a hook crashed on, so the diagnostic can name it. crashSite: undefined as CrashSite | undefined, })) for (const state of states) { try { await withContext(state.context, (ctx) => state.hooks['kubb:plugin:visit:start']?.call(ctx, ctx)) } catch (caughtError) { state.error = toError(caughtError) } } const visit = async (node: SchemaNode | OperationNode, call: (state: (typeof states)[number]) => unknown) => { for (const state of states) { if (state.error) continue try { await call(state) } catch (caughtError) { state.error = toError(caughtError) state.crashSite = getCrashSite(node) } } } for (const node of schemas) await visit(node, (state) => withContext(state.context, (ctx) => state.hooks['kubb:plugin:visit:schema']?.call(ctx, node, ctx))) for (const node of operations) await visit(node, (state) => withContext(state.context, (ctx) => state.hooks['kubb:plugin:visit:operation']?.call(ctx, node, ctx))) for (const state of states) { if (state.error) continue try { await withContext(state.context, (ctx) => state.hooks['kubb:plugin:visit:end']?.call(ctx, ctx)) } catch (caughtError) { state.error = toError(caughtError) } } // Close out every plugin in dependency order, so `kubb:plugin:end` and the timing diagnostics // still count up in plugin order for the CLI's `Plugins N/M` line. for (const { plugin, hrStart, error, crashSite } of states) { diagnostics.push(...(await this.#finishPlugin({ plugin, hrStart, error: error ?? undefined, crashSite }))) } return diagnostics } /** * Removes every listener the driver added. Listeners attached directly to `hooks` from outside * the driver survive. Called at the end of a build to prevent leaks across repeated builds. * * @internal */ dispose(): void { for (const unhook of this.#unhooks) unhook() this.#unhooks.length = 0 // Release the FileNode cache and parsed adapter graph so memory is reclaimed // between builds. The returned `BuildOutput.files` array still references any // FileNodes the caller needs to inspect. this.fileManager.dispose() this.inputNode = null this.#adapterSource = null this.#memo.clear() this.#contexts.clear() } [Symbol.dispose](): void { this.dispose() } /** * Returns the plugin's visit context, created once per plugin and shared by its bus hooks and the walk. */ getContext(plugin: NormalizedPlugin): PluginVisitContext { const key = plugin as NormalizedPlugin return storeMemo(this.#contexts, key, () => this.#createContext(key)) as unknown as PluginVisitContext } /** Drops the non-error problems whose code `config.diagnostics.ignore` lists. */ #withoutIgnored(diagnostics: Array): Array { const ignore = new Set(this.config.diagnostics?.ignore) if (!ignore.size) return diagnostics return diagnostics.filter((diagnostic) => !Diagnostics.isProblem(diagnostic) || diagnostic.severity === 'error' || !ignore.has(diagnostic.code)) } #createContext(plugin: NormalizedPlugin): PluginVisitContext { const driver = this // Collect into the active build only. The host renders each collected diagnostic once after the // build (the CLI via `Diagnostics.emit`, the agent via its post-build loop), so emitting a live // `kubb:error`/`kubb:warn`/`kubb:info` here would render it twice. const report = (diagnostic: Omit): void => { Diagnostics.report({ ...diagnostic, plugin: plugin.name }) } return { config: driver.config, signal: driver.options.signal, get root(): string { return resolve(driver.config.root, driver.config.output.path) }, hooks: driver.hooks, plugin, getPlugin: driver.getPlugin.bind(driver), // Close over the owning plugin so a missing dependency error names who required it. requirePlugin: ((name: string) => driver.requirePlugin(name, { requiredBy: plugin.name })) as PluginVisitContext['requirePlugin'], memo: driver.memo, driver, addFile: async (...files: Array) => { driver.fileManager.add(...files) }, upsertFile: async (...files: Array) => { driver.fileManager.upsert(...files) }, getFile: (path: string) => driver.fileManager.get(path), get meta(): InputMeta { return driver.inputNode?.meta ?? {} }, get schemas(): ReadonlyArray { return driver.inputNode?.schemas ?? [] }, get operations(): ReadonlyArray { return driver.inputNode?.operations ?? [] }, dispatch: (options) => driver.fileManager.dispatch(options), get adapter(): Adapter { // Generators only read `adapter` during AST hooks, which run after the // adapter is set, so it is guaranteed defined at read time. return driver.adapter! }, warn(message, options) { report({ code: Diagnostics.code.pluginWarning, severity: 'warning', message, ...options }) }, error(error, options) { if (Diagnostics.isError(error)) { report({ ...options, ...error.diagnostic }) return } const cause = typeof error === 'string' ? undefined : error report({ code: Diagnostics.code.pluginFailed, severity: 'error', message: typeof error === 'string' ? error : error.message, cause, ...options }) }, info(message, options) { report({ code: Diagnostics.code.pluginInfo, severity: 'info', message, ...options }) }, } } getPlugin(pluginName: TName): Plugin> | undefined getPlugin(pluginName: string): Plugin | undefined { return this.plugins.get(pluginName) } /** * Like `getPlugin` but throws a descriptive error when the plugin is not found. */ requirePlugin(pluginName: TName, context?: RequirePluginContext): Plugin> requirePlugin(pluginName: string, context?: RequirePluginContext): Plugin { const plugin = this.getPlugin(pluginName) if (plugin) return plugin throw pluginNotFoundError({ pluginName, requiredBy: context?.requiredBy }) } /** * Returns the resolver a plugin stored with kit's `setResolver`. Published plugins still call it through `ctx.driver`. * * @deprecated Use `ctx.getResolver(pluginName)` in a generator, or `getResolver(pluginName)` from `kubb/kit` in any other hook. Removed in Kubb v6. */ getResolver(pluginName: string): unknown { const key = `${pluginName}:resolver` if (this.memo.has(key)) return this.memo.get(key) throw new Diagnostics.Error({ code: Diagnostics.code.movedToKit, severity: 'error', message: `\`driver.getResolver\` moved to @kubb/kit, and plugin "${pluginName}" has no resolver set with \`setResolver\`.`, help: `Call \`ctx.getResolver('${pluginName}')\` in a generator, or \`getResolver('${pluginName}')\` from \`kubb/kit\` in any other hook.`, }) } } /** * @deprecated Use `Driver` instead. */ export const KubbDriver = Driver /** * @deprecated Use `Driver` instead. */ export type KubbDriver = Driver /** The `KUBB_PLUGIN_NOT_FOUND` error `requirePlugin` throws, naming the plugin that needed it. */ export function pluginNotFoundError({ pluginName, requiredBy }: { pluginName: string; requiredBy?: string }): DiagnosticError { const by = requiredBy ? ` by "${requiredBy}"` : '' const help = requiredBy ? ` (required by "${requiredBy}")` : '' return new Diagnostics.Error({ code: Diagnostics.code.pluginNotFound, severity: 'error', message: `Plugin "${pluginName}" is required${by} but not found. Make sure it is included in your Kubb config.`, help: `Add "${pluginName}" to the \`plugins\` array in kubb.config.ts${help}, or remove the dependency on it.`, location: { kind: 'config' }, ...(requiredBy ? { plugin: requiredBy } : {}), }) }