@kubb/core 5.0.0-beta.75 → 5.0.0-beta.77

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