@kubb/core 5.0.0-alpha.35 → 5.0.0-alpha.36

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