@kubb/core 5.0.0-alpha.4 → 5.0.0-alpha.41

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 (71) hide show
  1. package/dist/PluginDriver-BQwm8hDd.cjs +1729 -0
  2. package/dist/PluginDriver-BQwm8hDd.cjs.map +1 -0
  3. package/dist/PluginDriver-CgXFtmNP.js +1617 -0
  4. package/dist/PluginDriver-CgXFtmNP.js.map +1 -0
  5. package/dist/index.cjs +915 -1901
  6. package/dist/index.cjs.map +1 -1
  7. package/dist/index.d.ts +268 -264
  8. package/dist/index.js +894 -1863
  9. package/dist/index.js.map +1 -1
  10. package/dist/mocks.cjs +164 -0
  11. package/dist/mocks.cjs.map +1 -0
  12. package/dist/mocks.d.ts +74 -0
  13. package/dist/mocks.js +159 -0
  14. package/dist/mocks.js.map +1 -0
  15. package/dist/types-C6NCtNqM.d.ts +2151 -0
  16. package/package.json +11 -14
  17. package/src/FileManager.ts +131 -0
  18. package/src/FileProcessor.ts +84 -0
  19. package/src/Kubb.ts +174 -85
  20. package/src/PluginDriver.ts +941 -0
  21. package/src/constants.ts +33 -43
  22. package/src/createAdapter.ts +25 -0
  23. package/src/createKubb.ts +605 -0
  24. package/src/createPlugin.ts +31 -0
  25. package/src/createRenderer.ts +57 -0
  26. package/src/createStorage.ts +58 -0
  27. package/src/defineGenerator.ts +88 -100
  28. package/src/defineLogger.ts +13 -3
  29. package/src/defineParser.ts +45 -0
  30. package/src/definePlugin.ts +90 -7
  31. package/src/defineResolver.ts +453 -0
  32. package/src/devtools.ts +14 -14
  33. package/src/index.ts +12 -17
  34. package/src/mocks.ts +234 -0
  35. package/src/renderNode.ts +35 -0
  36. package/src/storages/fsStorage.ts +29 -9
  37. package/src/storages/memoryStorage.ts +2 -2
  38. package/src/types.ts +821 -152
  39. package/src/utils/TreeNode.ts +47 -9
  40. package/src/utils/diagnostics.ts +4 -1
  41. package/src/utils/executeStrategies.ts +16 -13
  42. package/src/utils/getBarrelFiles.ts +88 -15
  43. package/src/utils/isInputPath.ts +10 -0
  44. package/src/utils/packageJSON.ts +75 -0
  45. package/dist/chunk-ByKO4r7w.cjs +0 -38
  46. package/dist/hooks.cjs +0 -50
  47. package/dist/hooks.cjs.map +0 -1
  48. package/dist/hooks.d.ts +0 -49
  49. package/dist/hooks.js +0 -46
  50. package/dist/hooks.js.map +0 -1
  51. package/dist/types-Bbh1o0yW.d.ts +0 -1057
  52. package/src/BarrelManager.ts +0 -74
  53. package/src/PackageManager.ts +0 -180
  54. package/src/PluginManager.ts +0 -668
  55. package/src/PromiseManager.ts +0 -40
  56. package/src/build.ts +0 -420
  57. package/src/config.ts +0 -56
  58. package/src/defineAdapter.ts +0 -22
  59. package/src/defineStorage.ts +0 -56
  60. package/src/errors.ts +0 -1
  61. package/src/hooks/index.ts +0 -8
  62. package/src/hooks/useKubb.ts +0 -22
  63. package/src/hooks/useMode.ts +0 -11
  64. package/src/hooks/usePlugin.ts +0 -11
  65. package/src/hooks/usePluginManager.ts +0 -11
  66. package/src/utils/FunctionParams.ts +0 -155
  67. package/src/utils/formatters.ts +0 -56
  68. package/src/utils/getConfigs.ts +0 -30
  69. package/src/utils/getPlugins.ts +0 -23
  70. package/src/utils/linters.ts +0 -25
  71. package/src/utils/resolveOptions.ts +0 -93
@@ -0,0 +1,1617 @@
1
+ import { t as __name } from "./chunk--u3MIqq1.js";
2
+ import path, { basename, extname, resolve } from "node:path";
3
+ import { createFile, isOperationNode, isSchemaNode } from "@kubb/ast";
4
+ import { performance } from "node:perf_hooks";
5
+ import { deflateSync } from "fflate";
6
+ import { x } from "tinyexec";
7
+ //#region ../../internals/utils/src/casing.ts
8
+ /**
9
+ * Shared implementation for camelCase and PascalCase conversion.
10
+ * Splits on common word boundaries (spaces, hyphens, underscores, dots, slashes, colons)
11
+ * and capitalizes each word according to `pascal`.
12
+ *
13
+ * When `pascal` is `true` the first word is also capitalized (PascalCase), otherwise only subsequent words are.
14
+ */
15
+ function toCamelOrPascal(text, pascal) {
16
+ 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) => {
17
+ if (word.length > 1 && word === word.toUpperCase()) return word;
18
+ if (i === 0 && !pascal) return word.charAt(0).toLowerCase() + word.slice(1);
19
+ return word.charAt(0).toUpperCase() + word.slice(1);
20
+ }).join("").replace(/[^a-zA-Z0-9]/g, "");
21
+ }
22
+ /**
23
+ * Splits `text` on `.` and applies `transformPart` to each segment.
24
+ * The last segment receives `isLast = true`, all earlier segments receive `false`.
25
+ * Segments are joined with `/` to form a file path.
26
+ *
27
+ * Only splits on dots followed by a letter so that version numbers
28
+ * embedded in operationIds (e.g. `v2025.0`) are kept intact.
29
+ */
30
+ function applyToFileParts(text, transformPart) {
31
+ const parts = text.split(/\.(?=[a-zA-Z])/);
32
+ return parts.map((part, i) => transformPart(part, i === parts.length - 1)).join("/");
33
+ }
34
+ /**
35
+ * Converts `text` to camelCase.
36
+ * When `isFile` is `true`, dot-separated segments are each cased independently and joined with `/`.
37
+ *
38
+ * @example
39
+ * camelCase('hello-world') // 'helloWorld'
40
+ * camelCase('pet.petId', { isFile: true }) // 'pet/petId'
41
+ */
42
+ function camelCase(text, { isFile, prefix = "", suffix = "" } = {}) {
43
+ if (isFile) return applyToFileParts(text, (part, isLast) => camelCase(part, isLast ? {
44
+ prefix,
45
+ suffix
46
+ } : {}));
47
+ return toCamelOrPascal(`${prefix} ${text} ${suffix}`, false);
48
+ }
49
+ /**
50
+ * Converts `text` to PascalCase.
51
+ * When `isFile` is `true`, the last dot-separated segment is PascalCased and earlier segments are camelCased.
52
+ *
53
+ * @example
54
+ * pascalCase('hello-world') // 'HelloWorld'
55
+ * pascalCase('pet.petId', { isFile: true }) // 'pet/PetId'
56
+ */
57
+ function pascalCase(text, { isFile, prefix = "", suffix = "" } = {}) {
58
+ if (isFile) return applyToFileParts(text, (part, isLast) => isLast ? pascalCase(part, {
59
+ prefix,
60
+ suffix
61
+ }) : camelCase(part));
62
+ return toCamelOrPascal(`${prefix} ${text} ${suffix}`, true);
63
+ }
64
+ //#endregion
65
+ //#region ../../internals/utils/src/promise.ts
66
+ /** Returns `true` when `result` is a rejected `Promise.allSettled` result with a typed `reason`.
67
+ *
68
+ * @example
69
+ * ```ts
70
+ * const results = await Promise.allSettled([p1, p2])
71
+ * results.filter(isPromiseRejectedResult<Error>).map((r) => r.reason.message)
72
+ * ```
73
+ */
74
+ function isPromiseRejectedResult(result) {
75
+ return result.status === "rejected";
76
+ }
77
+ //#endregion
78
+ //#region ../../internals/utils/src/reserved.ts
79
+ /**
80
+ * JavaScript and Java reserved words.
81
+ * @link https://github.com/jonschlinkert/reserved/blob/master/index.js
82
+ */
83
+ const reservedWords = new Set([
84
+ "abstract",
85
+ "arguments",
86
+ "boolean",
87
+ "break",
88
+ "byte",
89
+ "case",
90
+ "catch",
91
+ "char",
92
+ "class",
93
+ "const",
94
+ "continue",
95
+ "debugger",
96
+ "default",
97
+ "delete",
98
+ "do",
99
+ "double",
100
+ "else",
101
+ "enum",
102
+ "eval",
103
+ "export",
104
+ "extends",
105
+ "false",
106
+ "final",
107
+ "finally",
108
+ "float",
109
+ "for",
110
+ "function",
111
+ "goto",
112
+ "if",
113
+ "implements",
114
+ "import",
115
+ "in",
116
+ "instanceof",
117
+ "int",
118
+ "interface",
119
+ "let",
120
+ "long",
121
+ "native",
122
+ "new",
123
+ "null",
124
+ "package",
125
+ "private",
126
+ "protected",
127
+ "public",
128
+ "return",
129
+ "short",
130
+ "static",
131
+ "super",
132
+ "switch",
133
+ "synchronized",
134
+ "this",
135
+ "throw",
136
+ "throws",
137
+ "transient",
138
+ "true",
139
+ "try",
140
+ "typeof",
141
+ "var",
142
+ "void",
143
+ "volatile",
144
+ "while",
145
+ "with",
146
+ "yield",
147
+ "Array",
148
+ "Date",
149
+ "hasOwnProperty",
150
+ "Infinity",
151
+ "isFinite",
152
+ "isNaN",
153
+ "isPrototypeOf",
154
+ "length",
155
+ "Math",
156
+ "name",
157
+ "NaN",
158
+ "Number",
159
+ "Object",
160
+ "prototype",
161
+ "String",
162
+ "toString",
163
+ "undefined",
164
+ "valueOf"
165
+ ]);
166
+ /**
167
+ * Prefixes `word` with `_` when it is a reserved JavaScript/Java identifier or starts with a digit.
168
+ *
169
+ * @example
170
+ * ```ts
171
+ * transformReservedWord('class') // '_class'
172
+ * transformReservedWord('42foo') // '_42foo'
173
+ * transformReservedWord('status') // 'status'
174
+ * ```
175
+ */
176
+ function transformReservedWord(word) {
177
+ const firstChar = word.charCodeAt(0);
178
+ if (word && (reservedWords.has(word) || firstChar >= 48 && firstChar <= 57)) return `_${word}`;
179
+ return word;
180
+ }
181
+ /**
182
+ * Returns `true` when `name` is a syntactically valid JavaScript variable name.
183
+ *
184
+ * @example
185
+ * ```ts
186
+ * isValidVarName('status') // true
187
+ * isValidVarName('class') // false (reserved word)
188
+ * isValidVarName('42foo') // false (starts with digit)
189
+ * ```
190
+ */
191
+ function isValidVarName(name) {
192
+ try {
193
+ new Function(`var ${name}`);
194
+ } catch {
195
+ return false;
196
+ }
197
+ return true;
198
+ }
199
+ //#endregion
200
+ //#region ../../internals/utils/src/string.ts
201
+ /**
202
+ * Strips the file extension from a path or file name.
203
+ * Only removes the last `.ext` segment when the dot is not part of a directory name.
204
+ *
205
+ * @example
206
+ * trimExtName('petStore.ts') // 'petStore'
207
+ * trimExtName('/src/models/pet.ts') // '/src/models/pet'
208
+ * trimExtName('/project.v2/gen/pet.ts') // '/project.v2/gen/pet'
209
+ * trimExtName('noExtension') // 'noExtension'
210
+ */
211
+ function trimExtName(text) {
212
+ const dotIndex = text.lastIndexOf(".");
213
+ if (dotIndex > 0 && !text.includes("/", dotIndex)) return text.slice(0, dotIndex);
214
+ return text;
215
+ }
216
+ //#endregion
217
+ //#region src/constants.ts
218
+ /**
219
+ * Base URL for the Kubb Studio web app.
220
+ */
221
+ const DEFAULT_STUDIO_URL = "https://studio.kubb.dev";
222
+ /**
223
+ * File name used for generated barrel (index) files.
224
+ */
225
+ const BARREL_FILENAME = "index.ts";
226
+ /**
227
+ * Default banner style written at the top of every generated file.
228
+ */
229
+ const DEFAULT_BANNER = "simple";
230
+ /**
231
+ * Default file-extension mapping used when no explicit mapping is configured.
232
+ */
233
+ const DEFAULT_EXTENSION = { ".ts": ".ts" };
234
+ /**
235
+ * Numeric log-level thresholds used internally to compare verbosity.
236
+ *
237
+ * Higher numbers are more verbose.
238
+ */
239
+ const logLevel = {
240
+ silent: Number.NEGATIVE_INFINITY,
241
+ error: 0,
242
+ warn: 1,
243
+ info: 3,
244
+ verbose: 4,
245
+ debug: 5
246
+ };
247
+ //#endregion
248
+ //#region ../../node_modules/.pnpm/yocto-queue@1.2.2/node_modules/yocto-queue/index.js
249
+ var Node$1 = class {
250
+ static {
251
+ __name(this, "Node");
252
+ }
253
+ value;
254
+ next;
255
+ constructor(value) {
256
+ this.value = value;
257
+ }
258
+ };
259
+ var Queue = class {
260
+ #head;
261
+ #tail;
262
+ #size;
263
+ constructor() {
264
+ this.clear();
265
+ }
266
+ enqueue(value) {
267
+ const node = new Node$1(value);
268
+ if (this.#head) {
269
+ this.#tail.next = node;
270
+ this.#tail = node;
271
+ } else {
272
+ this.#head = node;
273
+ this.#tail = node;
274
+ }
275
+ this.#size++;
276
+ }
277
+ dequeue() {
278
+ const current = this.#head;
279
+ if (!current) return;
280
+ this.#head = this.#head.next;
281
+ this.#size--;
282
+ if (!this.#head) this.#tail = void 0;
283
+ return current.value;
284
+ }
285
+ peek() {
286
+ if (!this.#head) return;
287
+ return this.#head.value;
288
+ }
289
+ clear() {
290
+ this.#head = void 0;
291
+ this.#tail = void 0;
292
+ this.#size = 0;
293
+ }
294
+ get size() {
295
+ return this.#size;
296
+ }
297
+ *[Symbol.iterator]() {
298
+ let current = this.#head;
299
+ while (current) {
300
+ yield current.value;
301
+ current = current.next;
302
+ }
303
+ }
304
+ *drain() {
305
+ while (this.#head) yield this.dequeue();
306
+ }
307
+ };
308
+ //#endregion
309
+ //#region ../../node_modules/.pnpm/p-limit@7.3.0/node_modules/p-limit/index.js
310
+ function pLimit(concurrency) {
311
+ let rejectOnClear = false;
312
+ if (typeof concurrency === "object") ({concurrency, rejectOnClear = false} = concurrency);
313
+ validateConcurrency(concurrency);
314
+ if (typeof rejectOnClear !== "boolean") throw new TypeError("Expected `rejectOnClear` to be a boolean");
315
+ const queue = new Queue();
316
+ let activeCount = 0;
317
+ const resumeNext = () => {
318
+ if (activeCount < concurrency && queue.size > 0) {
319
+ activeCount++;
320
+ queue.dequeue().run();
321
+ }
322
+ };
323
+ const next = () => {
324
+ activeCount--;
325
+ resumeNext();
326
+ };
327
+ const run = async (function_, resolve, arguments_) => {
328
+ const result = (async () => function_(...arguments_))();
329
+ resolve(result);
330
+ try {
331
+ await result;
332
+ } catch {}
333
+ next();
334
+ };
335
+ const enqueue = (function_, resolve, reject, arguments_) => {
336
+ const queueItem = { reject };
337
+ new Promise((internalResolve) => {
338
+ queueItem.run = internalResolve;
339
+ queue.enqueue(queueItem);
340
+ }).then(run.bind(void 0, function_, resolve, arguments_));
341
+ if (activeCount < concurrency) resumeNext();
342
+ };
343
+ const generator = (function_, ...arguments_) => new Promise((resolve, reject) => {
344
+ enqueue(function_, resolve, reject, arguments_);
345
+ });
346
+ Object.defineProperties(generator, {
347
+ activeCount: { get: () => activeCount },
348
+ pendingCount: { get: () => queue.size },
349
+ clearQueue: { value() {
350
+ if (!rejectOnClear) {
351
+ queue.clear();
352
+ return;
353
+ }
354
+ const abortError = AbortSignal.abort().reason;
355
+ while (queue.size > 0) queue.dequeue().reject(abortError);
356
+ } },
357
+ concurrency: {
358
+ get: () => concurrency,
359
+ set(newConcurrency) {
360
+ validateConcurrency(newConcurrency);
361
+ concurrency = newConcurrency;
362
+ queueMicrotask(() => {
363
+ while (activeCount < concurrency && queue.size > 0) resumeNext();
364
+ });
365
+ }
366
+ },
367
+ map: { async value(iterable, function_) {
368
+ const promises = Array.from(iterable, (value, index) => this(function_, value, index));
369
+ return Promise.all(promises);
370
+ } }
371
+ });
372
+ return generator;
373
+ }
374
+ function validateConcurrency(concurrency) {
375
+ if (!((Number.isInteger(concurrency) || concurrency === Number.POSITIVE_INFINITY) && concurrency > 0)) throw new TypeError("Expected `concurrency` to be a number from 1 and up");
376
+ }
377
+ //#endregion
378
+ //#region src/definePlugin.ts
379
+ /**
380
+ * Returns `true` when `plugin` is a hook-style plugin created with `definePlugin`.
381
+ *
382
+ * Used by `PluginDriver` to distinguish hook-style plugins from legacy `createPlugin` plugins
383
+ * so it can normalize them and register their handlers on the `AsyncEventEmitter`.
384
+ */
385
+ function isHookStylePlugin(plugin) {
386
+ return typeof plugin === "object" && plugin !== null && "hooks" in plugin;
387
+ }
388
+ /**
389
+ * Creates a plugin factory using the new hook-style (`hooks:`) API.
390
+ *
391
+ * The returned factory is called with optional options and produces a `HookStylePlugin`
392
+ * that coexists with plugins created via the legacy `createPlugin` API in the same
393
+ * `kubb.config.ts`.
394
+ *
395
+ * Lifecycle handlers are registered on the `PluginDriver`'s `AsyncEventEmitter`, enabling
396
+ * both the plugin's own handlers and external tooling (CLI, devtools) to observe every event.
397
+ *
398
+ * @example
399
+ * ```ts
400
+ * // With PluginFactoryOptions (recommended for real plugins)
401
+ * export const pluginTs = definePlugin<PluginTs>((options) => ({
402
+ * name: 'plugin-ts',
403
+ * hooks: {
404
+ * 'kubb:plugin:setup'(ctx) {
405
+ * ctx.setResolver(resolverTs) // typed as Partial<ResolverTs>
406
+ * },
407
+ * },
408
+ * }))
409
+ * ```
410
+ */
411
+ function definePlugin(factory) {
412
+ return (options) => factory(options ?? {});
413
+ }
414
+ //#endregion
415
+ //#region src/defineResolver.ts
416
+ /**
417
+ * Checks if an operation matches a pattern for a given filter type (`tag`, `operationId`, `path`, `method`).
418
+ */
419
+ function matchesOperationPattern(node, type, pattern) {
420
+ switch (type) {
421
+ case "tag": return node.tags.some((tag) => !!tag.match(pattern));
422
+ case "operationId": return !!node.operationId.match(pattern);
423
+ case "path": return !!node.path.match(pattern);
424
+ case "method": return !!node.method.toLowerCase().match(pattern);
425
+ case "contentType": return !!node.requestBody?.contentType?.match(pattern);
426
+ default: return false;
427
+ }
428
+ }
429
+ /**
430
+ * Checks if a schema matches a pattern for a given filter type (`schemaName`).
431
+ *
432
+ * Returns `null` when the filter type doesn't apply to schemas.
433
+ */
434
+ function matchesSchemaPattern(node, type, pattern) {
435
+ switch (type) {
436
+ case "schemaName": return node.name ? !!node.name.match(pattern) : false;
437
+ default: return null;
438
+ }
439
+ }
440
+ /**
441
+ * Default name resolver used by `defineResolver`.
442
+ *
443
+ * - `camelCase` for `function` and `file` types.
444
+ * - `PascalCase` for `type`.
445
+ * - `camelCase` for everything else.
446
+ */
447
+ function defaultResolver(name, type) {
448
+ let resolvedName = camelCase(name);
449
+ if (type === "file" || type === "function") resolvedName = camelCase(name, { isFile: type === "file" });
450
+ if (type === "type") resolvedName = pascalCase(name);
451
+ return resolvedName;
452
+ }
453
+ /**
454
+ * Default option resolver — applies include/exclude filters and merges matching override options.
455
+ *
456
+ * Returns `null` when the node is filtered out by an `exclude` rule or not matched by any `include` rule.
457
+ *
458
+ * @example Include/exclude filtering
459
+ * ```ts
460
+ * const options = defaultResolveOptions(operationNode, {
461
+ * options: { output: 'types' },
462
+ * exclude: [{ type: 'tag', pattern: 'internal' }],
463
+ * })
464
+ * // → null when node has tag 'internal'
465
+ * ```
466
+ *
467
+ * @example Override merging
468
+ * ```ts
469
+ * const options = defaultResolveOptions(operationNode, {
470
+ * options: { enumType: 'asConst' },
471
+ * override: [{ type: 'operationId', pattern: 'listPets', options: { enumType: 'enum' } }],
472
+ * })
473
+ * // → { enumType: 'enum' } when operationId matches
474
+ * ```
475
+ */
476
+ function defaultResolveOptions(node, { options, exclude = [], include, override = [] }) {
477
+ if (isOperationNode(node)) {
478
+ if (exclude.some(({ type, pattern }) => matchesOperationPattern(node, type, pattern))) return null;
479
+ if (include && !include.some(({ type, pattern }) => matchesOperationPattern(node, type, pattern))) return null;
480
+ const overrideOptions = override.find(({ type, pattern }) => matchesOperationPattern(node, type, pattern))?.options;
481
+ return {
482
+ ...options,
483
+ ...overrideOptions
484
+ };
485
+ }
486
+ if (isSchemaNode(node)) {
487
+ if (exclude.some(({ type, pattern }) => matchesSchemaPattern(node, type, pattern) === true)) return null;
488
+ if (include) {
489
+ const applicable = include.map(({ type, pattern }) => matchesSchemaPattern(node, type, pattern)).filter((r) => r !== null);
490
+ if (applicable.length > 0 && !applicable.includes(true)) return null;
491
+ }
492
+ const overrideOptions = override.find(({ type, pattern }) => matchesSchemaPattern(node, type, pattern) === true)?.options;
493
+ return {
494
+ ...options,
495
+ ...overrideOptions
496
+ };
497
+ }
498
+ return options;
499
+ }
500
+ /**
501
+ * Default path resolver used by `defineResolver`.
502
+ *
503
+ * - Returns the output directory in `single` mode.
504
+ * - Resolves into a tag- or path-based subdirectory when `group` and a `tag`/`path` value are provided.
505
+ * - Falls back to a flat `output/baseName` path otherwise.
506
+ *
507
+ * A custom `group.name` function overrides the default subdirectory naming.
508
+ * For `tag` groups the default is `${camelCase(tag)}Controller`.
509
+ * For `path` groups the default is the first path segment after `/`.
510
+ *
511
+ * @example Flat output
512
+ * ```ts
513
+ * defaultResolvePath({ baseName: 'petTypes.ts' }, { root: '/src', output: { path: 'types' } })
514
+ * // → '/src/types/petTypes.ts'
515
+ * ```
516
+ *
517
+ * @example Tag-based grouping
518
+ * ```ts
519
+ * defaultResolvePath(
520
+ * { baseName: 'petTypes.ts', tag: 'pets' },
521
+ * { root: '/src', output: { path: 'types' }, group: { type: 'tag' } },
522
+ * )
523
+ * // → '/src/types/petsController/petTypes.ts'
524
+ * ```
525
+ *
526
+ * @example Path-based grouping
527
+ * ```ts
528
+ * defaultResolvePath(
529
+ * { baseName: 'petTypes.ts', path: '/pets/list' },
530
+ * { root: '/src', output: { path: 'types' }, group: { type: 'path' } },
531
+ * )
532
+ * // → '/src/types/pets/petTypes.ts'
533
+ * ```
534
+ *
535
+ * @example Single-file mode
536
+ * ```ts
537
+ * defaultResolvePath(
538
+ * { baseName: 'petTypes.ts', pathMode: 'single' },
539
+ * { root: '/src', output: { path: 'types' } },
540
+ * )
541
+ * // → '/src/types'
542
+ * ```
543
+ */
544
+ function defaultResolvePath({ baseName, pathMode, tag, path: groupPath }, { root, output, group }) {
545
+ if ((pathMode ?? PluginDriver.getMode(path.resolve(root, output.path))) === "single") return path.resolve(root, output.path);
546
+ if (group && (groupPath || tag)) return path.resolve(root, output.path, group.name({ group: group.type === "path" ? groupPath : tag }), baseName);
547
+ return path.resolve(root, output.path, baseName);
548
+ }
549
+ /**
550
+ * Default file resolver used by `defineResolver`.
551
+ *
552
+ * Resolves a `FileNode` by combining name resolution (`resolver.default`) with
553
+ * path resolution (`resolver.resolvePath`). The resolved file always has empty
554
+ * `sources`, `imports`, and `exports` arrays — consumers populate those separately.
555
+ *
556
+ * In `single` mode the name is omitted and the file sits directly in the output directory.
557
+ *
558
+ * @example Resolve a schema file
559
+ * ```ts
560
+ * const file = defaultResolveFile.call(resolver,
561
+ * { name: 'pet', extname: '.ts' },
562
+ * { root: '/src', output: { path: 'types' } },
563
+ * )
564
+ * // → { baseName: 'pet.ts', path: '/src/types/pet.ts', sources: [], ... }
565
+ * ```
566
+ *
567
+ * @example Resolve an operation file with tag grouping
568
+ * ```ts
569
+ * const file = defaultResolveFile.call(resolver,
570
+ * { name: 'listPets', extname: '.ts', tag: 'pets' },
571
+ * { root: '/src', output: { path: 'types' }, group: { type: 'tag' } },
572
+ * )
573
+ * // → { baseName: 'listPets.ts', path: '/src/types/petsController/listPets.ts', ... }
574
+ * ```
575
+ */
576
+ function defaultResolveFile({ name, extname, tag, path: groupPath }, context) {
577
+ const pathMode = PluginDriver.getMode(path.resolve(context.root, context.output.path));
578
+ const baseName = `${pathMode === "single" ? "" : this.default(name, "file")}${extname}`;
579
+ const filePath = this.resolvePath({
580
+ baseName,
581
+ pathMode,
582
+ tag,
583
+ path: groupPath
584
+ }, context);
585
+ return createFile({
586
+ path: filePath,
587
+ baseName: path.basename(filePath),
588
+ meta: { pluginName: this.pluginName },
589
+ sources: [],
590
+ imports: [],
591
+ exports: []
592
+ });
593
+ }
594
+ /**
595
+ * Generates the default "Generated by Kubb" banner from config and optional node metadata.
596
+ */
597
+ function buildDefaultBanner({ title, description, version, config }) {
598
+ try {
599
+ let source = "";
600
+ if (Array.isArray(config.input)) {
601
+ const first = config.input[0];
602
+ if (first && "path" in first) source = path.basename(first.path);
603
+ } else if ("path" in config.input) source = path.basename(config.input.path);
604
+ else if ("data" in config.input) source = "text content";
605
+ let banner = "/**\n* Generated by Kubb (https://kubb.dev/).\n* Do not edit manually.\n";
606
+ if (config.output.defaultBanner === "simple") {
607
+ banner += "*/\n";
608
+ return banner;
609
+ }
610
+ if (source) banner += `* Source: ${source}\n`;
611
+ if (title) banner += `* Title: ${title}\n`;
612
+ if (description) {
613
+ const formattedDescription = description.replace(/\n/gm, "\n* ");
614
+ banner += `* Description: ${formattedDescription}\n`;
615
+ }
616
+ if (version) banner += `* OpenAPI spec version: ${version}\n`;
617
+ banner += "*/\n";
618
+ return banner;
619
+ } catch (_error) {
620
+ return "/**\n* Generated by Kubb (https://kubb.dev/).\n* Do not edit manually.\n*/";
621
+ }
622
+ }
623
+ /**
624
+ * Default banner resolver — returns the banner string for a generated file.
625
+ *
626
+ * A user-supplied `output.banner` overrides the default Kubb "Generated by Kubb" notice.
627
+ * When no `output.banner` is set, the Kubb notice is used (including `title` and `version`
628
+ * from the OAS spec when a `node` is provided).
629
+ *
630
+ * - When `output.banner` is a function and `node` is provided, returns `output.banner(node)`.
631
+ * - When `output.banner` is a function and `node` is absent, falls back to the Kubb notice.
632
+ * - When `output.banner` is a string, returns it directly.
633
+ * - When `config.output.defaultBanner` is `false`, returns `undefined`.
634
+ * - Otherwise returns the Kubb "Generated by Kubb" notice.
635
+ *
636
+ * @example String banner overrides default
637
+ * ```ts
638
+ * defaultResolveBanner(undefined, { output: { banner: '// my banner' }, config })
639
+ * // → '// my banner'
640
+ * ```
641
+ *
642
+ * @example Function banner with node
643
+ * ```ts
644
+ * defaultResolveBanner(inputNode, { output: { banner: (node) => `// v${node.version}` }, config })
645
+ * // → '// v3.0.0'
646
+ * ```
647
+ *
648
+ * @example No user banner — Kubb notice with OAS metadata
649
+ * ```ts
650
+ * defaultResolveBanner(inputNode, { config })
651
+ * // → '/** Generated by Kubb ... Title: Pet Store ... *\/'
652
+ * ```
653
+ *
654
+ * @example Disabled default banner
655
+ * ```ts
656
+ * defaultResolveBanner(undefined, { config: { output: { defaultBanner: false }, ...config } })
657
+ * // → undefined
658
+ * ```
659
+ */
660
+ function defaultResolveBanner(node, { output, config }) {
661
+ if (typeof output?.banner === "function") return output.banner(node);
662
+ if (typeof output?.banner === "string") return output.banner;
663
+ if (config.output.defaultBanner === false) return;
664
+ return buildDefaultBanner({
665
+ title: node?.meta?.title,
666
+ version: node?.meta?.version,
667
+ config
668
+ });
669
+ }
670
+ /**
671
+ * Default footer resolver — returns the footer string for a generated file.
672
+ *
673
+ * - When `output.footer` is a function and `node` is provided, calls it with the node.
674
+ * - When `output.footer` is a function and `node` is absent, returns `undefined`.
675
+ * - When `output.footer` is a string, returns it directly.
676
+ * - Otherwise returns `undefined`.
677
+ *
678
+ * @example String footer
679
+ * ```ts
680
+ * defaultResolveFooter(undefined, { output: { footer: '// end of file' }, config })
681
+ * // → '// end of file'
682
+ * ```
683
+ *
684
+ * @example Function footer with node
685
+ * ```ts
686
+ * defaultResolveFooter(inputNode, { output: { footer: (node) => `// ${node.title}` }, config })
687
+ * // → '// Pet Store'
688
+ * ```
689
+ */
690
+ function defaultResolveFooter(node, { output }) {
691
+ if (typeof output?.footer === "function") return node ? output.footer(node) : void 0;
692
+ if (typeof output?.footer === "string") return output.footer;
693
+ }
694
+ /**
695
+ * Defines a resolver for a plugin, injecting built-in defaults for name casing,
696
+ * include/exclude/override filtering, path resolution, and file construction.
697
+ *
698
+ * All four defaults can be overridden by providing them in the builder function:
699
+ * - `default` — name casing strategy (camelCase / PascalCase)
700
+ * - `resolveOptions` — include/exclude/override filtering
701
+ * - `resolvePath` — output path computation
702
+ * - `resolveFile` — full `FileNode` construction
703
+ *
704
+ * Methods in the builder have access to `this` (the full resolver object), so they
705
+ * can call other resolver methods without circular imports.
706
+ *
707
+ * @example Basic resolver with naming helpers
708
+ * ```ts
709
+ * export const resolver = defineResolver<PluginTs>(() => ({
710
+ * name: 'default',
711
+ * resolveName(node) {
712
+ * return this.default(node.name, 'function')
713
+ * },
714
+ * resolveTypedName(node) {
715
+ * return this.default(node.name, 'type')
716
+ * },
717
+ * }))
718
+ * ```
719
+ *
720
+ * @example Override resolvePath for a custom output structure
721
+ * ```ts
722
+ * export const resolver = defineResolver<PluginTs>(() => ({
723
+ * name: 'custom',
724
+ * resolvePath({ baseName }, { root, output }) {
725
+ * return path.resolve(root, output.path, 'generated', baseName)
726
+ * },
727
+ * }))
728
+ * ```
729
+ *
730
+ * @example Use this.default inside a helper
731
+ * ```ts
732
+ * export const resolver = defineResolver<PluginTs>(() => ({
733
+ * name: 'default',
734
+ * resolveParamName(node, param) {
735
+ * return this.default(`${node.operationId} ${param.in} ${param.name}`, 'type')
736
+ * },
737
+ * }))
738
+ * ```
739
+ */
740
+ function defineResolver(build) {
741
+ return {
742
+ default: defaultResolver,
743
+ resolveOptions: defaultResolveOptions,
744
+ resolvePath: defaultResolvePath,
745
+ resolveFile: defaultResolveFile,
746
+ resolveBanner: defaultResolveBanner,
747
+ resolveFooter: defaultResolveFooter,
748
+ ...build()
749
+ };
750
+ }
751
+ //#endregion
752
+ //#region src/devtools.ts
753
+ /**
754
+ * Encodes an `InputNode` as a compressed, URL-safe string.
755
+ *
756
+ * The JSON representation is deflate-compressed with {@link deflateSync} before
757
+ * base64url encoding, which typically reduces payload size by 70–80 % and
758
+ * keeps URLs well within browser and server path-length limits.
759
+ *
760
+ * Use {@link decodeAst} to reverse.
761
+ */
762
+ function encodeAst(input) {
763
+ const compressed = deflateSync(new TextEncoder().encode(JSON.stringify(input)));
764
+ return Buffer.from(compressed).toString("base64url");
765
+ }
766
+ /**
767
+ * Constructs the Kubb Studio URL for the given `InputNode`.
768
+ * When `options.ast` is `true`, navigates to the AST inspector (`/ast`).
769
+ * The `input` is encoded and attached as the `?root=` query parameter so Studio
770
+ * can decode and render it without a round-trip to any server.
771
+ */
772
+ function getStudioUrl(input, studioUrl, options = {}) {
773
+ return `${studioUrl.replace(/\/$/, "")}${options.ast ? "/ast" : ""}?root=${encodeAst(input)}`;
774
+ }
775
+ /**
776
+ * Opens the Kubb Studio URL for the given `InputNode` in the default browser —
777
+ *
778
+ * Falls back to printing the URL if the browser cannot be launched.
779
+ */
780
+ async function openInStudio(input, studioUrl, options = {}) {
781
+ const url = getStudioUrl(input, studioUrl, options);
782
+ const cmd = process.platform === "win32" ? "cmd" : process.platform === "darwin" ? "open" : "xdg-open";
783
+ const args = process.platform === "win32" ? [
784
+ "/c",
785
+ "start",
786
+ "",
787
+ url
788
+ ] : [url];
789
+ try {
790
+ await x(cmd, args);
791
+ } catch {
792
+ console.log(`\n ${url}\n`);
793
+ }
794
+ }
795
+ //#endregion
796
+ //#region src/FileManager.ts
797
+ function mergeFile(a, b) {
798
+ return {
799
+ ...a,
800
+ sources: [...a.sources || [], ...b.sources || []],
801
+ imports: [...a.imports || [], ...b.imports || []],
802
+ exports: [...a.exports || [], ...b.exports || []]
803
+ };
804
+ }
805
+ /**
806
+ * In-memory file store for generated files.
807
+ *
808
+ * Files with the same `path` are merged — sources, imports, and exports are concatenated.
809
+ * The `files` getter returns all stored files sorted by path length (shortest first).
810
+ *
811
+ * @example
812
+ * ```ts
813
+ * import { FileManager } from '@kubb/core'
814
+ *
815
+ * const manager = new FileManager()
816
+ * manager.upsert(myFile)
817
+ * console.log(manager.files) // all stored files
818
+ * ```
819
+ */
820
+ var FileManager = class {
821
+ #cache = /* @__PURE__ */ new Map();
822
+ #filesCache = null;
823
+ /**
824
+ * Adds one or more files. Files with the same path are merged — sources, imports,
825
+ * and exports from all calls with the same path are concatenated together.
826
+ */
827
+ add(...files) {
828
+ const resolvedFiles = [];
829
+ const mergedFiles = /* @__PURE__ */ new Map();
830
+ files.forEach((file) => {
831
+ const existing = mergedFiles.get(file.path);
832
+ if (existing) mergedFiles.set(file.path, mergeFile(existing, file));
833
+ else mergedFiles.set(file.path, file);
834
+ });
835
+ for (const file of mergedFiles.values()) {
836
+ const resolvedFile = createFile(file);
837
+ this.#cache.set(resolvedFile.path, resolvedFile);
838
+ this.#filesCache = null;
839
+ resolvedFiles.push(resolvedFile);
840
+ }
841
+ return resolvedFiles;
842
+ }
843
+ /**
844
+ * Adds or merges one or more files.
845
+ * If a file with the same path already exists, its sources/imports/exports are merged together.
846
+ */
847
+ upsert(...files) {
848
+ const resolvedFiles = [];
849
+ const mergedFiles = /* @__PURE__ */ new Map();
850
+ files.forEach((file) => {
851
+ const existing = mergedFiles.get(file.path);
852
+ if (existing) mergedFiles.set(file.path, mergeFile(existing, file));
853
+ else mergedFiles.set(file.path, file);
854
+ });
855
+ for (const file of mergedFiles.values()) {
856
+ const existing = this.#cache.get(file.path);
857
+ const resolvedFile = createFile(existing ? mergeFile(existing, file) : file);
858
+ this.#cache.set(resolvedFile.path, resolvedFile);
859
+ this.#filesCache = null;
860
+ resolvedFiles.push(resolvedFile);
861
+ }
862
+ return resolvedFiles;
863
+ }
864
+ getByPath(path) {
865
+ return this.#cache.get(path) ?? null;
866
+ }
867
+ deleteByPath(path) {
868
+ this.#cache.delete(path);
869
+ this.#filesCache = null;
870
+ }
871
+ clear() {
872
+ this.#cache.clear();
873
+ this.#filesCache = null;
874
+ }
875
+ /**
876
+ * All stored files, sorted by path length (shorter paths first).
877
+ * Barrel/index files (e.g. index.ts) are sorted last within each length bucket.
878
+ */
879
+ get files() {
880
+ if (this.#filesCache) return this.#filesCache;
881
+ const keys = [...this.#cache.keys()].sort((a, b) => {
882
+ if (a.length !== b.length) return a.length - b.length;
883
+ const aIsIndex = trimExtName(a).endsWith("index");
884
+ if (aIsIndex !== trimExtName(b).endsWith("index")) return aIsIndex ? 1 : -1;
885
+ return 0;
886
+ });
887
+ const files = [];
888
+ for (const key of keys) {
889
+ const file = this.#cache.get(key);
890
+ if (file) files.push(file);
891
+ }
892
+ this.#filesCache = files;
893
+ return files;
894
+ }
895
+ };
896
+ //#endregion
897
+ //#region src/renderNode.ts
898
+ /**
899
+ * Handles the return value of a plugin AST hook or generator method.
900
+ *
901
+ * - Renderer output → rendered via the provided `rendererFactory` (e.g. JSX), files stored in `driver.fileManager`
902
+ * - `Array<FileNode>` → added directly into `driver.fileManager`
903
+ * - `void` / `null` / `undefined` → no-op (plugin handled it via `this.upsertFile`)
904
+ *
905
+ * Pass a `rendererFactory` (e.g. `jsxRenderer` from `@kubb/renderer-jsx`) when the result
906
+ * may be a renderer element. Generators that only return `Array<FileNode>` do not need one.
907
+ */
908
+ async function applyHookResult(result, driver, rendererFactory) {
909
+ if (!result) return;
910
+ if (Array.isArray(result)) {
911
+ driver.fileManager.upsert(...result);
912
+ return;
913
+ }
914
+ if (!rendererFactory) return;
915
+ const renderer = rendererFactory();
916
+ await renderer.render(result);
917
+ driver.fileManager.upsert(...renderer.files);
918
+ renderer.unmount();
919
+ }
920
+ //#endregion
921
+ //#region src/utils/executeStrategies.ts
922
+ /**
923
+ * Runs promise functions in sequence, threading each result into the next call.
924
+ *
925
+ * - Each function receives the accumulated state from the previous call.
926
+ * - Skips functions that return a falsy value (acts as a no-op for that step).
927
+ * - Returns an array of all individual results.
928
+ * @deprecated
929
+ */
930
+ function hookSeq(promises) {
931
+ return promises.filter(Boolean).reduce((promise, func) => {
932
+ if (typeof func !== "function") throw new Error("HookSeq needs a function that returns a promise `() => Promise<unknown>`");
933
+ return promise.then((state) => {
934
+ const calledFunc = func(state);
935
+ if (calledFunc) return calledFunc.then(Array.prototype.concat.bind(state));
936
+ return state;
937
+ });
938
+ }, Promise.resolve([]));
939
+ }
940
+ /**
941
+ * Runs promise functions in sequence and returns the first non-null result.
942
+ *
943
+ * - Stops as soon as `nullCheck` passes for a result (default: `!== null`).
944
+ * - Subsequent functions are skipped once a match is found.
945
+ * @deprecated
946
+ */
947
+ function hookFirst(promises, nullCheck = (state) => state !== null) {
948
+ let promise = Promise.resolve(null);
949
+ for (const func of promises.filter(Boolean)) promise = promise.then((state) => {
950
+ if (nullCheck(state)) return state;
951
+ return func(state);
952
+ });
953
+ return promise;
954
+ }
955
+ /**
956
+ * Runs promise functions concurrently and returns all settled results.
957
+ *
958
+ * - Limits simultaneous executions to `concurrency` (default: unlimited).
959
+ * - Uses `Promise.allSettled` so individual failures do not cancel other tasks.
960
+ * @deprecated
961
+ */
962
+ function hookParallel(promises, concurrency = Number.POSITIVE_INFINITY) {
963
+ const limit = pLimit(concurrency);
964
+ const tasks = promises.filter(Boolean).map((promise) => limit(() => promise()));
965
+ return Promise.allSettled(tasks);
966
+ }
967
+ //#endregion
968
+ //#region src/PluginDriver.ts
969
+ const hookFirstNullCheck = (state) => !!state?.result;
970
+ var PluginDriver = class PluginDriver {
971
+ config;
972
+ options;
973
+ /**
974
+ * Returns `'single'` when `fileOrFolder` has a file extension, `'split'` otherwise.
975
+ *
976
+ * @example
977
+ * ```ts
978
+ * PluginDriver.getMode('src/gen/types.ts') // 'single'
979
+ * PluginDriver.getMode('src/gen/types') // 'split'
980
+ * ```
981
+ */
982
+ static getMode(fileOrFolder) {
983
+ if (!fileOrFolder) return "split";
984
+ return extname(fileOrFolder) ? "single" : "split";
985
+ }
986
+ /**
987
+ * The universal `@kubb/ast` `InputNode` produced by the adapter, set by
988
+ * the build pipeline after the adapter's `parse()` resolves.
989
+ */
990
+ inputNode = void 0;
991
+ adapter = void 0;
992
+ #studioIsOpen = false;
993
+ /**
994
+ * Central file store for all generated files.
995
+ * Plugins should use `this.addFile()` / `this.upsertFile()` (via their context) to
996
+ * add files; this property gives direct read/write access when needed.
997
+ */
998
+ fileManager = new FileManager();
999
+ plugins = /* @__PURE__ */ new Map();
1000
+ /**
1001
+ * Tracks which plugins have generators registered via `addGenerator()` (event-based path).
1002
+ * Used by the build loop to decide whether to emit generator events for a given plugin.
1003
+ */
1004
+ #pluginsWithEventGenerators = /* @__PURE__ */ new Set();
1005
+ #resolvers = /* @__PURE__ */ new Map();
1006
+ #defaultResolvers = /* @__PURE__ */ new Map();
1007
+ #hookListeners = /* @__PURE__ */ new Map();
1008
+ constructor(config, options) {
1009
+ this.config = config;
1010
+ this.options = {
1011
+ ...options,
1012
+ hooks: options.hooks
1013
+ };
1014
+ config.plugins.map((rawPlugin) => {
1015
+ if (isHookStylePlugin(rawPlugin)) return this.#normalizeHookStylePlugin(rawPlugin);
1016
+ return {
1017
+ ...rawPlugin,
1018
+ buildStart: rawPlugin.buildStart ?? (() => {}),
1019
+ buildEnd: rawPlugin.buildEnd ?? (() => {})
1020
+ };
1021
+ }).filter((plugin) => {
1022
+ if (typeof plugin.apply === "function") return plugin.apply(config);
1023
+ return true;
1024
+ }).sort((a, b) => {
1025
+ if (b.dependencies?.includes(a.name)) return -1;
1026
+ if (a.dependencies?.includes(b.name)) return 1;
1027
+ return 0;
1028
+ }).forEach((plugin) => {
1029
+ this.plugins.set(plugin.name, plugin);
1030
+ });
1031
+ }
1032
+ get hooks() {
1033
+ if (!this.options.hooks) throw new Error("hooks are not defined");
1034
+ return this.options.hooks;
1035
+ }
1036
+ /**
1037
+ * Creates a `Plugin`-compatible object from a hook-style plugin and registers
1038
+ * its lifecycle handlers on the `AsyncEventEmitter`.
1039
+ *
1040
+ * The normalized plugin has an empty `buildStart` — generators registered via
1041
+ * `addGenerator()` in `kubb:plugin:setup` are stored on `normalizedPlugin.generators`
1042
+ * and used by `runPluginAstHooks` during the build.
1043
+ */
1044
+ #normalizeHookStylePlugin(hookPlugin) {
1045
+ const generators = [];
1046
+ const driver = this;
1047
+ const normalizedPlugin = {
1048
+ name: hookPlugin.name,
1049
+ dependencies: hookPlugin.dependencies,
1050
+ options: {
1051
+ output: { path: "." },
1052
+ exclude: [],
1053
+ override: []
1054
+ },
1055
+ generators,
1056
+ inject: () => void 0,
1057
+ resolveName(name, type) {
1058
+ return driver.getResolver(hookPlugin.name).default(name, type);
1059
+ },
1060
+ resolvePath(baseName, pathMode, resolveOptions) {
1061
+ const resolver = driver.getResolver(hookPlugin.name);
1062
+ const opts = normalizedPlugin.options;
1063
+ const group = resolveOptions?.group;
1064
+ return resolver.resolvePath({
1065
+ baseName,
1066
+ pathMode,
1067
+ tag: group?.tag,
1068
+ path: group?.path
1069
+ }, {
1070
+ root: resolve(driver.config.root, driver.config.output.path),
1071
+ output: opts.output,
1072
+ group: opts.group
1073
+ });
1074
+ },
1075
+ buildStart() {},
1076
+ buildEnd() {}
1077
+ };
1078
+ this.registerPluginHooks(hookPlugin, normalizedPlugin);
1079
+ return normalizedPlugin;
1080
+ }
1081
+ /**
1082
+ * Registers a hook-style plugin's lifecycle handlers on the shared `AsyncEventEmitter`.
1083
+ *
1084
+ * For `kubb:plugin:setup`, the registered listener wraps the globally emitted context with a
1085
+ * plugin-specific one so that `addGenerator`, `setResolver`, `setTransformer`, and
1086
+ * `setRenderer` all target the correct `normalizedPlugin` entry in the plugins map.
1087
+ *
1088
+ * All other hooks are iterated and registered directly as pass-through listeners.
1089
+ * Any event key present in the global `KubbHooks` interface can be subscribed to.
1090
+ *
1091
+ * External tooling can subscribe to any of these events via `hooks.on(...)` to observe
1092
+ * the plugin lifecycle without modifying plugin behavior.
1093
+ */
1094
+ registerPluginHooks(hookPlugin, normalizedPlugin) {
1095
+ const { hooks } = hookPlugin;
1096
+ if (hooks["kubb:plugin:setup"]) {
1097
+ const setupHandler = (globalCtx) => {
1098
+ const pluginCtx = {
1099
+ ...globalCtx,
1100
+ options: hookPlugin.options ?? {},
1101
+ addGenerator: (gen) => {
1102
+ this.registerGenerator(normalizedPlugin.name, gen);
1103
+ },
1104
+ setResolver: (resolver) => {
1105
+ this.setPluginResolver(normalizedPlugin.name, resolver);
1106
+ },
1107
+ setTransformer: (visitor) => {
1108
+ normalizedPlugin.transformer = visitor;
1109
+ },
1110
+ setRenderer: (renderer) => {
1111
+ normalizedPlugin.renderer = renderer;
1112
+ },
1113
+ setOptions: (opts) => {
1114
+ normalizedPlugin.options = {
1115
+ ...normalizedPlugin.options,
1116
+ ...opts
1117
+ };
1118
+ },
1119
+ injectFile: (file) => {
1120
+ const fileNode = createFile({
1121
+ baseName: file.baseName,
1122
+ path: file.path,
1123
+ sources: file.sources ?? [],
1124
+ imports: [],
1125
+ exports: []
1126
+ });
1127
+ this.fileManager.add(fileNode);
1128
+ }
1129
+ };
1130
+ return hooks["kubb:plugin:setup"](pluginCtx);
1131
+ };
1132
+ this.hooks.on("kubb:plugin:setup", setupHandler);
1133
+ this.#trackHookListener("kubb:plugin:setup", setupHandler);
1134
+ }
1135
+ for (const [event, handler] of Object.entries(hooks)) {
1136
+ if (event === "kubb:plugin:setup" || !handler) continue;
1137
+ this.hooks.on(event, handler);
1138
+ this.#trackHookListener(event, handler);
1139
+ }
1140
+ }
1141
+ /**
1142
+ * Emits the `kubb:plugin:setup` event so that all registered hook-style plugin listeners
1143
+ * can configure generators, resolvers, transformers and renderers before `buildStart` runs.
1144
+ *
1145
+ * Call this once from `safeBuild` before the plugin execution loop begins.
1146
+ */
1147
+ async emitSetupHooks() {
1148
+ await this.hooks.emit("kubb:plugin:setup", {
1149
+ config: this.config,
1150
+ addGenerator: () => {},
1151
+ setResolver: () => {},
1152
+ setTransformer: () => {},
1153
+ setRenderer: () => {},
1154
+ setOptions: () => {},
1155
+ injectFile: () => {},
1156
+ updateConfig: () => {},
1157
+ options: {}
1158
+ });
1159
+ }
1160
+ /**
1161
+ * Registers a generator for the given plugin on the shared event emitter.
1162
+ *
1163
+ * The generator's `schema`, `operation`, and `operations` methods are registered as
1164
+ * listeners on `kubb:generate:schema`, `kubb:generate:operation`, and `kubb:generate:operations`
1165
+ * respectively. Each listener is scoped to the owning plugin via a `ctx.plugin.name` check
1166
+ * so that generators from different plugins do not cross-fire.
1167
+ *
1168
+ * The renderer resolution chain is: `generator.renderer → plugin.renderer → config.renderer`.
1169
+ * Set `generator.renderer = null` to explicitly opt out of rendering even when the plugin
1170
+ * declares a renderer.
1171
+ *
1172
+ * Call this method inside `addGenerator()` (in `kubb:plugin:setup`) to wire up a generator.
1173
+ */
1174
+ registerGenerator(pluginName, gen) {
1175
+ const resolveRenderer = () => {
1176
+ const plugin = this.plugins.get(pluginName);
1177
+ return gen.renderer === null ? void 0 : gen.renderer ?? plugin?.renderer ?? this.config.renderer;
1178
+ };
1179
+ if (gen.schema) {
1180
+ const schemaHandler = async (node, ctx) => {
1181
+ if (ctx.plugin.name !== pluginName) return;
1182
+ await applyHookResult(await gen.schema(node, ctx), this, resolveRenderer());
1183
+ };
1184
+ this.hooks.on("kubb:generate:schema", schemaHandler);
1185
+ this.#trackHookListener("kubb:generate:schema", schemaHandler);
1186
+ }
1187
+ if (gen.operation) {
1188
+ const operationHandler = async (node, ctx) => {
1189
+ if (ctx.plugin.name !== pluginName) return;
1190
+ await applyHookResult(await gen.operation(node, ctx), this, resolveRenderer());
1191
+ };
1192
+ this.hooks.on("kubb:generate:operation", operationHandler);
1193
+ this.#trackHookListener("kubb:generate:operation", operationHandler);
1194
+ }
1195
+ if (gen.operations) {
1196
+ const operationsHandler = async (nodes, ctx) => {
1197
+ if (ctx.plugin.name !== pluginName) return;
1198
+ await applyHookResult(await gen.operations(nodes, ctx), this, resolveRenderer());
1199
+ };
1200
+ this.hooks.on("kubb:generate:operations", operationsHandler);
1201
+ this.#trackHookListener("kubb:generate:operations", operationsHandler);
1202
+ }
1203
+ this.#pluginsWithEventGenerators.add(pluginName);
1204
+ }
1205
+ /**
1206
+ * Returns `true` when at least one generator was registered for the given plugin
1207
+ * via `addGenerator()` in `kubb:plugin:setup` (event-based path).
1208
+ *
1209
+ * Used by the build loop to decide whether to walk the AST and emit generator events
1210
+ * for a plugin that has no static `plugin.generators`.
1211
+ */
1212
+ hasRegisteredGenerators(pluginName) {
1213
+ return this.#pluginsWithEventGenerators.has(pluginName);
1214
+ }
1215
+ dispose() {
1216
+ for (const [event, handlers] of this.#hookListeners) for (const handler of handlers) this.hooks.off(event, handler);
1217
+ this.#hookListeners.clear();
1218
+ this.#pluginsWithEventGenerators.clear();
1219
+ }
1220
+ #trackHookListener(event, handler) {
1221
+ let handlers = this.#hookListeners.get(event);
1222
+ if (!handlers) {
1223
+ handlers = /* @__PURE__ */ new Set();
1224
+ this.#hookListeners.set(event, handlers);
1225
+ }
1226
+ handlers.add(handler);
1227
+ }
1228
+ #createDefaultResolver(pluginName) {
1229
+ const existingResolver = this.#defaultResolvers.get(pluginName);
1230
+ if (existingResolver) return existingResolver;
1231
+ const resolver = defineResolver(() => ({
1232
+ name: "default",
1233
+ pluginName
1234
+ }));
1235
+ this.#defaultResolvers.set(pluginName, resolver);
1236
+ return resolver;
1237
+ }
1238
+ setPluginResolver(pluginName, partial) {
1239
+ const merged = {
1240
+ ...this.#createDefaultResolver(pluginName),
1241
+ ...partial
1242
+ };
1243
+ this.#resolvers.set(pluginName, merged);
1244
+ const plugin = this.plugins.get(pluginName);
1245
+ if (plugin) plugin.resolver = merged;
1246
+ }
1247
+ getResolver(pluginName) {
1248
+ const dynamicResolver = this.#resolvers.get(pluginName);
1249
+ if (dynamicResolver) return dynamicResolver;
1250
+ const pluginResolver = this.plugins.get(pluginName)?.resolver;
1251
+ if (pluginResolver) return pluginResolver;
1252
+ return this.#createDefaultResolver(pluginName);
1253
+ }
1254
+ getContext(plugin) {
1255
+ const driver = this;
1256
+ const baseContext = {
1257
+ config: driver.config,
1258
+ get root() {
1259
+ return resolve(driver.config.root, driver.config.output.path);
1260
+ },
1261
+ getMode(output) {
1262
+ return PluginDriver.getMode(resolve(driver.config.root, driver.config.output.path, output.path));
1263
+ },
1264
+ hooks: driver.hooks,
1265
+ plugin,
1266
+ getPlugin: driver.getPlugin.bind(driver),
1267
+ requirePlugin: driver.requirePlugin.bind(driver),
1268
+ driver,
1269
+ addFile: async (...files) => {
1270
+ driver.fileManager.add(...files);
1271
+ },
1272
+ upsertFile: async (...files) => {
1273
+ driver.fileManager.upsert(...files);
1274
+ },
1275
+ get inputNode() {
1276
+ return driver.inputNode;
1277
+ },
1278
+ get adapter() {
1279
+ return driver.adapter;
1280
+ },
1281
+ get resolver() {
1282
+ return driver.getResolver(plugin.name);
1283
+ },
1284
+ get transformer() {
1285
+ return plugin.transformer;
1286
+ },
1287
+ warn(message) {
1288
+ driver.hooks.emit("kubb:warn", message);
1289
+ },
1290
+ error(error) {
1291
+ driver.hooks.emit("kubb:error", typeof error === "string" ? new Error(error) : error);
1292
+ },
1293
+ info(message) {
1294
+ driver.hooks.emit("kubb:info", message);
1295
+ },
1296
+ openInStudio(options) {
1297
+ if (!driver.config.devtools || driver.#studioIsOpen) return;
1298
+ if (typeof driver.config.devtools !== "object") throw new Error("Devtools must be an object");
1299
+ if (!driver.inputNode || !driver.adapter) throw new Error("adapter is not defined, make sure you have set the parser in kubb.config.ts");
1300
+ driver.#studioIsOpen = true;
1301
+ const studioUrl = driver.config.devtools?.studioUrl ?? "https://studio.kubb.dev";
1302
+ return openInStudio(driver.inputNode, studioUrl, options);
1303
+ }
1304
+ };
1305
+ let mergedExtras = {};
1306
+ for (const p of this.plugins.values()) if (typeof p.inject === "function") {
1307
+ const result = p.inject.call(baseContext);
1308
+ if (result !== null && typeof result === "object") mergedExtras = {
1309
+ ...mergedExtras,
1310
+ ...result
1311
+ };
1312
+ }
1313
+ return {
1314
+ ...baseContext,
1315
+ ...mergedExtras
1316
+ };
1317
+ }
1318
+ /**
1319
+ * @deprecated use resolvers context instead
1320
+ */
1321
+ getFile({ name, mode, extname, pluginName, options }) {
1322
+ const resolvedName = mode ? mode === "single" ? "" : this.resolveName({
1323
+ name,
1324
+ pluginName,
1325
+ type: "file"
1326
+ }) : name;
1327
+ const path = this.resolvePath({
1328
+ baseName: `${resolvedName}${extname}`,
1329
+ mode,
1330
+ pluginName,
1331
+ options
1332
+ });
1333
+ if (!path) throw new Error(`Filepath should be defined for resolvedName "${resolvedName}" and pluginName "${pluginName}"`);
1334
+ return createFile({
1335
+ path,
1336
+ baseName: basename(path),
1337
+ meta: { pluginName },
1338
+ sources: [],
1339
+ imports: [],
1340
+ exports: []
1341
+ });
1342
+ }
1343
+ /**
1344
+ * @deprecated use resolvers context instead
1345
+ */
1346
+ resolvePath = (params) => {
1347
+ const defaultPath = resolve(resolve(this.config.root, this.config.output.path), params.baseName);
1348
+ if (params.pluginName) return this.hookForPluginSync({
1349
+ pluginName: params.pluginName,
1350
+ hookName: "resolvePath",
1351
+ parameters: [
1352
+ params.baseName,
1353
+ params.mode,
1354
+ params.options
1355
+ ]
1356
+ })?.at(0) || defaultPath;
1357
+ return this.hookFirstSync({
1358
+ hookName: "resolvePath",
1359
+ parameters: [
1360
+ params.baseName,
1361
+ params.mode,
1362
+ params.options
1363
+ ]
1364
+ })?.result || defaultPath;
1365
+ };
1366
+ /**
1367
+ * @deprecated use resolvers context instead
1368
+ */
1369
+ resolveName = (params) => {
1370
+ if (params.pluginName) return transformReservedWord(this.hookForPluginSync({
1371
+ pluginName: params.pluginName,
1372
+ hookName: "resolveName",
1373
+ parameters: [params.name.trim(), params.type]
1374
+ })?.at(0) ?? params.name);
1375
+ const name = this.hookFirstSync({
1376
+ hookName: "resolveName",
1377
+ parameters: [params.name.trim(), params.type]
1378
+ })?.result;
1379
+ return transformReservedWord(name ?? params.name);
1380
+ };
1381
+ /**
1382
+ * Run a specific hookName for plugin x.
1383
+ */
1384
+ async hookForPlugin({ pluginName, hookName, parameters }) {
1385
+ const plugin = this.plugins.get(pluginName);
1386
+ if (!plugin) return [null];
1387
+ this.hooks.emit("kubb:plugins:hook:progress:start", {
1388
+ hookName,
1389
+ plugins: [plugin]
1390
+ });
1391
+ const result = await this.#execute({
1392
+ strategy: "hookFirst",
1393
+ hookName,
1394
+ parameters,
1395
+ plugin
1396
+ });
1397
+ this.hooks.emit("kubb:plugins:hook:progress:end", { hookName });
1398
+ return [result];
1399
+ }
1400
+ /**
1401
+ * Run a specific hookName for plugin x.
1402
+ */
1403
+ hookForPluginSync({ pluginName, hookName, parameters }) {
1404
+ const plugin = this.plugins.get(pluginName);
1405
+ if (!plugin) return null;
1406
+ const result = this.#executeSync({
1407
+ strategy: "hookFirst",
1408
+ hookName,
1409
+ parameters,
1410
+ plugin
1411
+ });
1412
+ return result !== null ? [result] : [];
1413
+ }
1414
+ /**
1415
+ * Returns the first non-null result.
1416
+ */
1417
+ async hookFirst({ hookName, parameters, skipped }) {
1418
+ const plugins = [];
1419
+ for (const plugin of this.plugins.values()) if (hookName in plugin && (skipped ? !skipped.has(plugin) : true)) plugins.push(plugin);
1420
+ this.hooks.emit("kubb:plugins:hook:progress:start", {
1421
+ hookName,
1422
+ plugins
1423
+ });
1424
+ const result = await hookFirst(plugins.map((plugin) => {
1425
+ return async () => {
1426
+ const value = await this.#execute({
1427
+ strategy: "hookFirst",
1428
+ hookName,
1429
+ parameters,
1430
+ plugin
1431
+ });
1432
+ return Promise.resolve({
1433
+ plugin,
1434
+ result: value
1435
+ });
1436
+ };
1437
+ }), hookFirstNullCheck);
1438
+ this.hooks.emit("kubb:plugins:hook:progress:end", { hookName });
1439
+ return result;
1440
+ }
1441
+ /**
1442
+ * Returns the first non-null result.
1443
+ */
1444
+ hookFirstSync({ hookName, parameters, skipped }) {
1445
+ let parseResult = null;
1446
+ for (const plugin of this.plugins.values()) {
1447
+ if (!(hookName in plugin)) continue;
1448
+ if (skipped?.has(plugin)) continue;
1449
+ parseResult = {
1450
+ result: this.#executeSync({
1451
+ strategy: "hookFirst",
1452
+ hookName,
1453
+ parameters,
1454
+ plugin
1455
+ }),
1456
+ plugin
1457
+ };
1458
+ if (parseResult.result != null) break;
1459
+ }
1460
+ return parseResult;
1461
+ }
1462
+ /**
1463
+ * Runs all plugins in parallel based on `this.plugin` order and `dependencies` settings.
1464
+ */
1465
+ async hookParallel({ hookName, parameters }) {
1466
+ const plugins = [];
1467
+ for (const plugin of this.plugins.values()) if (hookName in plugin) plugins.push(plugin);
1468
+ this.hooks.emit("kubb:plugins:hook:progress:start", {
1469
+ hookName,
1470
+ plugins
1471
+ });
1472
+ const pluginStartTimes = /* @__PURE__ */ new Map();
1473
+ const results = await hookParallel(plugins.map((plugin) => {
1474
+ return () => {
1475
+ pluginStartTimes.set(plugin, performance.now());
1476
+ return this.#execute({
1477
+ strategy: "hookParallel",
1478
+ hookName,
1479
+ parameters,
1480
+ plugin
1481
+ });
1482
+ };
1483
+ }), this.options.concurrency);
1484
+ results.forEach((result, index) => {
1485
+ if (isPromiseRejectedResult(result)) {
1486
+ const plugin = plugins[index];
1487
+ if (plugin) {
1488
+ const startTime = pluginStartTimes.get(plugin) ?? performance.now();
1489
+ this.hooks.emit("kubb:error", result.reason, {
1490
+ plugin,
1491
+ hookName,
1492
+ strategy: "hookParallel",
1493
+ duration: Math.round(performance.now() - startTime),
1494
+ parameters
1495
+ });
1496
+ }
1497
+ }
1498
+ });
1499
+ this.hooks.emit("kubb:plugins:hook:progress:end", { hookName });
1500
+ return results.reduce((acc, result) => {
1501
+ if (result.status === "fulfilled") acc.push(result.value);
1502
+ return acc;
1503
+ }, []);
1504
+ }
1505
+ /**
1506
+ * Execute a lifecycle hook sequentially for all plugins that implement it.
1507
+ */
1508
+ async hookSeq({ hookName, parameters }) {
1509
+ const plugins = [];
1510
+ for (const plugin of this.plugins.values()) if (hookName in plugin) plugins.push(plugin);
1511
+ this.hooks.emit("kubb:plugins:hook:progress:start", {
1512
+ hookName,
1513
+ plugins
1514
+ });
1515
+ await hookSeq(plugins.map((plugin) => {
1516
+ return () => this.#execute({
1517
+ strategy: "hookSeq",
1518
+ hookName,
1519
+ parameters,
1520
+ plugin
1521
+ });
1522
+ }));
1523
+ this.hooks.emit("kubb:plugins:hook:progress:end", { hookName });
1524
+ }
1525
+ getPlugin(pluginName) {
1526
+ return this.plugins.get(pluginName);
1527
+ }
1528
+ requirePlugin(pluginName) {
1529
+ const plugin = this.plugins.get(pluginName);
1530
+ if (!plugin) throw new Error(`[kubb] Plugin "${pluginName}" is required but not found. Make sure it is included in your Kubb config.`);
1531
+ return plugin;
1532
+ }
1533
+ /**
1534
+ * Emit hook-processing completion metadata after a plugin hook resolves.
1535
+ */
1536
+ #emitProcessingEnd({ startTime, output, strategy, hookName, plugin, parameters }) {
1537
+ this.hooks.emit("kubb:plugins:hook:processing:end", {
1538
+ duration: Math.round(performance.now() - startTime),
1539
+ parameters,
1540
+ output,
1541
+ strategy,
1542
+ hookName,
1543
+ plugin
1544
+ });
1545
+ }
1546
+ #execute({ strategy, hookName, parameters, plugin }) {
1547
+ const hook = plugin[hookName];
1548
+ if (!hook) return null;
1549
+ this.hooks.emit("kubb:plugins:hook:processing:start", {
1550
+ strategy,
1551
+ hookName,
1552
+ parameters,
1553
+ plugin
1554
+ });
1555
+ const startTime = performance.now();
1556
+ return (async () => {
1557
+ try {
1558
+ const output = typeof hook === "function" ? await Promise.resolve(hook.apply(this.getContext(plugin), parameters ?? [])) : hook;
1559
+ this.#emitProcessingEnd({
1560
+ startTime,
1561
+ output,
1562
+ strategy,
1563
+ hookName,
1564
+ plugin,
1565
+ parameters
1566
+ });
1567
+ return output;
1568
+ } catch (error) {
1569
+ this.hooks.emit("kubb:error", error, {
1570
+ plugin,
1571
+ hookName,
1572
+ strategy,
1573
+ duration: Math.round(performance.now() - startTime)
1574
+ });
1575
+ return null;
1576
+ }
1577
+ })();
1578
+ }
1579
+ /**
1580
+ * Execute a plugin lifecycle hook synchronously and return its output.
1581
+ */
1582
+ #executeSync({ strategy, hookName, parameters, plugin }) {
1583
+ const hook = plugin[hookName];
1584
+ if (!hook) return null;
1585
+ this.hooks.emit("kubb:plugins:hook:processing:start", {
1586
+ strategy,
1587
+ hookName,
1588
+ parameters,
1589
+ plugin
1590
+ });
1591
+ const startTime = performance.now();
1592
+ try {
1593
+ const output = typeof hook === "function" ? hook.apply(this.getContext(plugin), parameters) : hook;
1594
+ this.#emitProcessingEnd({
1595
+ startTime,
1596
+ output,
1597
+ strategy,
1598
+ hookName,
1599
+ plugin,
1600
+ parameters
1601
+ });
1602
+ return output;
1603
+ } catch (error) {
1604
+ this.hooks.emit("kubb:error", error, {
1605
+ plugin,
1606
+ hookName,
1607
+ strategy,
1608
+ duration: Math.round(performance.now() - startTime)
1609
+ });
1610
+ return null;
1611
+ }
1612
+ }
1613
+ };
1614
+ //#endregion
1615
+ export { definePlugin as a, DEFAULT_BANNER as c, logLevel as d, isValidVarName as f, defineResolver as i, DEFAULT_EXTENSION as l, applyHookResult as n, pLimit as o, camelCase as p, FileManager as r, BARREL_FILENAME as s, PluginDriver as t, DEFAULT_STUDIO_URL as u };
1616
+
1617
+ //# sourceMappingURL=PluginDriver-CgXFtmNP.js.map