@kubb/core 5.0.0-beta.7 → 5.0.0-beta.71

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