@kubb/core 5.0.0-beta.9 → 5.0.0-beta.91

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/LICENSE +17 -10
  2. package/README.md +20 -123
  3. package/dist/index.cjs +2241 -1138
  4. package/dist/index.cjs.map +1 -1
  5. package/dist/index.d.ts +135 -178
  6. package/dist/index.js +2233 -1131
  7. package/dist/index.js.map +1 -1
  8. package/dist/mocks.cjs +77 -24
  9. package/dist/mocks.cjs.map +1 -1
  10. package/dist/mocks.d.ts +37 -11
  11. package/dist/mocks.js +79 -28
  12. package/dist/mocks.js.map +1 -1
  13. package/dist/types-aNebW3Ui.d.ts +2815 -0
  14. package/dist/usingCtx-BriKju-v.js +577 -0
  15. package/dist/usingCtx-BriKju-v.js.map +1 -0
  16. package/dist/usingCtx-eyNeehd2.cjs +679 -0
  17. package/dist/usingCtx-eyNeehd2.cjs.map +1 -0
  18. package/package.json +7 -28
  19. package/dist/PluginDriver-Cu1Kj9S-.cjs +0 -1075
  20. package/dist/PluginDriver-Cu1Kj9S-.cjs.map +0 -1
  21. package/dist/PluginDriver-D8Z0Htid.js +0 -978
  22. package/dist/PluginDriver-D8Z0Htid.js.map +0 -1
  23. package/dist/createKubb-ALdb8lmq.d.ts +0 -2082
  24. package/src/FileManager.ts +0 -115
  25. package/src/FileProcessor.ts +0 -86
  26. package/src/PluginDriver.ts +0 -457
  27. package/src/constants.ts +0 -35
  28. package/src/createAdapter.ts +0 -108
  29. package/src/createKubb.ts +0 -1268
  30. package/src/createRenderer.ts +0 -57
  31. package/src/createStorage.ts +0 -70
  32. package/src/defineGenerator.ts +0 -175
  33. package/src/defineLogger.ts +0 -58
  34. package/src/defineMiddleware.ts +0 -62
  35. package/src/defineParser.ts +0 -44
  36. package/src/definePlugin.ts +0 -379
  37. package/src/defineResolver.ts +0 -654
  38. package/src/devtools.ts +0 -66
  39. package/src/index.ts +0 -20
  40. package/src/mocks.ts +0 -177
  41. package/src/storages/fsStorage.ts +0 -90
  42. package/src/storages/memoryStorage.ts +0 -55
  43. package/src/types.ts +0 -41
  44. /package/dist/{chunk--u3MIqq1.js → rolldown-runtime-C0LytTxp.js} +0 -0
package/dist/index.js CHANGED
@@ -1,150 +1,66 @@
1
- import { t as __name } from "./chunk--u3MIqq1.js";
2
- import { a as definePlugin, c as DEFAULT_STUDIO_URL, i as defineResolver, l as logLevel, n as applyHookResult, o as DEFAULT_BANNER, r as FileManager, s as DEFAULT_EXTENSION, t as PluginDriver, u as camelCase } from "./PluginDriver-D8Z0Htid.js";
3
- import { EventEmitter } from "node:events";
4
- import { access, mkdir, readFile, readdir, rm, writeFile } from "node:fs/promises";
5
- import { dirname, join, resolve } from "node:path";
6
- import * as ast from "@kubb/ast";
7
- import { collectUsedSchemaNames, extractStringsFromNodes, transform, walk } from "@kubb/ast";
8
- import { version } from "node:process";
9
- //#region ../../internals/utils/src/errors.ts
1
+ import "./rolldown-runtime-C0LytTxp.js";
2
+ import { a as toFilePath, c as BuildError, d as camelCase, i as clean, l as getErrorMessage, n as FileManager, o as toPosixPath, r as Hookable, s as write, t as _usingCtx, u as toError } from "./usingCtx-BriKju-v.js";
3
+ import { AsyncLocalStorage } from "node:async_hooks";
4
+ import { stripVTControlCharacters, styleText } from "node:util";
5
+ import { hash } from "node:crypto";
6
+ import { access, glob, readFile, rm } from "node:fs/promises";
7
+ import path, { join, relative, resolve } from "node:path";
8
+ import { ast, collectUsedSchemaNames, composeMacros, operationDef, schemaDef, transform } from "@kubb/ast";
9
+ import process$1 from "node:process";
10
+ //#region src/createAdapter.ts
10
11
  /**
11
- * Thrown when one or more errors occur during a Kubb build.
12
- * Carries the full list of underlying errors on `errors`.
12
+ * Defines a custom adapter that translates a spec format into Kubb's universal
13
+ * AST, for example GraphQL, gRPC, or AsyncAPI. The built-in `@kubb/adapter-oas`
14
+ * handles OpenAPI/Swagger documents.
13
15
  *
14
- * @example
15
- * ```ts
16
- * throw new BuildError('Build failed', { errors: [err1, err2] })
17
- * ```
18
- */
19
- var BuildError = class extends Error {
20
- errors;
21
- constructor(message, options) {
22
- super(message, { cause: options.cause });
23
- this.name = "BuildError";
24
- this.errors = options.errors;
25
- }
26
- };
27
- /**
28
- * Coerces an unknown thrown value to an `Error` instance.
29
- * Returns the value as-is when it is already an `Error`; otherwise wraps it with `String(value)`.
16
+ * Adapters must return an `InputNode` from `parse`. That node is what every
17
+ * plugin in the build consumes.
30
18
  *
31
19
  * @example
32
20
  * ```ts
33
- * try { ... } catch(err) {
34
- * throw new BuildError('Build failed', { cause: toError(err), errors: [] })
35
- * }
21
+ * import { createAdapter, type AdapterFactoryOptions } from '@kubb/core'
22
+ * import { ast } from '@kubb/ast'
23
+ *
24
+ * type MyAdapter = AdapterFactoryOptions<'my-adapter', { validate?: boolean }>
25
+ *
26
+ * export const myAdapter = createAdapter<MyAdapter>((options) => ({
27
+ * name: 'my-adapter',
28
+ * options,
29
+ * document: null,
30
+ * async parse(_source) {
31
+ * // Convert the source (path or inline data) into an InputNode.
32
+ * return ast.factory.createInput()
33
+ * },
34
+ * getImports: () => [],
35
+ * async validate() {
36
+ * // Throw here when the spec is invalid.
37
+ * },
38
+ * }))
36
39
  * ```
37
40
  */
38
- function toError(value) {
39
- return value instanceof Error ? value : new Error(String(value));
41
+ function createAdapter(build) {
42
+ return (options) => build(options ?? {});
40
43
  }
41
44
  //#endregion
42
- //#region ../../internals/utils/src/asyncEventEmitter.ts
45
+ //#region src/applyConfigDefaults.ts
43
46
  /**
44
- * Typed `EventEmitter` that awaits all async listeners before resolving.
45
- * Wraps Node's `EventEmitter` with full TypeScript event-map inference.
46
- *
47
- * @example
48
- * ```ts
49
- * const emitter = new AsyncEventEmitter<{ build: [name: string] }>()
50
- * emitter.on('build', async (name) => { console.log(name) })
51
- * await emitter.emit('build', 'petstore') // all listeners awaited
52
- * ```
47
+ * Fills in the config defaults shared by `defineConfig` and the unplugin factory: the fallback
48
+ * adapter, `defaultOutput`'s fields, and appending the barrel plugin when it's not already
49
+ * registered. Both entry points construct their own adapter, barrel plugin, and output defaults
50
+ * (`barrel` is a `@kubb/plugin-barrel` extension field core doesn't know about) and pass them in,
51
+ * so `@kubb/core` doesn't need to depend on `@kubb/adapter-oas` or `@kubb/plugin-barrel`.
53
52
  */
54
- var AsyncEventEmitter = class {
55
- /**
56
- * Maximum number of listeners per event before Node emits a memory-leak warning.
57
- * @default 10
58
- */
59
- constructor(maxListener = 10) {
60
- this.#emitter.setMaxListeners(maxListener);
61
- }
62
- #emitter = new EventEmitter();
63
- /**
64
- * Emits `eventName` and awaits all registered listeners sequentially.
65
- * Throws if any listener rejects, wrapping the cause with the event name and serialized arguments.
66
- *
67
- * @example
68
- * ```ts
69
- * await emitter.emit('build', 'petstore')
70
- * ```
71
- */
72
- async emit(eventName, ...eventArgs) {
73
- const listeners = this.#emitter.listeners(eventName);
74
- if (listeners.length === 0) return;
75
- for (const listener of listeners) try {
76
- await listener(...eventArgs);
77
- } catch (err) {
78
- let serializedArgs;
79
- try {
80
- serializedArgs = JSON.stringify(eventArgs);
81
- } catch {
82
- serializedArgs = String(eventArgs);
83
- }
84
- throw new Error(`Error in async listener for "${eventName}" with eventArgs ${serializedArgs}`, { cause: toError(err) });
53
+ function applyConfigDefaults(config, { defaultAdapter, barrelPlugin, barrelPluginName, defaultOutput }) {
54
+ const plugins = config.plugins?.some((plugin) => plugin.name === barrelPluginName) ? config.plugins ?? [] : [...config.plugins ?? [], barrelPlugin];
55
+ return {
56
+ adapter: config.adapter ?? defaultAdapter,
57
+ plugins,
58
+ output: {
59
+ ...defaultOutput,
60
+ ...config.output
85
61
  }
86
- }
87
- /**
88
- * Registers a persistent listener for `eventName`.
89
- *
90
- * @example
91
- * ```ts
92
- * emitter.on('build', async (name) => { console.log(name) })
93
- * ```
94
- */
95
- on(eventName, handler) {
96
- this.#emitter.on(eventName, handler);
97
- }
98
- /**
99
- * Registers a one-shot listener that removes itself after the first invocation.
100
- *
101
- * @example
102
- * ```ts
103
- * emitter.onOnce('build', async (name) => { console.log(name) })
104
- * ```
105
- */
106
- onOnce(eventName, handler) {
107
- const wrapper = (...args) => {
108
- this.off(eventName, wrapper);
109
- return handler(...args);
110
- };
111
- this.on(eventName, wrapper);
112
- }
113
- /**
114
- * Removes a previously registered listener.
115
- *
116
- * @example
117
- * ```ts
118
- * emitter.off('build', handler)
119
- * ```
120
- */
121
- off(eventName, handler) {
122
- this.#emitter.off(eventName, handler);
123
- }
124
- /**
125
- * Returns the number of listeners registered for `eventName`.
126
- *
127
- * @example
128
- * ```ts
129
- * emitter.on('build', handler)
130
- * emitter.listenerCount('build') // 1
131
- * ```
132
- */
133
- listenerCount(eventName) {
134
- return this.#emitter.listenerCount(eventName);
135
- }
136
- /**
137
- * Removes all listeners from every event channel.
138
- *
139
- * @example
140
- * ```ts
141
- * emitter.removeAll()
142
- * ```
143
- */
144
- removeAll() {
145
- this.#emitter.removeAllListeners();
146
- }
147
- };
62
+ };
63
+ }
148
64
  //#endregion
149
65
  //#region ../../internals/utils/src/time.ts
150
66
  /**
@@ -179,560 +95,1825 @@ function formatMs(ms) {
179
95
  return `${Math.round(ms)}ms`;
180
96
  }
181
97
  //#endregion
182
- //#region ../../internals/utils/src/fs.ts
98
+ //#region ../../internals/utils/src/colors.ts
99
+ /**
100
+ * Parses a CSS hex color string (`#RGB`) into its RGB channels.
101
+ * Falls back to `255` for any channel that cannot be parsed.
102
+ */
103
+ function parseHex(color) {
104
+ const int = Number.parseInt(color.replace("#", ""), 16);
105
+ return Number.isNaN(int) ? {
106
+ r: 255,
107
+ g: 255,
108
+ b: 255
109
+ } : {
110
+ r: int >> 16 & 255,
111
+ g: int >> 8 & 255,
112
+ b: int & 255
113
+ };
114
+ }
115
+ /**
116
+ * Returns a function that wraps a string in a 24-bit ANSI true-color escape sequence
117
+ * for the given hex color.
118
+ */
119
+ function hex(color) {
120
+ const { r, g, b } = parseHex(color);
121
+ return (text) => `\x1b[38;2;${r};${g};${b}m${text}\x1b[0m`;
122
+ }
123
+ hex("#F55A17"), hex("#F5A217"), hex("#F58517"), hex("#B45309"), hex("#FFFFFF"), hex("#adadc6"), hex("#FDA4AF");
183
124
  /**
184
- * Resolves to `true` when the file or directory at `path` exists.
185
- * Uses `Bun.file().exists()` when running under Bun, `fs.access` otherwise.
125
+ * ANSI color names used by {@link randomCliColor} for deterministic terminal coloring.
126
+ */
127
+ const randomColors = [
128
+ "black",
129
+ "red",
130
+ "green",
131
+ "yellow",
132
+ "blue",
133
+ "white",
134
+ "magenta",
135
+ "cyan",
136
+ "gray"
137
+ ];
138
+ /**
139
+ * Wraps `text` in a deterministic ANSI color derived from the text's SHA-256 hash.
186
140
  *
187
141
  * @example
188
142
  * ```ts
189
- * if (await exists('./kubb.config.ts')) {
190
- * const content = await read('./kubb.config.ts')
191
- * }
143
+ * randomCliColor('petstore') // '\x1b[33m' + 'petstore' + '\x1b[39m' (always the same color for 'petstore')
192
144
  * ```
193
145
  */
194
- async function exists(path) {
195
- if (typeof Bun !== "undefined") return Bun.file(path).exists();
196
- return access(path).then(() => true, () => false);
146
+ function randomCliColor(text) {
147
+ if (!text) return "";
148
+ const index = hash("sha256", text, "buffer").readUInt32BE(0) % randomColors.length;
149
+ return styleText(randomColors[index] ?? "white", text);
197
150
  }
151
+ //#endregion
152
+ //#region ../../internals/utils/src/promise.ts
198
153
  /**
199
- * Writes `data` to `path`, trimming leading/trailing whitespace before saving.
200
- * Skips the write when the trimmed content is empty or identical to what is already on disk.
201
- * Creates any missing parent directories automatically.
202
- * When `sanity` is `true`, re-reads the file after writing and throws if the content does not match.
154
+ * Wraps `factory` with a keyed cache backed by the provided store.
203
155
  *
204
- * @example
156
+ * Pass a `WeakMap` for object keys (results are GC-eligible when the key is
157
+ * collected) or a `Map` for primitive keys. For multi-argument functions,
158
+ * nest two `memoize` calls — the outer keyed by the first argument, the
159
+ * inner (created once per outer miss) keyed by the second.
160
+ *
161
+ * Because the cache is owned by the caller, it can be shared, inspected, or
162
+ * cleared independently of the memoized function.
163
+ *
164
+ * @example Single WeakMap key
165
+ * ```ts
166
+ * const cache = new WeakMap<SchemaNode, Set<string>>()
167
+ * const getRefs = memoize(cache, (node) => collectRefs(node))
168
+ * ```
169
+ *
170
+ * @example Single Map key (primitive)
171
+ * ```ts
172
+ * const cache = new Map<string, Resolver>()
173
+ * const getResolver = memoize(cache, (name) => buildResolver(name))
174
+ * ```
175
+ *
176
+ * @example Two-level (object + primitive)
205
177
  * ```ts
206
- * await write('./src/Pet.ts', source) // writes and returns trimmed content
207
- * await write('./src/Pet.ts', source) // null file unchanged
208
- * await write('./src/Pet.ts', ' ') // null — empty content skipped
178
+ * const outer = new WeakMap<Params[], Map<string, Params[]>>()
179
+ * const fn = memoize(outer, (params) => memoize(new Map(), (key) => transform(params, key)))
180
+ * fn(params)('camelcase')
209
181
  * ```
210
182
  */
211
- async function write(path, data, options = {}) {
212
- const trimmed = data.trim();
213
- if (trimmed === "") return null;
214
- const resolved = resolve(path);
215
- if (typeof Bun !== "undefined") {
216
- const file = Bun.file(resolved);
217
- if ((await file.exists() ? await file.text() : null) === trimmed) return null;
218
- await Bun.write(resolved, trimmed);
219
- return trimmed;
220
- }
221
- try {
222
- if (await readFile(resolved, { encoding: "utf-8" }) === trimmed) return null;
223
- } catch {}
224
- await mkdir(dirname(resolved), { recursive: true });
225
- await writeFile(resolved, trimmed, { encoding: "utf-8" });
226
- if (options.sanity) {
227
- const savedData = await readFile(resolved, { encoding: "utf-8" });
228
- if (savedData !== trimmed) throw new Error(`Sanity check failed for ${path}\n\nData[${data.length}]:\n${data}\n\nSaved[${savedData.length}]:\n${savedData}\n`);
229
- return savedData;
230
- }
231
- return trimmed;
183
+ function memoize(store, factory) {
184
+ return (key) => {
185
+ if (store.has(key)) return store.get(key);
186
+ const value = factory(key);
187
+ store.set(key, value);
188
+ return value;
189
+ };
232
190
  }
191
+ //#endregion
192
+ //#region package.json
193
+ var version = "5.0.0-beta.91";
194
+ //#endregion
195
+ //#region src/constants.ts
196
+ /**
197
+ * Plugin `include` filter types that select operations directly. When one of these is set
198
+ * without a `schemaName` include, the generate phase pre-scans operations to compute the set
199
+ * of schemas they reach, so unreachable schemas can be pruned for that plugin.
200
+ */
201
+ const OPERATION_FILTER_TYPES = /* @__PURE__ */ new Set([
202
+ "tag",
203
+ "operationId",
204
+ "path",
205
+ "method",
206
+ "contentType"
207
+ ]);
208
+ /**
209
+ * Stable codes Kubb attaches to a `Diagnostic`. Each maps to a known failure mode
210
+ * and stays stable so it can be referenced in tooling and (later) docs. Reference
211
+ * these instead of inlining the string at a throw site.
212
+ */
213
+ const diagnosticCode = {
214
+ /**
215
+ * Fallback for an unstructured error with no specific code.
216
+ */
217
+ unknown: "KUBB_UNKNOWN",
218
+ /**
219
+ * The file or URL set as `input` could not be read.
220
+ */
221
+ inputNotFound: "KUBB_INPUT_NOT_FOUND",
222
+ /**
223
+ * An adapter was configured without an `input`.
224
+ */
225
+ inputRequired: "KUBB_INPUT_REQUIRED",
226
+ /**
227
+ * A `$ref` (or equivalent reference) could not be resolved in the source document.
228
+ */
229
+ refNotFound: "KUBB_REF_NOT_FOUND",
230
+ /**
231
+ * A server variable value is not allowed by its `enum`.
232
+ */
233
+ invalidServerVariable: "KUBB_INVALID_SERVER_VARIABLE",
234
+ /**
235
+ * A required plugin is missing from the config.
236
+ */
237
+ pluginNotFound: "KUBB_PLUGIN_NOT_FOUND",
238
+ /**
239
+ * A plugin threw while generating.
240
+ */
241
+ pluginFailed: "KUBB_PLUGIN_FAILED",
242
+ /**
243
+ * A plugin reported a non-fatal warning through `ctx.warn`.
244
+ */
245
+ pluginWarning: "KUBB_PLUGIN_WARNING",
246
+ /**
247
+ * A plugin reported an informational message through `ctx.info`.
248
+ */
249
+ pluginInfo: "KUBB_PLUGIN_INFO",
250
+ /**
251
+ * A schema uses a `format` Kubb does not map to a specific type. Reserved for
252
+ * adapters to emit as a `warning`.
253
+ */
254
+ unsupportedFormat: "KUBB_UNSUPPORTED_FORMAT",
255
+ /**
256
+ * A referenced schema or operation is marked `deprecated`. Reserved for adapters
257
+ * to emit as an `info`.
258
+ */
259
+ deprecated: "KUBB_DEPRECATED",
260
+ /**
261
+ * An adapter is required but the config has none. The build cannot read the input
262
+ * without one.
263
+ */
264
+ adapterRequired: "KUBB_ADAPTER_REQUIRED",
265
+ /**
266
+ * A resolved output path escapes the output directory, which can stem from a path
267
+ * traversal in the spec or a misconfigured `group.name`.
268
+ */
269
+ pathTraversal: "KUBB_PATH_TRAVERSAL",
270
+ /**
271
+ * A plugin's options are invalid, for example `output.mode: 'file'` paired with a `group` option.
272
+ */
273
+ invalidPluginOptions: "KUBB_INVALID_PLUGIN_OPTIONS",
274
+ /**
275
+ * A post-generate shell hook (`hooks.done`) exited with a failure.
276
+ */
277
+ hookFailed: "KUBB_HOOK_FAILED",
278
+ /**
279
+ * The formatter pass over the generated files failed.
280
+ */
281
+ formatFailed: "KUBB_FORMAT_FAILED",
282
+ /**
283
+ * The linter pass over the generated files failed.
284
+ */
285
+ lintFailed: "KUBB_LINT_FAILED",
286
+ /**
287
+ * Not a failure. Carries a plugin's elapsed time, summed into the run total.
288
+ */
289
+ performance: "KUBB_PERFORMANCE",
290
+ /**
291
+ * Not a failure. A newer Kubb version is available on npm.
292
+ */
293
+ updateAvailable: "KUBB_UPDATE_AVAILABLE"
294
+ };
295
+ //#endregion
296
+ //#region src/Diagnostics.ts
297
+ /**
298
+ * Docs major version, derived from the package version so the link tracks the published major.
299
+ */
300
+ const docsMajor = version.split(".")[0] ?? "5";
233
301
  /**
234
- * Recursively removes `path`. Silently succeeds when `path` does not exist.
302
+ * Narrows a {@link Diagnostic} to the variant for `code`, or `null` when it does not match.
235
303
  *
236
304
  * @example
237
305
  * ```ts
238
- * await clean('./dist')
306
+ * const update = narrow(diagnostic, diagnosticCode.updateAvailable)
307
+ * if (update) {
308
+ * console.log(update.latestVersion)
309
+ * }
239
310
  * ```
240
311
  */
241
- async function clean(path) {
242
- return rm(path, {
243
- recursive: true,
244
- force: true
245
- });
312
+ function narrow(diagnostic, code) {
313
+ return diagnostic.code === code ? diagnostic : null;
246
314
  }
247
- //#endregion
248
- //#region ../../internals/utils/src/reserved.ts
249
315
  /**
250
- * JavaScript and Java reserved words.
251
- * @link https://github.com/jonschlinkert/reserved/blob/master/index.js
316
+ * Builds a type guard that narrows a {@link Diagnostic} to the variant for `kind`. A diagnostic
317
+ * with no `kind` is treated as a `problem`.
252
318
  */
253
- const reservedWords = new Set([
254
- "abstract",
255
- "arguments",
256
- "boolean",
257
- "break",
258
- "byte",
259
- "case",
260
- "catch",
261
- "char",
262
- "class",
263
- "const",
264
- "continue",
265
- "debugger",
266
- "default",
267
- "delete",
268
- "do",
269
- "double",
270
- "else",
271
- "enum",
272
- "eval",
273
- "export",
274
- "extends",
275
- "false",
276
- "final",
277
- "finally",
278
- "float",
279
- "for",
280
- "function",
281
- "goto",
282
- "if",
283
- "implements",
284
- "import",
285
- "in",
286
- "instanceof",
287
- "int",
288
- "interface",
289
- "let",
290
- "long",
291
- "native",
292
- "new",
293
- "null",
294
- "package",
295
- "private",
296
- "protected",
297
- "public",
298
- "return",
299
- "short",
300
- "static",
301
- "super",
302
- "switch",
303
- "synchronized",
304
- "this",
305
- "throw",
306
- "throws",
307
- "transient",
308
- "true",
309
- "try",
310
- "typeof",
311
- "var",
312
- "void",
313
- "volatile",
314
- "while",
315
- "with",
316
- "yield",
317
- "Array",
318
- "Date",
319
- "hasOwnProperty",
320
- "Infinity",
321
- "isFinite",
322
- "isNaN",
323
- "isPrototypeOf",
324
- "length",
325
- "Math",
326
- "name",
327
- "NaN",
328
- "Number",
329
- "Object",
330
- "prototype",
331
- "String",
332
- "toString",
333
- "undefined",
334
- "valueOf"
335
- ]);
319
+ function isKind(kind) {
320
+ return (diagnostic) => (diagnostic.kind ?? "problem") === kind;
321
+ }
336
322
  /**
337
- * Returns `true` when `name` is a syntactically valid JavaScript variable name.
323
+ * Returns `true` when the diagnostic is a build {@link ProblemDiagnostic}.
338
324
  *
339
325
  * @example
340
326
  * ```ts
341
- * isValidVarName('status') // true
342
- * isValidVarName('class') // false (reserved word)
343
- * isValidVarName('42foo') // false (starts with digit)
327
+ * if (isProblem(diagnostic)) {
328
+ * console.log(diagnostic.location)
329
+ * }
344
330
  * ```
345
331
  */
346
- function isValidVarName(name) {
347
- if (!name || reservedWords.has(name)) return false;
348
- return /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(name);
349
- }
350
- //#endregion
351
- //#region ../../internals/utils/src/urlPath.ts
332
+ const isProblem = isKind("problem");
352
333
  /**
353
- * Parses and transforms an OpenAPI/Swagger path string into various URL formats.
334
+ * Returns `true` when the diagnostic is a per-plugin {@link PerformanceDiagnostic}.
354
335
  *
355
336
  * @example
356
- * const p = new URLPath('/pet/{petId}')
357
- * p.URL // '/pet/:petId'
358
- * p.template // '`/pet/${petId}`'
337
+ * ```ts
338
+ * const timings = diagnostics.filter(isPerformance)
339
+ * ```
340
+ */
341
+ const isPerformance = isKind("performance");
342
+ /**
343
+ * Returns `true` when the diagnostic is a version-update {@link UpdateDiagnostic}.
344
+ *
345
+ * @example
346
+ * ```ts
347
+ * if (isUpdate(diagnostic)) {
348
+ * console.log(diagnostic.latestVersion)
349
+ * }
350
+ * ```
351
+ */
352
+ const isUpdate = isKind("update");
353
+ /**
354
+ * Accent color per severity. The color tints the `[CODE]` tag (red error, yellow warning,
355
+ * blue info).
356
+ */
357
+ const severityStyle = {
358
+ error: "red",
359
+ warning: "yellow",
360
+ info: "blue"
361
+ };
362
+ /**
363
+ * Explanation for every {@link diagnosticCode}. Use {@link Diagnostics.explain} to look one up
364
+ * and `Diagnostics.docsUrl` for the matching kubb.dev page.
365
+ */
366
+ const diagnosticCatalog = {
367
+ [diagnosticCode.unknown]: {
368
+ title: "Unknown error",
369
+ cause: "An error was thrown without a stable Kubb code, so it is reported as-is.",
370
+ fix: "Read the underlying message and stack. If it comes from a plugin or adapter, check its configuration; otherwise report it as a possible Kubb bug."
371
+ },
372
+ [diagnosticCode.inputNotFound]: {
373
+ title: "Input not found",
374
+ cause: "The file or URL set as `input` (or passed as `kubb generate PATH`) could not be read.",
375
+ fix: "Check that the path or URL exists and is readable, then set it as `input` or pass it on the CLI."
376
+ },
377
+ [diagnosticCode.inputRequired]: {
378
+ title: "Input required",
379
+ cause: "An adapter is configured but no `input` was provided.",
380
+ fix: "Set `input` to a file path, a URL, an inline spec (JSON/YAML string), or a parsed object in your Kubb config."
381
+ },
382
+ [diagnosticCode.refNotFound]: {
383
+ title: "Reference not found",
384
+ cause: "A `$ref` could not be resolved in the source document.",
385
+ fix: "Add the missing definition (for example under `components.schemas`) or fix the `$ref`. Run `kubb validate` to check the spec."
386
+ },
387
+ [diagnosticCode.invalidServerVariable]: {
388
+ title: "Invalid server variable",
389
+ cause: "A server variable value is not allowed by its `enum`.",
390
+ fix: "Use one of the values listed in the server variable `enum`, or update the spec."
391
+ },
392
+ [diagnosticCode.pluginNotFound]: {
393
+ title: "Plugin not found",
394
+ cause: "A plugin that another plugin depends on is missing from the config.",
395
+ fix: "Add the required plugin to the `plugins` array in kubb.config.ts, or remove the dependency on it."
396
+ },
397
+ [diagnosticCode.pluginFailed]: {
398
+ title: "Plugin failed",
399
+ cause: "A plugin threw while generating, or reported an error through `ctx.error`.",
400
+ fix: "Read the underlying error and check the plugin options and the schema or operation it failed on."
401
+ },
402
+ [diagnosticCode.pluginWarning]: {
403
+ title: "Plugin warning",
404
+ cause: "A plugin reported a non-fatal warning through `ctx.warn`.",
405
+ fix: "Review the message. It does not fail the build; adjust the plugin options or input if the warning is unwanted."
406
+ },
407
+ [diagnosticCode.pluginInfo]: {
408
+ title: "Plugin info",
409
+ cause: "A plugin reported an informational message through `ctx.info`.",
410
+ fix: "Informational only. No action is required."
411
+ },
412
+ [diagnosticCode.unsupportedFormat]: {
413
+ title: "Unsupported format",
414
+ cause: "A schema uses a `format` Kubb does not map to a specific type, so it falls back to the base type.",
415
+ fix: "Use a format Kubb supports, or handle the custom format with a parser or plugin."
416
+ },
417
+ [diagnosticCode.deprecated]: {
418
+ title: "Deprecated",
419
+ cause: "A referenced schema or operation is marked `deprecated`.",
420
+ fix: "Migrate off the deprecated definition if the warning is unwanted."
421
+ },
422
+ [diagnosticCode.adapterRequired]: {
423
+ title: "Adapter required",
424
+ cause: "An action needs an adapter but none is configured.",
425
+ fix: "Set `adapter` in kubb.config.ts, for example `adapterOas()`."
426
+ },
427
+ [diagnosticCode.pathTraversal]: {
428
+ title: "Path traversal",
429
+ cause: "A resolved output path escaped the output directory, which can stem from a path traversal in the spec or a misconfigured `group.name`.",
430
+ fix: "Keep generated paths within the output directory. Review the `group.name` function and the names coming from the spec."
431
+ },
432
+ [diagnosticCode.invalidPluginOptions]: {
433
+ title: "Invalid plugin options",
434
+ cause: "A plugin was configured with options that cannot be honored, for example `output.mode: 'file'` paired with a `group` option.",
435
+ fix: "Fix the plugin options. A single-file output has nothing to group, so remove the `group` option or use `output.mode: 'directory'`."
436
+ },
437
+ [diagnosticCode.hookFailed]: {
438
+ title: "Hook failed",
439
+ cause: "A post-generate shell hook (`hooks.done`) exited with a non-zero status.",
440
+ fix: "Check the command is installed and correct, and run it manually to see the error."
441
+ },
442
+ [diagnosticCode.formatFailed]: {
443
+ title: "Format failed",
444
+ cause: "The formatter pass over the generated files failed.",
445
+ fix: "Check the formatter (oxfmt, biome, or prettier) is installed and its config is valid, then run it manually on the output."
446
+ },
447
+ [diagnosticCode.lintFailed]: {
448
+ title: "Lint failed",
449
+ cause: "The linter pass over the generated files failed.",
450
+ fix: "Check the linter (oxlint, biome, or eslint) is installed and its config is valid, then run it manually on the output."
451
+ },
452
+ [diagnosticCode.performance]: {
453
+ title: "Performance",
454
+ cause: "Not a failure. Records a plugin’s elapsed time, summed into the run total.",
455
+ fix: "No action. This is an informational metric."
456
+ },
457
+ [diagnosticCode.updateAvailable]: {
458
+ title: "Update available",
459
+ cause: "A newer Kubb version is published on npm than the one running.",
460
+ fix: "Update the `@kubb/*` packages, for example `npm install -g @kubb/cli`, to get the latest fixes."
461
+ }
462
+ };
463
+ /**
464
+ * Static helpers for working with {@link Diagnostic}s, plus the run-scoped sink
465
+ * that lets deep code report a diagnostic without threading a callback.
466
+ *
467
+ * The sink lives in a single `AsyncLocalStorage` in the `@kubb/core` bundle.
468
+ * `Diagnostics.scope` activates it for a run, so anything inside that run (the
469
+ * adapter parse, a generator) reports through `Diagnostics.report` and lands
470
+ * in the same run.
359
471
  */
360
- var URLPath = class {
472
+ var Diagnostics = class Diagnostics {
473
+ static #reporterStorage = new AsyncLocalStorage();
361
474
  /**
362
- * The raw OpenAPI/Swagger path string, e.g. `/pet/{petId}`.
475
+ * The diagnostic code catalog, exposed as `Diagnostics.code` (e.g. `Diagnostics.code.refNotFound`).
363
476
  */
364
- path;
365
- #options;
366
- constructor(path, options = {}) {
367
- this.path = path;
368
- this.#options = options;
369
- }
370
- /** Converts the OpenAPI path to Express-style colon syntax, e.g. `/pet/{petId}` → `/pet/:petId`.
371
- *
372
- * @example
373
- * ```ts
374
- * new URLPath('/pet/{petId}').URL // '/pet/:petId'
375
- * ```
477
+ static code = diagnosticCode;
478
+ /**
479
+ * Type guard for a build {@link ProblemDiagnostic}.
376
480
  */
377
- get URL() {
378
- return this.toURLPath();
379
- }
380
- /** Returns `true` when `path` is a fully-qualified URL (e.g. starts with `https://`).
481
+ static isProblem = isProblem;
482
+ /**
483
+ * Type guard for a version-update {@link UpdateDiagnostic}.
484
+ */
485
+ static isUpdate = isUpdate;
486
+ /**
487
+ * Type guard for a per-plugin {@link PerformanceDiagnostic}.
488
+ */
489
+ static isPerformance = isPerformance;
490
+ /**
491
+ * Narrows a {@link Diagnostic} to the variant for `code`, or `null` when it does not match.
492
+ */
493
+ static narrow = narrow;
494
+ /**
495
+ * An `Error` that carries a {@link Diagnostic}, so structured problems can flow
496
+ * through the existing throw/catch paths while keeping their code and location.
381
497
  *
382
498
  * @example
383
499
  * ```ts
384
- * new URLPath('https://petstore.swagger.io/v2/pet').isURL // true
385
- * new URLPath('/pet/{petId}').isURL // false
500
+ * throw new Diagnostics.Error({ code: diagnosticCode.refNotFound, severity: 'error', message: `Could not find ${ref}`, location: { kind: 'schema', pointer: ref, ref } })
386
501
  * ```
387
502
  */
388
- get isURL() {
389
- try {
390
- return !!new URL(this.path).href;
391
- } catch {
392
- return false;
503
+ static Error = class DiagnosticError extends Error {
504
+ diagnostic;
505
+ constructor(diagnostic) {
506
+ super(diagnostic.message, { cause: diagnostic.cause });
507
+ this.name = "DiagnosticError";
508
+ this.diagnostic = diagnostic;
393
509
  }
394
- }
510
+ };
395
511
  /**
396
- * Converts the OpenAPI path to a TypeScript template literal string.
397
- *
398
- * @example
399
- * new URLPath('/pet/{petId}').template // '`/pet/${petId}`'
400
- * new URLPath('/account/monetary-accountID').template // '`/account/${monetaryAccountId}`'
512
+ * Structural check for a {@link Diagnostics.Error}, including one thrown from a duplicated
513
+ * `@kubb/core` copy where `instanceof` fails. Matches on the `name` and a `diagnostic`
514
+ * that carries a `code`.
401
515
  */
402
- get template() {
403
- return this.toTemplateString();
516
+ static isError(error) {
517
+ if (error instanceof Diagnostics.Error) return true;
518
+ return error instanceof Error && error.name === "DiagnosticError" && "diagnostic" in error && typeof error.diagnostic === "object" && error.diagnostic !== null && typeof error.diagnostic?.code === "string";
404
519
  }
405
- /** Returns the path and its extracted params as a structured `URLObject`, or as a stringified expression when `stringify` is set.
406
- *
407
- * @example
408
- * ```ts
409
- * new URLPath('/pet/{petId}').object
410
- * // { url: '/pet/:petId', params: { petId: 'petId' } }
411
- * ```
520
+ /**
521
+ * Runs `fn` with `sink` as the active diagnostic sink for the whole async
522
+ * subtree, so {@link Diagnostics.report} reaches it from anywhere inside.
412
523
  */
413
- get object() {
414
- return this.toObject();
524
+ static scope(sink, fn) {
525
+ return Diagnostics.#reporterStorage.run(sink, fn);
415
526
  }
416
- /** Returns a map of path parameter names, or `undefined` when the path has no parameters.
417
- *
418
- * @example
419
- * ```ts
420
- * new URLPath('/pet/{petId}').params // { petId: 'petId' }
421
- * new URLPath('/pet').params // undefined
422
- * ```
527
+ /**
528
+ * Collects a diagnostic into the active build via the run-scoped sink, without throwing.
529
+ * Returns `true` when a run consumed it, `false` when called outside a {@link Diagnostics.scope}
530
+ * (so callers can fall back to throwing). Use a `warning`/`info` severity for non-fatal issues.
531
+ * For rendering a diagnostic live on the hook bus, use {@link Diagnostics.emit} instead.
423
532
  */
424
- get params() {
425
- return this.getParams();
533
+ static report(diagnostic) {
534
+ const sink = Diagnostics.#reporterStorage.getStore();
535
+ if (!sink) return false;
536
+ sink(diagnostic);
537
+ return true;
426
538
  }
427
- #transformParam(raw) {
428
- const param = isValidVarName(raw) ? raw : camelCase(raw);
429
- return this.#options.casing === "camelcase" ? camelCase(param) : param;
539
+ /**
540
+ * Emits a diagnostic on the run's `kubb:diagnostic` hook so the loggers render it live.
541
+ * Use it instead of calling `hooks.callHook('kubb:diagnostic', ...)` directly. To collect a
542
+ * diagnostic into the build result from deep in a run, use {@link Diagnostics.report} instead.
543
+ */
544
+ static async emit(hooks, diagnostic) {
545
+ await hooks.callHook("kubb:diagnostic", { diagnostic });
430
546
  }
431
547
  /**
432
- * Iterates over every `{param}` token in `path`, calling `fn` with the raw token and transformed name.
548
+ * Coerces any thrown value into a {@link ProblemDiagnostic}. A {@link Diagnostics.Error}
549
+ * keeps its structured data, and anything else becomes a `KUBB_UNKNOWN` error.
433
550
  */
434
- #eachParam(fn) {
435
- for (const match of this.path.matchAll(/\{([^}]+)\}/g)) {
436
- const raw = match[1];
437
- fn(raw, this.#transformParam(raw));
551
+ static from(error) {
552
+ const seen = /* @__PURE__ */ new Set();
553
+ let current = error;
554
+ let root;
555
+ while (current instanceof Error && !seen.has(current)) {
556
+ if (Diagnostics.isError(current)) return current.diagnostic;
557
+ seen.add(current);
558
+ root = current;
559
+ current = current.cause;
438
560
  }
561
+ return {
562
+ code: diagnosticCode.unknown,
563
+ severity: "error",
564
+ message: root ? root.message : getErrorMessage(error),
565
+ cause: root
566
+ };
439
567
  }
440
- toObject({ type = "path", replacer, stringify } = {}) {
441
- const object = {
442
- url: type === "path" ? this.toURLPath() : this.toTemplateString({ replacer }),
443
- params: this.getParams()
568
+ /**
569
+ * Builds a per-plugin performance record. Reporters sum these into the run total.
570
+ */
571
+ static performance({ plugin, duration }) {
572
+ return {
573
+ kind: "performance",
574
+ code: diagnosticCode.performance,
575
+ severity: "info",
576
+ message: `${plugin} generated in ${Math.round(duration)}ms`,
577
+ plugin,
578
+ duration
444
579
  };
445
- if (stringify) {
446
- if (type === "template") return JSON.stringify(object).replaceAll("'", "").replaceAll(`"`, "");
447
- if (object.params) return `{ url: '${object.url}', params: ${JSON.stringify(object.params).replaceAll("'", "").replaceAll(`"`, "")} }`;
448
- return `{ url: '${object.url}' }`;
449
- }
450
- return object;
451
580
  }
452
581
  /**
453
- * Converts the OpenAPI path to a TypeScript template literal string.
454
- * An optional `replacer` can transform each extracted parameter name before interpolation.
455
- *
456
- * @example
457
- * new URLPath('/pet/{petId}').toTemplateString() // '`/pet/${petId}`'
582
+ * Builds the version-update notice shown when a newer Kubb is published on npm.
458
583
  */
459
- toTemplateString({ prefix = "", replacer } = {}) {
460
- return `\`${prefix}${this.path.split(/\{([^}]+)\}/).map((part, i) => {
461
- if (i % 2 === 0) return part;
462
- const param = this.#transformParam(part);
463
- return `\${${replacer ? replacer(param) : param}}`;
464
- }).join("")}\``;
584
+ static update({ currentVersion, latestVersion }) {
585
+ return {
586
+ kind: "update",
587
+ code: diagnosticCode.updateAvailable,
588
+ severity: "info",
589
+ message: `Update available: v${currentVersion} → v${latestVersion}. Run \`npm install -g @kubb/cli\` to update.`,
590
+ currentVersion,
591
+ latestVersion
592
+ };
465
593
  }
466
594
  /**
467
- * Extracts all `{param}` segments from the path and returns them as a key-value map.
468
- * An optional `replacer` transforms each parameter name in both key and value positions.
469
- * Returns `undefined` when no path parameters are found.
470
- *
471
- * @example
472
- * ```ts
473
- * new URLPath('/pet/{petId}/tag/{tagId}').getParams()
474
- * // { petId: 'petId', tagId: 'tagId' }
475
- * ```
595
+ * True when any diagnostic is an error, the severity that fails a build. Non-error
596
+ * diagnostics are ignored.
476
597
  */
477
- getParams(replacer) {
478
- const params = {};
479
- this.#eachParam((_raw, param) => {
480
- const key = replacer ? replacer(param) : param;
481
- params[key] = key;
482
- });
483
- return Object.keys(params).length > 0 ? params : void 0;
598
+ static hasError(diagnostics) {
599
+ return diagnostics.some((diagnostic) => diagnostic.severity === "error");
484
600
  }
485
- /** Converts the OpenAPI path to Express-style colon syntax.
486
- *
487
- * @example
488
- * ```ts
489
- * new URLPath('/pet/{petId}').toURLPath() // '/pet/:petId'
490
- * ```
601
+ /**
602
+ * Names of the plugins that failed, deduped, derived from the error diagnostics
603
+ * that carry a `plugin`.
491
604
  */
492
- toURLPath() {
493
- return this.path.replace(/\{([^}]+)\}/g, ":$1");
605
+ static failedPlugins(diagnostics) {
606
+ const names = /* @__PURE__ */ new Set();
607
+ for (const diagnostic of diagnostics) if (diagnostic.severity === "error" && diagnostic.plugin) names.add(diagnostic.plugin);
608
+ return [...names];
494
609
  }
495
- };
496
- //#endregion
497
- //#region src/createAdapter.ts
498
- /**
499
- * Factory for implementing custom adapters that translate non-OpenAPI specs into Kubb's AST.
500
- *
501
- * Use this to support GraphQL schemas, gRPC definitions, AsyncAPI, or custom domain-specific languages.
502
- * Built-in adapters include `@kubb/adapter-oas` for OpenAPI and Swagger documents.
503
- *
504
- * @note Adapters must parse their input format to Kubb's `InputNode` structure.
505
- *
506
- * @example
507
- * ```ts
508
- * export const myAdapter = createAdapter<MyAdapter>((options) => {
509
- * return {
510
- * name: 'my-adapter',
511
- * options,
512
- * async parse(source) {
513
- * // Transform source format to InputNode
514
- * return { ... }
515
- * },
516
- * }
517
- * })
518
- *
519
- * // Instantiate:
520
- * const adapter = myAdapter({ validate: true })
610
+ /**
611
+ * Counts `problem` diagnostics by severity for the run summary. `performance` and
612
+ * `update` diagnostics are ignored.
613
+ */
614
+ static count(diagnostics) {
615
+ let errors = 0;
616
+ let warnings = 0;
617
+ let infos = 0;
618
+ for (const diagnostic of diagnostics) {
619
+ if (!isProblem(diagnostic)) continue;
620
+ if (diagnostic.severity === "error") errors += 1;
621
+ else if (diagnostic.severity === "warning") warnings += 1;
622
+ else infos += 1;
623
+ }
624
+ return {
625
+ errors,
626
+ warnings,
627
+ infos
628
+ };
629
+ }
630
+ /**
631
+ * Drops duplicate `problem` diagnostics that share a code, location pointer, and
632
+ * plugin, so the same issue reported across several passes is shown once. Non-problem
633
+ * diagnostics are always kept.
634
+ */
635
+ static dedupe(diagnostics) {
636
+ const seen = /* @__PURE__ */ new Set();
637
+ const result = [];
638
+ for (const diagnostic of diagnostics) {
639
+ if (!isProblem(diagnostic)) {
640
+ result.push(diagnostic);
641
+ continue;
642
+ }
643
+ const pointer = diagnostic.location && "pointer" in diagnostic.location ? diagnostic.location.pointer : "";
644
+ const key = `${diagnostic.code} ${pointer} ${diagnostic.plugin ?? ""}`;
645
+ if (seen.has(key)) continue;
646
+ seen.add(key);
647
+ result.push(diagnostic);
648
+ }
649
+ return result;
650
+ }
651
+ /**
652
+ * Builds the kubb.dev docs URL for a diagnostic code, e.g.
653
+ * `KUBB_REF_NOT_FOUND` → `https://kubb.dev/docs/5.x/reference/diagnostics/kubb-ref-not-found`.
654
+ */
655
+ static docsUrl(code) {
656
+ const slug = code.toLowerCase().replaceAll("_", "-");
657
+ return `https://kubb.dev/docs/${docsMajor}.x/reference/diagnostics/${slug}`;
658
+ }
659
+ /**
660
+ * The catalog entry for a code: its title, cause, and fix. Mirrors the kubb.dev
661
+ * `/diagnostics/<slug>` page.
662
+ */
663
+ static explain(code) {
664
+ return diagnosticCatalog[code];
665
+ }
666
+ /**
667
+ * Reduces a diagnostic to its JSON-safe fields plus a `docsUrl`, for machine-readable
668
+ * consumers. The `cause`, `kind`, and `duration` are dropped, and absent optional
669
+ * fields are omitted rather than set to `undefined`.
670
+ */
671
+ static serialize(diagnostic) {
672
+ const problem = isProblem(diagnostic) ? diagnostic : void 0;
673
+ return {
674
+ code: diagnostic.code,
675
+ severity: diagnostic.severity,
676
+ message: diagnostic.message,
677
+ ...problem?.location ? { location: problem.location } : {},
678
+ ...problem?.help ? { help: problem.help } : {},
679
+ ...problem?.plugin ? { plugin: problem.plugin } : {},
680
+ ...diagnostic.code === diagnosticCode.unknown ? {} : { docsUrl: Diagnostics.docsUrl(diagnostic.code) }
681
+ };
682
+ }
683
+ /**
684
+ * Renders a {@link Diagnostic} for terminal output as its parts: the `headline`
685
+ * (`[CODE] plugin: message`, with the code in the severity color) and the indented `details`
686
+ * rows (`at:` pointer, `fix:` help, `see:` docs link).
687
+ *
688
+ * Hosts compose these to fit their gutter: a clack logger passes `[headline, ...details]` as the
689
+ * message with no gutter symbol, while plain text outputs use {@link Diagnostics.formatLines}.
690
+ */
691
+ static format(diagnostic) {
692
+ const { code, severity, message } = diagnostic;
693
+ const color = severityStyle[severity];
694
+ const problem = isProblem(diagnostic) ? diagnostic : void 0;
695
+ const tag = styleText(color, styleText("bold", `[${code}]`));
696
+ const headline = problem?.plugin ? `${tag} ${problem.plugin}: ${message}` : `${tag}: ${message}`;
697
+ const details = [];
698
+ if (problem?.location && "pointer" in problem.location) details.push(` ${styleText("dim", "at:")} ${styleText("cyan", problem.location.pointer)}`);
699
+ if (problem?.help) details.push(` ${styleText("cyan", "fix:")} ${problem.help}`);
700
+ if (code !== diagnosticCode.unknown) details.push(` ${styleText("dim", "see:")} ${styleText("cyan", Diagnostics.docsUrl(code))}`);
701
+ return {
702
+ headline,
703
+ details
704
+ };
705
+ }
706
+ /**
707
+ * The self-contained block form of {@link Diagnostics.format}: the `headline` followed by the
708
+ * indented detail rows. Used where there is no gutter (plain and file output).
709
+ */
710
+ static formatLines(diagnostic) {
711
+ const { headline, details } = Diagnostics.format(diagnostic);
712
+ return [headline, ...details];
713
+ }
714
+ };
715
+ //#endregion
716
+ //#region src/definePlugin.ts
717
+ /**
718
+ * Merges the `output.mode` default into the output config and validates the combination.
719
+ * Throws `KUBB_INVALID_PLUGIN_OPTIONS` when `mode: 'file'` is paired with a `group` option,
720
+ * since a single-file output has nothing to group.
721
+ */
722
+ function normalizeOutput({ output, group, pluginName }) {
723
+ const mode = output.mode ?? "directory";
724
+ if (mode === "file" && group) throw new Diagnostics.Error({
725
+ code: diagnosticCode.invalidPluginOptions,
726
+ severity: "error",
727
+ message: `Plugin "${pluginName}" sets \`output.mode: 'file'\` but also configures a \`group\` option.`,
728
+ help: "A single-file output has nothing to group. Remove the `group` option, or use `output.mode: 'directory'` to organize files into subdirectories.",
729
+ location: { kind: "config" },
730
+ plugin: pluginName
731
+ });
732
+ return {
733
+ ...output,
734
+ mode
735
+ };
736
+ }
737
+ /**
738
+ * Wraps a plugin factory and returns a function that accepts user options and
739
+ * yields a typed `Plugin`. Lifecycle handlers go inside a single `hooks` object.
740
+ *
741
+ * Pass a `PluginFactoryOptions` type parameter to get a typed `ctx` inside
742
+ * `kubb:plugin:setup`. Plugin names should follow the `plugin-<feature>`
743
+ * convention (`plugin-react-query`, `plugin-zod`, ...).
744
+ *
745
+ * @example
746
+ * ```ts
747
+ * import { definePlugin } from '@kubb/core'
748
+ *
749
+ * export const pluginTs = definePlugin((options: { prefix?: string } = {}) => ({
750
+ * name: 'plugin-ts',
751
+ * hooks: {
752
+ * 'kubb:plugin:setup'(ctx) {
753
+ * ctx.setResolver(resolverTs)
754
+ * },
755
+ * },
756
+ * }))
521
757
  * ```
522
758
  */
523
- function createAdapter(build) {
524
- return (options) => build(options ?? {});
759
+ function definePlugin(factory) {
760
+ return (options) => factory(options ?? {});
525
761
  }
526
762
  //#endregion
527
- //#region package.json
528
- var version$1 = "5.0.0-beta.9";
763
+ //#region src/input.ts
764
+ /**
765
+ * Classifies an `input` value so callers branch on it once instead of repeating the checks.
766
+ *
767
+ * A non-string is a parsed spec (`object`). A string is `inline` when it holds OpenAPI content,
768
+ * meaning it starts with `{` or `[`, spans multiple lines, or opens with a YAML `openapi:` or
769
+ * `swagger:` key. Otherwise a string is a `url` when it parses as one, or a `file` path.
770
+ */
771
+ function getInputKind(input) {
772
+ if (typeof input !== "string") return "object";
773
+ const trimmed = input.trimStart();
774
+ if (trimmed.startsWith("{") || trimmed.startsWith("[") || input.includes("\n") || /^(openapi|swagger)\s*:/i.test(trimmed)) return "inline";
775
+ if (URL.canParse(input)) return "url";
776
+ return "file";
777
+ }
778
+ /**
779
+ * Normalizes `config.input` into an `AdapterSource` the adapter can parse.
780
+ *
781
+ * A parsed object and inline content become `{ type: 'data' }`; a URL is kept verbatim and a
782
+ * local path is resolved against `config.root`, both as `{ type: 'path' }`.
783
+ */
784
+ function inputToAdapterSource(config) {
785
+ const input = config.input;
786
+ if (!input) throw new Diagnostics.Error({
787
+ code: Diagnostics.code.inputRequired,
788
+ severity: "error",
789
+ message: "An adapter is configured without an input.",
790
+ help: "Set `input` to a file path, a URL, an inline spec (JSON/YAML string), or a parsed object in your Kubb config.",
791
+ location: { kind: "config" }
792
+ });
793
+ if (typeof input !== "string") return {
794
+ type: "data",
795
+ data: input
796
+ };
797
+ const kind = getInputKind(input);
798
+ if (kind === "inline") return {
799
+ type: "data",
800
+ data: input
801
+ };
802
+ if (kind === "url") return {
803
+ type: "path",
804
+ path: input
805
+ };
806
+ return {
807
+ type: "path",
808
+ path: resolve(config.root, input)
809
+ };
810
+ }
529
811
  //#endregion
530
- //#region ../../node_modules/.pnpm/yocto-queue@1.2.2/node_modules/yocto-queue/index.js
531
- var Node$1 = class {
532
- static {
533
- __name(this, "Node");
812
+ //#region src/Resolver.ts
813
+ function isNamespace(value) {
814
+ return typeof value === "object" && value !== null && !Array.isArray(value);
815
+ }
816
+ /**
817
+ * Shared brand for reaching a resolver's build options. `Resolver.merge` reads this instead of
818
+ * relying on `instanceof`, which fails when a CommonJS config and the ESM CLI each load their own
819
+ * copy of `@kubb/core`. `Symbol.for` resolves to one key across those copies, so the options stay
820
+ * reachable and a `file` override is never dropped.
821
+ */
822
+ const resolverOptions = Symbol.for("@kubb/core/resolver/options");
823
+ /**
824
+ * Built-in `file.baseName`: casts the identifier with `toFilePath` and appends the extension.
825
+ */
826
+ function toBaseName({ name, extname }) {
827
+ return `${toFilePath(name)}${extname}`;
828
+ }
829
+ /**
830
+ * Base constraint for all plugin resolver objects.
831
+ *
832
+ * The built-in machinery lives under `default`. Generators call the top-level `name` and
833
+ * `file`, and a plugin overrides them to set its conventions. Extend with top-level helpers
834
+ * (`typeName`, …) and/or grouped namespaces (`query`, `schema`, …).
835
+ *
836
+ * @example Top-level helper
837
+ * ```ts
838
+ * type MyResolver = Resolver & {
839
+ * typeName(name: string): string
840
+ * }
841
+ * ```
842
+ *
843
+ * @example Grouped namespace
844
+ * ```ts
845
+ * type MyResolver = Resolver & {
846
+ * query: {
847
+ * name(node: OperationNode): string
848
+ * keyName(node: OperationNode): string
849
+ * }
850
+ * }
851
+ * ```
852
+ */
853
+ var Resolver = class Resolver {
854
+ static #patternCache = /* @__PURE__ */ new Map();
855
+ static #optionsCache = /* @__PURE__ */ new WeakMap();
856
+ pluginName;
857
+ #options;
858
+ #baseName;
859
+ #filePath;
860
+ constructor(options) {
861
+ this.pluginName = options.pluginName;
862
+ this.#options = options;
863
+ this.#baseName = options.file?.baseName ? options.file.baseName.bind(this) : toBaseName;
864
+ this.#filePath = options.file?.path ? options.file.path.bind(this) : void 0;
865
+ this.#apply(options);
534
866
  }
535
- value;
536
- next;
537
- constructor(value) {
538
- this.value = value;
867
+ /** Exposes the raw build options so `Resolver.merge` can read them across `@kubb/core` copies. */
868
+ get [resolverOptions]() {
869
+ return this.#options;
539
870
  }
540
- };
541
- var Queue = class {
542
- #head;
543
- #tail;
544
- #size;
545
- constructor() {
546
- this.clear();
547
- }
548
- enqueue(value) {
549
- const node = new Node$1(value);
550
- if (this.#head) {
551
- this.#tail.next = node;
552
- this.#tail = node;
553
- } else {
554
- this.#head = node;
555
- this.#tail = node;
871
+ /**
872
+ * The built-in resolution machinery. Always reaches the untouched defaults, even when a
873
+ * plugin overrides the top-level `name` or `file`.
874
+ */
875
+ get default() {
876
+ return {
877
+ name: camelCase,
878
+ options: this.#resolveOptions.bind(this),
879
+ path: this.#resolvePath.bind(this),
880
+ file: this.#resolveFile.bind(this),
881
+ banner: this.#resolveBanner.bind(this),
882
+ footer: this.#resolveFooter.bind(this)
883
+ };
884
+ }
885
+ name(name) {
886
+ return this.default.name(name);
887
+ }
888
+ file(options) {
889
+ return this.#resolveFile(options);
890
+ }
891
+ /**
892
+ * Merges `override` over `base` and returns a new resolver with helpers re-bound. Top-level
893
+ * keys replace, and a namespace (or `file`) merges per method, so overriding `query.name`
894
+ * keeps the base `query.keyName`. Used when applying `setResolver` partial overrides. Reads a
895
+ * resolver's options through the shared brand rather than `instanceof`, so a `file` override
896
+ * survives even when `base` and `override` come from different `@kubb/core` copies.
897
+ */
898
+ static merge(base, override) {
899
+ const patch = resolverOptions in override ? override[resolverOptions] : override;
900
+ const merged = { ...base[resolverOptions] };
901
+ for (const [key, value] of Object.entries(patch)) {
902
+ if (value === void 0) continue;
903
+ const current = merged[key];
904
+ merged[key] = isNamespace(value) && isNamespace(current) ? {
905
+ ...current,
906
+ ...value
907
+ } : value;
556
908
  }
557
- this.#size++;
558
- }
559
- dequeue() {
560
- const current = this.#head;
561
- if (!current) return;
562
- this.#head = this.#head.next;
563
- this.#size--;
564
- if (!this.#head) this.#tail = void 0;
565
- return current.value;
566
- }
567
- peek() {
568
- if (!this.#head) return;
569
- return this.#head.value;
570
- }
571
- clear() {
572
- this.#head = void 0;
573
- this.#tail = void 0;
574
- this.#size = 0;
575
- }
576
- get size() {
577
- return this.#size;
578
- }
579
- *[Symbol.iterator]() {
580
- let current = this.#head;
581
- while (current) {
582
- yield current.value;
583
- current = current.next;
909
+ return new Resolver(merged);
910
+ }
911
+ /**
912
+ * Binds each entry of `options` onto the resolver, so `this.name`, `this.default`, and
913
+ * `this.file` resolve there for top-level helpers and namespace methods alike. `default`
914
+ * is skipped so it can't be shadowed.
915
+ */
916
+ #apply(options) {
917
+ const root = this;
918
+ const bind = (value) => typeof value === "function" ? value.bind(root) : value;
919
+ for (const [key, value] of Object.entries(options)) {
920
+ if (key === "pluginName" || key === "default" || key === "file" || value === void 0) continue;
921
+ root[key] = isNamespace(value) ? Object.fromEntries(Object.entries(value).map(([method, member]) => [method, bind(member)])) : bind(value);
922
+ }
923
+ }
924
+ static #testPattern(value, pattern) {
925
+ if (typeof pattern === "string") {
926
+ let regex = Resolver.#patternCache.get(pattern);
927
+ regex ??= new RegExp(pattern);
928
+ Resolver.#patternCache.set(pattern, regex);
929
+ return regex.test(value);
584
930
  }
931
+ return value.match(pattern) !== null;
585
932
  }
586
- *drain() {
587
- while (this.#head) yield this.dequeue();
933
+ static #matchesOperation(node, { type, pattern }) {
934
+ if (type === "tag") return node.tags.some((tag) => Resolver.#testPattern(tag, pattern));
935
+ if (type === "operationId") return Resolver.#testPattern(node.operationId, pattern);
936
+ if (type === "path") return node.path !== void 0 && Resolver.#testPattern(node.path, pattern);
937
+ if (type === "method") return node.method !== void 0 && Resolver.#testPattern(node.method.toLowerCase(), pattern);
938
+ if (type === "contentType") return node.requestBody?.content?.some((c) => Resolver.#testPattern(c.contentType, pattern)) ?? false;
939
+ return false;
588
940
  }
589
- };
590
- //#endregion
591
- //#region ../../node_modules/.pnpm/p-limit@7.3.0/node_modules/p-limit/index.js
592
- function pLimit(concurrency) {
593
- let rejectOnClear = false;
594
- if (typeof concurrency === "object") ({concurrency, rejectOnClear = false} = concurrency);
595
- validateConcurrency(concurrency);
596
- if (typeof rejectOnClear !== "boolean") throw new TypeError("Expected `rejectOnClear` to be a boolean");
597
- const queue = new Queue();
598
- let activeCount = 0;
599
- const resumeNext = () => {
600
- if (activeCount < concurrency && queue.size > 0) {
601
- activeCount++;
602
- queue.dequeue().run();
941
+ /**
942
+ * Returns `null` when the filter type doesn't apply to schemas, so include rules built
943
+ * from operation filters (e.g. `tag`) don't exclude every schema.
944
+ */
945
+ static #matchesSchema(node, { type, pattern }) {
946
+ if (type === "schemaName") return node.name ? Resolver.#testPattern(node.name, pattern) : false;
947
+ return null;
948
+ }
949
+ static #computeOptions(node, { options, exclude = [], include, override = [] }) {
950
+ if (operationDef.is(node)) {
951
+ if (exclude.some((filter) => Resolver.#matchesOperation(node, filter))) return null;
952
+ if (include && !include.some((filter) => Resolver.#matchesOperation(node, filter))) return null;
953
+ return {
954
+ ...options,
955
+ ...override.find((filter) => Resolver.#matchesOperation(node, filter))?.options
956
+ };
603
957
  }
604
- };
605
- const next = () => {
606
- activeCount--;
607
- resumeNext();
608
- };
609
- const run = async (function_, resolve, arguments_) => {
610
- const result = (async () => function_(...arguments_))();
611
- resolve(result);
612
- try {
613
- await result;
614
- } catch {}
615
- next();
616
- };
617
- const enqueue = (function_, resolve, reject, arguments_) => {
618
- const queueItem = { reject };
619
- new Promise((internalResolve) => {
620
- queueItem.run = internalResolve;
621
- queue.enqueue(queueItem);
622
- }).then(run.bind(void 0, function_, resolve, arguments_));
623
- if (activeCount < concurrency) resumeNext();
624
- };
625
- const generator = (function_, ...arguments_) => new Promise((resolve, reject) => {
626
- enqueue(function_, resolve, reject, arguments_);
627
- });
628
- Object.defineProperties(generator, {
629
- activeCount: { get: () => activeCount },
630
- pendingCount: { get: () => queue.size },
631
- clearQueue: { value() {
632
- if (!rejectOnClear) {
633
- queue.clear();
634
- return;
958
+ if (schemaDef.is(node)) {
959
+ if (exclude.some((filter) => Resolver.#matchesSchema(node, filter) === true)) return null;
960
+ if (include) {
961
+ const applicable = include.map((filter) => Resolver.#matchesSchema(node, filter)).filter((result) => result !== null);
962
+ if (applicable.length > 0 && !applicable.includes(true)) return null;
635
963
  }
636
- const abortError = AbortSignal.abort().reason;
637
- while (queue.size > 0) queue.dequeue().reject(abortError);
638
- } },
639
- concurrency: {
640
- get: () => concurrency,
641
- set(newConcurrency) {
642
- validateConcurrency(newConcurrency);
643
- concurrency = newConcurrency;
644
- queueMicrotask(() => {
645
- while (activeCount < concurrency && queue.size > 0) resumeNext();
646
- });
647
- }
648
- },
649
- map: { async value(iterable, function_) {
650
- const promises = Array.from(iterable, (value, index) => this(function_, value, index));
651
- return Promise.all(promises);
652
- } }
653
- });
654
- return generator;
655
- }
656
- function validateConcurrency(concurrency) {
657
- if (!((Number.isInteger(concurrency) || concurrency === Number.POSITIVE_INFINITY) && concurrency > 0)) throw new TypeError("Expected `concurrency` to be a number from 1 and up");
658
- }
964
+ return {
965
+ ...options,
966
+ ...override.find((filter) => Resolver.#matchesSchema(node, filter) === true)?.options
967
+ };
968
+ }
969
+ return options;
970
+ }
971
+ /**
972
+ * Applies include/exclude filters and merges matching override options, caching the result
973
+ * per `(options, node)` pair. Returns `null` when the node is filtered out.
974
+ */
975
+ #resolveOptions(node, context) {
976
+ const { options } = context;
977
+ if (typeof options !== "object" || options === null) return Resolver.#computeOptions(node, context);
978
+ let byOptions = Resolver.#optionsCache.get(options);
979
+ if (!byOptions) {
980
+ byOptions = /* @__PURE__ */ new WeakMap();
981
+ Resolver.#optionsCache.set(options, byOptions);
982
+ }
983
+ const cached = byOptions.get(node);
984
+ if (cached) return cached.value;
985
+ const result = Resolver.#computeOptions(node, context);
986
+ byOptions.set(node, { value: result });
987
+ return result;
988
+ }
989
+ /**
990
+ * A custom `group.name` wins; otherwise `tag` groups use the camelCased tag and `path`
991
+ * groups use the first non-traversal segment (`''` when none remain, placing the file in
992
+ * the output root, kept safe by the caller's boundary check).
993
+ */
994
+ static #resolveGroupDir(group, groupValue) {
995
+ if (group.name) return group.name({ group: groupValue });
996
+ if (group.type === "tag") return camelCase(groupValue);
997
+ const segment = groupValue.split("/").filter((part) => part !== "" && part !== "." && part !== "..")[0];
998
+ return segment ? camelCase(segment) : "";
999
+ }
1000
+ /**
1001
+ * `mode: 'file'` resolves directly to `output.path`. `mode: 'directory'` (default) resolves
1002
+ * to `output.path/{baseName}`, or into a subdirectory when `group` and a `tag`/`path` value
1003
+ * are provided.
1004
+ */
1005
+ #resolvePath({ baseName, tag, path: groupPath, root, output, group }) {
1006
+ if (output.mode === "file") return path.resolve(root, output.path);
1007
+ const outputDir = path.resolve(root, output.path);
1008
+ const result = group && (groupPath || tag) ? path.resolve(outputDir, Resolver.#resolveGroupDir(group, group.type === "path" ? groupPath : tag), baseName) : path.resolve(outputDir, baseName);
1009
+ const outputDirWithSep = outputDir.endsWith(path.sep) ? outputDir : `${outputDir}${path.sep}`;
1010
+ if (result !== outputDir && !result.startsWith(outputDirWithSep)) throw new Diagnostics.Error({
1011
+ code: Diagnostics.code.pathTraversal,
1012
+ severity: "error",
1013
+ message: `Resolved path "${result}" is outside the output directory "${outputDir}".`,
1014
+ help: "This can stem from a path traversal in the OpenAPI specification or a misconfigured `group.name` function. Keep generated paths within the output directory.",
1015
+ location: { kind: "config" }
1016
+ });
1017
+ return result;
1018
+ }
1019
+ /**
1020
+ * Resolves a resolver-supplied full path (`file.path`) against `root`, bypassing `output.path`
1021
+ * and `group`. The path may not escape `root`, which keeps a `file.path` that interpolates
1022
+ * spec-derived values from writing outside the project.
1023
+ */
1024
+ #resolveOverridePath(filePath, root) {
1025
+ const resolved = path.resolve(root, filePath);
1026
+ const rootWithSep = root.endsWith(path.sep) ? root : `${root}${path.sep}`;
1027
+ if (resolved !== root && !resolved.startsWith(rootWithSep)) throw new Diagnostics.Error({
1028
+ code: Diagnostics.code.pathTraversal,
1029
+ severity: "error",
1030
+ message: `Resolved path "${resolved}" is outside the project root "${root}".`,
1031
+ help: "A resolver `file.path` must return a path inside the project root.",
1032
+ location: { kind: "config" }
1033
+ });
1034
+ return resolved;
1035
+ }
1036
+ /**
1037
+ * Builds a `FileNode`. When `#filePath` (the resolver's `file.path`) is set it owns the whole
1038
+ * path; otherwise the base name (from `#baseName`, the resolver's `file.baseName` or the
1039
+ * built-in `toBaseName`) is placed by the `output.path`/`group` layout. The resolved file starts
1040
+ * with empty `sources`, `imports`, and `exports`, which consumers populate separately.
1041
+ */
1042
+ #resolveFile(options) {
1043
+ const { name, extname, tag, path: groupPath, root, output, group } = options;
1044
+ const baseName = this.#baseName({
1045
+ name,
1046
+ extname
1047
+ });
1048
+ const filePath = this.#filePath ? this.#resolveOverridePath(this.#filePath({
1049
+ baseName,
1050
+ output
1051
+ }), root) : this.#resolvePath({
1052
+ baseName,
1053
+ tag,
1054
+ path: groupPath,
1055
+ root,
1056
+ output,
1057
+ group
1058
+ });
1059
+ return ast.factory.createFile({
1060
+ path: filePath,
1061
+ baseName: path.basename(filePath),
1062
+ meta: { pluginName: this.pluginName },
1063
+ sources: [],
1064
+ imports: [],
1065
+ exports: []
1066
+ });
1067
+ }
1068
+ /**
1069
+ * Missing fields default to empty/`false` so the `BannerMeta` shape stays stable even when
1070
+ * a caller (e.g. the barrel plugin) has no document metadata.
1071
+ */
1072
+ static #buildBannerMeta(meta, file) {
1073
+ return {
1074
+ title: meta?.title,
1075
+ description: meta?.description,
1076
+ version: meta?.version,
1077
+ baseURL: meta?.baseURL,
1078
+ circularNames: meta?.circularNames ?? [],
1079
+ enumNames: meta?.enumNames ?? [],
1080
+ filePath: file?.path ?? "",
1081
+ baseName: file?.baseName ?? "",
1082
+ isBarrel: file?.isBarrel ?? false,
1083
+ isAggregation: file?.isAggregation ?? false
1084
+ };
1085
+ }
1086
+ /**
1087
+ * Resolves a user-configured banner/footer value. `undefined` means not configured.
1088
+ */
1089
+ static #resolveUserText(value, meta, file) {
1090
+ if (typeof value === "function") return value(Resolver.#buildBannerMeta(meta, file));
1091
+ if (typeof value === "string") return value;
1092
+ }
1093
+ static #buildDefaultBanner({ title, version, config }) {
1094
+ const lines = [
1095
+ "/**",
1096
+ "* Generated by Kubb (https://kubb.dev/).",
1097
+ "* Do not edit manually."
1098
+ ];
1099
+ if (config.output.defaultBanner !== "simple") {
1100
+ const input = config.input;
1101
+ let source = "";
1102
+ if (typeof input === "string") source = getInputKind(input) === "inline" ? "text content" : path.basename(input);
1103
+ else if (input) source = "text content";
1104
+ if (source) lines.push(`* Source: ${source}`);
1105
+ if (title) lines.push(`* Title: ${title}`);
1106
+ if (version) lines.push(`* OpenAPI spec version: ${version}`);
1107
+ }
1108
+ return `${lines.join("\n")}\n*/\n`;
1109
+ }
1110
+ /**
1111
+ * A user-supplied `output.banner` overrides the default Kubb notice. When
1112
+ * `config.output.defaultBanner` is `false` and no user banner is set, returns `null`.
1113
+ */
1114
+ #resolveBanner(meta, { output, config, file }) {
1115
+ const userBanner = Resolver.#resolveUserText(output?.banner, meta, file);
1116
+ if (userBanner !== void 0) return userBanner;
1117
+ if (config.output.defaultBanner === false) return null;
1118
+ return Resolver.#buildDefaultBanner({
1119
+ title: meta?.title,
1120
+ version: meta?.version,
1121
+ config
1122
+ });
1123
+ }
1124
+ #resolveFooter(meta, { output, file }) {
1125
+ return Resolver.#resolveUserText(output?.footer, meta, file) ?? null;
1126
+ }
1127
+ };
659
1128
  //#endregion
660
- //#region src/FileProcessor.ts
661
- function joinSources(file) {
662
- return file.sources.map((item) => extractStringsFromNodes(item.nodes)).filter(Boolean).join("\n\n");
1129
+ //#region src/createResolver.ts
1130
+ /**
1131
+ * Defines a plugin resolver, the object that decides what every generated symbol and file
1132
+ * path is called. Override the top-level `name` and `file` to set the plugin's conventions,
1133
+ * and add your own naming helpers, top-level (`typeName`, …) or grouped in namespaces
1134
+ * (`query`, `schema`, …). Every method reaches sibling helpers and the built-in machinery
1135
+ * through `this.name`, `this.file`, and `this.default`.
1136
+ *
1137
+ * @example Custom identifier casing
1138
+ * ```ts
1139
+ * export const resolverTs = createResolver<PluginTs>({
1140
+ * pluginName: 'plugin-ts',
1141
+ * name(name) {
1142
+ * return ensureValidVarName(pascalCase(name))
1143
+ * },
1144
+ * })
1145
+ * ```
1146
+ *
1147
+ * @example Rename generated files with `file.baseName`
1148
+ * ```ts
1149
+ * export const resolverFaker = createResolver<PluginFaker>({
1150
+ * pluginName: 'plugin-faker',
1151
+ * name(name) {
1152
+ * return camelCase(name, { prefix: 'create' })
1153
+ * },
1154
+ * file: {
1155
+ * baseName({ name, extname }) {
1156
+ * return `${camelCase(name, { prefix: 'create' })}${extname}`
1157
+ * },
1158
+ * },
1159
+ * })
1160
+ * ```
1161
+ *
1162
+ * @example Own the full path with `file.path`
1163
+ * ```ts
1164
+ * export const resolverFaker = createResolver<PluginFaker>({
1165
+ * pluginName: 'plugin-faker',
1166
+ * file: {
1167
+ * path({ baseName, output }) {
1168
+ * return `${output.path}/mocks/${baseName}`
1169
+ * },
1170
+ * },
1171
+ * })
1172
+ * ```
1173
+ */
1174
+ function createResolver(options) {
1175
+ return new Resolver(options);
663
1176
  }
1177
+ //#endregion
1178
+ //#region src/Transform.ts
664
1179
  /**
665
- * Converts a single file to a string using the registered parsers.
666
- * Falls back to joining source values when no matching parser is found.
1180
+ * Holds an ordered list of macros per plugin, keyed by plugin name. Each plugin's macros run in
1181
+ * isolation on the original adapter node and are composed into a single `Visitor` that the
1182
+ * `@kubb/ast` `transform` primitive applies. `applyTo` is a per-plugin lookup, not a cross-plugin
1183
+ * chain, so plugin A's macros never see plugin B's output. When a plugin has no macros, `applyTo`
1184
+ * returns the original node reference, and `transform` does the same when the composed visitor
1185
+ * leaves the tree untouched, so callers can detect a no-op by identity.
667
1186
  *
668
- * @internal
1187
+ * Registration order matches the order setup hooks fire, which the driver has already sorted by
1188
+ * `enforce` and dependency edges. The registry preserves that order. Macro `enforce` only reorders
1189
+ * within a single plugin's list.
669
1190
  */
670
- var FileProcessor = class {
671
- #limit = pLimit(100);
672
- async parse(file, { parsers, extension } = {}) {
673
- const parseExtName = extension?.[file.extname] || void 0;
674
- if (!parsers || !file.extname) return joinSources(file);
675
- const parser = parsers.get(file.extname);
676
- if (!parser) return joinSources(file);
677
- return parser.parse(file, { extname: parseExtName });
678
- }
679
- async run(files, { parsers, mode = "sequential", extension, onStart, onEnd, onUpdate } = {}) {
680
- await onStart?.(files);
681
- const total = files.length;
682
- let processed = 0;
683
- const processOne = async (file) => {
684
- const source = await this.parse(file, {
685
- extension,
686
- parsers
1191
+ var Transform = class {
1192
+ #macros = /* @__PURE__ */ new Map();
1193
+ #composed = /* @__PURE__ */ new Map();
1194
+ #memo = /* @__PURE__ */ new Map();
1195
+ /**
1196
+ * Appends `macro` to the plugin's list, after any macros already registered.
1197
+ */
1198
+ add(pluginName, macro) {
1199
+ const list = this.#macros.get(pluginName);
1200
+ if (list) list.push(macro);
1201
+ else this.#macros.set(pluginName, [macro]);
1202
+ this.#invalidate(pluginName);
1203
+ }
1204
+ /**
1205
+ * Replaces the plugin's macro list with `macros`.
1206
+ */
1207
+ set(pluginName, macros) {
1208
+ this.#macros.set(pluginName, [...macros]);
1209
+ this.#invalidate(pluginName);
1210
+ }
1211
+ /**
1212
+ * Runs the plugin's macros on `node`. Returns the original node reference when the plugin has no
1213
+ * macros, so callers can compare by identity to detect a no-op.
1214
+ */
1215
+ applyTo(pluginName, node) {
1216
+ const visitor = this.#visitorFor(pluginName);
1217
+ if (!visitor) return node;
1218
+ let memo = this.#memo.get(pluginName);
1219
+ if (!memo) {
1220
+ memo = /* @__PURE__ */ new WeakMap();
1221
+ this.#memo.set(pluginName, memo);
1222
+ }
1223
+ const cached = memo.get(node);
1224
+ if (cached) return cached;
1225
+ const result = transform(node, visitor);
1226
+ memo.set(node, result);
1227
+ return result;
1228
+ }
1229
+ /**
1230
+ * Clears every registration. Called from the driver's `dispose()` so macros do not leak across
1231
+ * builds.
1232
+ */
1233
+ dispose() {
1234
+ this.#macros.clear();
1235
+ this.#composed.clear();
1236
+ this.#memo.clear();
1237
+ }
1238
+ #invalidate(pluginName) {
1239
+ this.#composed.delete(pluginName);
1240
+ this.#memo.delete(pluginName);
1241
+ }
1242
+ #visitorFor(pluginName) {
1243
+ const macros = this.#macros.get(pluginName);
1244
+ if (!macros || macros.length === 0) return void 0;
1245
+ let composed = this.#composed.get(pluginName);
1246
+ if (!composed) {
1247
+ composed = composeMacros(macros);
1248
+ this.#composed.set(pluginName, composed);
1249
+ }
1250
+ return composed;
1251
+ }
1252
+ };
1253
+ //#endregion
1254
+ //#region src/KubbDriver.ts
1255
+ const ENFORCE_ORDER = {
1256
+ pre: -1,
1257
+ post: 1
1258
+ };
1259
+ const enforceWeight = (plugin) => plugin.enforce ? ENFORCE_ORDER[plugin.enforce] : 0;
1260
+ var KubbDriver = class {
1261
+ config;
1262
+ options;
1263
+ /**
1264
+ * The `InputNode` produced by the adapter. Set after adapter setup.
1265
+ */
1266
+ inputNode = null;
1267
+ adapter = null;
1268
+ /**
1269
+ * Raw adapter source so `adapter.parse()` can run lazily.
1270
+ * Intentionally outlives the build, cleared by `dispose()`.
1271
+ */
1272
+ #adapterSource = null;
1273
+ /**
1274
+ * Central file store for all generated files.
1275
+ * Plugins should use `this.addFile()` / `this.upsertFile()` (via their context) to
1276
+ * add files. This property gives direct read/write access when needed.
1277
+ */
1278
+ fileManager = new FileManager();
1279
+ plugins = /* @__PURE__ */ new Map();
1280
+ /**
1281
+ * Tracks which plugins have generators registered via `addGenerator()` (hook-based path).
1282
+ * Used by the build loop to decide whether to emit generator hooks for a given plugin.
1283
+ */
1284
+ #hookGeneratorPlugins = /* @__PURE__ */ new Set();
1285
+ #resolvers = /* @__PURE__ */ new Map();
1286
+ #defaultResolvers = /* @__PURE__ */ new Map();
1287
+ /**
1288
+ * Removers for every listener the driver added (plugin, generator) so `dispose()` can detach
1289
+ * them in one pass. External `hooks.hook(...)` listeners are not tracked.
1290
+ */
1291
+ #unhooks = [];
1292
+ /**
1293
+ * Transform registry. Plugins populate it during `kubb:plugin:setup` via `addMacro`/`setMacros`,
1294
+ * and `#runGenerators` reads it once per `(plugin, node)` pair through `applyTo`.
1295
+ */
1296
+ #transforms = new Transform();
1297
+ constructor(config, options) {
1298
+ this.config = config;
1299
+ this.options = options;
1300
+ this.adapter = config.adapter ?? null;
1301
+ }
1302
+ /**
1303
+ * Normalizes every configured plugin, orders them, and registers their lifecycle handlers.
1304
+ * A plugin that another lists as a dependency runs first, then `enforce: 'pre'` before
1305
+ * `'post'`. When the config has an adapter, the adapter source is resolved from the input
1306
+ * so `run` can parse it later.
1307
+ */
1308
+ async setup() {
1309
+ const normalized = this.#sortPlugins(this.config.plugins.map((rawPlugin) => {
1310
+ return {
1311
+ name: rawPlugin.name,
1312
+ dependencies: rawPlugin.dependencies,
1313
+ enforce: rawPlugin.enforce,
1314
+ hooks: rawPlugin.hooks,
1315
+ options: rawPlugin.options ?? {
1316
+ output: {
1317
+ path: ".",
1318
+ mode: "directory"
1319
+ },
1320
+ exclude: [],
1321
+ override: []
1322
+ }
1323
+ };
1324
+ }));
1325
+ for (const plugin of normalized) {
1326
+ this.#registerPlugin(plugin);
1327
+ this.plugins.set(plugin.name, plugin);
1328
+ }
1329
+ if (this.config.adapter) this.#adapterSource = inputToAdapterSource(this.config);
1330
+ }
1331
+ /**
1332
+ * Orders plugins so every dependency runs before its dependents (Kahn's algorithm), with
1333
+ * `enforce` (`'pre'` before normal before `'post'`) and declaration order as tiebreaks.
1334
+ * A pairwise `Array.sort` comparator cannot do this: dependency relations are not transitive
1335
+ * at the comparator level, so a chain where A depends on B and B depends on C could come out
1336
+ * wrong when A and C are never compared directly. Dependencies on plugins missing from the
1337
+ * config are ignored here and surface later through `requirePlugin`.
1338
+ */
1339
+ #sortPlugins(plugins) {
1340
+ const queue = [...plugins].sort((a, b) => enforceWeight(a) - enforceWeight(b));
1341
+ const names = new Set(queue.map((plugin) => plugin.name));
1342
+ const blockedBy = new Map(queue.map((plugin) => [plugin.name, new Set(plugin.dependencies?.filter((name) => names.has(name) && name !== plugin.name))]));
1343
+ const sorted = [];
1344
+ for (const _ of plugins) {
1345
+ const index = queue.findIndex((plugin) => blockedBy.get(plugin.name)?.size === 0);
1346
+ if (index === -1) throw new Diagnostics.Error({
1347
+ code: Diagnostics.code.invalidPluginOptions,
1348
+ severity: "error",
1349
+ message: `Plugin dependencies form a cycle: ${queue.map((plugin) => plugin.name).join(" → ")}.`,
1350
+ help: "Remove one of the `dependencies` entries so the plugins can be ordered.",
1351
+ location: { kind: "config" }
687
1352
  });
688
- const currentProcessed = ++processed;
689
- const percentage = currentProcessed / total * 100;
690
- await onUpdate?.({
691
- file,
692
- source,
693
- processed: currentProcessed,
694
- percentage,
695
- total
1353
+ const [plugin] = queue.splice(index, 1);
1354
+ if (!plugin) break;
1355
+ sorted.push(plugin);
1356
+ for (const blockers of blockedBy.values()) blockers.delete(plugin.name);
1357
+ }
1358
+ return sorted;
1359
+ }
1360
+ get hooks() {
1361
+ return this.options.hooks;
1362
+ }
1363
+ /**
1364
+ * Parses the adapter source into `this.inputNode`. Idempotent, so repeated calls from
1365
+ * `run` do not re-parse.
1366
+ */
1367
+ async #parseInput() {
1368
+ if (this.inputNode || !this.adapter || !this.#adapterSource) return;
1369
+ this.inputNode = await this.adapter.parse(this.#adapterSource);
1370
+ }
1371
+ /**
1372
+ * Registers a plugin's lifecycle hooks on the shared `Hookable` as pass-through listeners that
1373
+ * external tooling can observe via `hooks.hook(...)`. The returned remover is tracked for
1374
+ * `dispose`. `kubb:plugin:setup` is skipped here; `setupHooks` invokes it directly with a
1375
+ * plugin-scoped context.
1376
+ *
1377
+ * @internal
1378
+ */
1379
+ #registerPlugin(plugin) {
1380
+ const { hooks } = plugin;
1381
+ if (!hooks) return;
1382
+ const { "kubb:plugin:setup": _setup, ...configHooks } = hooks;
1383
+ this.#unhooks.push(this.hooks.addHooks(configHooks));
1384
+ }
1385
+ /**
1386
+ * Runs each plugin's `kubb:plugin:setup` handler, in plugin order, with a context scoped to that
1387
+ * plugin so `addGenerator`, `setResolver`, `addMacro`, `setMacros`, and `setOptions` target its
1388
+ * `NormalizedPlugin` entry. Called once from `run` before the plugin execution loop begins, so
1389
+ * plugins can configure generators, resolvers, macros, and options before `buildStart`.
1390
+ */
1391
+ async setupHooks() {
1392
+ for (const plugin of this.plugins.values()) {
1393
+ const setup = plugin.hooks?.["kubb:plugin:setup"];
1394
+ if (!setup) continue;
1395
+ await setup({
1396
+ config: this.config,
1397
+ options: plugin.options ?? {},
1398
+ addGenerator: (...generators) => {
1399
+ for (const generator of generators) this.registerGenerator(plugin.name, generator);
1400
+ },
1401
+ setResolver: (resolver) => {
1402
+ this.setPluginResolver(plugin.name, resolver);
1403
+ },
1404
+ addMacro: (macro) => {
1405
+ this.#transforms.add(plugin.name, macro);
1406
+ },
1407
+ setMacros: (macros) => {
1408
+ this.#transforms.set(plugin.name, macros);
1409
+ },
1410
+ setOptions: (opts) => {
1411
+ plugin.options = {
1412
+ ...plugin.options,
1413
+ ...opts
1414
+ };
1415
+ if (plugin.options.output) {
1416
+ const group = "group" in plugin.options ? plugin.options.group : void 0;
1417
+ plugin.options.output = normalizeOutput({
1418
+ output: plugin.options.output,
1419
+ group,
1420
+ pluginName: plugin.name
1421
+ });
1422
+ }
1423
+ },
1424
+ injectFile: (userFileNode) => {
1425
+ this.fileManager.add(ast.factory.createFile(userFileNode));
1426
+ }
696
1427
  });
1428
+ }
1429
+ }
1430
+ /**
1431
+ * Registers a generator for the given plugin on the shared hook emitter.
1432
+ *
1433
+ * The generator's `schema`, `operation`, and `operations` methods are registered as
1434
+ * listeners on `kubb:generate:schema`, `kubb:generate:operation`, and `kubb:generate:operations`
1435
+ * respectively. Each listener is scoped to the owning plugin via a `ctx.plugin.name` check
1436
+ * so that generators from different plugins do not cross-fire.
1437
+ *
1438
+ * The renderer comes from `generator.renderer`. Set `generator.renderer = null` (or leave it
1439
+ * unset) to opt out of rendering.
1440
+ *
1441
+ * Call this method inside `addGenerator()` (in `kubb:plugin:setup`) to wire up a generator.
1442
+ */
1443
+ registerGenerator(pluginName, generator) {
1444
+ const wrap = (method) => {
1445
+ if (!method) return void 0;
1446
+ return async (node, ctx) => {
1447
+ if (ctx.plugin.name !== pluginName) return;
1448
+ const result = await method(node, ctx);
1449
+ await this.dispatch({
1450
+ result,
1451
+ renderer: generator.renderer
1452
+ });
1453
+ };
1454
+ };
1455
+ this.#unhooks.push(this.hooks.addHooks({
1456
+ "kubb:generate:schema": wrap(generator.schema),
1457
+ "kubb:generate:operation": wrap(generator.operation),
1458
+ "kubb:generate:operations": wrap(generator.operations)
1459
+ }));
1460
+ this.#hookGeneratorPlugins.add(pluginName);
1461
+ }
1462
+ /**
1463
+ * Returns `true` when at least one generator was registered for the given plugin
1464
+ * via `addGenerator()` in `kubb:plugin:setup`.
1465
+ *
1466
+ * Used by the build loop to decide whether to walk the AST and emit generator hooks
1467
+ * for a plugin.
1468
+ */
1469
+ hasHookGenerators(pluginName) {
1470
+ return this.#hookGeneratorPlugins.has(pluginName);
1471
+ }
1472
+ /**
1473
+ * Runs the full plugin pipeline. Returns the diagnostics collected so far even
1474
+ * when an outer hook throws, since the orchestrator preserves partial state by capturing
1475
+ * the failure as a {@link Diagnostic} instead of propagating. Each plugin also
1476
+ * contributes a `timing` diagnostic for the run summary.
1477
+ */
1478
+ async run() {
1479
+ const { hooks, config, fileManager } = this;
1480
+ const diagnostics = [];
1481
+ const parsersMap = /* @__PURE__ */ new Map();
1482
+ for (const parser of config.parsers) if (parser.extNames) for (const ext of parser.extNames) parsersMap.set(ext, parser);
1483
+ const onWriteStart = async (files) => {
1484
+ await hooks.callHook("kubb:files:processing:start", { files });
1485
+ };
1486
+ const updateBuffer = [];
1487
+ const onWriteUpdate = (item) => {
1488
+ updateBuffer.push(item);
1489
+ };
1490
+ const onWriteEnd = async (files) => {
1491
+ await hooks.callHook("kubb:files:processing:update", { files: updateBuffer.map((item) => ({
1492
+ ...item,
1493
+ config
1494
+ })) });
1495
+ updateBuffer.length = 0;
1496
+ await hooks.callHook("kubb:files:processing:end", { files });
1497
+ };
1498
+ const unhookWrites = fileManager.hooks.addHooks({
1499
+ start: onWriteStart,
1500
+ update: onWriteUpdate,
1501
+ end: onWriteEnd
1502
+ });
1503
+ return Diagnostics.scope((diagnostic) => diagnostics.push(diagnostic), async () => {
1504
+ try {
1505
+ const outputRoot = resolve(config.root, config.output.path);
1506
+ await this.#parseInput();
1507
+ await this.setupHooks();
1508
+ if (this.adapter && this.inputNode) await hooks.callHook("kubb:build:start", Object.assign({
1509
+ config,
1510
+ adapter: this.adapter,
1511
+ meta: this.inputNode.meta,
1512
+ getPlugin: this.getPlugin.bind(this)
1513
+ }, this.#filesPayload()));
1514
+ const generatorPlugins = [];
1515
+ for (const plugin of this.plugins.values()) {
1516
+ const context = this.getContext(plugin);
1517
+ const hrStart = process.hrtime();
1518
+ try {
1519
+ await hooks.callHook("kubb:plugin:start", { plugin });
1520
+ } catch (caughtError) {
1521
+ const error = toError(caughtError);
1522
+ const duration = getElapsedMs(hrStart);
1523
+ await this.#emitPluginEnd({
1524
+ plugin,
1525
+ duration,
1526
+ success: false,
1527
+ error
1528
+ });
1529
+ diagnostics.push({
1530
+ ...Diagnostics.from(error),
1531
+ plugin: plugin.name
1532
+ }, Diagnostics.performance({
1533
+ plugin: plugin.name,
1534
+ duration
1535
+ }));
1536
+ continue;
1537
+ }
1538
+ if (this.hasHookGenerators(plugin.name)) {
1539
+ generatorPlugins.push({
1540
+ plugin,
1541
+ context,
1542
+ hrStart
1543
+ });
1544
+ continue;
1545
+ }
1546
+ const duration = getElapsedMs(hrStart);
1547
+ diagnostics.push(Diagnostics.performance({
1548
+ plugin: plugin.name,
1549
+ duration
1550
+ }));
1551
+ await this.#emitPluginEnd({
1552
+ plugin,
1553
+ duration,
1554
+ success: true
1555
+ });
1556
+ }
1557
+ diagnostics.push(...await this.#runGenerators(generatorPlugins));
1558
+ await hooks.callHook("kubb:plugins:end", Object.assign({ config }, this.#filesPayload()));
1559
+ await fileManager.write(fileManager.files, {
1560
+ storage: config.storage,
1561
+ parsers: parsersMap
1562
+ });
1563
+ await hooks.callHook("kubb:build:end", {
1564
+ files: this.fileManager.files,
1565
+ config,
1566
+ outputDir: outputRoot
1567
+ });
1568
+ return { diagnostics: Diagnostics.dedupe(diagnostics) };
1569
+ } catch (caughtError) {
1570
+ diagnostics.push(Diagnostics.from(caughtError));
1571
+ return { diagnostics: Diagnostics.dedupe(diagnostics) };
1572
+ } finally {
1573
+ unhookWrites();
1574
+ }
1575
+ });
1576
+ }
1577
+ #filesPayload() {
1578
+ const driver = this;
1579
+ return {
1580
+ get files() {
1581
+ return driver.fileManager.files;
1582
+ },
1583
+ upsertFile: (...files) => driver.fileManager.upsert(...files)
697
1584
  };
698
- if (mode === "sequential") for (const file of files) await processOne(file);
699
- else await Promise.all(files.map((file) => this.#limit(() => processOne(file))));
700
- await onEnd?.(files);
701
- return files;
1585
+ }
1586
+ #emitPluginEnd({ plugin, duration, success, error }) {
1587
+ return this.hooks.callHook("kubb:plugin:end", Object.assign({
1588
+ plugin,
1589
+ duration,
1590
+ success,
1591
+ ...error ? { error } : {},
1592
+ config: this.config
1593
+ }, this.#filesPayload()));
1594
+ }
1595
+ /**
1596
+ * Runs schemas and operations through every plugin's generators. Each node is run
1597
+ * through the plugin's macros (from `this.#transforms`) before the generator sees it,
1598
+ * so plugins stay isolated and the hot path stays per-node. Schemas run before operations
1599
+ * so file output stays deterministic across runs.
1600
+ * A failing plugin contributes an error diagnostic so the rest of the build continues.
1601
+ * Every plugin also contributes a `timing` diagnostic.
1602
+ *
1603
+ * Plugins are processed one at a time, in full, so `kubb:plugin:end` fires as each one
1604
+ * completes rather than all at once at the end. That ordering drives the CLI's
1605
+ * `Plugins N/M` counter.
1606
+ *
1607
+ * When `this.inputNode` is `null`, every entry still gets a `kubb:plugin:end` so
1608
+ * post-plugin listeners (the barrel writer and friends) complete.
1609
+ */
1610
+ async #runGenerators(entries) {
1611
+ const diagnostics = [];
1612
+ if (entries.length === 0) return diagnostics;
1613
+ if (!this.inputNode) {
1614
+ for (const { plugin, hrStart } of entries) {
1615
+ const duration = getElapsedMs(hrStart);
1616
+ diagnostics.push(Diagnostics.performance({
1617
+ plugin: plugin.name,
1618
+ duration
1619
+ }));
1620
+ await this.#emitPluginEnd({
1621
+ plugin,
1622
+ duration,
1623
+ success: true
1624
+ });
1625
+ }
1626
+ return diagnostics;
1627
+ }
1628
+ const transforms = this.#transforms;
1629
+ const { schemas, operations } = this.inputNode;
1630
+ const emitsSchemaHook = this.hooks.listenerCount("kubb:generate:schema") > 0;
1631
+ const emitsOperationHook = this.hooks.listenerCount("kubb:generate:operation") > 0;
1632
+ const emitsOperationsHook = this.hooks.listenerCount("kubb:generate:operations") > 0;
1633
+ const allowedSchemaNamesByPlugin = /* @__PURE__ */ new Map();
1634
+ for (const { plugin } of entries) {
1635
+ const { exclude, include, override } = plugin.options;
1636
+ if (!((include?.some(({ type }) => OPERATION_FILTER_TYPES.has(type)) ?? false) && !(include?.some(({ type }) => type === "schemaName") ?? false))) continue;
1637
+ const resolver = this.getResolver(plugin.name);
1638
+ const includedOps = operations.filter((operation) => resolver.default.options(operation, {
1639
+ options: plugin.options,
1640
+ exclude,
1641
+ include,
1642
+ override
1643
+ }) !== null);
1644
+ allowedSchemaNamesByPlugin.set(plugin.name, collectUsedSchemaNames(includedOps, schemas));
1645
+ }
1646
+ for (const { plugin, context, hrStart } of entries) {
1647
+ const generatorContext = {
1648
+ ...context,
1649
+ resolver: this.getResolver(plugin.name)
1650
+ };
1651
+ const { exclude, include, override } = plugin.options;
1652
+ const optionsAreStatic = !exclude?.length && !include?.length && !override?.length;
1653
+ const allowedSchemaNames = allowedSchemaNamesByPlugin.get(plugin.name) ?? null;
1654
+ let error = null;
1655
+ const resolveForPlugin = (node) => {
1656
+ const transformedNode = transforms.applyTo(plugin.name, node);
1657
+ if (optionsAreStatic) return {
1658
+ transformedNode,
1659
+ options: plugin.options
1660
+ };
1661
+ const options = generatorContext.resolver.default.options(transformedNode, {
1662
+ options: plugin.options,
1663
+ exclude,
1664
+ include,
1665
+ override
1666
+ });
1667
+ if (options === null) return null;
1668
+ return {
1669
+ transformedNode,
1670
+ options
1671
+ };
1672
+ };
1673
+ if (emitsSchemaHook) for (const node of schemas) {
1674
+ if (error) break;
1675
+ try {
1676
+ const resolved = resolveForPlugin(node);
1677
+ if (!resolved) continue;
1678
+ const { transformedNode, options } = resolved;
1679
+ if (allowedSchemaNames !== null && transformedNode.name && !allowedSchemaNames.has(transformedNode.name)) continue;
1680
+ await this.hooks.callHook("kubb:generate:schema", transformedNode, {
1681
+ ...generatorContext,
1682
+ options
1683
+ });
1684
+ } catch (caughtError) {
1685
+ error = toError(caughtError);
1686
+ }
1687
+ }
1688
+ if (emitsOperationHook) for (const node of operations) {
1689
+ if (error) break;
1690
+ try {
1691
+ const resolved = resolveForPlugin(node);
1692
+ if (!resolved) continue;
1693
+ await this.hooks.callHook("kubb:generate:operation", resolved.transformedNode, {
1694
+ ...generatorContext,
1695
+ options: resolved.options
1696
+ });
1697
+ } catch (caughtError) {
1698
+ error = toError(caughtError);
1699
+ }
1700
+ }
1701
+ if (!error && emitsOperationsHook) try {
1702
+ const ctx = {
1703
+ ...generatorContext,
1704
+ options: plugin.options
1705
+ };
1706
+ const pluginOperations = operations.reduce((acc, node) => {
1707
+ const resolved = resolveForPlugin(node);
1708
+ if (resolved) acc.push(resolved.transformedNode);
1709
+ return acc;
1710
+ }, []);
1711
+ await this.hooks.callHook("kubb:generate:operations", pluginOperations, ctx);
1712
+ } catch (caughtError) {
1713
+ error = toError(caughtError);
1714
+ }
1715
+ const duration = getElapsedMs(hrStart);
1716
+ await this.#emitPluginEnd({
1717
+ plugin,
1718
+ duration,
1719
+ success: !error,
1720
+ error: error ?? void 0
1721
+ });
1722
+ if (error) diagnostics.push({
1723
+ ...Diagnostics.from(error),
1724
+ plugin: plugin.name
1725
+ });
1726
+ diagnostics.push(Diagnostics.performance({
1727
+ plugin: plugin.name,
1728
+ duration
1729
+ }));
1730
+ }
1731
+ return diagnostics;
1732
+ }
1733
+ /**
1734
+ * Stores whatever a generator method or `kubb:generate:*` hook returned.
1735
+ *
1736
+ * - An `Array<FileNode>` goes straight into `fileManager` via `upsert`.
1737
+ * - A renderer element runs through `renderer` (the renderer factory, e.g. JSX) and the
1738
+ * produced files go to `fileManager.upsert`.
1739
+ * - A falsy result is treated as a no-op. The generator wrote files itself via
1740
+ * `ctx.upsertFile`.
1741
+ *
1742
+ * Pass `renderer` when the result may be a renderer element. Generators that only return
1743
+ * `Array<FileNode>` do not need one.
1744
+ */
1745
+ async dispatch({ result, renderer }) {
1746
+ try {
1747
+ var _usingCtx$2 = _usingCtx();
1748
+ if (!result) return;
1749
+ if (Array.isArray(result)) {
1750
+ this.fileManager.upsert(...result);
1751
+ return;
1752
+ }
1753
+ if (!renderer) return;
1754
+ const instance = _usingCtx$2.u(renderer());
1755
+ await instance.render(result);
1756
+ this.fileManager.upsert(...instance.files);
1757
+ } catch (_) {
1758
+ _usingCtx$2.e = _;
1759
+ } finally {
1760
+ _usingCtx$2.d();
1761
+ }
1762
+ }
1763
+ /**
1764
+ * Removes every listener the driver added. Listeners attached directly to `hooks` from outside
1765
+ * the driver survive. Called at the end of a build to prevent leaks across repeated builds.
1766
+ *
1767
+ * @internal
1768
+ */
1769
+ dispose() {
1770
+ for (const unhook of this.#unhooks) unhook();
1771
+ this.#unhooks.length = 0;
1772
+ this.#hookGeneratorPlugins.clear();
1773
+ this.#transforms.dispose();
1774
+ this.#resolvers.clear();
1775
+ this.#defaultResolvers.clear();
1776
+ this.fileManager.dispose();
1777
+ this.inputNode = null;
1778
+ this.#adapterSource = null;
1779
+ }
1780
+ [Symbol.dispose]() {
1781
+ this.dispose();
1782
+ }
1783
+ #getDefaultResolver = memoize(this.#defaultResolvers, (pluginName) => createResolver({ pluginName }));
1784
+ /**
1785
+ * Merges `partial` with the plugin's default resolver and stores the result.
1786
+ * Also mirrors it onto `plugin.resolver` so callers using `getPlugin(name).resolver`
1787
+ * get the up-to-date resolver without going through `getResolver()`.
1788
+ */
1789
+ setPluginResolver(pluginName, partial) {
1790
+ const defaultResolver = this.#getDefaultResolver(pluginName);
1791
+ const merged = Resolver.merge(defaultResolver, partial);
1792
+ this.#resolvers.set(pluginName, merged);
1793
+ const plugin = this.plugins.get(pluginName);
1794
+ if (plugin) plugin.resolver = merged;
1795
+ }
1796
+ getResolver(pluginName) {
1797
+ return this.#resolvers.get(pluginName) ?? this.#getDefaultResolver(pluginName);
1798
+ }
1799
+ getContext(plugin) {
1800
+ const driver = this;
1801
+ const report = (diagnostic) => {
1802
+ Diagnostics.report({
1803
+ ...diagnostic,
1804
+ plugin: plugin.name
1805
+ });
1806
+ };
1807
+ return {
1808
+ config: driver.config,
1809
+ get root() {
1810
+ return resolve(driver.config.root, driver.config.output.path);
1811
+ },
1812
+ hooks: driver.hooks,
1813
+ plugin,
1814
+ getPlugin: driver.getPlugin.bind(driver),
1815
+ requirePlugin: ((name) => driver.requirePlugin(name, { requiredBy: plugin.name })),
1816
+ getResolver: driver.getResolver.bind(driver),
1817
+ driver,
1818
+ addFile: async (...files) => {
1819
+ driver.fileManager.add(...files);
1820
+ },
1821
+ upsertFile: async (...files) => {
1822
+ driver.fileManager.upsert(...files);
1823
+ },
1824
+ get meta() {
1825
+ return driver.inputNode?.meta ?? {
1826
+ circularNames: [],
1827
+ enumNames: []
1828
+ };
1829
+ },
1830
+ get adapter() {
1831
+ return driver.adapter;
1832
+ },
1833
+ get resolver() {
1834
+ return driver.getResolver(plugin.name);
1835
+ },
1836
+ warn(message) {
1837
+ report({
1838
+ code: Diagnostics.code.pluginWarning,
1839
+ severity: "warning",
1840
+ message
1841
+ });
1842
+ },
1843
+ error(error) {
1844
+ const cause = typeof error === "string" ? void 0 : error;
1845
+ report({
1846
+ code: Diagnostics.code.pluginFailed,
1847
+ severity: "error",
1848
+ message: typeof error === "string" ? error : error.message,
1849
+ cause
1850
+ });
1851
+ },
1852
+ info(message) {
1853
+ report({
1854
+ code: Diagnostics.code.pluginInfo,
1855
+ severity: "info",
1856
+ message
1857
+ });
1858
+ }
1859
+ };
1860
+ }
1861
+ getPlugin(pluginName) {
1862
+ return this.plugins.get(pluginName);
1863
+ }
1864
+ requirePlugin(pluginName, context) {
1865
+ const plugin = this.getPlugin(pluginName);
1866
+ if (plugin) return plugin;
1867
+ const requiredBy = context?.requiredBy;
1868
+ const by = requiredBy ? ` by "${requiredBy}"` : "";
1869
+ const help = requiredBy ? ` (required by "${requiredBy}")` : "";
1870
+ throw new Diagnostics.Error({
1871
+ code: Diagnostics.code.pluginNotFound,
1872
+ severity: "error",
1873
+ message: `Plugin "${pluginName}" is required${by} but not found. Make sure it is included in your Kubb config.`,
1874
+ help: `Add "${pluginName}" to the \`plugins\` array in kubb.config.ts${help}, or remove the dependency on it.`,
1875
+ location: { kind: "config" }
1876
+ });
702
1877
  }
703
1878
  };
704
1879
  //#endregion
705
1880
  //#region src/createStorage.ts
706
1881
  /**
707
- * Factory for implementing custom storage backends that control where generated files are written.
708
- *
709
- * Takes a builder function `(options: TOptions) => Storage` and returns a factory `(options?: TOptions) => Storage`.
710
- * Kubb provides filesystem and in-memory implementations out of the box.
1882
+ * Defines a custom storage backend. The builder receives user options and
1883
+ * returns a `Storage` implementation. Kubb ships with filesystem and in-memory
1884
+ * storages. A custom backend writes generated files elsewhere, such as cloud
1885
+ * storage or a database.
711
1886
  *
712
- * @note Call the returned factory with optional options to instantiate the storage adapter.
713
- *
714
- * @example
1887
+ * @example In-memory storage (the built-in implementation)
715
1888
  * ```ts
716
1889
  * import { createStorage } from '@kubb/core'
717
1890
  *
718
1891
  * export const memoryStorage = createStorage(() => {
719
1892
  * const store = new Map<string, string>()
1893
+ *
720
1894
  * return {
721
1895
  * name: 'memory',
722
- * async hasItem(key) { return store.has(key) },
723
- * async getItem(key) { return store.get(key) ?? null },
724
- * async setItem(key, value) { store.set(key, value) },
725
- * async removeItem(key) { store.delete(key) },
1896
+ * async hasItem(key) {
1897
+ * return store.has(key)
1898
+ * },
1899
+ * async getItem(key) {
1900
+ * return store.get(key) ?? null
1901
+ * },
1902
+ * async setItem(key, value) {
1903
+ * store.set(key, value)
1904
+ * },
1905
+ * async removeItem(key) {
1906
+ * store.delete(key)
1907
+ * },
726
1908
  * async getKeys(base) {
727
1909
  * const keys = [...store.keys()]
728
1910
  * return base ? keys.filter((k) => k.startsWith(base)) : keys
729
1911
  * },
730
- * async clear(base) { if (!base) store.clear() },
1912
+ * async clear(base) {
1913
+ * if (!base) store.clear()
1914
+ * },
731
1915
  * }
732
1916
  * })
733
- *
734
- * // Instantiate:
735
- * const storage = memoryStorage()
736
1917
  * ```
737
1918
  */
738
1919
  function createStorage(build) {
@@ -740,6 +1921,29 @@ function createStorage(build) {
740
1921
  }
741
1922
  //#endregion
742
1923
  //#region src/storages/fsStorage.ts
1924
+ const WRITE_CONCURRENCY = 50;
1925
+ function createLimiter(concurrency) {
1926
+ let active = 0;
1927
+ const queue = [];
1928
+ function next() {
1929
+ if (active >= concurrency) return;
1930
+ const run = queue.shift();
1931
+ if (!run) return;
1932
+ active++;
1933
+ run();
1934
+ }
1935
+ return function limit(task) {
1936
+ return new Promise((resolve, reject) => {
1937
+ queue.push(() => {
1938
+ task().then(resolve, reject).finally(() => {
1939
+ active--;
1940
+ next();
1941
+ });
1942
+ });
1943
+ next();
1944
+ });
1945
+ };
1946
+ }
743
1947
  /**
744
1948
  * Built-in filesystem storage driver.
745
1949
  *
@@ -747,642 +1951,540 @@ function createStorage(build) {
747
1951
  * Keys are resolved against `process.cwd()`, so root-relative paths such as
748
1952
  * `src/gen/api/getPets.ts` are written to the correct location without extra configuration.
749
1953
  *
750
- * Internally uses the `write` utility from `@internals/utils`, which:
751
- * - trims leading/trailing whitespace before writing
752
- * - skips the write when file content is already identical (deduplication)
753
- * - creates missing parent directories automatically
754
- * - supports Bun's native file API when running under Bun
1954
+ * Writes are deduplicated and directory-safe:
1955
+ * - leading and trailing whitespace is trimmed before writing
1956
+ * - the write is skipped when the file content is already identical
1957
+ * - missing parent directories are created automatically
1958
+ * - Bun's native file API is used when running under Bun
1959
+ * - concurrent `setItem` calls are capped at {@link WRITE_CONCURRENCY} in flight, so a caller
1960
+ * can fire every file's write without pacing itself
755
1961
  *
756
1962
  * @example
757
1963
  * ```ts
758
1964
  * import { fsStorage } from '@kubb/core'
759
1965
  * import { defineConfig } from 'kubb'
760
- *
761
- * export default defineConfig({
762
- * input: { path: './petStore.yaml' },
763
- * output: { path: './src/gen' },
764
- * storage: fsStorage(),
765
- * })
766
- * ```
767
- */
768
- const fsStorage = createStorage(() => ({
769
- name: "fs",
770
- async hasItem(key) {
771
- try {
772
- await access(resolve(key));
773
- return true;
774
- } catch (_error) {
775
- return false;
776
- }
777
- },
778
- async getItem(key) {
779
- try {
780
- return await readFile(resolve(key), "utf8");
781
- } catch (_error) {
782
- return null;
783
- }
784
- },
785
- async setItem(key, value) {
786
- await write(resolve(key), value, { sanity: false });
787
- },
788
- async removeItem(key) {
789
- await rm(resolve(key), { force: true });
790
- },
791
- async getKeys(base) {
792
- const keys = [];
793
- const resolvedBase = resolve(base ?? process.cwd());
794
- async function walk(dir, prefix) {
795
- let entries;
1966
+ *
1967
+ * export default defineConfig({
1968
+ * input: './petStore.yaml',
1969
+ * output: { path: './src/gen' },
1970
+ * storage: fsStorage(),
1971
+ * })
1972
+ * ```
1973
+ */
1974
+ const fsStorage = createStorage(() => {
1975
+ const limit = createLimiter(WRITE_CONCURRENCY);
1976
+ return {
1977
+ name: "fs",
1978
+ async hasItem(key) {
796
1979
  try {
797
- entries = await readdir(dir, { withFileTypes: true });
1980
+ await access(resolve(key));
1981
+ return true;
798
1982
  } catch (_error) {
799
- return;
1983
+ return false;
800
1984
  }
801
- for (const entry of entries) {
802
- const rel = prefix ? `${prefix}/${entry.name}` : entry.name;
803
- if (entry.isDirectory()) await walk(join(dir, entry.name), rel);
804
- else keys.push(rel);
1985
+ },
1986
+ async getItem(key) {
1987
+ try {
1988
+ return await readFile(resolve(key), "utf8");
1989
+ } catch (_error) {
1990
+ return null;
805
1991
  }
1992
+ },
1993
+ async setItem(key, value) {
1994
+ await limit(() => write(resolve(key), value, { sanity: false }));
1995
+ },
1996
+ async removeItem(key) {
1997
+ await rm(resolve(key), { force: true });
1998
+ },
1999
+ async getKeys(base) {
2000
+ const resolvedBase = resolve(base ?? process.cwd());
2001
+ const keys = [];
2002
+ try {
2003
+ for await (const entry of glob("**/*", {
2004
+ cwd: resolvedBase,
2005
+ withFileTypes: true
2006
+ })) if (entry.isFile()) keys.push(toPosixPath(relative(resolvedBase, join(entry.parentPath, entry.name))));
2007
+ } catch (_error) {}
2008
+ return keys;
2009
+ },
2010
+ async clear(base) {
2011
+ if (!base) return;
2012
+ await clean(resolve(base));
806
2013
  }
807
- await walk(resolvedBase, "");
808
- return keys;
809
- },
810
- async clear(base) {
811
- if (!base) return;
812
- await clean(resolve(base));
813
- }
814
- }));
2014
+ };
2015
+ });
815
2016
  //#endregion
816
2017
  //#region src/createKubb.ts
817
- async function setup(userConfig, options = {}) {
818
- const hooks = options.hooks ?? new AsyncEventEmitter();
819
- const config = {
2018
+ function resolveConfig(userConfig) {
2019
+ return {
820
2020
  ...userConfig,
821
2021
  root: userConfig.root || process.cwd(),
822
2022
  parsers: userConfig.parsers ?? [],
823
- adapter: userConfig.adapter,
824
2023
  output: {
825
2024
  format: false,
826
2025
  lint: false,
827
- extension: DEFAULT_EXTENSION,
828
- defaultBanner: DEFAULT_BANNER,
2026
+ defaultBanner: "simple",
829
2027
  ...userConfig.output
830
2028
  },
831
2029
  storage: userConfig.storage ?? fsStorage(),
832
- devtools: userConfig.devtools ? {
833
- studioUrl: DEFAULT_STUDIO_URL,
834
- ...typeof userConfig.devtools === "boolean" ? {} : userConfig.devtools
835
- } : void 0,
2030
+ reporters: userConfig.reporters ?? [],
836
2031
  plugins: userConfig.plugins ?? []
837
2032
  };
838
- const driver = new PluginDriver(config, { hooks });
839
- const sources = /* @__PURE__ */ new Map();
840
- const diagnosticInfo = getDiagnosticInfo();
841
- await hooks.emit("kubb:debug", {
842
- date: /* @__PURE__ */ new Date(),
843
- logs: [
844
- "Configuration:",
845
- ` • Name: ${userConfig.name || "unnamed"}`,
846
- ` • Root: ${userConfig.root || process.cwd()}`,
847
- ` • Output: ${userConfig.output?.path || "not specified"}`,
848
- ` • Plugins: ${userConfig.plugins?.length || 0}`,
849
- "Output Settings:",
850
- ` • Storage: ${config.storage.name}`,
851
- ` • Formatter: ${userConfig.output?.format || "none"}`,
852
- ` • Linter: ${userConfig.output?.lint || "none"}`,
853
- "Environment:",
854
- Object.entries(diagnosticInfo).map(([key, value]) => ` • ${key}: ${value}`).join("\n")
855
- ]
856
- });
857
- try {
858
- if (isInputPath(userConfig) && !new URLPath(userConfig.input.path).isURL) {
859
- await exists(userConfig.input.path);
860
- await hooks.emit("kubb:debug", {
861
- date: /* @__PURE__ */ new Date(),
862
- logs: [`✓ Input file validated: ${userConfig.input.path}`]
863
- });
864
- }
865
- } catch (caughtError) {
866
- if (isInputPath(userConfig)) {
867
- const error = caughtError;
868
- throw new Error(`Cannot read file/URL defined in \`input.path\` or set with \`kubb generate PATH\` in the CLI of your Kubb config ${userConfig.input.path}`, { cause: error });
869
- }
870
- }
871
- if (config.output.clean) {
872
- await hooks.emit("kubb:debug", {
873
- date: /* @__PURE__ */ new Date(),
874
- logs: ["Cleaning output directories", ` • Output: ${config.output.path}`]
875
- });
876
- await config.storage.clear(resolve(config.root, config.output.path));
877
- }
878
- function registerMiddlewareHook(event, middlewareHooks) {
879
- const handler = middlewareHooks[event];
880
- if (handler) hooks.on(event, handler);
881
- }
882
- for (const middleware of config.middleware ?? []) for (const event of Object.keys(middleware.hooks)) registerMiddlewareHook(event, middleware.hooks);
883
- if (config.adapter) {
884
- const source = inputToAdapterSource(config);
885
- await hooks.emit("kubb:debug", {
886
- date: /* @__PURE__ */ new Date(),
887
- logs: [`Running adapter: ${config.adapter.name}`]
888
- });
889
- driver.adapter = config.adapter;
890
- driver.inputNode = await config.adapter.parse(source);
891
- await hooks.emit("kubb:debug", {
892
- date: /* @__PURE__ */ new Date(),
893
- logs: [
894
- `✓ Adapter '${config.adapter.name}' resolved InputNode`,
895
- ` • Schemas: ${driver.inputNode.schemas.length}`,
896
- ` • Operations: ${driver.inputNode.operations.length}`
897
- ]
898
- });
899
- }
900
- return {
901
- config,
902
- hooks,
903
- driver,
904
- sources
905
- };
906
2033
  }
907
2034
  /**
908
- * Walks the AST and dispatches nodes to a plugin's direct AST hooks
909
- * (`schema`, `operation`, `operations`).
2035
+ * Kubb code-generation instance bound to a single config entry. Resolves the user
2036
+ * config in the constructor, so `config` is available right away, and shares `hooks`,
2037
+ * `storage`, and `driver` across the `setup → build` lifecycle.
2038
+ *
2039
+ * `createKubb` takes a plain config object (the shape `defineConfig` produces),
2040
+ * not a fluent builder.
910
2041
  *
911
- * When `include` contains only operation-scoped filters (`tag`, `operationId`, `path`,
912
- * `method`, `contentType`) and no `schemaName` filter, the function pre-computes the set
913
- * of top-level schema names transitively reachable from the included operations and skips
914
- * schemas that fall outside that set. This ensures that component schemas referenced
915
- * exclusively by excluded operations are not generated.
2042
+ * Attach hook listeners to `.hooks` before calling `setup()` or `build()`.
2043
+ *
2044
+ * @example
2045
+ * ```ts
2046
+ * const kubb = createKubb(userConfig)
2047
+ * kubb.hooks.hook('kubb:plugin:end', ({ plugin, duration }) => console.log(plugin.name, duration))
2048
+ * const { files, diagnostics } = await kubb.safeBuild()
2049
+ * ```
916
2050
  */
917
- async function runPluginAstHooks(plugin, context) {
918
- const { adapter, inputNode, resolver, driver } = context;
919
- const { exclude, include, override } = plugin.options;
920
- if (!adapter || !inputNode) throw new Error(`[${plugin.name}] No adapter found. Add an OAS adapter (e.g. adapterOas()) before this plugin in your Kubb config.`);
921
- function resolveRenderer(gen) {
922
- return gen.renderer === null ? void 0 : gen.renderer ?? plugin.renderer ?? context.config.renderer;
923
- }
924
- const generators = plugin.generators ?? [];
925
- const collectedOperations = [];
926
- const generatorContext = {
927
- ...context,
928
- resolver: driver.getResolver(plugin.name)
929
- };
930
- const operationFilterTypes = new Set([
931
- "tag",
932
- "operationId",
933
- "path",
934
- "method",
935
- "contentType"
936
- ]);
937
- const hasOperationBasedIncludes = include?.some(({ type }) => operationFilterTypes.has(type)) ?? false;
938
- const hasSchemaNameIncludes = include?.some(({ type }) => type === "schemaName") ?? false;
939
- let allowedSchemaNames;
940
- if (hasOperationBasedIncludes && !hasSchemaNameIncludes) allowedSchemaNames = collectUsedSchemaNames(inputNode.operations.filter((op) => resolver.resolveOptions(op, {
941
- options: plugin.options,
942
- exclude,
943
- include,
944
- override
945
- }) !== null), inputNode.schemas);
946
- await walk(inputNode, {
947
- depth: "shallow",
948
- async schema(node) {
949
- const transformedNode = plugin.transformer ? transform(node, plugin.transformer) : node;
950
- if (allowedSchemaNames !== void 0 && transformedNode.name && !allowedSchemaNames.has(transformedNode.name)) return;
951
- const options = resolver.resolveOptions(transformedNode, {
952
- options: plugin.options,
953
- exclude,
954
- include,
955
- override
956
- });
957
- if (options === null) return;
958
- const ctx = {
959
- ...generatorContext,
960
- options
961
- };
962
- for (const gen of generators) {
963
- if (!gen.schema) continue;
964
- await applyHookResult(await gen.schema(transformedNode, ctx), driver, resolveRenderer(gen));
965
- }
966
- await driver.hooks.emit("kubb:generate:schema", transformedNode, ctx);
967
- },
968
- async operation(node) {
969
- const transformedNode = plugin.transformer ? transform(node, plugin.transformer) : node;
970
- const options = resolver.resolveOptions(transformedNode, {
971
- options: plugin.options,
972
- exclude,
973
- include,
974
- override
975
- });
976
- if (options !== null) {
977
- collectedOperations.push(transformedNode);
978
- const ctx = {
979
- ...generatorContext,
980
- options
981
- };
982
- for (const gen of generators) {
983
- if (!gen.operation) continue;
984
- await applyHookResult(await gen.operation(transformedNode, ctx), driver, resolveRenderer(gen));
985
- }
986
- await driver.hooks.emit("kubb:generate:operation", transformedNode, ctx);
987
- }
988
- }
989
- });
990
- if (collectedOperations.length > 0) {
991
- const ctx = {
992
- ...generatorContext,
993
- options: plugin.options
994
- };
995
- for (const gen of generators) {
996
- if (!gen.operations) continue;
997
- await applyHookResult(await gen.operations(collectedOperations, ctx), driver, resolveRenderer(gen));
2051
+ var Kubb = class {
2052
+ hooks;
2053
+ config;
2054
+ #driver = null;
2055
+ #storage = null;
2056
+ constructor(userConfig, options = {}) {
2057
+ this.config = resolveConfig(userConfig);
2058
+ this.hooks = options.hooks ?? new Hookable();
2059
+ }
2060
+ get storage() {
2061
+ if (!this.#storage) throw new Error("[kubb] setup() must be called before accessing storage");
2062
+ return this.#storage;
2063
+ }
2064
+ get driver() {
2065
+ if (!this.#driver) throw new Error("[kubb] setup() must be called before accessing driver");
2066
+ return this.#driver;
2067
+ }
2068
+ /**
2069
+ * Initializes the driver and storage. `build()` calls this automatically.
2070
+ */
2071
+ async setup() {
2072
+ const config = this.config;
2073
+ const driver = new KubbDriver(config, { hooks: this.hooks });
2074
+ this.hooks.setMaxListeners(Math.max(10, config.plugins.length * 4));
2075
+ if (config.output.clean) await config.storage.clear(resolve(config.root, config.output.path));
2076
+ await driver.setup();
2077
+ this.#driver = driver;
2078
+ this.#storage = config.storage;
2079
+ }
2080
+ /**
2081
+ * Runs the full pipeline and throws on any plugin error.
2082
+ * Automatically calls `setup()` if needed.
2083
+ */
2084
+ async build() {
2085
+ const out = await this.safeBuild();
2086
+ if (Diagnostics.hasError(out.diagnostics)) {
2087
+ const errors = out.diagnostics.filter(Diagnostics.isProblem).filter((diagnostic) => diagnostic.severity === "error").map((diagnostic) => diagnostic.cause ?? new Diagnostics.Error(diagnostic));
2088
+ throw new BuildError(`Build failed with ${errors.length} ${errors.length === 1 ? "error" : "errors"}`, { errors });
998
2089
  }
999
- await driver.hooks.emit("kubb:generate:operations", collectedOperations, ctx);
2090
+ return out;
1000
2091
  }
1001
- }
1002
- async function safeBuild(setupResult) {
1003
- const { driver, hooks, sources } = setupResult;
1004
- const failedPlugins = /* @__PURE__ */ new Set();
1005
- const pluginTimings = /* @__PURE__ */ new Map();
1006
- const config = driver.config;
1007
- try {
1008
- await driver.emitSetupHooks();
1009
- if (driver.adapter && driver.inputNode) await hooks.emit("kubb:build:start", {
1010
- config,
1011
- adapter: driver.adapter,
1012
- inputNode: driver.inputNode,
1013
- getPlugin: driver.getPlugin.bind(driver),
1014
- get files() {
1015
- return driver.fileManager.files;
1016
- },
1017
- upsertFile: (...files) => driver.fileManager.upsert(...files)
1018
- });
1019
- for (const plugin of driver.plugins.values()) {
1020
- const context = driver.getContext(plugin);
1021
- const hrStart = process.hrtime();
1022
- try {
1023
- const timestamp = /* @__PURE__ */ new Date();
1024
- await hooks.emit("kubb:plugin:start", { plugin });
1025
- await hooks.emit("kubb:debug", {
1026
- date: timestamp,
1027
- logs: ["Starting plugin...", ` • Plugin Name: ${plugin.name}`]
1028
- });
1029
- if (plugin.generators?.length || driver.hasRegisteredGenerators(plugin.name)) await runPluginAstHooks(plugin, context);
1030
- const duration = getElapsedMs(hrStart);
1031
- pluginTimings.set(plugin.name, duration);
1032
- await hooks.emit("kubb:plugin:end", {
1033
- plugin,
1034
- duration,
1035
- success: true,
1036
- config,
1037
- get files() {
1038
- return driver.fileManager.files;
1039
- },
1040
- upsertFile: (...files) => driver.fileManager.upsert(...files)
1041
- });
1042
- await hooks.emit("kubb:debug", {
1043
- date: /* @__PURE__ */ new Date(),
1044
- logs: [`✓ Plugin started successfully (${formatMs(duration)})`]
1045
- });
1046
- } catch (caughtError) {
1047
- const error = caughtError;
1048
- const errorTimestamp = /* @__PURE__ */ new Date();
1049
- const duration = getElapsedMs(hrStart);
1050
- await hooks.emit("kubb:plugin:end", {
1051
- plugin,
1052
- duration,
1053
- success: false,
1054
- error,
1055
- config,
1056
- get files() {
1057
- return driver.fileManager.files;
1058
- },
1059
- upsertFile: (...files) => driver.fileManager.upsert(...files)
1060
- });
1061
- await hooks.emit("kubb:debug", {
1062
- date: errorTimestamp,
1063
- logs: [
1064
- "✗ Plugin start failed",
1065
- ` • Plugin Name: ${plugin.name}`,
1066
- ` • Error: ${error.constructor.name} - ${error.message}`,
1067
- " • Stack Trace:",
1068
- error.stack || "No stack trace available"
1069
- ]
1070
- });
1071
- failedPlugins.add({
1072
- plugin,
1073
- error
1074
- });
1075
- }
2092
+ /**
2093
+ * Runs the full pipeline and captures errors in `BuildOutput` instead of throwing.
2094
+ * Automatically calls `setup()` if needed. This is the canonical call: it never throws on
2095
+ * plugin errors, so callers stay in control of how failures surface.
2096
+ */
2097
+ async safeBuild() {
2098
+ try {
2099
+ var _usingCtx$1 = _usingCtx();
2100
+ if (!this.#driver) await this.setup();
2101
+ const self = _usingCtx$1.u(this);
2102
+ const driver = self.driver;
2103
+ const storage = self.storage;
2104
+ const { diagnostics } = await driver.run();
2105
+ return {
2106
+ diagnostics,
2107
+ files: driver.fileManager.files,
2108
+ driver,
2109
+ storage
2110
+ };
2111
+ } catch (_) {
2112
+ _usingCtx$1.e = _;
2113
+ } finally {
2114
+ _usingCtx$1.d();
1076
2115
  }
1077
- await hooks.emit("kubb:plugins:end", {
1078
- config,
1079
- get files() {
1080
- return driver.fileManager.files;
1081
- },
1082
- upsertFile: (...files) => driver.fileManager.upsert(...files)
1083
- });
1084
- const files = driver.fileManager.files;
1085
- const parsersMap = /* @__PURE__ */ new Map();
1086
- for (const parser of config.parsers) if (parser.extNames) for (const extname of parser.extNames) parsersMap.set(extname, parser);
1087
- const fileProcessor = new FileProcessor();
1088
- await hooks.emit("kubb:debug", {
1089
- date: /* @__PURE__ */ new Date(),
1090
- logs: [`Writing ${files.length} files...`]
1091
- });
1092
- await fileProcessor.run(files, {
1093
- parsers: parsersMap,
1094
- mode: "parallel",
1095
- extension: config.output.extension,
1096
- onStart: async (processingFiles) => {
1097
- await hooks.emit("kubb:files:processing:start", { files: processingFiles });
1098
- },
1099
- onUpdate: async ({ file, source, processed, total, percentage }) => {
1100
- await hooks.emit("kubb:file:processing:update", {
1101
- file,
1102
- source,
1103
- processed,
1104
- total,
1105
- percentage,
1106
- config
1107
- });
1108
- if (source) {
1109
- await config.storage.setItem(file.path, source);
1110
- sources.set(file.path, source);
1111
- }
1112
- },
1113
- onEnd: async (processedFiles) => {
1114
- await hooks.emit("kubb:files:processing:end", { files: processedFiles });
1115
- await hooks.emit("kubb:debug", {
1116
- date: /* @__PURE__ */ new Date(),
1117
- logs: [`✓ File write process completed for ${processedFiles.length} files`]
1118
- });
1119
- }
1120
- });
1121
- await hooks.emit("kubb:build:end", {
1122
- files,
1123
- config,
1124
- outputDir: resolve(config.root, config.output.path)
1125
- });
1126
- return {
1127
- failedPlugins,
1128
- files,
1129
- driver,
1130
- pluginTimings,
1131
- sources
1132
- };
1133
- } catch (error) {
1134
- return {
1135
- failedPlugins,
1136
- files: [],
1137
- driver,
1138
- pluginTimings,
1139
- error,
1140
- sources
1141
- };
1142
- } finally {
1143
- driver.dispose();
1144
2116
  }
1145
- }
1146
- async function build(setupResult) {
1147
- const { files, driver, failedPlugins, pluginTimings, error, sources } = await safeBuild(setupResult);
1148
- if (error) throw error;
1149
- if (failedPlugins.size > 0) {
1150
- const errors = [...failedPlugins].map(({ error }) => error);
1151
- throw new BuildError(`Build Error with ${failedPlugins.size} failed plugins`, { errors });
2117
+ dispose() {
2118
+ this.#driver?.dispose();
1152
2119
  }
1153
- return {
1154
- failedPlugins,
1155
- files,
1156
- driver,
1157
- pluginTimings,
1158
- error: void 0,
1159
- sources
1160
- };
1161
- }
1162
- /**
1163
- * Returns a snapshot of the current runtime environment.
1164
- *
1165
- * Useful for attaching context to debug logs and error reports so that
1166
- * issues can be reproduced without manual information gathering.
1167
- */
1168
- function getDiagnosticInfo() {
1169
- return {
1170
- nodeVersion: version,
1171
- KubbVersion: version$1,
1172
- platform: process.platform,
1173
- arch: process.arch,
1174
- cwd: process.cwd()
1175
- };
1176
- }
1177
- function isInputPath(config) {
1178
- return typeof config?.input === "object" && config.input !== null && "path" in config.input;
1179
- }
1180
- function inputToAdapterSource(config) {
1181
- const input = config.input;
1182
- if (!input) throw new Error("[kubb] input is required when using an adapter. Provide input.path or input.data in your config.");
1183
- if ("data" in input) return {
1184
- type: "data",
1185
- data: input.data
1186
- };
1187
- if (new URLPath(input.path).isURL) return {
1188
- type: "path",
1189
- path: input.path
1190
- };
1191
- return {
1192
- type: "path",
1193
- path: resolve(config.root, input.path)
1194
- };
1195
- }
2120
+ [Symbol.dispose]() {
2121
+ this.dispose();
2122
+ }
2123
+ };
1196
2124
  /**
1197
- * Creates a Kubb instance bound to a single config entry.
1198
- *
1199
- * Accepts a user-facing config shape and resolves it to a full {@link Config} during
1200
- * `setup()`. The instance then holds shared state (`hooks`, `sources`, `driver`, `config`)
1201
- * across the `setup → build` lifecycle. Attach event listeners to `kubb.hooks` before
1202
- * calling `setup()` or `build()`.
2125
+ * Constructs a {@link Kubb} build orchestrator from a user config. Equivalent
2126
+ * to `new Kubb(userConfig, options)` and the canonical public entry point.
1203
2127
  *
1204
2128
  * @example
1205
2129
  * ```ts
1206
- * const kubb = createKubb(userConfig)
2130
+ * import { createKubb } from '@kubb/core'
2131
+ * import { adapterOas } from '@kubb/adapter-oas'
2132
+ * import { pluginTs } from '@kubb/plugin-ts'
1207
2133
  *
1208
- * kubb.hooks.on('kubb:plugin:end', ({ plugin, duration }) => {
1209
- * console.log(`${plugin.name} completed in ${duration}ms`)
2134
+ * const kubb = createKubb({
2135
+ * input: './petStore.yaml',
2136
+ * output: { path: './src/gen' },
2137
+ * adapter: adapterOas(),
2138
+ * plugins: [pluginTs()],
1210
2139
  * })
1211
2140
  *
1212
- * const { files, failedPlugins } = await kubb.safeBuild()
2141
+ * await kubb.build()
1213
2142
  * ```
1214
2143
  */
1215
2144
  function createKubb(userConfig, options = {}) {
1216
- const hooks = options.hooks ?? new AsyncEventEmitter();
1217
- let setupResult;
1218
- const instance = {
1219
- get hooks() {
1220
- return hooks;
1221
- },
1222
- get sources() {
1223
- return setupResult?.sources ?? /* @__PURE__ */ new Map();
1224
- },
1225
- get driver() {
1226
- return setupResult?.driver;
1227
- },
1228
- get config() {
1229
- return setupResult?.config;
1230
- },
1231
- async setup() {
1232
- setupResult = await setup(userConfig, { hooks });
1233
- },
1234
- async build() {
1235
- if (!setupResult) await instance.setup();
1236
- return build(setupResult);
1237
- },
1238
- async safeBuild() {
1239
- if (!setupResult) await instance.setup();
1240
- return safeBuild(setupResult);
1241
- }
1242
- };
1243
- return instance;
2145
+ return new Kubb(userConfig, options);
1244
2146
  }
1245
2147
  //#endregion
1246
- //#region src/createRenderer.ts
2148
+ //#region src/createReporter.ts
1247
2149
  /**
1248
- * Creates a renderer factory for use in generator definitions.
2150
+ * Numeric log-level thresholds used internally to compare verbosity.
1249
2151
  *
1250
- * Wrap your renderer factory function with this helper to register it as the
1251
- * renderer for a generator. Core will call this factory once per render cycle
1252
- * to obtain a fresh renderer instance.
2152
+ * Higher numbers are more verbose.
2153
+ */
2154
+ const logLevel = {
2155
+ silent: Number.NEGATIVE_INFINITY,
2156
+ error: 0,
2157
+ warn: 1,
2158
+ info: 3,
2159
+ verbose: 4
2160
+ };
2161
+ /**
2162
+ * Defines a reporter. When the definition has a `drain`, the returned reporter buffers each value
2163
+ * `report` returns and hands the array to `drain` once, then clears it. Without a `drain`, nothing
2164
+ * is buffered. Wiring the reporter onto the run's hooks is the host's job, so the reporter only
2165
+ * ever deals with a {@link GenerationResult}.
1253
2166
  *
1254
2167
  * @example
1255
2168
  * ```ts
1256
- * // packages/renderer-jsx/src/index.ts
1257
- * export const jsxRenderer = createRenderer(() => {
1258
- * const runtime = new Runtime()
1259
- * return {
1260
- * async render(element) { await runtime.render(element) },
1261
- * get files() { return runtime.nodes },
1262
- * unmount(error) { runtime.unmount(error) },
1263
- * }
1264
- * })
2169
+ * import { createReporter, Diagnostics } from '@kubb/core'
1265
2170
  *
1266
- * // packages/plugin-zod/src/generators/zodGenerator.tsx
1267
- * import { jsxRenderer } from '@kubb/renderer-jsx'
1268
- * export const zodGenerator = defineGenerator<PluginZod>({
1269
- * name: 'zod',
1270
- * renderer: jsxRenderer,
1271
- * schema(node, options) { return <File ...>...</File> },
2171
+ * export const jsonReporter = createReporter({
2172
+ * name: 'json',
2173
+ * report(result) {
2174
+ * return { status: Diagnostics.hasError(result.diagnostics) ? 'failed' : 'success', diagnostics: result.diagnostics }
2175
+ * },
2176
+ * drain(context, reports) {
2177
+ * process.stdout.write(`${JSON.stringify(reports, null, 2)}\n`)
2178
+ * },
1272
2179
  * })
1273
2180
  * ```
1274
2181
  */
1275
- function createRenderer(factory) {
1276
- return factory;
2182
+ function createReporter(reporter) {
2183
+ const reports = /* @__PURE__ */ new Set();
2184
+ return {
2185
+ name: reporter.name,
2186
+ async report(result, context) {
2187
+ const report = await reporter.report(result, context);
2188
+ reports.add(report);
2189
+ },
2190
+ async drain(context) {
2191
+ await reporter.drain?.(context, Array.from(reports));
2192
+ reports.clear();
2193
+ },
2194
+ [Symbol.dispose]() {
2195
+ reports.clear();
2196
+ }
2197
+ };
1277
2198
  }
1278
2199
  //#endregion
1279
- //#region src/defineGenerator.ts
2200
+ //#region src/reporters/report.ts
1280
2201
  /**
1281
- * Defines a generator. Returns the object as-is with correct `this` typings.
1282
- * `applyHookResult` handles renderer elements and `File[]` uniformly using
1283
- * the generator's declared `renderer` factory.
2202
+ * Builds the normalized {@link Report} for one config from its {@link GenerationResult}. Splits the
2203
+ * diagnostics into problems and per-plugin timings (slowest first) and derives the plugin and issue
2204
+ * counts, so every reporter renders the same data.
1284
2205
  */
1285
- function defineGenerator(generator) {
1286
- return generator;
2206
+ function buildReport(result) {
2207
+ const { config, diagnostics, filesCreated, status, hrStart } = result;
2208
+ const failed = Diagnostics.failedPlugins(diagnostics);
2209
+ const total = config.plugins?.length ?? 0;
2210
+ const counts = Diagnostics.count(diagnostics);
2211
+ const problems = diagnostics.filter(Diagnostics.isProblem);
2212
+ const timings = diagnostics.filter(Diagnostics.isPerformance).sort((a, b) => b.duration - a.duration).map((diagnostic) => ({
2213
+ plugin: diagnostic.plugin,
2214
+ durationMs: diagnostic.duration
2215
+ }));
2216
+ return {
2217
+ name: config.name ?? "",
2218
+ status,
2219
+ plugins: {
2220
+ passed: total - failed.length,
2221
+ failed,
2222
+ total
2223
+ },
2224
+ counts,
2225
+ filesCreated,
2226
+ durationMs: getElapsedMs(hrStart),
2227
+ output: resolve(config.root, config.output.path),
2228
+ timings,
2229
+ diagnostics: problems.map((diagnostic) => Diagnostics.serialize(diagnostic))
2230
+ };
2231
+ }
2232
+ //#endregion
2233
+ //#region src/reporters/cliReporter.ts
2234
+ /**
2235
+ * Builds the vitest/jest-style summary for one {@link Report}: right-aligned dim labels with
2236
+ * `N passed (total)` counts, and a per-plugin `Timings` section when `showTimings`.
2237
+ */
2238
+ function buildSummaryLines(report, { showTimings }) {
2239
+ const { status, plugins, counts, filesCreated, durationMs, output, timings } = report;
2240
+ const rows = [];
2241
+ rows.push(["Plugins", status === "success" ? `${styleText("green", `${plugins.passed} passed`)} (${plugins.total})` : `${styleText("green", `${plugins.passed} passed`)} | ${styleText("red", `${plugins.failed.length} failed`)} (${plugins.total})`]);
2242
+ if (status === "failed" && plugins.failed.length > 0) rows.push(["Failed", plugins.failed.map((name) => randomCliColor(name)).join(", ")]);
2243
+ if (counts.errors > 0 || counts.warnings > 0) {
2244
+ const issues = [counts.errors > 0 ? styleText("red", `${counts.errors} ${counts.errors === 1 ? "error" : "errors"}`) : void 0, counts.warnings > 0 ? styleText("yellow", `${counts.warnings} ${counts.warnings === 1 ? "warning" : "warnings"}`) : void 0].filter(Boolean).join(" | ");
2245
+ rows.push(["Issues", issues]);
2246
+ }
2247
+ rows.push(["Files", `${styleText("green", String(filesCreated))} generated`]);
2248
+ rows.push(["Duration", styleText("green", formatMs(durationMs))]);
2249
+ rows.push(["Output", output]);
2250
+ const labelWidth = Math.max(...rows.map(([label]) => label.length), timings.length > 0 ? 7 : 0);
2251
+ const lines = rows.map(([label, value]) => `${styleText("dim", label.padStart(labelWidth))} ${value}`);
2252
+ if (showTimings && timings.length > 0) {
2253
+ const nameWidth = Math.max(0, ...timings.map((timing) => timing.plugin.length));
2254
+ const indent = " ".repeat(labelWidth + 2);
2255
+ lines.push(styleText("dim", "Timings".padStart(labelWidth)));
2256
+ for (const timing of timings) {
2257
+ const timeStr = formatMs(timing.durationMs);
2258
+ const barLength = Math.min(Math.ceil(timing.durationMs / 100), 10);
2259
+ const bar = styleText("dim", "█".repeat(barLength));
2260
+ lines.push(`${indent}${styleText("dim", "•")} ${timing.plugin.padEnd(nameWidth)} ${bar} ${timeStr}`);
2261
+ }
2262
+ }
2263
+ return lines;
2264
+ }
2265
+ /**
2266
+ * Renders the summary as plain `console.log` lines so it works in every CLI (no clack/TTY
2267
+ * dependency): a blank line, the config name colored by status, then the summary rows.
2268
+ */
2269
+ function renderSummary(lines, { title, status }) {
2270
+ console.log("");
2271
+ if (title) console.log(styleText(status === "failed" ? "red" : "green", title));
2272
+ for (const line of lines) console.log(line);
1287
2273
  }
2274
+ /**
2275
+ * The default `cli` reporter. Renders the {@link Report} for each config as it finishes, independent
2276
+ * of the live logger view. Suppressed at `silent`. The `verbose` level adds the per-plugin timings.
2277
+ */
2278
+ const cliReporter = createReporter({
2279
+ name: "cli",
2280
+ report(result, { logLevel: logLevel$1 }) {
2281
+ if (logLevel$1 <= logLevel.silent) return;
2282
+ const report = buildReport(result);
2283
+ renderSummary(buildSummaryLines(report, { showTimings: logLevel$1 >= logLevel.verbose }), {
2284
+ title: report.name,
2285
+ status: report.status
2286
+ });
2287
+ }
2288
+ });
1288
2289
  //#endregion
1289
- //#region src/defineLogger.ts
2290
+ //#region src/reporters/fileReporter.ts
2291
+ /**
2292
+ * Builds the `## Summary` section: the same counts the cli and json reporters expose, as a list of
2293
+ * `label value` rows with the labels padded to a common width.
2294
+ */
2295
+ function buildSummarySection(report) {
2296
+ const { status, plugins, counts, filesCreated, durationMs, output } = report;
2297
+ const rows = [["Status", status], ["Plugins", status === "success" ? `${plugins.passed} passed (${plugins.total})` : `${plugins.passed} passed | ${plugins.failed.length} failed (${plugins.total})`]];
2298
+ if (plugins.failed.length > 0) rows.push(["Failed", plugins.failed.join(", ")]);
2299
+ rows.push(["Issues", `${counts.errors} errors | ${counts.warnings} warnings | ${counts.infos} infos`]);
2300
+ rows.push(["Files", `${filesCreated} generated`]);
2301
+ rows.push(["Duration", formatMs(durationMs)]);
2302
+ rows.push(["Output", output]);
2303
+ const labelWidth = Math.max(...rows.map(([label]) => label.length));
2304
+ return [
2305
+ "## Summary",
2306
+ "",
2307
+ ...rows.map(([label, value]) => ` ${label.padEnd(labelWidth)} ${value}`)
2308
+ ];
2309
+ }
2310
+ /**
2311
+ * Builds the `## Problems` section: each problem rendered in the miette block format, blocks
2312
+ * separated by a blank line. Returns an empty array when there are no problems, so the caller
2313
+ * can drop the heading.
2314
+ */
2315
+ function buildProblemSection(diagnostics) {
2316
+ const problems = diagnostics.filter(Diagnostics.isProblem);
2317
+ if (problems.length === 0) return [];
2318
+ return [
2319
+ "## Problems",
2320
+ "",
2321
+ problems.map((diagnostic) => Diagnostics.formatLines(diagnostic).join("\n")).join("\n\n")
2322
+ ];
2323
+ }
1290
2324
  /**
1291
- * Wraps a logger definition into a typed {@link Logger}.
2325
+ * Builds the `## Timings` section from a {@link Report}: one `plugin duration` row per record,
2326
+ * slowest first with the plugin names left-aligned and the durations right-aligned. Returns an
2327
+ * empty array when there are no timings.
2328
+ */
2329
+ function buildTimingSection(report) {
2330
+ const { timings } = report;
2331
+ if (timings.length === 0) return [];
2332
+ const nameWidth = Math.max(...timings.map((timing) => timing.plugin.length));
2333
+ const durations = timings.map((timing) => formatMs(timing.durationMs));
2334
+ const durationWidth = Math.max(...durations.map((duration) => duration.length));
2335
+ return [
2336
+ "## Timings",
2337
+ "",
2338
+ ...timings.map((timing, index) => ` ${timing.plugin.padEnd(nameWidth)} ${durations[index].padStart(durationWidth)}`)
2339
+ ];
2340
+ }
2341
+ /**
2342
+ * The `file` reporter. Writes a config's {@link Report} to `.kubb/kubb-<name>-<timestamp>.log` as a
2343
+ * plain-text document: a `# <name> — <timestamp>` header, a `## Summary` with the same counts the
2344
+ * cli and json reporters expose, a `## Problems` section in the miette block format, and a
2345
+ * `## Timings` section. Selected with `--reporter file` (or `reporters: ['file']`).
1292
2346
  *
1293
- * The optional second type parameter `TInstallReturn` allows loggers to return
1294
- * a value from `install` for example, a sink factory that the caller can
1295
- * forward to hook execution.
2347
+ * @note It captures the collected diagnostics once a config finishes, not the live
2348
+ * `kubb:info`/`kubb:plugin` hook stream. Color is stripped so the file stays plain text even when
2349
+ * the run is attached to a TTY.
2350
+ */
2351
+ const fileReporter = createReporter({
2352
+ name: "file",
2353
+ async report(result) {
2354
+ const { diagnostics, config } = result;
2355
+ if (diagnostics.length === 0) return;
2356
+ const report = buildReport(result);
2357
+ const content = stripVTControlCharacters([config.name ? `# ${config.name} — ${(/* @__PURE__ */ new Date()).toISOString()}` : `# ${(/* @__PURE__ */ new Date()).toISOString()}`, ...[
2358
+ buildSummarySection(report),
2359
+ buildProblemSection(diagnostics),
2360
+ buildTimingSection(report)
2361
+ ].filter((section) => section.length > 0).map((section) => section.join("\n"))].join("\n\n"));
2362
+ const baseName = `${[
2363
+ "kubb",
2364
+ config.name,
2365
+ Date.now()
2366
+ ].filter(Boolean).join("-")}.log`;
2367
+ const pathName = resolve(process$1.cwd(), ".kubb", baseName);
2368
+ await write(pathName, `${content}\n`);
2369
+ console.error(`Debug log written to ${relative(process$1.cwd(), pathName)}`);
2370
+ }
2371
+ });
2372
+ //#endregion
2373
+ //#region src/reporters/jsonReporter.ts
2374
+ /**
2375
+ * The `json` reporter. `report` returns one config's {@link Report}, which {@link createReporter}
2376
+ * buffers, and `drain` writes them as a single pretty-printed JSON array on `kubb:lifecycle:end`.
2377
+ * Buffering keeps a multi-config run one valid JSON document on stdout instead of concatenated
2378
+ * objects that would break `jq .`. The terminal reporter is suppressed while `json` is active so
2379
+ * stdout stays valid JSON.
2380
+ */
2381
+ const jsonReporter = createReporter({
2382
+ name: "json",
2383
+ report(result) {
2384
+ return buildReport(result);
2385
+ },
2386
+ drain(_context, reports) {
2387
+ process$1.stdout.write(`${JSON.stringify(reports, null, 2)}\n`);
2388
+ }
2389
+ });
2390
+ //#endregion
2391
+ //#region src/createRenderer.ts
2392
+ /**
2393
+ * Defines a renderer factory. Renderers turn the generator's return value
2394
+ * (JSX, a template string, a tree of any shape) into `FileNode`s that get
2395
+ * written to disk.
1296
2396
  *
1297
- * @example Basic logger
1298
- * ```ts
1299
- * export const myLogger = defineLogger({
1300
- * name: 'my-logger',
1301
- * install(context, options) {
1302
- * context.on('kubb:info', (message) => console.log('ℹ', message))
1303
- * context.on('kubb:error', (error) => console.error('✗', error.message))
1304
- * },
1305
- * })
1306
- * ```
2397
+ * A renderer can target output formats beyond JSX, for instance a Handlebars
2398
+ * renderer or one that writes binary files. Plugins and generators pick the
2399
+ * renderer to use via the `renderer` field on `defineGenerator`.
1307
2400
  *
1308
- * @example Logger that returns a hook sink factory
2401
+ * @example A minimal renderer that wraps a custom runtime
1309
2402
  * ```ts
1310
- * export const myLogger = defineLogger<LoggerOptions, HookSinkFactory>({
1311
- * name: 'my-logger',
1312
- * install(context, options) {
1313
- * // register event handlers …
1314
- * return (commandWithArgs) => ({ onStdout: console.log })
1315
- * },
2403
+ * import { createRenderer } from '@kubb/core'
2404
+ *
2405
+ * export const myRenderer = createRenderer(() => {
2406
+ * const runtime = new MyRuntime()
2407
+ * return {
2408
+ * async render(element) {
2409
+ * await runtime.render(element)
2410
+ * },
2411
+ * get files() {
2412
+ * return runtime.files
2413
+ * },
2414
+ * [Symbol.dispose]() {
2415
+ * runtime.dispose()
2416
+ * },
2417
+ * }
1316
2418
  * })
1317
2419
  * ```
1318
2420
  */
1319
- function defineLogger(logger) {
1320
- return logger;
2421
+ function createRenderer(factory) {
2422
+ return factory;
1321
2423
  }
1322
2424
  //#endregion
1323
- //#region src/defineMiddleware.ts
2425
+ //#region src/defineGenerator.ts
1324
2426
  /**
1325
- * Creates a middleware factory using the hook-style `hooks` API.
1326
- *
1327
- * Middleware handlers fire after all plugin handlers for any given event, making them ideal for post-processing, logging, and auditing.
1328
- * Per-build state (such as accumulators) belongs inside the factory closure so each `createKubb` invocation gets its own isolated instance.
2427
+ * Defines a generator: a unit of work that runs during the plugin's AST walk
2428
+ * and produces files. Plugins register generators via `ctx.addGenerator()`
2429
+ * inside `kubb:plugin:setup`.
1329
2430
  *
1330
- * @note The factory can accept typed options. See examples for using options and per-build state patterns.
2431
+ * The returned object is the input as-is, but with `this` types preserved so
2432
+ * `schema`/`operation`/`operations` methods are correctly typed against the
2433
+ * plugin's `PluginFactoryOptions`. Renderer elements and `FileNode[]` returns
2434
+ * are both handled by the runtime, so pick whichever style fits.
1331
2435
  *
1332
- * @example
1333
- * ```ts
1334
- * import { defineMiddleware } from '@kubb/core'
2436
+ * @example JSX-based schema generator
2437
+ * ```tsx
2438
+ * import { defineGenerator } from '@kubb/core'
2439
+ * import { jsxRenderer } from '@kubb/renderer-jsx'
1335
2440
  *
1336
- * // Stateless middleware
1337
- * export const logMiddleware = defineMiddleware(() => ({
1338
- * name: 'log-middleware',
1339
- * hooks: {
1340
- * 'kubb:build:end'({ files }) {
1341
- * console.log(`Build complete with ${files.length} files`)
1342
- * },
2441
+ * export const typeGenerator = defineGenerator({
2442
+ * name: 'typescript',
2443
+ * renderer: jsxRenderer,
2444
+ * schema(node, ctx) {
2445
+ * return (
2446
+ * <File path={`${ctx.root}/${node.name}.ts`}>
2447
+ * <Type node={node} resolver={ctx.resolver} />
2448
+ * </File>
2449
+ * )
1343
2450
  * },
1344
- * }))
1345
- *
1346
- * // Middleware with options and per-build state
1347
- * export const prefixMiddleware = defineMiddleware((options: { prefix: string } = { prefix: '' }) => {
1348
- * const seen = new Set<string>()
1349
- * return {
1350
- * name: 'prefix-middleware',
1351
- * hooks: {
1352
- * 'kubb:plugin:end'({ plugin }) {
1353
- * seen.add(`${options.prefix}${plugin.name}`)
1354
- * },
1355
- * },
1356
- * }
1357
2451
  * })
1358
2452
  * ```
1359
2453
  */
1360
- function defineMiddleware(factory) {
1361
- return (options) => factory(options ?? {});
2454
+ function defineGenerator(generator) {
2455
+ return generator;
1362
2456
  }
1363
2457
  //#endregion
1364
2458
  //#region src/defineParser.ts
1365
2459
  /**
1366
- * Defines a parser with type safety. Creates parsers that transform generated files to strings based on their extension.
2460
+ * Wraps a parser factory and returns a function that accepts user options and
2461
+ * yields a typed {@link Parser}. Mirrors {@link definePlugin}: the factory
2462
+ * receives the caller's options, and calling the returned function without
2463
+ * options passes an empty object.
1367
2464
  *
1368
- * @note Call the returned factory with optional options to instantiate the parser.
2465
+ * Register the result in the `parsers` array on `defineConfig`, calling it to
2466
+ * apply options (`parserTs({ extension: { '.ts': '.js' } })`).
1369
2467
  *
1370
2468
  * @example
1371
2469
  * ```ts
1372
2470
  * import { defineParser } from '@kubb/core'
2471
+ * import { extractStringsFromNodes } from '@kubb/ast'
1373
2472
  *
1374
- * export const jsonParser = defineParser({
2473
+ * export const parserJson = defineParser((options: { pretty?: boolean } = {}) => ({
1375
2474
  * name: 'json',
1376
2475
  * extNames: ['.json'],
1377
2476
  * parse(file) {
1378
- * const { extractStringsFromNodes } = await import('@kubb/ast')
1379
- * return file.sources.map((s) => extractStringsFromNodes(s.nodes ?? [])).join('\n')
2477
+ * const source = file.sources.map((source) => extractStringsFromNodes(source.nodes ?? [])).join('\n')
2478
+ * return options.pretty ? JSON.stringify(JSON.parse(source), null, 2) : source
1380
2479
  * },
1381
- * })
2480
+ * print(...nodes) {
2481
+ * return nodes.map(String).join('\n')
2482
+ * },
2483
+ * }))
1382
2484
  * ```
1383
2485
  */
1384
- function defineParser(parser) {
1385
- return parser;
2486
+ function defineParser(factory) {
2487
+ return (options) => factory(options ?? {});
1386
2488
  }
1387
2489
  //#endregion
1388
2490
  //#region src/storages/memoryStorage.ts
@@ -1399,7 +2501,7 @@ function defineParser(parser) {
1399
2501
  * import { defineConfig } from 'kubb'
1400
2502
  *
1401
2503
  * export default defineConfig({
1402
- * input: { path: './petStore.yaml' },
2504
+ * input: './petStore.yaml',
1403
2505
  * output: { path: './src/gen' },
1404
2506
  * storage: memoryStorage(),
1405
2507
  * })
@@ -1435,6 +2537,6 @@ const memoryStorage = createStorage(() => {
1435
2537
  };
1436
2538
  });
1437
2539
  //#endregion
1438
- export { AsyncEventEmitter, FileManager, FileProcessor, PluginDriver, URLPath, ast, createAdapter, createKubb, createRenderer, createStorage, defineGenerator, defineLogger, defineMiddleware, defineParser, definePlugin, defineResolver, fsStorage, isInputPath, logLevel, memoryStorage };
2540
+ export { Diagnostics, Hookable, KubbDriver, Resolver, applyConfigDefaults, cliReporter, createAdapter, createKubb, createRenderer, createReporter, createResolver, createStorage, defineGenerator, defineParser, definePlugin, fileReporter, fsStorage, getInputKind, jsonReporter, logLevel, memoryStorage };
1439
2541
 
1440
2542
  //# sourceMappingURL=index.js.map