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