@kubb/core 5.0.0-beta.3 → 5.0.0-beta.31

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 (46) hide show
  1. package/README.md +8 -38
  2. package/dist/KubbDriver-CFx2DdhF.js +2131 -0
  3. package/dist/KubbDriver-CFx2DdhF.js.map +1 -0
  4. package/dist/KubbDriver-vyD7F0Ip.cjs +2252 -0
  5. package/dist/KubbDriver-vyD7F0Ip.cjs.map +1 -0
  6. package/dist/{types-CC09VtBt.d.ts → createKubb-6zii1jo-.d.ts} +1610 -1257
  7. package/dist/index.cjs +351 -1125
  8. package/dist/index.cjs.map +1 -1
  9. package/dist/index.d.ts +3 -186
  10. package/dist/index.js +341 -1119
  11. package/dist/index.js.map +1 -1
  12. package/dist/mocks.cjs +30 -21
  13. package/dist/mocks.cjs.map +1 -1
  14. package/dist/mocks.d.ts +5 -5
  15. package/dist/mocks.js +29 -20
  16. package/dist/mocks.js.map +1 -1
  17. package/package.json +6 -18
  18. package/src/FileManager.ts +78 -61
  19. package/src/FileProcessor.ts +48 -38
  20. package/src/KubbDriver.ts +930 -0
  21. package/src/constants.ts +11 -6
  22. package/src/createAdapter.ts +113 -17
  23. package/src/createKubb.ts +1039 -478
  24. package/src/createRenderer.ts +58 -27
  25. package/src/createStorage.ts +36 -23
  26. package/src/defineGenerator.ts +127 -15
  27. package/src/defineLogger.ts +66 -7
  28. package/src/defineMiddleware.ts +19 -17
  29. package/src/defineParser.ts +30 -13
  30. package/src/definePlugin.ts +329 -14
  31. package/src/defineResolver.ts +365 -167
  32. package/src/devtools.ts +8 -1
  33. package/src/index.ts +2 -2
  34. package/src/mocks.ts +11 -14
  35. package/src/storages/fsStorage.ts +13 -37
  36. package/src/types.ts +48 -1292
  37. package/dist/PluginDriver-BXibeQk-.cjs +0 -1036
  38. package/dist/PluginDriver-BXibeQk-.cjs.map +0 -1
  39. package/dist/PluginDriver-DV3p2Hky.js +0 -945
  40. package/dist/PluginDriver-DV3p2Hky.js.map +0 -1
  41. package/src/Kubb.ts +0 -300
  42. package/src/PluginDriver.ts +0 -424
  43. package/src/renderNode.ts +0 -35
  44. package/src/utils/diagnostics.ts +0 -18
  45. package/src/utils/isInputPath.ts +0 -10
  46. package/src/utils/packageJSON.ts +0 -99
@@ -0,0 +1,2131 @@
1
+ import "./chunk--u3MIqq1.js";
2
+ import { EventEmitter } from "node:events";
3
+ import path, { extname, resolve } from "node:path";
4
+ import { collectUsedSchemaNames, createFile, createStreamInput, extractStringsFromNodes, isOperationNode, isSchemaNode, transform } from "@kubb/ast";
5
+ import { deflateSync } from "fflate";
6
+ import { x } from "tinyexec";
7
+ //#region ../../internals/utils/src/errors.ts
8
+ /**
9
+ * Thrown when one or more errors occur during a Kubb build.
10
+ * Carries the full list of underlying errors on `errors`.
11
+ *
12
+ * @example
13
+ * ```ts
14
+ * throw new BuildError('Build failed', { errors: [err1, err2] })
15
+ * ```
16
+ */
17
+ var BuildError = class extends Error {
18
+ errors;
19
+ constructor(message, options) {
20
+ super(message, { cause: options.cause });
21
+ this.name = "BuildError";
22
+ this.errors = options.errors;
23
+ }
24
+ };
25
+ /**
26
+ * Coerces an unknown thrown value to an `Error` instance.
27
+ * Returns the value as-is when it is already an `Error`; otherwise wraps it with `String(value)`.
28
+ *
29
+ * @example
30
+ * ```ts
31
+ * try { ... } catch(err) {
32
+ * throw new BuildError('Build failed', { cause: toError(err), errors: [] })
33
+ * }
34
+ * ```
35
+ */
36
+ function toError(value) {
37
+ return value instanceof Error ? value : new Error(String(value));
38
+ }
39
+ //#endregion
40
+ //#region ../../internals/utils/src/asyncEventEmitter.ts
41
+ /**
42
+ * Typed `EventEmitter` that awaits all async listeners before resolving.
43
+ * Wraps Node's `EventEmitter` with full TypeScript event-map inference.
44
+ *
45
+ * @example
46
+ * ```ts
47
+ * const emitter = new AsyncEventEmitter<{ build: [name: string] }>()
48
+ * emitter.on('build', async (name) => { console.log(name) })
49
+ * await emitter.emit('build', 'petstore') // all listeners awaited
50
+ * ```
51
+ */
52
+ var AsyncEventEmitter = class {
53
+ /**
54
+ * Maximum number of listeners per event before Node emits a memory-leak warning.
55
+ * @default 10
56
+ */
57
+ constructor(maxListener = 10) {
58
+ this.#emitter.setMaxListeners(maxListener);
59
+ }
60
+ #emitter = new EventEmitter();
61
+ /**
62
+ * Emits `eventName` and awaits all registered listeners sequentially.
63
+ * Throws if any listener rejects, wrapping the cause with the event name and serialized arguments.
64
+ *
65
+ * @example
66
+ * ```ts
67
+ * await emitter.emit('build', 'petstore')
68
+ * ```
69
+ */
70
+ emit(eventName, ...eventArgs) {
71
+ const listeners = this.#emitter.listeners(eventName);
72
+ if (listeners.length === 0) return;
73
+ return this.#emitAll(eventName, listeners, eventArgs);
74
+ }
75
+ async #emitAll(eventName, listeners, eventArgs) {
76
+ for (const listener of listeners) try {
77
+ await listener(...eventArgs);
78
+ } catch (err) {
79
+ let serializedArgs;
80
+ try {
81
+ serializedArgs = JSON.stringify(eventArgs);
82
+ } catch {
83
+ serializedArgs = String(eventArgs);
84
+ }
85
+ throw new Error(`Error in async listener for "${eventName}" with eventArgs ${serializedArgs}`, { cause: toError(err) });
86
+ }
87
+ }
88
+ /**
89
+ * Registers a persistent listener for `eventName`.
90
+ *
91
+ * @example
92
+ * ```ts
93
+ * emitter.on('build', async (name) => { console.log(name) })
94
+ * ```
95
+ */
96
+ on(eventName, handler) {
97
+ this.#emitter.on(eventName, handler);
98
+ }
99
+ /**
100
+ * Registers a one-shot listener that removes itself after the first invocation.
101
+ *
102
+ * @example
103
+ * ```ts
104
+ * emitter.onOnce('build', async (name) => { console.log(name) })
105
+ * ```
106
+ */
107
+ onOnce(eventName, handler) {
108
+ const wrapper = (...args) => {
109
+ this.off(eventName, wrapper);
110
+ return handler(...args);
111
+ };
112
+ this.on(eventName, wrapper);
113
+ }
114
+ /**
115
+ * Removes a previously registered listener.
116
+ *
117
+ * @example
118
+ * ```ts
119
+ * emitter.off('build', handler)
120
+ * ```
121
+ */
122
+ off(eventName, handler) {
123
+ this.#emitter.off(eventName, handler);
124
+ }
125
+ /**
126
+ * Returns the number of listeners registered for `eventName`.
127
+ *
128
+ * @example
129
+ * ```ts
130
+ * emitter.on('build', handler)
131
+ * emitter.listenerCount('build') // 1
132
+ * ```
133
+ */
134
+ listenerCount(eventName) {
135
+ return this.#emitter.listenerCount(eventName);
136
+ }
137
+ /**
138
+ * Removes all listeners from every event channel.
139
+ *
140
+ * @example
141
+ * ```ts
142
+ * emitter.removeAll()
143
+ * ```
144
+ */
145
+ removeAll() {
146
+ this.#emitter.removeAllListeners();
147
+ }
148
+ };
149
+ //#endregion
150
+ //#region ../../internals/utils/src/casing.ts
151
+ /**
152
+ * Shared implementation for camelCase and PascalCase conversion.
153
+ * Splits on common word boundaries (spaces, hyphens, underscores, dots, slashes, colons)
154
+ * and capitalizes each word according to `pascal`.
155
+ *
156
+ * When `pascal` is `true` the first word is also capitalized (PascalCase), otherwise only subsequent words are.
157
+ */
158
+ function toCamelOrPascal(text, pascal) {
159
+ return text.trim().replace(/([a-z\d])([A-Z])/g, "$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g, "$1 $2").replace(/(\d)([a-z])/g, "$1 $2").split(/[\s\-_./\\:]+/).filter(Boolean).map((word, i) => {
160
+ if (word.length > 1 && word === word.toUpperCase()) return word;
161
+ if (i === 0 && !pascal) return word.charAt(0).toLowerCase() + word.slice(1);
162
+ return word.charAt(0).toUpperCase() + word.slice(1);
163
+ }).join("").replace(/[^a-zA-Z0-9]/g, "");
164
+ }
165
+ /**
166
+ * Splits `text` on `.` and applies `transformPart` to each segment.
167
+ * The last segment receives `isLast = true`, all earlier segments receive `false`.
168
+ * Segments are joined with `/` to form a file path.
169
+ *
170
+ * Only splits on dots followed by a letter so that version numbers
171
+ * embedded in operationIds (e.g. `v2025.0`) are kept intact.
172
+ *
173
+ * Empty segments are filtered before joining. They arise when the text starts with
174
+ * a dot followed immediately by a letter (e.g. `..Schema` splits into `['..', 'Schema']`
175
+ * and `'..'` transforms to an empty string). Without this filter the join would produce
176
+ * a leading `/`, which `path.resolve` would interpret as an absolute path, allowing
177
+ * generated files to escape the configured output directory.
178
+ */
179
+ function applyToFileParts(text, transformPart) {
180
+ const parts = text.split(/\.(?=[a-zA-Z])/);
181
+ return parts.map((part, i) => transformPart(part, i === parts.length - 1)).filter(Boolean).join("/");
182
+ }
183
+ /**
184
+ * Converts `text` to camelCase.
185
+ * When `isFile` is `true`, dot-separated segments are each cased independently and joined with `/`.
186
+ *
187
+ * @example
188
+ * camelCase('hello-world') // 'helloWorld'
189
+ * camelCase('pet.petId', { isFile: true }) // 'pet/petId'
190
+ */
191
+ function camelCase(text, { isFile, prefix = "", suffix = "" } = {}) {
192
+ if (isFile) return applyToFileParts(text, (part, isLast) => camelCase(part, isLast ? {
193
+ prefix,
194
+ suffix
195
+ } : {}));
196
+ return toCamelOrPascal(`${prefix} ${text} ${suffix}`, false);
197
+ }
198
+ /**
199
+ * Converts `text` to PascalCase.
200
+ * When `isFile` is `true`, the last dot-separated segment is PascalCased and earlier segments are camelCased.
201
+ *
202
+ * @example
203
+ * pascalCase('hello-world') // 'HelloWorld'
204
+ * pascalCase('pet.petId', { isFile: true }) // 'pet/PetId'
205
+ */
206
+ function pascalCase(text, { isFile, prefix = "", suffix = "" } = {}) {
207
+ if (isFile) return applyToFileParts(text, (part, isLast) => isLast ? pascalCase(part, {
208
+ prefix,
209
+ suffix
210
+ }) : camelCase(part));
211
+ return toCamelOrPascal(`${prefix} ${text} ${suffix}`, true);
212
+ }
213
+ //#endregion
214
+ //#region ../../internals/utils/src/time.ts
215
+ /**
216
+ * Calculates elapsed time in milliseconds from a high-resolution `process.hrtime` start time.
217
+ * Rounds to 2 decimal places for sub-millisecond precision without noise.
218
+ *
219
+ * @example
220
+ * ```ts
221
+ * const start = process.hrtime()
222
+ * doWork()
223
+ * getElapsedMs(start) // 42.35
224
+ * ```
225
+ */
226
+ function getElapsedMs(hrStart) {
227
+ const [seconds, nanoseconds] = process.hrtime(hrStart);
228
+ const ms = seconds * 1e3 + nanoseconds / 1e6;
229
+ return Math.round(ms * 100) / 100;
230
+ }
231
+ /**
232
+ * Converts a millisecond duration into a human-readable string (`ms`, `s`, or `m s`).
233
+ *
234
+ * @example
235
+ * ```ts
236
+ * formatMs(250) // '250ms'
237
+ * formatMs(1500) // '1.50s'
238
+ * formatMs(90000) // '1m 30.0s'
239
+ * ```
240
+ */
241
+ function formatMs(ms) {
242
+ if (ms >= 6e4) return `${Math.floor(ms / 6e4)}m ${(ms % 6e4 / 1e3).toFixed(1)}s`;
243
+ if (ms >= 1e3) return `${(ms / 1e3).toFixed(2)}s`;
244
+ return `${Math.round(ms)}ms`;
245
+ }
246
+ //#endregion
247
+ //#region ../../internals/utils/src/promise.ts
248
+ function* chunks(arr, size) {
249
+ for (let i = 0; i < arr.length; i += size) yield arr.slice(i, i + size);
250
+ }
251
+ /**
252
+ * Slices `source` into batches of `concurrency` items and awaits `process` for each batch.
253
+ * Accepts both plain arrays (sync) and `AsyncIterable` (streaming).
254
+ *
255
+ * `process` controls whether items inside a batch run in parallel; this helper only
256
+ * controls batch size and per-batch flushing.
257
+ *
258
+ * @example
259
+ * ```ts
260
+ * // parallel dispatch inside each batch
261
+ * await forBatches(schemas, (batch) => Promise.all(batch.map(process)), { concurrency: 8 })
262
+ *
263
+ * // async iterable with a flush after every batch
264
+ * await forBatches(stream.schemas, (batch) => dispatch(batch), { concurrency: 8, flush })
265
+ * ```
266
+ */
267
+ async function forBatches(source, process, options) {
268
+ const { concurrency, flush } = options;
269
+ if (Array.isArray(source)) {
270
+ for (const batch of chunks(source, concurrency)) {
271
+ await process(batch);
272
+ if (flush) await flush();
273
+ }
274
+ return;
275
+ }
276
+ const batch = [];
277
+ for await (const item of source) {
278
+ batch.push(item);
279
+ if (batch.length >= concurrency) {
280
+ await process(batch.splice(0));
281
+ if (flush) await flush();
282
+ }
283
+ }
284
+ if (batch.length > 0) {
285
+ await process(batch.splice(0));
286
+ if (flush) await flush();
287
+ }
288
+ }
289
+ /** Returns `true` when `result` is a thenable `Promise`.
290
+ *
291
+ * @example
292
+ * ```ts
293
+ * isPromise(Promise.resolve(1)) // true
294
+ * isPromise(42) // false
295
+ * ```
296
+ */
297
+ function isPromise(result) {
298
+ return result !== null && result !== void 0 && typeof result["then"] === "function";
299
+ }
300
+ /**
301
+ * Wraps `factory` with a keyed cache backed by the provided store.
302
+ *
303
+ * Pass a `WeakMap` for object keys (results are GC-eligible when the key is
304
+ * collected) or a `Map` for primitive keys. For multi-argument functions,
305
+ * nest two `memoize` calls — the outer keyed by the first argument, the
306
+ * inner (created once per outer miss) keyed by the second.
307
+ *
308
+ * Because the cache is owned by the caller, it can be shared, inspected, or
309
+ * cleared independently of the memoized function.
310
+ *
311
+ * @example Single WeakMap key
312
+ * ```ts
313
+ * const cache = new WeakMap<SchemaNode, Set<string>>()
314
+ * const getRefs = memoize(cache, (node) => collectRefs(node))
315
+ * ```
316
+ *
317
+ * @example Single Map key (primitive)
318
+ * ```ts
319
+ * const cache = new Map<string, Resolver>()
320
+ * const getResolver = memoize(cache, (name) => buildResolver(name))
321
+ * ```
322
+ *
323
+ * @example Two-level (object + primitive)
324
+ * ```ts
325
+ * const outer = new WeakMap<Params[], Map<string, Params[]>>()
326
+ * const fn = memoize(outer, (params) => memoize(new Map(), (key) => transform(params, key)))
327
+ * fn(params)('camelcase')
328
+ * ```
329
+ */
330
+ function memoize(store, factory) {
331
+ return (key) => {
332
+ if (store.has(key)) return store.get(key);
333
+ const value = factory(key);
334
+ store.set(key, value);
335
+ return value;
336
+ };
337
+ }
338
+ /**
339
+ * Wraps a plain array in a reusable `AsyncIterable`.
340
+ * Each `[Symbol.asyncIterator]()` call returns a fresh generator so the
341
+ * iterable can be consumed multiple times (e.g. once per plugin pre-scan).
342
+ *
343
+ * @example
344
+ * ```ts
345
+ * const stream = arrayToAsyncIterable([1, 2, 3])
346
+ * for await (const n of stream) console.log(n) // 1, 2, 3
347
+ * ```
348
+ */
349
+ function arrayToAsyncIterable(arr) {
350
+ return { [Symbol.asyncIterator]() {
351
+ return (async function* () {
352
+ yield* arr;
353
+ })();
354
+ } };
355
+ }
356
+ //#endregion
357
+ //#region ../../internals/utils/src/reserved.ts
358
+ /**
359
+ * JavaScript and Java reserved words.
360
+ * @link https://github.com/jonschlinkert/reserved/blob/master/index.js
361
+ */
362
+ const reservedWords = new Set([
363
+ "abstract",
364
+ "arguments",
365
+ "boolean",
366
+ "break",
367
+ "byte",
368
+ "case",
369
+ "catch",
370
+ "char",
371
+ "class",
372
+ "const",
373
+ "continue",
374
+ "debugger",
375
+ "default",
376
+ "delete",
377
+ "do",
378
+ "double",
379
+ "else",
380
+ "enum",
381
+ "eval",
382
+ "export",
383
+ "extends",
384
+ "false",
385
+ "final",
386
+ "finally",
387
+ "float",
388
+ "for",
389
+ "function",
390
+ "goto",
391
+ "if",
392
+ "implements",
393
+ "import",
394
+ "in",
395
+ "instanceof",
396
+ "int",
397
+ "interface",
398
+ "let",
399
+ "long",
400
+ "native",
401
+ "new",
402
+ "null",
403
+ "package",
404
+ "private",
405
+ "protected",
406
+ "public",
407
+ "return",
408
+ "short",
409
+ "static",
410
+ "super",
411
+ "switch",
412
+ "synchronized",
413
+ "this",
414
+ "throw",
415
+ "throws",
416
+ "transient",
417
+ "true",
418
+ "try",
419
+ "typeof",
420
+ "var",
421
+ "void",
422
+ "volatile",
423
+ "while",
424
+ "with",
425
+ "yield",
426
+ "Array",
427
+ "Date",
428
+ "hasOwnProperty",
429
+ "Infinity",
430
+ "isFinite",
431
+ "isNaN",
432
+ "isPrototypeOf",
433
+ "length",
434
+ "Math",
435
+ "name",
436
+ "NaN",
437
+ "Number",
438
+ "Object",
439
+ "prototype",
440
+ "String",
441
+ "toString",
442
+ "undefined",
443
+ "valueOf"
444
+ ]);
445
+ /**
446
+ * Returns `true` when `name` is a syntactically valid JavaScript variable name.
447
+ *
448
+ * @example
449
+ * ```ts
450
+ * isValidVarName('status') // true
451
+ * isValidVarName('class') // false (reserved word)
452
+ * isValidVarName('42foo') // false (starts with digit)
453
+ * ```
454
+ */
455
+ function isValidVarName(name) {
456
+ if (!name || reservedWords.has(name)) return false;
457
+ return /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(name);
458
+ }
459
+ //#endregion
460
+ //#region ../../internals/utils/src/urlPath.ts
461
+ /**
462
+ * Parses and transforms an OpenAPI/Swagger path string into various URL formats.
463
+ *
464
+ * @example
465
+ * const p = new URLPath('/pet/{petId}')
466
+ * p.URL // '/pet/:petId'
467
+ * p.template // '`/pet/${petId}`'
468
+ */
469
+ var URLPath = class {
470
+ /**
471
+ * The raw OpenAPI/Swagger path string, e.g. `/pet/{petId}`.
472
+ */
473
+ path;
474
+ #options;
475
+ constructor(path, options = {}) {
476
+ this.path = path;
477
+ this.#options = options;
478
+ }
479
+ /** Converts the OpenAPI path to Express-style colon syntax, e.g. `/pet/{petId}` → `/pet/:petId`.
480
+ *
481
+ * @example
482
+ * ```ts
483
+ * new URLPath('/pet/{petId}').URL // '/pet/:petId'
484
+ * ```
485
+ */
486
+ get URL() {
487
+ return this.toURLPath();
488
+ }
489
+ /** Returns `true` when `path` is a fully-qualified URL (e.g. starts with `https://`).
490
+ *
491
+ * @example
492
+ * ```ts
493
+ * new URLPath('https://petstore.swagger.io/v2/pet').isURL // true
494
+ * new URLPath('/pet/{petId}').isURL // false
495
+ * ```
496
+ */
497
+ get isURL() {
498
+ try {
499
+ return !!new URL(this.path).href;
500
+ } catch {
501
+ return false;
502
+ }
503
+ }
504
+ /**
505
+ * Converts the OpenAPI path to a TypeScript template literal string.
506
+ *
507
+ * @example
508
+ * new URLPath('/pet/{petId}').template // '`/pet/${petId}`'
509
+ * new URLPath('/account/monetary-accountID').template // '`/account/${monetaryAccountId}`'
510
+ */
511
+ get template() {
512
+ return this.toTemplateString();
513
+ }
514
+ /** Returns the path and its extracted params as a structured `URLObject`, or as a stringified expression when `stringify` is set.
515
+ *
516
+ * @example
517
+ * ```ts
518
+ * new URLPath('/pet/{petId}').object
519
+ * // { url: '/pet/:petId', params: { petId: 'petId' } }
520
+ * ```
521
+ */
522
+ get object() {
523
+ return this.toObject();
524
+ }
525
+ /** Returns a map of path parameter names, or `undefined` when the path has no parameters.
526
+ *
527
+ * @example
528
+ * ```ts
529
+ * new URLPath('/pet/{petId}').params // { petId: 'petId' }
530
+ * new URLPath('/pet').params // undefined
531
+ * ```
532
+ */
533
+ get params() {
534
+ return this.getParams();
535
+ }
536
+ #transformParam(raw) {
537
+ const param = isValidVarName(raw) ? raw : camelCase(raw);
538
+ return this.#options.casing === "camelcase" ? camelCase(param) : param;
539
+ }
540
+ /**
541
+ * Iterates over every `{param}` token in `path`, calling `fn` with the raw token and transformed name.
542
+ */
543
+ #eachParam(fn) {
544
+ for (const match of this.path.matchAll(/\{([^}]+)\}/g)) {
545
+ const raw = match[1];
546
+ fn(raw, this.#transformParam(raw));
547
+ }
548
+ }
549
+ toObject({ type = "path", replacer, stringify } = {}) {
550
+ const object = {
551
+ url: type === "path" ? this.toURLPath() : this.toTemplateString({ replacer }),
552
+ params: this.getParams()
553
+ };
554
+ if (stringify) {
555
+ if (type === "template") return JSON.stringify(object).replaceAll("'", "").replaceAll(`"`, "");
556
+ if (object.params) return `{ url: '${object.url}', params: ${JSON.stringify(object.params).replaceAll("'", "").replaceAll(`"`, "")} }`;
557
+ return `{ url: '${object.url}' }`;
558
+ }
559
+ return object;
560
+ }
561
+ /**
562
+ * Converts the OpenAPI path to a TypeScript template literal string.
563
+ * An optional `replacer` can transform each extracted parameter name before interpolation.
564
+ *
565
+ * @example
566
+ * new URLPath('/pet/{petId}').toTemplateString() // '`/pet/${petId}`'
567
+ */
568
+ toTemplateString({ prefix, replacer } = {}) {
569
+ const result = this.path.split(/\{([^}]+)\}/).map((part, i) => {
570
+ if (i % 2 === 0) return part;
571
+ const param = this.#transformParam(part);
572
+ return `\${${replacer ? replacer(param) : param}}`;
573
+ }).join("");
574
+ return `\`${prefix ?? ""}${result}\``;
575
+ }
576
+ /**
577
+ * Extracts all `{param}` segments from the path and returns them as a key-value map.
578
+ * An optional `replacer` transforms each parameter name in both key and value positions.
579
+ * Returns `undefined` when no path parameters are found.
580
+ *
581
+ * @example
582
+ * ```ts
583
+ * new URLPath('/pet/{petId}/tag/{tagId}').getParams()
584
+ * // { petId: 'petId', tagId: 'tagId' }
585
+ * ```
586
+ */
587
+ getParams(replacer) {
588
+ const params = {};
589
+ this.#eachParam((_raw, param) => {
590
+ const key = replacer ? replacer(param) : param;
591
+ params[key] = key;
592
+ });
593
+ return Object.keys(params).length > 0 ? params : void 0;
594
+ }
595
+ /** Converts the OpenAPI path to Express-style colon syntax.
596
+ *
597
+ * @example
598
+ * ```ts
599
+ * new URLPath('/pet/{petId}').toURLPath() // '/pet/:petId'
600
+ * ```
601
+ */
602
+ toURLPath() {
603
+ return this.path.replace(/\{([^}]+)\}/g, ":$1");
604
+ }
605
+ };
606
+ //#endregion
607
+ //#region src/constants.ts
608
+ /**
609
+ * Base URL for the Kubb Studio web app.
610
+ */
611
+ const DEFAULT_STUDIO_URL = "https://kubb.studio";
612
+ /**
613
+ * Default banner style written at the top of every generated file.
614
+ */
615
+ const DEFAULT_BANNER = "simple";
616
+ /**
617
+ * Default file-extension mapping used when no explicit mapping is configured.
618
+ */
619
+ const DEFAULT_EXTENSION = { ".ts": ".ts" };
620
+ /**
621
+ * Numeric log-level thresholds used internally to compare verbosity.
622
+ *
623
+ * Higher numbers are more verbose.
624
+ */
625
+ const logLevel = {
626
+ silent: Number.NEGATIVE_INFINITY,
627
+ error: 0,
628
+ warn: 1,
629
+ info: 3,
630
+ verbose: 4,
631
+ debug: 5
632
+ };
633
+ //#endregion
634
+ //#region src/definePlugin.ts
635
+ /**
636
+ * Wraps a plugin factory and returns a function that accepts user options and
637
+ * yields a fully typed `Plugin`. Lifecycle handlers go inside a single
638
+ * `hooks` object (inspired by Astro integrations).
639
+ *
640
+ * Pass a `PluginFactoryOptions` type parameter to get a typed `ctx` inside
641
+ * `kubb:plugin:setup`. Plugin names should follow the `plugin-<feature>`
642
+ * convention (`plugin-react-query`, `plugin-zod`, ...).
643
+ *
644
+ * @example
645
+ * ```ts
646
+ * import { definePlugin } from '@kubb/core'
647
+ *
648
+ * export const pluginTs = definePlugin((options: { prefix?: string } = {}) => ({
649
+ * name: 'plugin-ts',
650
+ * hooks: {
651
+ * 'kubb:plugin:setup'(ctx) {
652
+ * ctx.setResolver(resolverTs)
653
+ * },
654
+ * },
655
+ * }))
656
+ * ```
657
+ */
658
+ function definePlugin(factory) {
659
+ return (options) => factory(options ?? {});
660
+ }
661
+ /**
662
+ * Detects whether an output path points at a single file (`'single'`) or a
663
+ * directory (`'split'`). Decided purely from the presence of a file extension.
664
+ *
665
+ * @example Directory
666
+ * `getMode('./types') // 'split'`
667
+ *
668
+ * @example Single file
669
+ * `getMode('./api.ts') // 'single'`
670
+ */
671
+ function getMode(fileOrFolder) {
672
+ if (!fileOrFolder) return "split";
673
+ return extname(fileOrFolder) ? "single" : "split";
674
+ }
675
+ //#endregion
676
+ //#region src/defineResolver.ts
677
+ /**
678
+ * Merges document `meta` with per-file `file` context into the `BannerMeta` passed to a
679
+ * `banner`/`footer` function. Missing fields default to empty/`false` so the object shape
680
+ * is stable even when a caller (e.g. the barrel middleware) has no document metadata.
681
+ */
682
+ function buildBannerMeta({ meta, file }) {
683
+ return {
684
+ title: meta?.title,
685
+ description: meta?.description,
686
+ version: meta?.version,
687
+ baseURL: meta?.baseURL,
688
+ circularNames: meta?.circularNames ?? [],
689
+ enumNames: meta?.enumNames ?? [],
690
+ filePath: file?.path ?? "",
691
+ baseName: file?.baseName ?? "",
692
+ isBarrel: file?.isBarrel ?? false,
693
+ isAggregation: file?.isAggregation ?? false
694
+ };
695
+ }
696
+ const stringPatternCache = /* @__PURE__ */ new Map();
697
+ function testPattern(value, pattern) {
698
+ if (typeof pattern === "string") {
699
+ let regex = stringPatternCache.get(pattern);
700
+ if (!regex) {
701
+ regex = new RegExp(pattern);
702
+ stringPatternCache.set(pattern, regex);
703
+ }
704
+ return regex.test(value);
705
+ }
706
+ return value.match(pattern) !== null;
707
+ }
708
+ /**
709
+ * Checks if an operation matches a pattern for a given filter type (`tag`, `operationId`, `path`, `method`).
710
+ */
711
+ function matchesOperationPattern(node, type, pattern) {
712
+ if (type === "tag") return node.tags.some((tag) => testPattern(tag, pattern));
713
+ if (type === "operationId") return testPattern(node.operationId, pattern);
714
+ if (type === "path") return node.path !== void 0 && testPattern(node.path, pattern);
715
+ if (type === "method") return node.method !== void 0 && testPattern(node.method.toLowerCase(), pattern);
716
+ if (type === "contentType") return node.requestBody?.content?.some((c) => testPattern(c.contentType, pattern)) ?? false;
717
+ return false;
718
+ }
719
+ /**
720
+ * Checks if a schema matches a pattern for a given filter type (`schemaName`).
721
+ *
722
+ * Returns `null` when the filter type doesn't apply to schemas.
723
+ */
724
+ function matchesSchemaPattern(node, type, pattern) {
725
+ if (type === "schemaName") return node.name ? testPattern(node.name, pattern) : false;
726
+ return null;
727
+ }
728
+ /**
729
+ * Default name resolver used by `defineResolver`.
730
+ *
731
+ * - `camelCase` for `function` and `file` types.
732
+ * - `PascalCase` for `type`.
733
+ * - `camelCase` for everything else.
734
+ */
735
+ function defaultResolver(name, type) {
736
+ if (type === "file" || type === "function") return camelCase(name, { isFile: type === "file" });
737
+ if (type === "type") return pascalCase(name);
738
+ return camelCase(name);
739
+ }
740
+ /**
741
+ * Default option resolver — applies include/exclude filters and merges matching override options.
742
+ *
743
+ * Returns `null` when the node is filtered out by an `exclude` rule or not matched by any `include` rule.
744
+ *
745
+ * @example Include/exclude filtering
746
+ * ```ts
747
+ * const options = defaultResolveOptions(operationNode, {
748
+ * options: { output: 'types' },
749
+ * exclude: [{ type: 'tag', pattern: 'internal' }],
750
+ * })
751
+ * // → null when node has tag 'internal'
752
+ * ```
753
+ *
754
+ * @example Override merging
755
+ * ```ts
756
+ * const options = defaultResolveOptions(operationNode, {
757
+ * options: { enumType: 'asConst' },
758
+ * override: [{ type: 'operationId', pattern: 'listPets', options: { enumType: 'enum' } }],
759
+ * })
760
+ * // → { enumType: 'enum' } when operationId matches
761
+ * ```
762
+ */
763
+ const resolveOptionsCache = /* @__PURE__ */ new WeakMap();
764
+ function computeOptions(node, options, exclude, include, override) {
765
+ if (isOperationNode(node)) {
766
+ if (exclude.some(({ type, pattern }) => matchesOperationPattern(node, type, pattern))) return null;
767
+ if (include && !include.some(({ type, pattern }) => matchesOperationPattern(node, type, pattern))) return null;
768
+ const overrideOptions = override.find(({ type, pattern }) => matchesOperationPattern(node, type, pattern))?.options;
769
+ return {
770
+ ...options,
771
+ ...overrideOptions
772
+ };
773
+ }
774
+ if (isSchemaNode(node)) {
775
+ if (exclude.some(({ type, pattern }) => matchesSchemaPattern(node, type, pattern) === true)) return null;
776
+ if (include) {
777
+ const applicable = include.map(({ type, pattern }) => matchesSchemaPattern(node, type, pattern)).filter((r) => r !== null);
778
+ if (applicable.length > 0 && !applicable.includes(true)) return null;
779
+ }
780
+ const overrideOptions = override.find(({ type, pattern }) => matchesSchemaPattern(node, type, pattern) === true)?.options;
781
+ return {
782
+ ...options,
783
+ ...overrideOptions
784
+ };
785
+ }
786
+ return options;
787
+ }
788
+ function defaultResolveOptions(node, { options, exclude = [], include, override = [] }) {
789
+ const optionsKey = options;
790
+ let byOptions = resolveOptionsCache.get(optionsKey);
791
+ if (!byOptions) {
792
+ byOptions = /* @__PURE__ */ new WeakMap();
793
+ resolveOptionsCache.set(optionsKey, byOptions);
794
+ }
795
+ const cached = byOptions.get(node);
796
+ if (cached !== void 0) return cached.value;
797
+ const result = computeOptions(node, options, exclude, include, override);
798
+ byOptions.set(node, { value: result });
799
+ return result;
800
+ }
801
+ /**
802
+ * Default path resolver used by `defineResolver`.
803
+ *
804
+ * - Returns the output directory in `single` mode.
805
+ * - Resolves into a tag- or path-based subdirectory when `group` and a `tag`/`path` value are provided.
806
+ * - Falls back to a flat `output/baseName` path otherwise.
807
+ *
808
+ * A custom `group.name` function overrides the default subdirectory naming.
809
+ * For `tag` groups the default is `${camelCase(tag)}Controller`.
810
+ * For `path` groups the default is the first path segment after `/`.
811
+ *
812
+ * @example Flat output
813
+ * ```ts
814
+ * defaultResolvePath({ baseName: 'petTypes.ts' }, { root: '/src', output: { path: 'types' } })
815
+ * // → '/src/types/petTypes.ts'
816
+ * ```
817
+ *
818
+ * @example Tag-based grouping
819
+ * ```ts
820
+ * defaultResolvePath(
821
+ * { baseName: 'petTypes.ts', tag: 'pets' },
822
+ * { root: '/src', output: { path: 'types' }, group: { type: 'tag' } },
823
+ * )
824
+ * // → '/src/types/petsController/petTypes.ts'
825
+ * ```
826
+ *
827
+ * @example Path-based grouping
828
+ * ```ts
829
+ * defaultResolvePath(
830
+ * { baseName: 'petTypes.ts', path: '/pets/list' },
831
+ * { root: '/src', output: { path: 'types' }, group: { type: 'path' } },
832
+ * )
833
+ * // → '/src/types/pets/petTypes.ts'
834
+ * ```
835
+ *
836
+ * @example Single-file mode
837
+ * ```ts
838
+ * defaultResolvePath(
839
+ * { baseName: 'petTypes.ts', pathMode: 'single' },
840
+ * { root: '/src', output: { path: 'types' } },
841
+ * )
842
+ * // → '/src/types'
843
+ * ```
844
+ */
845
+ function defaultResolvePath({ baseName, pathMode, tag, path: groupPath }, { root, output, group }) {
846
+ if ((pathMode ?? getMode(path.resolve(root, output.path))) === "single") return path.resolve(root, output.path);
847
+ const result = (() => {
848
+ if (group && (groupPath || tag)) {
849
+ const groupValue = group.type === "path" ? groupPath : tag;
850
+ const defaultName = group.type === "tag" ? ({ group: g }) => `${camelCase(g)}Controller` : ({ group: g }) => {
851
+ const segment = g.split("/").filter((s) => s !== "" && s !== "." && s !== "..")[0];
852
+ return segment ? camelCase(segment) : "";
853
+ };
854
+ const resolveName = group.name ?? defaultName;
855
+ return path.resolve(root, output.path, resolveName({ group: groupValue }), baseName);
856
+ }
857
+ return path.resolve(root, output.path, baseName);
858
+ })();
859
+ const outputDir = path.resolve(root, output.path);
860
+ const outputDirWithSep = outputDir.endsWith(path.sep) ? outputDir : `${outputDir}${path.sep}`;
861
+ if (result !== outputDir && !result.startsWith(outputDirWithSep)) throw new Error(`[Kubb] Resolved path "${result}" is outside the output directory "${outputDir}". This may indicate a path traversal attempt in the OpenAPI specification or a misconfigured group.name function.`);
862
+ return result;
863
+ }
864
+ /**
865
+ * Default file resolver used by `defineResolver`.
866
+ *
867
+ * Resolves a `FileNode` by combining name resolution (`resolver.default`) with
868
+ * path resolution (`resolver.resolvePath`). The resolved file always has empty
869
+ * `sources`, `imports`, and `exports` arrays — consumers populate those separately.
870
+ *
871
+ * In `single` mode the name is omitted and the file sits directly in the output directory.
872
+ *
873
+ * @example Resolve a schema file
874
+ * ```ts
875
+ * const file = defaultResolveFile.call(
876
+ * resolver,
877
+ * { name: 'pet', extname: '.ts' },
878
+ * { root: '/src', output: { path: 'types' } },
879
+ * )
880
+ * // → { baseName: 'pet.ts', path: '/src/types/pet.ts', sources: [], ... }
881
+ * ```
882
+ *
883
+ * @example Resolve an operation file with tag grouping
884
+ * ```ts
885
+ * const file = defaultResolveFile.call(
886
+ * resolver,
887
+ * { name: 'listPets', extname: '.ts', tag: 'pets' },
888
+ * { root: '/src', output: { path: 'types' }, group: { type: 'tag' } },
889
+ * )
890
+ * // → { baseName: 'listPets.ts', path: '/src/types/petsController/listPets.ts', ... }
891
+ * ```
892
+ */
893
+ function defaultResolveFile({ name, extname, tag, path: groupPath }, context) {
894
+ const pathMode = getMode(path.resolve(context.root, context.output.path));
895
+ const baseName = `${pathMode === "single" ? "" : this.default(name, "file")}${extname}`;
896
+ const filePath = this.resolvePath({
897
+ baseName,
898
+ pathMode,
899
+ tag,
900
+ path: groupPath
901
+ }, context);
902
+ return createFile({
903
+ path: filePath,
904
+ baseName: path.basename(filePath),
905
+ meta: { pluginName: this.pluginName },
906
+ sources: [],
907
+ imports: [],
908
+ exports: []
909
+ });
910
+ }
911
+ /**
912
+ * Generates the default "Generated by Kubb" banner from config and optional node metadata.
913
+ */
914
+ function buildDefaultBanner({ title, description, version, config }) {
915
+ try {
916
+ const source = (() => {
917
+ if (Array.isArray(config.input)) {
918
+ const first = config.input[0];
919
+ if (first && "path" in first) return path.basename(first.path);
920
+ return "";
921
+ }
922
+ if (config.input && "path" in config.input) return path.basename(config.input.path);
923
+ if (config.input && "data" in config.input) return "text content";
924
+ return "";
925
+ })();
926
+ let banner = "/**\n* Generated by Kubb (https://kubb.dev/).\n* Do not edit manually.\n";
927
+ if (config.output.defaultBanner === "simple") {
928
+ banner += "*/\n";
929
+ return banner;
930
+ }
931
+ if (source) banner += `* Source: ${source}\n`;
932
+ if (title) banner += `* Title: ${title}\n`;
933
+ if (description) {
934
+ const formattedDescription = description.replace(/\n/gm, "\n* ");
935
+ banner += `* Description: ${formattedDescription}\n`;
936
+ }
937
+ if (version) banner += `* OpenAPI spec version: ${version}\n`;
938
+ banner += "*/\n";
939
+ return banner;
940
+ } catch (_error) {
941
+ return "/**\n* Generated by Kubb (https://kubb.dev/).\n* Do not edit manually.\n*/";
942
+ }
943
+ }
944
+ /**
945
+ * Default banner resolver — returns the banner string for a generated file.
946
+ *
947
+ * A user-supplied `output.banner` overrides the default Kubb "Generated by Kubb" notice.
948
+ * When no `output.banner` is set, the Kubb notice is used (including `title` and `version`
949
+ * from the document metadata when `meta` is provided).
950
+ *
951
+ * - When `output.banner` is a function, calls it with the file's `BannerMeta` and returns the result.
952
+ * - When `output.banner` is a string, returns it directly.
953
+ * - When `config.output.defaultBanner` is `false`, returns `undefined`.
954
+ * - Otherwise returns the Kubb "Generated by Kubb" notice.
955
+ *
956
+ * @example String banner overrides default
957
+ * ```ts
958
+ * defaultResolveBanner(undefined, { output: { banner: '// my banner' }, config })
959
+ * // → '// my banner'
960
+ * ```
961
+ *
962
+ * @example Function banner with metadata
963
+ * ```ts
964
+ * defaultResolveBanner(meta, { output: { banner: (m) => `// v${m.version}` }, config })
965
+ * // → '// v3.0.0'
966
+ * ```
967
+ *
968
+ * @example Function banner skips re-export files
969
+ * ```ts
970
+ * defaultResolveBanner(meta, { output: { banner: (m) => (m.isBarrel ? '' : "'use server'") }, config, file: { path, baseName, isBarrel: true } })
971
+ * // → ''
972
+ * ```
973
+ *
974
+ * @example No user banner — Kubb notice with OAS metadata
975
+ * ```ts
976
+ * defaultResolveBanner(meta, { config })
977
+ * // → '/** Generated by Kubb ... Title: Pet Store ... *\/'
978
+ * ```
979
+ *
980
+ * @example Disabled default banner
981
+ * ```ts
982
+ * defaultResolveBanner(undefined, { config: { output: { defaultBanner: false }, ...config } })
983
+ * // → null
984
+ * ```
985
+ */
986
+ function defaultResolveBanner(meta, { output, config, file }) {
987
+ if (typeof output?.banner === "function") return output.banner(buildBannerMeta({
988
+ meta,
989
+ file
990
+ }));
991
+ if (typeof output?.banner === "string") return output.banner;
992
+ if (config.output.defaultBanner === false) return null;
993
+ return buildDefaultBanner({
994
+ title: meta?.title,
995
+ version: meta?.version,
996
+ config
997
+ });
998
+ }
999
+ /**
1000
+ * Default footer resolver — returns the footer string for a generated file.
1001
+ *
1002
+ * - When `output.footer` is a function, calls it with the file's `BannerMeta` and returns the result.
1003
+ * - When `output.footer` is a string, returns it directly.
1004
+ * - Otherwise returns `undefined`.
1005
+ *
1006
+ * @example String footer
1007
+ * ```ts
1008
+ * defaultResolveFooter(undefined, { output: { footer: '// end of file' }, config })
1009
+ * // → '// end of file'
1010
+ * ```
1011
+ *
1012
+ * @example Function footer with metadata
1013
+ * ```ts
1014
+ * defaultResolveFooter(meta, { output: { footer: (m) => `// ${m.title}` }, config })
1015
+ * // → '// Pet Store'
1016
+ * ```
1017
+ */
1018
+ function defaultResolveFooter(meta, { output, file }) {
1019
+ if (typeof output?.footer === "function") return output.footer(buildBannerMeta({
1020
+ meta,
1021
+ file
1022
+ }));
1023
+ if (typeof output?.footer === "string") return output.footer;
1024
+ return null;
1025
+ }
1026
+ /**
1027
+ * Defines a plugin resolver. The resolver is the object that decides what
1028
+ * every generated symbol and file path is called. Built-in defaults handle
1029
+ * name casing, include/exclude/override filtering, output path computation,
1030
+ * and file construction. Supply your own to override any of them:
1031
+ *
1032
+ * - `default` — name casing strategy (camelCase / PascalCase).
1033
+ * - `resolveOptions` — include/exclude/override filtering.
1034
+ * - `resolvePath` — output path computation.
1035
+ * - `resolveFile` — full `FileNode` construction.
1036
+ * - `resolveBanner` / `resolveFooter` — top/bottom-of-file text.
1037
+ *
1038
+ * Methods in the returned object can call sibling resolver methods via `this`,
1039
+ * which keeps custom rules small (`this.default(name, 'type')` to delegate).
1040
+ *
1041
+ * @example Basic resolver with naming helpers
1042
+ * ```ts
1043
+ * export const resolverTs = defineResolver<PluginTs>(() => ({
1044
+ * name: 'default',
1045
+ * resolveName(name) {
1046
+ * return this.default(name, 'function')
1047
+ * },
1048
+ * resolveTypeName(name) {
1049
+ * return this.default(name, 'type')
1050
+ * },
1051
+ * }))
1052
+ * ```
1053
+ *
1054
+ * @example Custom output path
1055
+ * ```ts
1056
+ * import path from 'node:path'
1057
+ *
1058
+ * export const resolverTs = defineResolver<PluginTs>(() => ({
1059
+ * name: 'custom',
1060
+ * resolvePath({ baseName }, { root, output }) {
1061
+ * return path.resolve(root, output.path, 'generated', baseName)
1062
+ * },
1063
+ * }))
1064
+ * ```
1065
+ */
1066
+ function defineResolver(build) {
1067
+ let resolver;
1068
+ resolver = {
1069
+ default: defaultResolver,
1070
+ resolveOptions: defaultResolveOptions,
1071
+ resolvePath: defaultResolvePath,
1072
+ resolveFile: (params, context) => defaultResolveFile.call(resolver, params, context),
1073
+ resolveBanner: defaultResolveBanner,
1074
+ resolveFooter: defaultResolveFooter,
1075
+ ...build()
1076
+ };
1077
+ return resolver;
1078
+ }
1079
+ //#endregion
1080
+ //#region src/devtools.ts
1081
+ /**
1082
+ * Encodes an `InputNode` as a compressed, URL-safe string.
1083
+ *
1084
+ * The JSON representation is deflate-compressed with {@link deflateSync} before
1085
+ * base64url encoding, which typically reduces payload size by 70–80 % and
1086
+ * keeps URLs well within browser and server path-length limits.
1087
+ *
1088
+ * Use {@link decodeAst} to reverse.
1089
+ */
1090
+ function encodeAst(input) {
1091
+ const compressed = deflateSync(new TextEncoder().encode(JSON.stringify(input)));
1092
+ return Buffer.from(compressed).toString("base64url");
1093
+ }
1094
+ /**
1095
+ * Constructs the Kubb Studio URL for the given `InputNode`.
1096
+ * When `options.ast` is `true`, navigates to the AST inspector (`/ast`).
1097
+ * The `input` is encoded and attached as the `?root=` query parameter so Studio
1098
+ * can decode and render it without a round-trip to any server.
1099
+ */
1100
+ function getStudioUrl(input, studioUrl, options = {}) {
1101
+ return `${studioUrl.replace(/\/$/, "")}${options.ast ? "/ast" : ""}?root=${encodeAst(input)}`;
1102
+ }
1103
+ /**
1104
+ * Opens the Kubb Studio URL for the given `InputNode` in the default browser —
1105
+ *
1106
+ * Falls back to printing the URL if the browser cannot be launched.
1107
+ */
1108
+ async function openInStudio(input, studioUrl, options = {}) {
1109
+ const url = getStudioUrl(input, studioUrl, options);
1110
+ const cmd = process.platform === "win32" ? "cmd" : process.platform === "darwin" ? "open" : "xdg-open";
1111
+ const args = process.platform === "win32" ? [
1112
+ "/c",
1113
+ "start",
1114
+ "",
1115
+ url
1116
+ ] : [url];
1117
+ try {
1118
+ await x(cmd, args);
1119
+ } catch {
1120
+ console.log(`\n ${url}\n`);
1121
+ }
1122
+ }
1123
+ //#endregion
1124
+ //#region src/FileManager.ts
1125
+ function mergeFile(a, b) {
1126
+ return {
1127
+ ...a,
1128
+ banner: b.banner,
1129
+ footer: b.footer,
1130
+ sources: a.sources.length ? b.sources.length ? [...a.sources, ...b.sources] : a.sources : b.sources,
1131
+ imports: a.imports.length ? b.imports.length ? [...a.imports, ...b.imports] : a.imports : b.imports,
1132
+ exports: a.exports.length ? b.exports.length ? [...a.exports, ...b.exports] : a.exports : b.exports
1133
+ };
1134
+ }
1135
+ function isIndexPath(path) {
1136
+ return path.endsWith("/index.ts") || path === "index.ts";
1137
+ }
1138
+ function compareFiles(a, b) {
1139
+ const lenDiff = a.path.length - b.path.length;
1140
+ if (lenDiff !== 0) return lenDiff;
1141
+ const aIsIndex = isIndexPath(a.path);
1142
+ const bIsIndex = isIndexPath(b.path);
1143
+ if (aIsIndex && !bIsIndex) return 1;
1144
+ if (!aIsIndex && bIsIndex) return -1;
1145
+ return 0;
1146
+ }
1147
+ /**
1148
+ * In-memory file store for generated files. Files sharing a `path` are merged
1149
+ * (sources/imports/exports concatenated). The `files` getter is sorted by
1150
+ * path length (barrel `index.ts` last within a bucket).
1151
+ *
1152
+ * @example
1153
+ * ```ts
1154
+ * const manager = new FileManager()
1155
+ * manager.upsert(myFile)
1156
+ * manager.files // sorted view
1157
+ * ```
1158
+ */
1159
+ var FileManager = class {
1160
+ #cache = /* @__PURE__ */ new Map();
1161
+ #sorted = null;
1162
+ #onUpsert = null;
1163
+ /**
1164
+ * Registers a callback invoked with the resolved {@link FileNode} on every
1165
+ * `add` / `upsert`. Used by the build loop to track newly written files
1166
+ * without keeping its own scan-based diff. Single subscriber by design —
1167
+ * setting again replaces the previous callback. Pass `null` to detach.
1168
+ */
1169
+ setOnUpsert(callback) {
1170
+ this.#onUpsert = callback;
1171
+ }
1172
+ add(...files) {
1173
+ return this.#store(files, false);
1174
+ }
1175
+ upsert(...files) {
1176
+ return this.#store(files, true);
1177
+ }
1178
+ #store(files, mergeExisting) {
1179
+ const batch = files.length > 1 ? this.#dedupe(files) : files;
1180
+ const resolved = [];
1181
+ for (const file of batch) {
1182
+ const existing = this.#cache.get(file.path);
1183
+ const merged = existing && mergeExisting ? createFile(mergeFile(existing, file)) : createFile(file);
1184
+ this.#cache.set(merged.path, merged);
1185
+ resolved.push(merged);
1186
+ this.#onUpsert?.(merged);
1187
+ }
1188
+ if (resolved.length > 0) this.#sorted = null;
1189
+ return resolved;
1190
+ }
1191
+ #dedupe(files) {
1192
+ const seen = /* @__PURE__ */ new Map();
1193
+ for (const file of files) {
1194
+ const prev = seen.get(file.path);
1195
+ seen.set(file.path, prev ? mergeFile(prev, file) : file);
1196
+ }
1197
+ return [...seen.values()];
1198
+ }
1199
+ getByPath(path) {
1200
+ return this.#cache.get(path) ?? null;
1201
+ }
1202
+ deleteByPath(path) {
1203
+ if (!this.#cache.delete(path)) return;
1204
+ this.#sorted = null;
1205
+ }
1206
+ clear() {
1207
+ this.#cache.clear();
1208
+ this.#sorted = null;
1209
+ }
1210
+ /**
1211
+ * Releases all stored files. Called by the core after `kubb:build:end`.
1212
+ */
1213
+ dispose() {
1214
+ this.clear();
1215
+ this.#onUpsert = null;
1216
+ }
1217
+ [Symbol.dispose]() {
1218
+ this.dispose();
1219
+ }
1220
+ /**
1221
+ * All stored files in stable sort order (shortest path first, barrel files
1222
+ * last within a length bucket). Returns a cached view — do not mutate.
1223
+ */
1224
+ get files() {
1225
+ return this.#sorted ??= [...this.#cache.values()].sort(compareFiles);
1226
+ }
1227
+ };
1228
+ //#endregion
1229
+ //#region src/FileProcessor.ts
1230
+ function joinSources(file) {
1231
+ const sources = file.sources;
1232
+ if (sources.length === 0) return "";
1233
+ const parts = [];
1234
+ for (const source of sources) {
1235
+ const s = extractStringsFromNodes(source.nodes);
1236
+ if (s) parts.push(s);
1237
+ }
1238
+ return parts.join("\n\n");
1239
+ }
1240
+ /**
1241
+ * Converts a single file to a string using the registered parsers.
1242
+ * Falls back to joining source values when no matching parser is found.
1243
+ *
1244
+ * @internal
1245
+ */
1246
+ var FileProcessor = class {
1247
+ events = new AsyncEventEmitter();
1248
+ parse(file, { parsers, extension } = {}) {
1249
+ const parseExtName = extension?.[file.extname] || void 0;
1250
+ if (!parsers || !file.extname) return joinSources(file);
1251
+ const parser = parsers.get(file.extname);
1252
+ if (!parser) return joinSources(file);
1253
+ return parser.parse(file, { extname: parseExtName });
1254
+ }
1255
+ *stream(files, options = {}) {
1256
+ const total = files.length;
1257
+ if (total === 0) return;
1258
+ let processed = 0;
1259
+ for (const file of files) {
1260
+ const source = this.parse(file, options);
1261
+ processed++;
1262
+ yield {
1263
+ file,
1264
+ source,
1265
+ processed,
1266
+ total,
1267
+ percentage: processed / total * 100
1268
+ };
1269
+ }
1270
+ }
1271
+ async run(files, options = {}) {
1272
+ await this.events.emit("start", files);
1273
+ for (const { file, source, processed, total, percentage } of this.stream(files, options)) await this.events.emit("update", {
1274
+ file,
1275
+ source,
1276
+ processed,
1277
+ percentage,
1278
+ total
1279
+ });
1280
+ await this.events.emit("end", files);
1281
+ return files;
1282
+ }
1283
+ /**
1284
+ * Clears all registered event listeners.
1285
+ */
1286
+ dispose() {
1287
+ this.events.removeAll();
1288
+ }
1289
+ [Symbol.dispose]() {
1290
+ this.dispose();
1291
+ }
1292
+ };
1293
+ //#endregion
1294
+ //#region \0@oxc-project+runtime@0.129.0/helpers/usingCtx.js
1295
+ function _usingCtx() {
1296
+ var r = "function" == typeof SuppressedError ? SuppressedError : function(r, e) {
1297
+ var n = Error();
1298
+ return n.name = "SuppressedError", n.error = r, n.suppressed = e, n;
1299
+ };
1300
+ var e = {};
1301
+ var n = [];
1302
+ function using(r, e) {
1303
+ if (null != e) {
1304
+ if (Object(e) !== e) throw new TypeError("using declarations can only be used with objects, functions, null, or undefined.");
1305
+ if (r) var o = e[Symbol.asyncDispose || Symbol["for"]("Symbol.asyncDispose")];
1306
+ if (void 0 === o && (o = e[Symbol.dispose || Symbol["for"]("Symbol.dispose")], r)) var t = o;
1307
+ if ("function" != typeof o) throw new TypeError("Object is not disposable.");
1308
+ t && (o = function o() {
1309
+ try {
1310
+ t.call(e);
1311
+ } catch (r) {
1312
+ return Promise.reject(r);
1313
+ }
1314
+ }), n.push({
1315
+ v: e,
1316
+ d: o,
1317
+ a: r
1318
+ });
1319
+ } else r && n.push({
1320
+ d: e,
1321
+ a: r
1322
+ });
1323
+ return e;
1324
+ }
1325
+ return {
1326
+ e,
1327
+ u: using.bind(null, !1),
1328
+ a: using.bind(null, !0),
1329
+ d: function d() {
1330
+ var o;
1331
+ var t = this.e;
1332
+ var s = 0;
1333
+ function next() {
1334
+ for (; o = n.pop();) try {
1335
+ if (!o.a && 1 === s) return s = 0, n.push(o), Promise.resolve().then(next);
1336
+ if (o.d) {
1337
+ var r = o.d.call(o.v);
1338
+ if (o.a) return s |= 2, Promise.resolve(r).then(next, err);
1339
+ } else s |= 1;
1340
+ } catch (r) {
1341
+ return err(r);
1342
+ }
1343
+ if (1 === s) return t !== e ? Promise.reject(t) : Promise.resolve();
1344
+ if (t !== e) throw t;
1345
+ }
1346
+ function err(n) {
1347
+ return t = t !== e ? new r(n, t) : n, next();
1348
+ }
1349
+ return next();
1350
+ }
1351
+ };
1352
+ }
1353
+ //#endregion
1354
+ //#region src/KubbDriver.ts
1355
+ function enforceOrder(enforce) {
1356
+ return enforce === "pre" ? -1 : enforce === "post" ? 1 : 0;
1357
+ }
1358
+ const OPERATION_FILTER_TYPES = new Set([
1359
+ "tag",
1360
+ "operationId",
1361
+ "path",
1362
+ "method",
1363
+ "contentType"
1364
+ ]);
1365
+ var KubbDriver = class KubbDriver {
1366
+ config;
1367
+ options;
1368
+ /**
1369
+ * Returns `'single'` when `fileOrFolder` has a file extension, `'split'` otherwise.
1370
+ *
1371
+ * @example
1372
+ * ```ts
1373
+ * KubbDriver.getMode('src/gen/types.ts') // 'single'
1374
+ * KubbDriver.getMode('src/gen/types') // 'split'
1375
+ * ```
1376
+ */
1377
+ static getMode(fileOrFolder) {
1378
+ return getMode(fileOrFolder);
1379
+ }
1380
+ /**
1381
+ * The streaming `InputStreamNode` produced by the adapter.
1382
+ * Always set after adapter setup — parse-only adapters are wrapped automatically.
1383
+ */
1384
+ inputNode = null;
1385
+ adapter = null;
1386
+ /**
1387
+ * Studio session state, kept together so `dispose()` can reset it atomically.
1388
+ *
1389
+ * - `source` holds the raw adapter source so `adapter.parse()` can be called lazily.
1390
+ * Intentionally outlives the build; cleared by `dispose()`.
1391
+ * - `isOpen` prevents opening the studio more than once per build.
1392
+ * - `inputNode` caches the parse promise so `adapter.parse()` is called at most once
1393
+ * per studio session, even when `openInStudio()` is called multiple times.
1394
+ */
1395
+ #studio = {
1396
+ source: null,
1397
+ isOpen: false,
1398
+ inputNode: null
1399
+ };
1400
+ #middlewareListeners = [];
1401
+ /**
1402
+ * Central file store for all generated files.
1403
+ * Plugins should use `this.addFile()` / `this.upsertFile()` (via their context) to
1404
+ * add files; this property gives direct read/write access when needed.
1405
+ */
1406
+ fileManager = new FileManager();
1407
+ #fileProcessor = new FileProcessor();
1408
+ plugins = /* @__PURE__ */ new Map();
1409
+ /**
1410
+ * Tracks which plugins have generators registered via `addGenerator()` (event-based path).
1411
+ * Used by the build loop to decide whether to emit generator events for a given plugin.
1412
+ */
1413
+ #eventGeneratorPlugins = /* @__PURE__ */ new Set();
1414
+ #resolvers = /* @__PURE__ */ new Map();
1415
+ #defaultResolvers = /* @__PURE__ */ new Map();
1416
+ #hookListeners = /* @__PURE__ */ new Map();
1417
+ constructor(config, options) {
1418
+ this.config = config;
1419
+ this.options = options;
1420
+ this.adapter = config.adapter ?? null;
1421
+ }
1422
+ async setup() {
1423
+ const normalized = this.config.plugins.map((rawPlugin) => this.#normalizePlugin(rawPlugin));
1424
+ normalized.sort((a, b) => {
1425
+ if (b.dependencies?.includes(a.name)) return -1;
1426
+ if (a.dependencies?.includes(b.name)) return 1;
1427
+ return enforceOrder(a.enforce) - enforceOrder(b.enforce);
1428
+ });
1429
+ for (const plugin of normalized) {
1430
+ if (plugin.apply) plugin.apply(this.config);
1431
+ this.#registerPlugin(plugin);
1432
+ this.plugins.set(plugin.name, plugin);
1433
+ }
1434
+ if (this.config.middleware) for (const middleware of this.config.middleware) for (const event of Object.keys(middleware.hooks)) this.#registerMiddleware(event, middleware.hooks);
1435
+ if (this.config.adapter) await this.#registerAdapter(this.config.adapter);
1436
+ }
1437
+ get hooks() {
1438
+ return this.options.hooks;
1439
+ }
1440
+ /**
1441
+ * Creates an `NormalizedPlugin` from a hook-style plugin and registers
1442
+ * its lifecycle handlers on the `AsyncEventEmitter`.
1443
+ */
1444
+ #normalizePlugin(plugin) {
1445
+ const normalized = {
1446
+ name: plugin.name,
1447
+ dependencies: plugin.dependencies,
1448
+ enforce: plugin.enforce,
1449
+ hooks: plugin.hooks,
1450
+ options: plugin.options ?? {
1451
+ output: { path: "." },
1452
+ exclude: [],
1453
+ override: []
1454
+ }
1455
+ };
1456
+ if ("apply" in plugin && typeof plugin.apply === "function") normalized.apply = plugin.apply;
1457
+ return normalized;
1458
+ }
1459
+ async #registerAdapter(adapter) {
1460
+ const source = inputToAdapterSource(this.config);
1461
+ this.#studio.source = source;
1462
+ if (adapter.stream) {
1463
+ this.inputNode = await adapter.stream(source);
1464
+ await this.hooks.emit("kubb:debug", {
1465
+ date: /* @__PURE__ */ new Date(),
1466
+ logs: [`✓ Adapter '${adapter.name}' producing input stream`]
1467
+ });
1468
+ } else {
1469
+ const inputNode = await adapter.parse(source);
1470
+ this.inputNode = createStreamInput(arrayToAsyncIterable(inputNode.schemas), arrayToAsyncIterable(inputNode.operations), inputNode.meta);
1471
+ await this.hooks.emit("kubb:debug", {
1472
+ date: /* @__PURE__ */ new Date(),
1473
+ logs: [
1474
+ `✓ Adapter '${adapter.name}' resolved InputNode (wrapped as stream)`,
1475
+ ` • Schemas: ${inputNode.schemas.length}`,
1476
+ ` • Operations: ${inputNode.operations.length}`
1477
+ ]
1478
+ });
1479
+ }
1480
+ }
1481
+ #registerMiddleware(event, middlewareHooks) {
1482
+ const handler = middlewareHooks[event];
1483
+ if (!handler) return;
1484
+ this.hooks.on(event, handler);
1485
+ this.#middlewareListeners.push([event, handler]);
1486
+ }
1487
+ /**
1488
+ * Registers a hook-style plugin's lifecycle handlers on the shared `AsyncEventEmitter`.
1489
+ *
1490
+ * For `kubb:plugin:setup`, the registered listener wraps the globally emitted context with a
1491
+ * plugin-specific one so that `addGenerator`, `setResolver`, `setTransformer`, and
1492
+ * `setRenderer` all target the correct `normalizedPlugin` entry in the plugins map.
1493
+ *
1494
+ * All other hooks are iterated and registered directly as pass-through listeners.
1495
+ * Any event key present in the global `KubbHooks` interface can be subscribed to.
1496
+ *
1497
+ * External tooling can subscribe to any of these events via `hooks.on(...)` to observe
1498
+ * the plugin lifecycle without modifying plugin behavior.
1499
+ *
1500
+ * @internal
1501
+ */
1502
+ #registerPlugin(plugin) {
1503
+ const { hooks } = plugin;
1504
+ if (!hooks) return;
1505
+ if (hooks["kubb:plugin:setup"]) {
1506
+ const setupHandler = (globalCtx) => {
1507
+ const pluginCtx = {
1508
+ ...globalCtx,
1509
+ options: plugin.options ?? {},
1510
+ addGenerator: (gen) => {
1511
+ this.registerGenerator(plugin.name, gen);
1512
+ },
1513
+ setResolver: (resolver) => {
1514
+ this.setPluginResolver(plugin.name, resolver);
1515
+ },
1516
+ setTransformer: (visitor) => {
1517
+ plugin.transformer = visitor;
1518
+ },
1519
+ setRenderer: (renderer) => {
1520
+ plugin.renderer = renderer;
1521
+ },
1522
+ setOptions: (opts) => {
1523
+ plugin.options = {
1524
+ ...plugin.options,
1525
+ ...opts
1526
+ };
1527
+ },
1528
+ injectFile: (userFileNode) => {
1529
+ this.fileManager.add(createFile(userFileNode));
1530
+ }
1531
+ };
1532
+ return hooks["kubb:plugin:setup"](pluginCtx);
1533
+ };
1534
+ this.hooks.on("kubb:plugin:setup", setupHandler);
1535
+ this.#trackHookListener("kubb:plugin:setup", setupHandler);
1536
+ }
1537
+ for (const [event, handler] of Object.entries(hooks)) {
1538
+ if (event === "kubb:plugin:setup" || !handler) continue;
1539
+ this.hooks.on(event, handler);
1540
+ this.#trackHookListener(event, handler);
1541
+ }
1542
+ }
1543
+ /**
1544
+ * Emits the `kubb:plugin:setup` event so that all registered hook-style plugin listeners
1545
+ * can configure generators, resolvers, transformers and renderers before `buildStart` runs.
1546
+ *
1547
+ * Call this once from `safeBuild` before the plugin execution loop begins.
1548
+ */
1549
+ async emitSetupHooks() {
1550
+ const noop = () => {};
1551
+ await this.hooks.emit("kubb:plugin:setup", {
1552
+ config: this.config,
1553
+ options: {},
1554
+ addGenerator: noop,
1555
+ setResolver: noop,
1556
+ setTransformer: noop,
1557
+ setRenderer: noop,
1558
+ setOptions: noop,
1559
+ injectFile: noop,
1560
+ updateConfig: noop
1561
+ });
1562
+ }
1563
+ /**
1564
+ * Registers a generator for the given plugin on the shared event emitter.
1565
+ *
1566
+ * The generator's `schema`, `operation`, and `operations` methods are registered as
1567
+ * listeners on `kubb:generate:schema`, `kubb:generate:operation`, and `kubb:generate:operations`
1568
+ * respectively. Each listener is scoped to the owning plugin via a `ctx.plugin.name` check
1569
+ * so that generators from different plugins do not cross-fire.
1570
+ *
1571
+ * The renderer resolution chain is: `generator.renderer → plugin.renderer → config.renderer`.
1572
+ * Set `generator.renderer = null` to explicitly opt out of rendering even when the plugin
1573
+ * declares a renderer.
1574
+ *
1575
+ * Call this method inside `addGenerator()` (in `kubb:plugin:setup`) to wire up a generator.
1576
+ */
1577
+ registerGenerator(pluginName, gen) {
1578
+ const resolveRenderer = () => {
1579
+ const plugin = this.plugins.get(pluginName);
1580
+ return gen.renderer === null ? void 0 : gen.renderer ?? plugin?.renderer ?? this.config.renderer;
1581
+ };
1582
+ if (gen.schema) {
1583
+ const schemaHandler = async (node, ctx) => {
1584
+ if (ctx.plugin.name !== pluginName) return;
1585
+ await applyHookResult({
1586
+ result: await gen.schema(node, ctx),
1587
+ driver: this,
1588
+ rendererFactory: resolveRenderer()
1589
+ });
1590
+ };
1591
+ this.hooks.on("kubb:generate:schema", schemaHandler);
1592
+ this.#trackHookListener("kubb:generate:schema", schemaHandler);
1593
+ }
1594
+ if (gen.operation) {
1595
+ const operationHandler = async (node, ctx) => {
1596
+ if (ctx.plugin.name !== pluginName) return;
1597
+ await applyHookResult({
1598
+ result: await gen.operation(node, ctx),
1599
+ driver: this,
1600
+ rendererFactory: resolveRenderer()
1601
+ });
1602
+ };
1603
+ this.hooks.on("kubb:generate:operation", operationHandler);
1604
+ this.#trackHookListener("kubb:generate:operation", operationHandler);
1605
+ }
1606
+ if (gen.operations) {
1607
+ const operationsHandler = async (nodes, ctx) => {
1608
+ if (ctx.plugin.name !== pluginName) return;
1609
+ await applyHookResult({
1610
+ result: await gen.operations(nodes, ctx),
1611
+ driver: this,
1612
+ rendererFactory: resolveRenderer()
1613
+ });
1614
+ };
1615
+ this.hooks.on("kubb:generate:operations", operationsHandler);
1616
+ this.#trackHookListener("kubb:generate:operations", operationsHandler);
1617
+ }
1618
+ this.#eventGeneratorPlugins.add(pluginName);
1619
+ }
1620
+ /**
1621
+ * Returns `true` when at least one generator was registered for the given plugin
1622
+ * via `addGenerator()` in `kubb:plugin:setup` (event-based path).
1623
+ *
1624
+ * Used by the build loop to decide whether to walk the AST and emit generator events
1625
+ * for a plugin that has no static `plugin.generators`.
1626
+ */
1627
+ hasEventGenerators(pluginName) {
1628
+ return this.#eventGeneratorPlugins.has(pluginName);
1629
+ }
1630
+ /**
1631
+ * Runs the full plugin pipeline. Returns timings/failures collected so far even
1632
+ * when an outer hook throws — the orchestrator preserves partial state by capturing
1633
+ * the error into `error` instead of propagating.
1634
+ */
1635
+ async run({ storage }) {
1636
+ const hooks = this.hooks;
1637
+ const config = this.config;
1638
+ const failedPlugins = /* @__PURE__ */ new Set();
1639
+ const pluginTimings = /* @__PURE__ */ new Map();
1640
+ const parsersMap = /* @__PURE__ */ new Map();
1641
+ for (const parser of config.parsers) if (parser.extNames) for (const ext of parser.extNames) parsersMap.set(ext, parser);
1642
+ const pendingFiles = /* @__PURE__ */ new Map();
1643
+ this.fileManager.setOnUpsert((file) => {
1644
+ pendingFiles.set(file.path, file);
1645
+ });
1646
+ try {
1647
+ const flushPending = async () => {
1648
+ if (pendingFiles.size === 0) return;
1649
+ const files = [...pendingFiles.values()];
1650
+ pendingFiles.clear();
1651
+ await hooks.emit("kubb:debug", {
1652
+ date: /* @__PURE__ */ new Date(),
1653
+ logs: [`Writing ${files.length} files...`]
1654
+ });
1655
+ await hooks.emit("kubb:files:processing:start", { files });
1656
+ const items = [...this.#fileProcessor.stream(files, {
1657
+ parsers: parsersMap,
1658
+ extension: config.output.extension
1659
+ })];
1660
+ await hooks.emit("kubb:files:processing:update", { files: items.map(({ file, source, processed, total, percentage }) => ({
1661
+ file,
1662
+ source,
1663
+ processed,
1664
+ total,
1665
+ percentage,
1666
+ config
1667
+ })) });
1668
+ const queue = [];
1669
+ for (const { file, source } of items) if (source) {
1670
+ queue.push(storage.setItem(file.path, source));
1671
+ if (queue.length >= 50) await Promise.all(queue.splice(0));
1672
+ }
1673
+ await Promise.all(queue);
1674
+ await hooks.emit("kubb:files:processing:end", { files });
1675
+ await hooks.emit("kubb:debug", {
1676
+ date: /* @__PURE__ */ new Date(),
1677
+ logs: [`✓ File write process completed for ${files.length} files`]
1678
+ });
1679
+ };
1680
+ await this.emitSetupHooks();
1681
+ if (this.adapter && this.inputNode) await hooks.emit("kubb:build:start", Object.assign({
1682
+ config,
1683
+ adapter: this.adapter,
1684
+ meta: this.inputNode.meta,
1685
+ getPlugin: this.getPlugin.bind(this)
1686
+ }, this.#filesPayload()));
1687
+ const generatorPlugins = [];
1688
+ for (const plugin of this.plugins.values()) {
1689
+ const context = this.getContext(plugin);
1690
+ const hrStart = process.hrtime();
1691
+ try {
1692
+ await hooks.emit("kubb:plugin:start", { plugin });
1693
+ await hooks.emit("kubb:debug", {
1694
+ date: /* @__PURE__ */ new Date(),
1695
+ logs: ["Starting plugin...", ` • Plugin Name: ${plugin.name}`]
1696
+ });
1697
+ } catch (caughtError) {
1698
+ const error = caughtError;
1699
+ const duration = getElapsedMs(hrStart);
1700
+ pluginTimings.set(plugin.name, duration);
1701
+ await this.#emitPluginEnd({
1702
+ plugin,
1703
+ duration,
1704
+ success: false,
1705
+ error
1706
+ });
1707
+ failedPlugins.add({
1708
+ plugin,
1709
+ error
1710
+ });
1711
+ continue;
1712
+ }
1713
+ if (plugin.generators?.length || this.hasEventGenerators(plugin.name)) {
1714
+ generatorPlugins.push({
1715
+ plugin,
1716
+ context,
1717
+ hrStart
1718
+ });
1719
+ continue;
1720
+ }
1721
+ const duration = getElapsedMs(hrStart);
1722
+ pluginTimings.set(plugin.name, duration);
1723
+ await this.#emitPluginEnd({
1724
+ plugin,
1725
+ duration,
1726
+ success: true
1727
+ });
1728
+ await hooks.emit("kubb:debug", {
1729
+ date: /* @__PURE__ */ new Date(),
1730
+ logs: [`✓ Plugin started successfully (${formatMs(duration)})`]
1731
+ });
1732
+ }
1733
+ if (generatorPlugins.length > 0) if (this.inputNode) {
1734
+ const { timings, failed } = await this.#runGenerators(generatorPlugins, flushPending);
1735
+ await flushPending();
1736
+ for (const [name, duration] of timings) pluginTimings.set(name, duration);
1737
+ for (const entry of failed) failedPlugins.add(entry);
1738
+ } else for (const { plugin, hrStart } of generatorPlugins) {
1739
+ const duration = getElapsedMs(hrStart);
1740
+ pluginTimings.set(plugin.name, duration);
1741
+ await this.#emitPluginEnd({
1742
+ plugin,
1743
+ duration,
1744
+ success: true
1745
+ });
1746
+ }
1747
+ await hooks.emit("kubb:plugins:end", Object.assign({ config }, this.#filesPayload()));
1748
+ await flushPending();
1749
+ const files = this.fileManager.files;
1750
+ await hooks.emit("kubb:build:end", {
1751
+ files,
1752
+ config,
1753
+ outputDir: resolve(config.root, config.output.path)
1754
+ });
1755
+ return {
1756
+ failedPlugins,
1757
+ pluginTimings
1758
+ };
1759
+ } catch (caughtError) {
1760
+ return {
1761
+ failedPlugins,
1762
+ pluginTimings,
1763
+ error: caughtError
1764
+ };
1765
+ } finally {
1766
+ this.fileManager.setOnUpsert(null);
1767
+ }
1768
+ }
1769
+ #filesPayload() {
1770
+ const driver = this;
1771
+ return {
1772
+ get files() {
1773
+ return driver.fileManager.files;
1774
+ },
1775
+ upsertFile: (...files) => driver.fileManager.upsert(...files)
1776
+ };
1777
+ }
1778
+ #emitPluginEnd({ plugin, duration, success, error }) {
1779
+ return this.hooks.emit("kubb:plugin:end", Object.assign({
1780
+ plugin,
1781
+ duration,
1782
+ success,
1783
+ ...error ? { error } : {},
1784
+ config: this.config
1785
+ }, this.#filesPayload()));
1786
+ }
1787
+ async #runGenerators(entries, flushPending) {
1788
+ const timings = /* @__PURE__ */ new Map();
1789
+ const failed = /* @__PURE__ */ new Set();
1790
+ const driver = this;
1791
+ const { schemas, operations } = this.inputNode;
1792
+ const states = entries.map(({ plugin, context, hrStart }) => {
1793
+ const { exclude, include, override } = plugin.options;
1794
+ const hasExclude = Array.isArray(exclude) && exclude.length > 0;
1795
+ const hasInclude = Array.isArray(include) && include.length > 0;
1796
+ const hasOverride = Array.isArray(override) && override.length > 0;
1797
+ return {
1798
+ plugin,
1799
+ generatorContext: {
1800
+ ...context,
1801
+ resolver: this.getResolver(plugin.name)
1802
+ },
1803
+ generators: plugin.generators ?? [],
1804
+ hrStart,
1805
+ failed: false,
1806
+ error: null,
1807
+ optionsAreStatic: !hasExclude && !hasInclude && !hasOverride,
1808
+ allowedSchemaNames: null
1809
+ };
1810
+ });
1811
+ const emitsSchemaHook = this.hooks.listenerCount("kubb:generate:schema") > 0;
1812
+ const emitsOperationHook = this.hooks.listenerCount("kubb:generate:operation") > 0;
1813
+ const pruningStates = states.filter(({ plugin }) => {
1814
+ const { include } = plugin.options;
1815
+ return (include?.some(({ type }) => OPERATION_FILTER_TYPES.has(type)) ?? false) && !(include?.some(({ type }) => type === "schemaName") ?? false);
1816
+ });
1817
+ if (pruningStates.length > 0) {
1818
+ const allSchemas = [];
1819
+ for await (const schema of schemas) allSchemas.push(schema);
1820
+ const includedOpsByState = new Map(pruningStates.map((s) => [s, []]));
1821
+ for await (const operation of operations) for (const state of pruningStates) {
1822
+ const { exclude, include, override } = state.plugin.options;
1823
+ if (state.generatorContext.resolver.resolveOptions(operation, {
1824
+ options: state.plugin.options,
1825
+ exclude,
1826
+ include,
1827
+ override
1828
+ }) !== null) includedOpsByState.get(state)?.push(operation);
1829
+ }
1830
+ for (const state of pruningStates) {
1831
+ state.allowedSchemaNames = collectUsedSchemaNames(includedOpsByState.get(state) ?? [], allSchemas);
1832
+ includedOpsByState.delete(state);
1833
+ }
1834
+ }
1835
+ const resolveRendererFor = (gen, state) => gen.renderer === null ? void 0 : gen.renderer ?? state.plugin.renderer ?? state.generatorContext.config.renderer;
1836
+ const dispatchNode = async (state, node, dispatch) => {
1837
+ if (state.failed) return;
1838
+ try {
1839
+ const { plugin, generatorContext, generators } = state;
1840
+ const transformedNode = plugin.transformer ? transform(node, plugin.transformer) : node;
1841
+ if (dispatch.checkAllowedNames && state.allowedSchemaNames !== null && "name" in transformedNode && transformedNode.name && !state.allowedSchemaNames.has(transformedNode.name)) return;
1842
+ const { exclude, include, override } = plugin.options;
1843
+ const options = state.optionsAreStatic ? plugin.options : generatorContext.resolver.resolveOptions(transformedNode, {
1844
+ options: plugin.options,
1845
+ exclude,
1846
+ include,
1847
+ override
1848
+ });
1849
+ if (options === null) return;
1850
+ const ctx = {
1851
+ ...generatorContext,
1852
+ options
1853
+ };
1854
+ for (const gen of generators) {
1855
+ const generate = gen[dispatch.method];
1856
+ if (!generate) continue;
1857
+ const raw = generate(transformedNode, ctx);
1858
+ const applied = applyHookResult({
1859
+ result: isPromise(raw) ? await raw : raw,
1860
+ driver,
1861
+ rendererFactory: resolveRendererFor(gen, state)
1862
+ });
1863
+ if (isPromise(applied)) await applied;
1864
+ }
1865
+ if (dispatch.emit) await dispatch.emit(transformedNode, ctx);
1866
+ } catch (caughtError) {
1867
+ state.failed = true;
1868
+ state.error = caughtError;
1869
+ }
1870
+ };
1871
+ const schemaDispatch = {
1872
+ method: "schema",
1873
+ checkAllowedNames: true,
1874
+ emit: emitsSchemaHook ? (node, ctx) => this.hooks.emit("kubb:generate:schema", node, ctx) : null
1875
+ };
1876
+ const operationDispatch = {
1877
+ method: "operation",
1878
+ checkAllowedNames: false,
1879
+ emit: emitsOperationHook ? (node, ctx) => this.hooks.emit("kubb:generate:operation", node, ctx) : null
1880
+ };
1881
+ const needsCollectedOperations = this.hooks.listenerCount("kubb:generate:operations") > 0 || states.some((s) => s.generators.some((g) => !!g.operations));
1882
+ const collectedOperations = needsCollectedOperations ? [] : void 0;
1883
+ await forBatches(schemas, (nodes) => Promise.all(nodes.flatMap((n) => states.map((state) => dispatchNode(state, n, schemaDispatch)))), {
1884
+ concurrency: 8,
1885
+ flush: flushPending
1886
+ });
1887
+ await forBatches(operations, (nodes) => {
1888
+ if (needsCollectedOperations) collectedOperations.push(...nodes);
1889
+ return Promise.all(nodes.flatMap((n) => states.map((state) => dispatchNode(state, n, operationDispatch))));
1890
+ }, {
1891
+ concurrency: 8,
1892
+ flush: flushPending
1893
+ });
1894
+ for (const state of states) {
1895
+ if (!state.failed && needsCollectedOperations) try {
1896
+ const { plugin, generatorContext, generators } = state;
1897
+ const ctx = {
1898
+ ...generatorContext,
1899
+ options: plugin.options
1900
+ };
1901
+ const pluginOperations = state.optionsAreStatic ? collectedOperations : collectedOperations.filter((node) => {
1902
+ const transformed = plugin.transformer ? transform(node, plugin.transformer) : node;
1903
+ const { exclude, include, override } = plugin.options;
1904
+ return generatorContext.resolver.resolveOptions(transformed, {
1905
+ options: plugin.options,
1906
+ exclude,
1907
+ include,
1908
+ override
1909
+ }) !== null;
1910
+ });
1911
+ for (const gen of generators) {
1912
+ if (!gen.operations) continue;
1913
+ await applyHookResult({
1914
+ result: await gen.operations(pluginOperations, ctx),
1915
+ driver,
1916
+ rendererFactory: resolveRendererFor(gen, state)
1917
+ });
1918
+ }
1919
+ await this.hooks.emit("kubb:generate:operations", pluginOperations, ctx);
1920
+ } catch (caughtError) {
1921
+ state.failed = true;
1922
+ state.error = caughtError;
1923
+ }
1924
+ const duration = getElapsedMs(state.hrStart);
1925
+ timings.set(state.plugin.name, duration);
1926
+ await this.#emitPluginEnd({
1927
+ plugin: state.plugin,
1928
+ duration,
1929
+ success: !state.failed,
1930
+ error: state.failed && state.error ? state.error : void 0
1931
+ });
1932
+ if (state.failed && state.error) failed.add({
1933
+ plugin: state.plugin,
1934
+ error: state.error
1935
+ });
1936
+ await this.hooks.emit("kubb:debug", {
1937
+ date: /* @__PURE__ */ new Date(),
1938
+ logs: [state.failed ? "✗ Plugin start failed" : `✓ Plugin started successfully (${formatMs(duration)})`]
1939
+ });
1940
+ }
1941
+ return {
1942
+ timings,
1943
+ failed
1944
+ };
1945
+ }
1946
+ /**
1947
+ * Unregisters all plugin lifecycle listeners from the shared event emitter.
1948
+ * Called at the end of a build to prevent listener leaks across repeated builds.
1949
+ *
1950
+ * @internal
1951
+ */
1952
+ dispose() {
1953
+ for (const [event, handlers] of this.#hookListeners) for (const handler of handlers) this.hooks.off(event, handler);
1954
+ this.#hookListeners.clear();
1955
+ this.#eventGeneratorPlugins.clear();
1956
+ this.#resolvers.clear();
1957
+ this.#defaultResolvers.clear();
1958
+ this.fileManager.dispose();
1959
+ this.#fileProcessor.dispose();
1960
+ this.inputNode = null;
1961
+ this.#studio = {
1962
+ source: null,
1963
+ isOpen: false,
1964
+ inputNode: null
1965
+ };
1966
+ for (const [event, handler] of this.#middlewareListeners) this.hooks.off(event, handler);
1967
+ }
1968
+ [Symbol.dispose]() {
1969
+ this.dispose();
1970
+ }
1971
+ #trackHookListener(event, handler) {
1972
+ let handlers = this.#hookListeners.get(event);
1973
+ if (!handlers) {
1974
+ handlers = /* @__PURE__ */ new Set();
1975
+ this.#hookListeners.set(event, handlers);
1976
+ }
1977
+ handlers.add(handler);
1978
+ }
1979
+ #getDefaultResolver = memoize(this.#defaultResolvers, (pluginName) => defineResolver(() => ({
1980
+ name: "default",
1981
+ pluginName
1982
+ })));
1983
+ /**
1984
+ * Merges `partial` with the plugin's default resolver and stores the result.
1985
+ * Also mirrors it onto `plugin.resolver` so callers using `getPlugin(name).resolver`
1986
+ * get the up-to-date resolver without going through `getResolver()`.
1987
+ */
1988
+ setPluginResolver(pluginName, partial) {
1989
+ const merged = {
1990
+ ...this.#getDefaultResolver(pluginName),
1991
+ ...partial
1992
+ };
1993
+ this.#resolvers.set(pluginName, merged);
1994
+ const plugin = this.plugins.get(pluginName);
1995
+ if (plugin) plugin.resolver = merged;
1996
+ }
1997
+ getResolver(pluginName) {
1998
+ return this.#resolvers.get(pluginName) ?? this.plugins.get(pluginName)?.resolver ?? this.#getDefaultResolver(pluginName);
1999
+ }
2000
+ getContext(plugin) {
2001
+ const driver = this;
2002
+ return {
2003
+ config: driver.config,
2004
+ get root() {
2005
+ return resolve(driver.config.root, driver.config.output.path);
2006
+ },
2007
+ getMode(output) {
2008
+ return KubbDriver.getMode(resolve(driver.config.root, driver.config.output.path, output.path));
2009
+ },
2010
+ hooks: driver.hooks,
2011
+ plugin,
2012
+ getPlugin: driver.getPlugin.bind(driver),
2013
+ requirePlugin: driver.requirePlugin.bind(driver),
2014
+ getResolver: driver.getResolver.bind(driver),
2015
+ driver,
2016
+ addFile: async (...files) => {
2017
+ driver.fileManager.add(...files);
2018
+ },
2019
+ upsertFile: async (...files) => {
2020
+ driver.fileManager.upsert(...files);
2021
+ },
2022
+ get meta() {
2023
+ return driver.inputNode?.meta ?? {
2024
+ circularNames: [],
2025
+ enumNames: []
2026
+ };
2027
+ },
2028
+ get adapter() {
2029
+ return driver.adapter;
2030
+ },
2031
+ get resolver() {
2032
+ return driver.getResolver(plugin.name);
2033
+ },
2034
+ get transformer() {
2035
+ return plugin.transformer;
2036
+ },
2037
+ warn(message) {
2038
+ driver.hooks.emit("kubb:warn", { message });
2039
+ },
2040
+ error(error) {
2041
+ driver.hooks.emit("kubb:error", { error: typeof error === "string" ? new Error(error) : error });
2042
+ },
2043
+ info(message) {
2044
+ driver.hooks.emit("kubb:info", { message });
2045
+ },
2046
+ async openInStudio(options) {
2047
+ if (!driver.config.devtools || driver.#studio.isOpen) return;
2048
+ if (typeof driver.config.devtools !== "object") throw new Error("Devtools must be an object");
2049
+ if (!driver.adapter || !driver.#studio.source) throw new Error("adapter is not defined, make sure you have set the parser in kubb.config.ts");
2050
+ driver.#studio.isOpen = true;
2051
+ const studioUrl = driver.config.devtools?.studioUrl ?? "https://kubb.studio";
2052
+ driver.#studio.inputNode ??= Promise.resolve(driver.adapter.parse(driver.#studio.source));
2053
+ return openInStudio(await driver.#studio.inputNode, studioUrl, options);
2054
+ }
2055
+ };
2056
+ }
2057
+ getPlugin(pluginName) {
2058
+ return this.plugins.get(pluginName);
2059
+ }
2060
+ requirePlugin(pluginName) {
2061
+ const plugin = this.plugins.get(pluginName);
2062
+ if (!plugin) throw new Error(`[kubb] Plugin "${pluginName}" is required but not found. Make sure it is included in your Kubb config.`);
2063
+ return plugin;
2064
+ }
2065
+ };
2066
+ /**
2067
+ * Handles the return value of a plugin AST hook or generator method.
2068
+ *
2069
+ * - Renderer output → rendered via the provided `rendererFactory` (e.g. JSX), files stored in `driver.fileManager`
2070
+ * - `Array<FileNode>` → added directly into `driver.fileManager`
2071
+ * - `void` / `null` / `undefined` → no-op (plugin handled it via `this.upsertFile`)
2072
+ *
2073
+ * Pass a `rendererFactory` (e.g. `jsxRenderer` from `@kubb/renderer-jsx`) when the result
2074
+ * may be a renderer element. Generators that only return `Array<FileNode>` do not need one.
2075
+ */
2076
+ function applyHookResult({ result, driver, rendererFactory }) {
2077
+ if (!result) return;
2078
+ if (Array.isArray(result)) {
2079
+ driver.fileManager.upsert(...result);
2080
+ return;
2081
+ }
2082
+ if (!rendererFactory) return;
2083
+ const renderer = rendererFactory();
2084
+ if (renderer.stream) try {
2085
+ var _usingCtx$1 = _usingCtx();
2086
+ const r = _usingCtx$1.u(renderer);
2087
+ for (const file of r.stream(result)) driver.fileManager.upsert(file);
2088
+ return;
2089
+ } catch (_) {
2090
+ _usingCtx$1.e = _;
2091
+ } finally {
2092
+ _usingCtx$1.d();
2093
+ }
2094
+ return applyAsyncRender({
2095
+ renderer,
2096
+ result,
2097
+ driver
2098
+ });
2099
+ }
2100
+ async function applyAsyncRender({ renderer, result, driver }) {
2101
+ try {
2102
+ var _usingCtx3 = _usingCtx();
2103
+ const r = _usingCtx3.u(renderer);
2104
+ await r.render(result);
2105
+ driver.fileManager.upsert(...r.files);
2106
+ } catch (_) {
2107
+ _usingCtx3.e = _;
2108
+ } finally {
2109
+ _usingCtx3.d();
2110
+ }
2111
+ }
2112
+ function inputToAdapterSource(config) {
2113
+ const input = config.input;
2114
+ if (!input) throw new Error("[kubb] input is required when using an adapter. Provide input.path or input.data in your config.");
2115
+ if ("data" in input) return {
2116
+ type: "data",
2117
+ data: input.data
2118
+ };
2119
+ if (new URLPath(input.path).isURL) return {
2120
+ type: "path",
2121
+ path: input.path
2122
+ };
2123
+ return {
2124
+ type: "path",
2125
+ path: resolve(config.root, input.path)
2126
+ };
2127
+ }
2128
+ //#endregion
2129
+ export { FileManager as a, DEFAULT_BANNER as c, logLevel as d, URLPath as f, FileProcessor as i, DEFAULT_EXTENSION as l, BuildError as m, applyHookResult as n, defineResolver as o, AsyncEventEmitter as p, _usingCtx as r, definePlugin as s, KubbDriver as t, DEFAULT_STUDIO_URL as u };
2130
+
2131
+ //# sourceMappingURL=KubbDriver-CFx2DdhF.js.map