@kubb/core 5.6.2 → 5.7.0

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,2784 @@
1
+ import "./rolldown-runtime-C0LytTxp.js";
2
+ import { AsyncLocalStorage } from "node:async_hooks";
3
+ import { styleText } from "node:util";
4
+ import { access, mkdir, readFile, rm, writeFile } from "node:fs/promises";
5
+ import path, { dirname, isAbsolute, relative, resolve } from "node:path";
6
+ import { ast, collectImportedRefNames, collectUsedSchemaNames, composeMacros, extractStringsFromNodes, operationDef, schemaDef, transform } from "@kubb/ast";
7
+ import { satisfies } from "verkit";
8
+ import { EventEmitter } from "node:events";
9
+ //#region ../../internals/utils/src/casing.ts
10
+ /**
11
+ * Shared implementation for camelCase and PascalCase conversion.
12
+ * Splits on common word boundaries (spaces, hyphens, underscores, dots, slashes, colons)
13
+ * and capitalizes each word according to `pascal`.
14
+ *
15
+ * When `pascal` is `true` the first word is also capitalized (PascalCase), otherwise only subsequent words are.
16
+ */
17
+ function toCamelOrPascal(text, pascal) {
18
+ 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) => {
19
+ if (word.length > 1 && word === word.toUpperCase()) return word;
20
+ return (i === 0 && !pascal ? word.charAt(0).toLowerCase() : word.charAt(0).toUpperCase()) + word.slice(1);
21
+ }).join("").replace(/[^a-zA-Z0-9]/g, "");
22
+ }
23
+ /**
24
+ * Converts `text` to camelCase.
25
+ *
26
+ * @example Word boundaries
27
+ * `camelCase('hello-world') // 'helloWorld'`
28
+ *
29
+ * @example With a prefix
30
+ * `camelCase('tag', { prefix: 'create' }) // 'createTag'`
31
+ */
32
+ function camelCase(text, { prefix = "", suffix = "" } = {}) {
33
+ return toCamelOrPascal(`${prefix} ${text} ${suffix}`, false);
34
+ }
35
+ //#endregion
36
+ //#region ../../internals/utils/src/errors.ts
37
+ /**
38
+ * Coerces an unknown thrown value to an `Error` instance.
39
+ * Returns the value as-is when it is already an `Error`; otherwise wraps it with `String(value)`.
40
+ *
41
+ * @example
42
+ * ```ts
43
+ * try { ... } catch(err) {
44
+ * throw new Error('Build failed', { cause: toError(err) })
45
+ * }
46
+ * ```
47
+ */
48
+ function toError(value) {
49
+ return value instanceof Error ? value : new Error(String(value));
50
+ }
51
+ /**
52
+ * Extracts a human-readable message from any thrown value.
53
+ *
54
+ * @example
55
+ * ```ts
56
+ * getErrorMessage(new Error('oops')) // 'oops'
57
+ * getErrorMessage('plain string') // 'plain string'
58
+ * ```
59
+ */
60
+ function getErrorMessage(value) {
61
+ return value instanceof Error ? value.message : String(value);
62
+ }
63
+ //#endregion
64
+ //#region ../../internals/utils/src/runtime.ts
65
+ /**
66
+ * Detects the JavaScript runtime executing the current process and exposes its name and version.
67
+ *
68
+ * Prefer the shared {@link runtime} instance over constructing your own.
69
+ */
70
+ var Runtime = class {
71
+ /**
72
+ * `true` when the current process is running under Bun.
73
+ *
74
+ * Detection keys off the global `Bun` object rather than `process.versions`,
75
+ * because Bun polyfills `process.versions.node` for Node compatibility and would
76
+ * otherwise look like Node.
77
+ *
78
+ * @example
79
+ * ```ts
80
+ * if (runtime.isBun) {
81
+ * await Bun.write(path, data)
82
+ * }
83
+ * ```
84
+ */
85
+ get isBun() {
86
+ return typeof Bun !== "undefined";
87
+ }
88
+ /**
89
+ * `true` when the current process is running under Deno.
90
+ */
91
+ get isDeno() {
92
+ return typeof globalThis.Deno !== "undefined";
93
+ }
94
+ /**
95
+ * `true` when the current process is running under Node.
96
+ *
97
+ * Bun and Deno are excluded first so a polyfilled `process` does not register as Node.
98
+ */
99
+ get isNode() {
100
+ return !this.isBun && !this.isDeno && typeof process !== "undefined" && process.versions?.node != null;
101
+ }
102
+ /**
103
+ * Name of the runtime executing the current process.
104
+ *
105
+ * @example
106
+ * ```ts
107
+ * runtime.name // 'bun' when run with `bun kubb`, 'node' otherwise
108
+ * ```
109
+ */
110
+ get name() {
111
+ if (this.isBun) return "bun";
112
+ if (this.isDeno) return "deno";
113
+ return "node";
114
+ }
115
+ /**
116
+ * Version of the active runtime, or an empty string when it cannot be read.
117
+ *
118
+ * @example
119
+ * ```ts
120
+ * runtime.version // '1.3.11' under Bun, '22.22.2' under Node
121
+ * ```
122
+ */
123
+ get version() {
124
+ if (this.isBun) return process.versions.bun ?? "";
125
+ if (this.isDeno) return globalThis.Deno?.version?.deno ?? "";
126
+ return process.versions?.node ?? "";
127
+ }
128
+ };
129
+ /**
130
+ * Shared {@link Runtime} instance describing the JavaScript runtime executing the current process.
131
+ */
132
+ const runtime = new Runtime();
133
+ //#endregion
134
+ //#region ../../internals/utils/src/fs.ts
135
+ /**
136
+ * Resolves to `true` when the file or directory at `path` exists.
137
+ * Uses `Bun.file().exists()` when running under Bun, `fs.access` otherwise.
138
+ *
139
+ * @example
140
+ * ```ts
141
+ * if (await exists('./kubb.config.ts')) {
142
+ * const content = await read('./kubb.config.ts')
143
+ * }
144
+ * ```
145
+ */
146
+ async function exists(path) {
147
+ if (runtime.isBun) return Bun.file(path).exists();
148
+ return access(path).then(() => true, () => false);
149
+ }
150
+ /**
151
+ * Reads the file at `path` as a UTF-8 string.
152
+ * Uses `Bun.file().text()` when running under Bun, `fs.readFile` otherwise.
153
+ *
154
+ * @example
155
+ * ```ts
156
+ * const source = await read('./src/Pet.ts')
157
+ * ```
158
+ */
159
+ async function read(path) {
160
+ if (runtime.isBun) return Bun.file(path).text();
161
+ return readFile(path, { encoding: "utf8" });
162
+ }
163
+ /**
164
+ * Whether `stored` already holds `source`, comparing on the trimmed text rather than the exact
165
+ * bytes. Surrounding whitespace is what a formatter adds and what editors strip, and neither is a
166
+ * reason to rewrite the file.
167
+ *
168
+ * Both sides are trimmed, so a storage that keeps bytes verbatim settles on the same answer as one
169
+ * that normalizes what it stores. Trimming only `stored` would leave a source with leading
170
+ * whitespace rewritten on every build, since the stored copy keeps the whitespace the comparison
171
+ * has already dropped.
172
+ */
173
+ function matchesStored({ stored, source }) {
174
+ return stored.trim() === source.trim();
175
+ }
176
+ /**
177
+ * Writes `data` to `path`, trimming surrounding whitespace and ending the file with a single newline
178
+ * the way prettier, biome, and oxfmt all do.
179
+ * Skips the write when the trimmed content is empty, or when the file already holds that content.
180
+ * Creates any missing parent directories automatically.
181
+ * When `sanity` is `true`, re-reads the file after writing and throws if the content does not match.
182
+ *
183
+ * @example
184
+ * ```ts
185
+ * await write('./src/Pet.ts', source) // writes and returns the trimmed content plus a newline
186
+ * await write('./src/Pet.ts', source) // null — file unchanged
187
+ * await write('./src/Pet.ts', ' ') // null — empty content skipped
188
+ * ```
189
+ */
190
+ async function write(path, data, options = {}) {
191
+ const trimmed = data.trim();
192
+ if (trimmed === "") return null;
193
+ const content = `${trimmed}\n`;
194
+ const resolved = resolve(path);
195
+ let stored = options.stored;
196
+ if (stored === void 0) {
197
+ if (runtime.isBun) {
198
+ const file = Bun.file(resolved);
199
+ stored = await file.exists() ? await file.text() : null;
200
+ } else try {
201
+ stored = await readFile(resolved, { encoding: "utf-8" });
202
+ } catch {
203
+ stored = null;
204
+ }
205
+ }
206
+ if (matchesStored({
207
+ stored: stored ?? "",
208
+ source: trimmed
209
+ })) return null;
210
+ if (runtime.isBun) {
211
+ await Bun.write(resolved, content);
212
+ return content;
213
+ }
214
+ try {
215
+ await writeFile(resolved, content, { encoding: "utf-8" });
216
+ } catch (error) {
217
+ if (error.code !== "ENOENT") throw error;
218
+ await mkdir(dirname(resolved), { recursive: true });
219
+ await writeFile(resolved, content, { encoding: "utf-8" });
220
+ }
221
+ if (options.sanity) {
222
+ const savedData = await readFile(resolved, { encoding: "utf-8" });
223
+ if (savedData !== content) throw new Error(`Sanity check failed for ${path}\n\nData[${data.length}]:\n${data}\n\nSaved[${savedData.length}]:\n${savedData}\n`);
224
+ return savedData;
225
+ }
226
+ return content;
227
+ }
228
+ /**
229
+ * Recursively removes `path`. Silently succeeds when `path` does not exist.
230
+ *
231
+ * @example
232
+ * ```ts
233
+ * await clean('./dist')
234
+ * ```
235
+ */
236
+ async function clean(path) {
237
+ return rm(path, {
238
+ recursive: true,
239
+ force: true
240
+ });
241
+ }
242
+ /**
243
+ * Converts a filesystem path to use POSIX (`/`) separators.
244
+ *
245
+ * Most of the codebase compares and composes paths as strings (prefix matching, joining for
246
+ * import specifiers, splitting on `/`). On POSIX `path.resolve` already returns `/`-separated
247
+ * paths, but on Windows it returns `\`-separated paths, which breaks every such comparison.
248
+ *
249
+ * Routing every path that crosses a module boundary through `toPosixPath` keeps the rest of the
250
+ * code platform-agnostic. The conversion runs unconditionally so Windows-specific behavior is
251
+ * exercisable from POSIX CI.
252
+ *
253
+ * @example
254
+ * toPosixPath('C:\\repo\\src\\pet.ts') // 'C:/repo/src/pet.ts'
255
+ */
256
+ function toPosixPath(filePath) {
257
+ return filePath.replaceAll("\\", "/");
258
+ }
259
+ /**
260
+ * Resolves to `true` when `path` is `parent` itself or nested inside it. Both sides are resolved
261
+ * to absolute paths first, so relative and `..`-containing inputs compare correctly.
262
+ *
263
+ * Guards a destructive or an out-of-tree operation: before wiping an output directory, check that
264
+ * it does not contain the project root, and before loading a path a caller supplied, check that it
265
+ * did not escape the directory it is allowed to read from.
266
+ *
267
+ * @example
268
+ * isPathInside('./src/gen', '.') // true — nested inside the root
269
+ * isPathInside('.', '.') // true — the same directory counts as inside
270
+ * isPathInside('.', './src/gen') // false — the root is not inside its own output
271
+ * isPathInside('../other', '.') // false — escapes the root
272
+ */
273
+ function isPathInside(path, parent) {
274
+ const resolvedPath = resolve(path);
275
+ const resolvedParent = resolve(parent);
276
+ if (resolvedPath === resolvedParent) return true;
277
+ const rel = relative(resolvedParent, resolvedPath);
278
+ return rel !== "" && !rel.startsWith("..") && !isAbsolute(rel);
279
+ }
280
+ //#endregion
281
+ //#region ../../internals/utils/src/promise.ts
282
+ /**
283
+ * Runs `run` over every item with at most `limit` in flight. Workers share one iterator, so each
284
+ * takes the next item the moment it frees up instead of waiting for a batch to drain.
285
+ *
286
+ * @example
287
+ * ```ts
288
+ * await inParallel({ items: files, limit: 50, run: (file) => storage.writeItem(file.path, file.source) })
289
+ * ```
290
+ */
291
+ async function inParallel({ items, limit, run }) {
292
+ const queue = items.entries();
293
+ const worker = async () => {
294
+ for (const [index, item] of queue) await run(item, index);
295
+ };
296
+ await Promise.all(Array.from({ length: Math.min(limit, items.length) }, () => worker()));
297
+ }
298
+ //#endregion
299
+ //#region ../../internals/utils/src/time.ts
300
+ /**
301
+ * Calculates elapsed time in milliseconds from a high-resolution `process.hrtime` start time.
302
+ * Rounds to 2 decimal places for sub-millisecond precision without noise.
303
+ *
304
+ * @example
305
+ * ```ts
306
+ * const start = process.hrtime()
307
+ * doWork()
308
+ * getElapsedMs(start) // 42.35
309
+ * ```
310
+ */
311
+ function getElapsedMs(hrStart) {
312
+ const [seconds, nanoseconds] = process.hrtime(hrStart);
313
+ const ms = seconds * 1e3 + nanoseconds / 1e6;
314
+ return Math.round(ms * 100) / 100;
315
+ }
316
+ /**
317
+ * Converts a millisecond duration into a human-readable string (`ms`, `s`, or `m s`).
318
+ *
319
+ * @example
320
+ * ```ts
321
+ * formatMs(250) // '250ms'
322
+ * formatMs(1500) // '1.50s'
323
+ * formatMs(90000) // '1m 30.0s'
324
+ * ```
325
+ */
326
+ function formatMs(ms) {
327
+ if (ms >= 6e4) return `${Math.floor(ms / 6e4)}m ${(ms % 6e4 / 1e3).toFixed(1)}s`;
328
+ if (ms >= 1e3) return `${(ms / 1e3).toFixed(2)}s`;
329
+ return `${Math.round(ms)}ms`;
330
+ }
331
+ //#endregion
332
+ //#region package.json
333
+ var version = "5.7.0";
334
+ //#endregion
335
+ //#region src/constants.ts
336
+ /**
337
+ * Stable codes Kubb attaches to a `Diagnostic`. Each maps to a known failure mode
338
+ * and stays stable so it can be referenced in tooling and (later) docs. Reference
339
+ * these instead of inlining the string at a throw site.
340
+ */
341
+ const diagnosticCode = {
342
+ /**
343
+ * Fallback for an unstructured error with no specific code.
344
+ */
345
+ unknown: "KUBB_UNKNOWN",
346
+ /**
347
+ * The file or URL set as `input` could not be read.
348
+ */
349
+ inputNotFound: "KUBB_INPUT_NOT_FOUND",
350
+ /**
351
+ * A URL set as `input` (or referenced by a `$ref`) answered with a 4xx or 5xx status
352
+ * instead of the document.
353
+ */
354
+ inputRequestFailed: "KUBB_INPUT_REQUEST_FAILED",
355
+ /**
356
+ * A URL set as `input` (or referenced by a `$ref`) never answered, so the request failed
357
+ * before a status was returned.
358
+ */
359
+ inputUnreachable: "KUBB_INPUT_UNREACHABLE",
360
+ /**
361
+ * An adapter was configured without an `input`.
362
+ */
363
+ inputRequired: "KUBB_INPUT_REQUIRED",
364
+ /**
365
+ * `input` uses the v4 `{ path }` / `{ data }` wrapper, which v5 reads as a parsed
366
+ * document instead of a pointer to one.
367
+ */
368
+ legacyInput: "KUBB_LEGACY_INPUT",
369
+ /**
370
+ * The parsed `input` carries no `openapi` or `swagger` version, so it is not a
371
+ * document the adapter can read.
372
+ */
373
+ invalidDocument: "KUBB_INVALID_DOCUMENT",
374
+ /** The document fails OpenAPI schema validation. Reported as a warning. */
375
+ invalidSpec: "KUBB_INVALID_SPEC",
376
+ /**
377
+ * A `$ref` (or equivalent reference) could not be resolved in the source document.
378
+ */
379
+ refNotFound: "KUBB_REF_NOT_FOUND",
380
+ /**
381
+ * A server variable value is not allowed by its `enum`.
382
+ */
383
+ invalidServerVariable: "KUBB_INVALID_SERVER_VARIABLE",
384
+ /**
385
+ * A required plugin is missing from the config.
386
+ */
387
+ pluginNotFound: "KUBB_PLUGIN_NOT_FOUND",
388
+ /**
389
+ * The running Kubb or Node.js version is outside a plugin's `meta.compatibility`.
390
+ */
391
+ incompatibleExtension: "KUBB_INCOMPATIBLE_EXTENSION",
392
+ /**
393
+ * A required entry in a plugin's `dependencies` record is missing from the config.
394
+ */
395
+ missingDependency: "KUBB_MISSING_DEPENDENCY",
396
+ /**
397
+ * A dependency's `meta.version` is outside the range a plugin's `dependencies` record declares.
398
+ */
399
+ incompatibleDependency: "KUBB_INCOMPATIBLE_DEPENDENCY",
400
+ /**
401
+ * A plugin threw while generating.
402
+ */
403
+ pluginFailed: "KUBB_PLUGIN_FAILED",
404
+ /**
405
+ * A plugin reported a non-fatal warning through `ctx.warn`.
406
+ */
407
+ pluginWarning: "KUBB_PLUGIN_WARNING",
408
+ /**
409
+ * A plugin reported an informational message through `ctx.info`.
410
+ */
411
+ pluginInfo: "KUBB_PLUGIN_INFO",
412
+ /**
413
+ * A `kubb/kit` composable was called outside a plugin's `setup` and `kubb:plugin:setup`.
414
+ */
415
+ noContext: "KUBB_NO_CONTEXT",
416
+ /**
417
+ * A schema uses a `format` Kubb does not map to a specific type. Reserved for
418
+ * adapters to emit as a `warning`.
419
+ */
420
+ unsupportedFormat: "KUBB_UNSUPPORTED_FORMAT",
421
+ /**
422
+ * A referenced schema or operation is marked `deprecated`. Reserved for adapters
423
+ * to emit as an `info`.
424
+ */
425
+ deprecated: "KUBB_DEPRECATED",
426
+ /**
427
+ * An adapter is required but the config has none. The build cannot read the input
428
+ * without one.
429
+ */
430
+ adapterRequired: "KUBB_ADAPTER_REQUIRED",
431
+ /**
432
+ * A resolved output path escapes the output directory, which can stem from a path
433
+ * traversal in the spec or a misconfigured `group.name`.
434
+ */
435
+ pathTraversal: "KUBB_PATH_TRAVERSAL",
436
+ /**
437
+ * `output.clean` is enabled but `output.path` resolves to the project root or a parent of it,
438
+ * so cleaning would delete kubb.config and every source file.
439
+ */
440
+ cleanRoot: "KUBB_CLEAN_ROOT",
441
+ /**
442
+ * A plugin's options are invalid, for example `output.mode: 'file'` paired with a `group` option.
443
+ */
444
+ invalidPluginOptions: "KUBB_INVALID_PLUGIN_OPTIONS",
445
+ /**
446
+ * A post-generate command (`output.postGenerate`) exited with a failure.
447
+ */
448
+ postGenerateFailed: "KUBB_POST_GENERATE_FAILED",
449
+ /**
450
+ * The formatter pass over the generated files failed.
451
+ */
452
+ formatFailed: "KUBB_FORMAT_FAILED",
453
+ /**
454
+ * The linter pass over the generated files failed.
455
+ */
456
+ lintFailed: "KUBB_LINT_FAILED",
457
+ /**
458
+ * A barrel tries to re-export the same name from more than one module.
459
+ */
460
+ barrelDuplicateExport: "KUBB_BARREL_DUPLICATE_EXPORT",
461
+ /**
462
+ * Not a failure. Carries a plugin's elapsed time, summed into the run total.
463
+ */
464
+ performance: "KUBB_PERFORMANCE",
465
+ /**
466
+ * Not a failure. A newer Kubb version is available on npm.
467
+ */
468
+ updateAvailable: "KUBB_UPDATE_AVAILABLE"
469
+ };
470
+ //#endregion
471
+ //#region src/Diagnostics.ts
472
+ /**
473
+ * Docs major version, derived from the package version so the link tracks the published major.
474
+ */
475
+ const docsMajor = version.split(".")[0] ?? "5";
476
+ /**
477
+ * Builds a type guard that narrows a {@link Diagnostic} to the variant for `kind`. A diagnostic
478
+ * with no `kind` is treated as a `problem`.
479
+ */
480
+ function isKind(kind) {
481
+ return (diagnostic) => (diagnostic.kind ?? "problem") === kind;
482
+ }
483
+ /**
484
+ * Returns `true` when the diagnostic is a build {@link ProblemDiagnostic}.
485
+ *
486
+ * @example
487
+ * ```ts
488
+ * if (isProblem(diagnostic)) {
489
+ * console.log(diagnostic.location)
490
+ * }
491
+ * ```
492
+ */
493
+ const isProblem = isKind("problem");
494
+ /**
495
+ * Returns `true` when the diagnostic is a per-plugin {@link PerformanceDiagnostic}.
496
+ *
497
+ * @example
498
+ * ```ts
499
+ * const timings = diagnostics.filter(isPerformance)
500
+ * ```
501
+ */
502
+ const isPerformance = isKind("performance");
503
+ /**
504
+ * Returns `true` when the diagnostic is a version-update {@link UpdateDiagnostic}.
505
+ *
506
+ * @example
507
+ * ```ts
508
+ * if (isUpdate(diagnostic)) {
509
+ * console.log(diagnostic.latestVersion)
510
+ * }
511
+ * ```
512
+ */
513
+ const isUpdate = isKind("update");
514
+ /**
515
+ * Accent color per severity. The color tints the `[CODE]` tag (red error, yellow warning,
516
+ * blue info).
517
+ */
518
+ const severityStyle = {
519
+ error: "red",
520
+ warning: "yellow",
521
+ info: "blue"
522
+ };
523
+ const countKey = {
524
+ error: "errors",
525
+ warning: "warnings",
526
+ info: "infos"
527
+ };
528
+ /**
529
+ * Explanation for every {@link diagnosticCode}. Use {@link Diagnostics.explain} to look one up
530
+ * and `Diagnostics.docsUrl` for the matching kubb.dev page.
531
+ */
532
+ const diagnosticCatalog = {
533
+ [diagnosticCode.unknown]: {
534
+ title: "Unknown error",
535
+ cause: "An error was thrown without a stable Kubb code, so it is reported as-is.",
536
+ fix: "Read the underlying message and stack. If it comes from a plugin or adapter, check its configuration; otherwise report it as a possible Kubb bug."
537
+ },
538
+ [diagnosticCode.inputNotFound]: {
539
+ title: "Input not found",
540
+ cause: "The file set as `input` (or passed as `kubb generate PATH`) could not be read. A URL reports `KUBB_INPUT_REQUEST_FAILED` or `KUBB_INPUT_UNREACHABLE` instead.",
541
+ fix: "Check that the path exists and is readable, then set it as `input` or pass it on the CLI."
542
+ },
543
+ [diagnosticCode.inputRequestFailed]: {
544
+ title: "Input request failed",
545
+ cause: "A URL set as `input` (or reached through a `$ref`) answered with a 4xx or 5xx status instead of the document.",
546
+ fix: "Open the URL to see what the server returns. A 401 or 403 needs credentials Kubb does not send, so download the document and point `input` at the local file. A 404 means the path is wrong, and a 5xx means the server itself failed."
547
+ },
548
+ [diagnosticCode.inputUnreachable]: {
549
+ title: "Input unreachable",
550
+ cause: "A URL set as `input` (or reached through a `$ref`) never answered, so the request failed before a status came back. A refused connection, an unknown host, an expired certificate, and a timeout all land here.",
551
+ fix: "Check that the host is running and reachable from this machine. For a local server, start it and confirm the port matches the one in `input`."
552
+ },
553
+ [diagnosticCode.inputRequired]: {
554
+ title: "Input required",
555
+ cause: "An adapter is configured but no `input` was provided.",
556
+ fix: "Set `input` to a file path, a URL, an inline spec (JSON/YAML string), or a parsed object in your Kubb config."
557
+ },
558
+ [diagnosticCode.legacyInput]: {
559
+ title: "Legacy input shape",
560
+ cause: "`input` is a `{ path }` or `{ data }` wrapper, which v4 used to point at a document and v5 reads as the document itself.",
561
+ fix: "Unwrap it: `input: { path: \"./petStore.yaml\" }` becomes `input: \"./petStore.yaml\"`, and `input: { data: spec }` becomes `input: spec`."
562
+ },
563
+ [diagnosticCode.invalidDocument]: {
564
+ title: "Invalid document",
565
+ cause: "The parsed `input` has no `openapi` or `swagger` version field, so it is not an OpenAPI or Swagger document.",
566
+ fix: "Point `input` at a document that declares `openapi` or `swagger`, and check that a passed object is the spec itself rather than a wrapper around it."
567
+ },
568
+ [diagnosticCode.invalidSpec]: {
569
+ title: "Invalid spec",
570
+ cause: "The document does not pass OpenAPI schema validation. Kubb still generates from it, but the output can be incomplete or wrong.",
571
+ fix: "Fix the reported problem in the spec. Run `kubb validate` to list every error, or set `validate: false` on the adapter to skip the check."
572
+ },
573
+ [diagnosticCode.refNotFound]: {
574
+ title: "Reference not found",
575
+ cause: "A `$ref` could not be resolved in the source document.",
576
+ fix: "Add the missing definition (for example under `components.schemas`) or fix the `$ref`. Run `kubb validate` to check the spec."
577
+ },
578
+ [diagnosticCode.invalidServerVariable]: {
579
+ title: "Invalid server variable",
580
+ cause: "A server variable value is not allowed by its `enum`.",
581
+ fix: "Use one of the values listed in the server variable `enum`, or update the spec."
582
+ },
583
+ [diagnosticCode.pluginNotFound]: {
584
+ title: "Plugin not found",
585
+ cause: "A plugin that another plugin depends on is missing from the config.",
586
+ fix: "Add the required plugin to the `plugins` array in kubb.config.ts, or remove the dependency on it."
587
+ },
588
+ [diagnosticCode.incompatibleExtension]: {
589
+ title: "Incompatible extension",
590
+ cause: "A plugin sets `meta.compatibility.kubb` or `meta.compatibility.node` to a range the running Kubb or Node.js version does not satisfy.",
591
+ fix: "Upgrade Kubb or Node.js to a version in the range, or install a version of the plugin that supports your current Kubb and Node.js."
592
+ },
593
+ [diagnosticCode.missingDependency]: {
594
+ title: "Missing dependency",
595
+ cause: "A plugin lists another plugin in its `dependencies` record without `optional: true`, and the config does not include it.",
596
+ fix: "Add the missing plugin to the `plugins` array in kubb.config.ts."
597
+ },
598
+ [diagnosticCode.incompatibleDependency]: {
599
+ title: "Incompatible dependency",
600
+ cause: "A plugin's `dependencies` record sets a `version` range, and the configured plugin's `meta.version` falls outside it.",
601
+ fix: "Install a version of the dependency inside the range, or a version of the dependent plugin that supports the installed dependency."
602
+ },
603
+ [diagnosticCode.pluginFailed]: {
604
+ title: "Plugin failed",
605
+ cause: "A plugin threw while generating, or reported an error through `ctx.error`.",
606
+ fix: "Read the underlying error and check the plugin options and the schema or operation it failed on."
607
+ },
608
+ [diagnosticCode.pluginWarning]: {
609
+ title: "Plugin warning",
610
+ cause: "A plugin reported a non-fatal warning through `ctx.warn`.",
611
+ fix: "Review the message. It does not fail the build; adjust the plugin options or input if the warning is unwanted."
612
+ },
613
+ [diagnosticCode.pluginInfo]: {
614
+ title: "Plugin info",
615
+ cause: "A plugin reported an informational message through `ctx.info`.",
616
+ fix: "Informational only. No action is required."
617
+ },
618
+ [diagnosticCode.noContext]: {
619
+ title: "No plugin context",
620
+ cause: "A `kubb/kit` composable such as `useKubb()` or `addGenerator()` ran outside the `setup` and `kubb:plugin:setup` of a plugin, so there is no plugin to apply it to.",
621
+ fix: "Call the composable inside `setup` or `kubb:plugin:setup`, including in code that setup awaits."
622
+ },
623
+ [diagnosticCode.unsupportedFormat]: {
624
+ title: "Unsupported format",
625
+ cause: "A schema uses a `format` Kubb does not map to a specific type, so it falls back to the base type.",
626
+ fix: "Use a format Kubb supports, or handle the custom format with a parser or plugin."
627
+ },
628
+ [diagnosticCode.deprecated]: {
629
+ title: "Deprecated",
630
+ cause: "A referenced schema or operation is marked `deprecated`.",
631
+ fix: "Migrate off the deprecated definition if the warning is unwanted."
632
+ },
633
+ [diagnosticCode.adapterRequired]: {
634
+ title: "Adapter required",
635
+ cause: "An action needs an adapter but none is configured.",
636
+ fix: "Set `adapter` in kubb.config.ts, for example `adapterOas()`."
637
+ },
638
+ [diagnosticCode.pathTraversal]: {
639
+ title: "Path traversal",
640
+ cause: "A resolved output path escaped the output directory, which can stem from a path traversal in the spec or a misconfigured `group.name`.",
641
+ fix: "Keep generated paths within the output directory. Review the `group.name` function and the names coming from the spec."
642
+ },
643
+ [diagnosticCode.cleanRoot]: {
644
+ title: "Clean targets the project root",
645
+ cause: "`output.clean` is enabled and `output.path` resolves to the project root or a parent of it, so cleaning would delete `kubb.config` and every source file.",
646
+ fix: "Point `output.path` at a subdirectory such as `./src/gen` so clean only removes generated code, or disable `output.clean`."
647
+ },
648
+ [diagnosticCode.invalidPluginOptions]: {
649
+ title: "Invalid plugin options",
650
+ cause: "A plugin was configured with options that cannot be honored, for example `output.mode: 'file'` paired with a `group` option.",
651
+ fix: "Fix the plugin options. A single-file output has nothing to group, so remove the `group` option or use `output.mode: 'directory'`."
652
+ },
653
+ [diagnosticCode.postGenerateFailed]: {
654
+ title: "Post-generate command failed",
655
+ cause: "A post-generate command (`output.postGenerate`) exited with a non-zero status.",
656
+ fix: "Check the command is installed and correct, and run it manually to see the error."
657
+ },
658
+ [diagnosticCode.formatFailed]: {
659
+ title: "Format failed",
660
+ cause: "The formatter pass over the generated files failed.",
661
+ fix: "Check the formatter (oxfmt, biome, or prettier) is installed and its config is valid, then run it manually on the output."
662
+ },
663
+ [diagnosticCode.lintFailed]: {
664
+ title: "Lint failed",
665
+ cause: "The linter pass over the generated files failed.",
666
+ fix: "Check the linter (oxlint, biome, or eslint) is installed and its config is valid, then run it manually on the output."
667
+ },
668
+ [diagnosticCode.barrelDuplicateExport]: {
669
+ title: "Duplicate barrel export",
670
+ cause: "Two generated modules export the same name, so the barrel cannot re-export both.",
671
+ fix: "Rename one of the colliding declarations, or configure the plugin resolver to produce distinct names."
672
+ },
673
+ [diagnosticCode.performance]: {
674
+ title: "Performance",
675
+ cause: "Not a failure. Records a plugin’s elapsed time, summed into the run total.",
676
+ fix: "No action. This is an informational metric."
677
+ },
678
+ [diagnosticCode.updateAvailable]: {
679
+ title: "Update available",
680
+ cause: "A newer Kubb version is published on npm than the one running.",
681
+ fix: "Update the `@kubb/*` packages, for example `npm install -g @kubb/cli`, to get the latest fixes."
682
+ }
683
+ };
684
+ /**
685
+ * Static helpers for working with {@link Diagnostic}s, plus the run-scoped sink
686
+ * that lets deep code report a diagnostic without threading a callback.
687
+ *
688
+ * The sink lives in a single `AsyncLocalStorage` in the `@kubb/core` bundle.
689
+ * `Diagnostics.scope` activates it for a run, so anything inside that run (the
690
+ * adapter parse, a generator) reports through `Diagnostics.report` and lands
691
+ * in the same run.
692
+ */
693
+ var Diagnostics = class Diagnostics {
694
+ static #reporterStorage = new AsyncLocalStorage();
695
+ /**
696
+ * The diagnostic code catalog, exposed as `Diagnostics.code` (e.g. `Diagnostics.code.refNotFound`).
697
+ */
698
+ static code = diagnosticCode;
699
+ /**
700
+ * Type guard for a build {@link ProblemDiagnostic}.
701
+ */
702
+ static isProblem = isProblem;
703
+ /**
704
+ * Type guard for a version-update {@link UpdateDiagnostic}.
705
+ */
706
+ static isUpdate = isUpdate;
707
+ /**
708
+ * Type guard for a per-plugin {@link PerformanceDiagnostic}.
709
+ */
710
+ static isPerformance = isPerformance;
711
+ /**
712
+ * An `Error` that carries a {@link Diagnostic}, so structured problems can flow
713
+ * through the existing throw/catch paths while keeping their code and location.
714
+ *
715
+ * @example
716
+ * ```ts
717
+ * throw new Diagnostics.Error({ code: diagnosticCode.refNotFound, severity: 'error', message: `Could not find ${ref}`, location: { kind: 'schema', pointer: ref, ref } })
718
+ * ```
719
+ */
720
+ static Error = class DiagnosticError extends Error {
721
+ diagnostic;
722
+ constructor(diagnostic) {
723
+ super(diagnostic.message, { cause: diagnostic.cause });
724
+ this.name = "DiagnosticError";
725
+ this.diagnostic = diagnostic;
726
+ }
727
+ };
728
+ /**
729
+ * Structural check for a {@link Diagnostics.Error}, including one thrown from a duplicated
730
+ * `@kubb/core` copy where `instanceof` fails. Matches on the `name` and a `diagnostic`
731
+ * that carries a `code`.
732
+ */
733
+ static isError(error) {
734
+ if (error instanceof Diagnostics.Error) return true;
735
+ if (!(error instanceof Error) || error.name !== "DiagnosticError") return false;
736
+ const { diagnostic } = error;
737
+ return typeof diagnostic === "object" && diagnostic !== null && typeof diagnostic.code === "string";
738
+ }
739
+ /**
740
+ * Runs `fn` with `sink` as the active diagnostic sink for the whole async
741
+ * subtree, so {@link Diagnostics.report} reaches it from anywhere inside.
742
+ */
743
+ static scope(sink, fn) {
744
+ return Diagnostics.#reporterStorage.run(sink, fn);
745
+ }
746
+ /**
747
+ * Collects a diagnostic into the active build via the run-scoped sink, without throwing.
748
+ * Returns `true` when a run consumed it, `false` when called outside a {@link Diagnostics.scope}
749
+ * (so callers can fall back to throwing). Use a `warning`/`info` severity for non-fatal issues.
750
+ * For rendering a diagnostic live on the hook bus, use {@link Diagnostics.emit} instead.
751
+ */
752
+ static report(diagnostic) {
753
+ const sink = Diagnostics.#reporterStorage.getStore();
754
+ if (!sink) return false;
755
+ sink(diagnostic);
756
+ return true;
757
+ }
758
+ /**
759
+ * Emits a diagnostic on the run's `kubb:diagnostic` hook so the loggers render it live.
760
+ * Use it instead of calling `hooks.callHook('kubb:diagnostic', ...)` directly. To collect a
761
+ * diagnostic into the build result from deep in a run, use {@link Diagnostics.report} instead.
762
+ */
763
+ static async emit(hooks, diagnostic) {
764
+ await hooks.callHook("kubb:diagnostic", { diagnostic });
765
+ }
766
+ /**
767
+ * Coerces any thrown value into a {@link ProblemDiagnostic}. A {@link Diagnostics.Error}
768
+ * keeps its structured data, and anything else becomes a `KUBB_UNKNOWN` error.
769
+ */
770
+ static from(error) {
771
+ const seen = /* @__PURE__ */ new Set();
772
+ let current = error;
773
+ let root;
774
+ while (current instanceof Error && !seen.has(current)) {
775
+ if (Diagnostics.isError(current)) return current.diagnostic;
776
+ seen.add(current);
777
+ root = current;
778
+ current = current.cause;
779
+ }
780
+ return {
781
+ code: diagnosticCode.unknown,
782
+ severity: "error",
783
+ message: root ? root.message : getErrorMessage(error),
784
+ cause: root
785
+ };
786
+ }
787
+ /**
788
+ * Builds a per-plugin performance record. Reporters sum these into the run total.
789
+ */
790
+ static performance({ plugin, duration }) {
791
+ return {
792
+ kind: "performance",
793
+ code: diagnosticCode.performance,
794
+ severity: "info",
795
+ message: `${plugin} generated in ${Math.round(duration)}ms`,
796
+ plugin,
797
+ duration
798
+ };
799
+ }
800
+ /**
801
+ * Builds the version-update notice shown when a newer Kubb is published on npm.
802
+ */
803
+ static update({ currentVersion, latestVersion }) {
804
+ return {
805
+ kind: "update",
806
+ code: diagnosticCode.updateAvailable,
807
+ severity: "info",
808
+ message: `Update available: v${currentVersion} → v${latestVersion}. Run \`npm install -g @kubb/cli\` to update.`,
809
+ currentVersion,
810
+ latestVersion
811
+ };
812
+ }
813
+ /**
814
+ * True when any diagnostic is an error, the severity that fails a build. Non-error
815
+ * diagnostics are ignored.
816
+ */
817
+ static hasError(diagnostics) {
818
+ return diagnostics.some((diagnostic) => diagnostic.severity === "error");
819
+ }
820
+ /**
821
+ * Names of the plugins that failed, deduped, derived from the error diagnostics
822
+ * that carry a `plugin`.
823
+ */
824
+ static failedPlugins(diagnostics) {
825
+ return [...new Set(diagnostics.flatMap((diagnostic) => diagnostic.severity === "error" && diagnostic.plugin ? [diagnostic.plugin] : []))];
826
+ }
827
+ /**
828
+ * Counts `problem` diagnostics by severity for the run summary. `performance` and
829
+ * `update` diagnostics are ignored.
830
+ */
831
+ static count(diagnostics) {
832
+ const counts = {
833
+ errors: 0,
834
+ warnings: 0,
835
+ infos: 0
836
+ };
837
+ for (const diagnostic of diagnostics.filter(isProblem)) counts[countKey[diagnostic.severity]] += 1;
838
+ return counts;
839
+ }
840
+ /**
841
+ * Drops duplicate `problem` diagnostics that share a code, location pointer, and
842
+ * plugin, so the same issue reported across several passes is shown once. Non-problem
843
+ * diagnostics are always kept.
844
+ */
845
+ static dedupe(diagnostics) {
846
+ const seen = /* @__PURE__ */ new Set();
847
+ const result = [];
848
+ for (const diagnostic of diagnostics) {
849
+ if (!isProblem(diagnostic)) {
850
+ result.push(diagnostic);
851
+ continue;
852
+ }
853
+ const pointer = diagnostic.location && "pointer" in diagnostic.location ? diagnostic.location.pointer : "";
854
+ const key = `${diagnostic.code} ${pointer} ${diagnostic.plugin ?? ""}`;
855
+ if (seen.has(key)) continue;
856
+ seen.add(key);
857
+ result.push(diagnostic);
858
+ }
859
+ return result;
860
+ }
861
+ /**
862
+ * Builds the kubb.dev docs URL for a diagnostic code, e.g.
863
+ * `KUBB_REF_NOT_FOUND` → `https://kubb.dev/docs/5.x/reference/diagnostics#kubb-ref-not-found`.
864
+ */
865
+ static docsUrl(code) {
866
+ const slug = code.toLowerCase().replaceAll("_", "-");
867
+ return `https://kubb.dev/docs/${docsMajor}.x/reference/diagnostics#${slug}`;
868
+ }
869
+ /**
870
+ * The catalog entry for a code: its title, cause, and fix. Mirrors the kubb.dev
871
+ * `/reference/diagnostics#<slug>` section.
872
+ */
873
+ static explain(code) {
874
+ return diagnosticCatalog[code];
875
+ }
876
+ /**
877
+ * Reduces a diagnostic to its JSON-safe fields plus a `docsUrl`, for machine-readable
878
+ * consumers. The `cause`, `kind`, and `duration` are dropped, and absent optional
879
+ * fields are omitted rather than set to `undefined`.
880
+ */
881
+ static serialize(diagnostic) {
882
+ const problem = isProblem(diagnostic) ? diagnostic : void 0;
883
+ return {
884
+ code: diagnostic.code,
885
+ severity: diagnostic.severity,
886
+ message: diagnostic.message,
887
+ ...problem?.location ? { location: problem.location } : {},
888
+ ...problem?.help ? { help: problem.help } : {},
889
+ ...problem?.plugin ? { plugin: problem.plugin } : {},
890
+ ...diagnostic.code === diagnosticCode.unknown ? {} : { docsUrl: Diagnostics.docsUrl(diagnostic.code) }
891
+ };
892
+ }
893
+ /**
894
+ * Renders a {@link Diagnostic} for terminal output as its parts: the `headline`
895
+ * (`[CODE] plugin: message`, with the code in the severity color) and the indented `details`
896
+ * rows (`at:` pointer, `fix:` help, `see:` docs link).
897
+ *
898
+ * Hosts compose these to fit their gutter: a clack logger passes `[headline, ...details]` as the
899
+ * message with no gutter symbol, while plain text outputs use {@link Diagnostics.formatLines}.
900
+ */
901
+ static format(diagnostic) {
902
+ const { code, severity, message } = diagnostic;
903
+ const color = severityStyle[severity];
904
+ const problem = isProblem(diagnostic) ? diagnostic : void 0;
905
+ const tag = styleText(color, styleText("bold", `[${code}]`));
906
+ const headline = problem?.plugin ? `${tag} ${problem.plugin}: ${message}` : `${tag}: ${message}`;
907
+ const details = [];
908
+ if (problem?.location && "pointer" in problem.location) details.push(` ${styleText("dim", "at:")} ${styleText("cyan", problem.location.pointer)}`);
909
+ if (problem?.help) details.push(` ${styleText("cyan", "fix:")} ${problem.help}`);
910
+ if (code !== diagnosticCode.unknown) details.push(` ${styleText("dim", "see:")} ${styleText("cyan", Diagnostics.docsUrl(code))}`);
911
+ return {
912
+ headline,
913
+ details
914
+ };
915
+ }
916
+ /**
917
+ * The self-contained block form of {@link Diagnostics.format}: the `headline` followed by the
918
+ * indented detail rows. Used where there is no gutter (plain and file output).
919
+ */
920
+ static formatLines(diagnostic) {
921
+ const { headline, details } = Diagnostics.format(diagnostic);
922
+ return [headline, ...details];
923
+ }
924
+ };
925
+ //#endregion
926
+ //#region src/composables.ts
927
+ /**
928
+ * Holds the setup context of the plugin whose `setup` or `kubb:plugin:setup` is running. `KubbDriver` sets it for each plugin.
929
+ */
930
+ const kubbContext = new AsyncLocalStorage();
931
+ function requireContext(caller) {
932
+ const ctx = kubbContext.getStore();
933
+ if (ctx) return ctx;
934
+ throw new Diagnostics.Error({
935
+ code: Diagnostics.code.noContext,
936
+ severity: "error",
937
+ message: `\`${caller}()\` was called outside a plugin setup.`,
938
+ help: `Call \`${caller}()\` inside \`setup\` or \`kubb:plugin:setup\`, including in code that setup awaits.`
939
+ });
940
+ }
941
+ /**
942
+ * Returns the context of the plugin whose `kubb:plugin:setup` is running. It stays available after an `await`.
943
+ * Throws `KUBB_NO_CONTEXT` outside setup.
944
+ */
945
+ function useKubb() {
946
+ return requireContext("useKubb");
947
+ }
948
+ /**
949
+ * Returns the same context as {@link useKubb}, or `undefined` outside `setup` and `kubb:plugin:setup`.
950
+ */
951
+ function tryUseKubb() {
952
+ return kubbContext.getStore();
953
+ }
954
+ /**
955
+ * Registers generators on the plugin being set up, like `ctx.addGenerator`.
956
+ *
957
+ * @example
958
+ * `addGenerator(typeGenerator, enumGenerator)`
959
+ */
960
+ function addGenerator(...generators) {
961
+ requireContext("addGenerator").addGenerator(...generators);
962
+ }
963
+ /**
964
+ * Sets the resolver of the plugin being set up, like `ctx.setResolver`.
965
+ */
966
+ function setResolver(resolver) {
967
+ requireContext("setResolver").setResolver(resolver);
968
+ }
969
+ /**
970
+ * Adds a macro to the plugin being set up, like `ctx.addMacro`.
971
+ */
972
+ function addMacro(macro) {
973
+ requireContext("addMacro").addMacro(macro);
974
+ }
975
+ /**
976
+ * Replaces the macros of the plugin being set up, like `ctx.setMacros`.
977
+ */
978
+ function setMacros(macros) {
979
+ requireContext("setMacros").setMacros(macros);
980
+ }
981
+ /**
982
+ * Adds a raw file to the build output, like `ctx.injectFile`.
983
+ */
984
+ function injectFile(file) {
985
+ requireContext("injectFile").injectFile(file);
986
+ }
987
+ /**
988
+ * Returns the options the user passed to the plugin being set up, like `ctx.options`.
989
+ */
990
+ function useOptions() {
991
+ return requireContext("useOptions").options;
992
+ }
993
+ /**
994
+ * Sets the resolved options of the plugin being set up, like `ctx.setOptions`.
995
+ */
996
+ function setOptions(options) {
997
+ requireContext("setOptions").setOptions(options);
998
+ }
999
+ /**
1000
+ * Returns the resolved build configuration, like `ctx.config`.
1001
+ */
1002
+ function useConfig() {
1003
+ return requireContext("useConfig").config;
1004
+ }
1005
+ /**
1006
+ * Returns another plugin from the config, typed through `Kubb.PluginRegistry`, like `ctx.requirePlugin`.
1007
+ */
1008
+ function requirePlugin(name) {
1009
+ return requireContext("requirePlugin").requirePlugin(name);
1010
+ }
1011
+ //#endregion
1012
+ //#region src/defineExtension.ts
1013
+ /**
1014
+ * Returns `meta`, or `{ name }` for an extension that only sets the deprecated `name`. Throws `KUBB_INVALID_PLUGIN_OPTIONS` when it has neither.
1015
+ */
1016
+ function resolveMeta({ name, meta }) {
1017
+ if (meta) return meta;
1018
+ if (name) return { name };
1019
+ throw new Diagnostics.Error({
1020
+ code: Diagnostics.code.invalidPluginOptions,
1021
+ severity: "error",
1022
+ message: "An extension has neither `meta.name` nor `name`.",
1023
+ help: "Set `meta: { name }` on the plugin or parser.",
1024
+ location: { kind: "config" }
1025
+ });
1026
+ }
1027
+ /**
1028
+ * Throws `KUBB_INCOMPATIBLE_EXTENSION` when the running Kubb or Node.js version is outside `meta.compatibility`.
1029
+ */
1030
+ function checkCompatibility(meta) {
1031
+ const checks = [{
1032
+ target: "Kubb",
1033
+ range: meta.compatibility?.kubb,
1034
+ version
1035
+ }, {
1036
+ target: "Node.js",
1037
+ range: meta.compatibility?.node,
1038
+ version: process.versions.node
1039
+ }];
1040
+ for (const { target, range, version } of checks) {
1041
+ if (!range || satisfies(version, range, { includePrerelease: true })) continue;
1042
+ throw new Diagnostics.Error({
1043
+ code: Diagnostics.code.incompatibleExtension,
1044
+ severity: "error",
1045
+ message: `"${meta.name}" requires ${target} ${range}, but ${version} is running.`,
1046
+ help: `Use a ${target} version that satisfies ${range}, or a version of "${meta.name}" that supports ${target} ${version}.`,
1047
+ location: { kind: "config" },
1048
+ plugin: meta.name
1049
+ });
1050
+ }
1051
+ }
1052
+ /**
1053
+ * Throws `KUBB_MISSING_DEPENDENCY` for a missing required entry in a `dependencies` record, and
1054
+ * `KUBB_INCOMPATIBLE_DEPENDENCY` when an entry's `meta.version` is out of range. Arrays are not checked.
1055
+ */
1056
+ function checkDependencies({ name, dependencies, plugins }) {
1057
+ if (!dependencies || Array.isArray(dependencies)) return;
1058
+ for (const [dependencyName, dependency] of Object.entries(dependencies)) {
1059
+ const target = plugins.get(dependencyName);
1060
+ if (!target) {
1061
+ if (dependency?.optional) continue;
1062
+ throw new Diagnostics.Error({
1063
+ code: Diagnostics.code.missingDependency,
1064
+ severity: "error",
1065
+ message: `Plugin "${dependencyName}" is required by "${name}" but not found.`,
1066
+ help: `Add "${dependencyName}" to the \`plugins\` array in kubb.config.ts.`,
1067
+ location: { kind: "config" },
1068
+ plugin: name
1069
+ });
1070
+ }
1071
+ const range = dependency?.version;
1072
+ const version = target.meta?.version;
1073
+ if (!range || !version || satisfies(version, range, { includePrerelease: true })) continue;
1074
+ throw new Diagnostics.Error({
1075
+ code: Diagnostics.code.incompatibleDependency,
1076
+ severity: "error",
1077
+ message: `"${name}" requires "${dependencyName}" ${range}, but ${version} is configured.`,
1078
+ help: `Install a version of "${dependencyName}" that satisfies ${range}.`,
1079
+ location: { kind: "config" },
1080
+ plugin: name
1081
+ });
1082
+ }
1083
+ }
1084
+ function defineExtension({ kind, meta, build }) {
1085
+ const factory = (options) => build(options ?? {});
1086
+ return Object.assign(factory, meta ? {
1087
+ kind,
1088
+ meta
1089
+ } : { kind });
1090
+ }
1091
+ //#endregion
1092
+ //#region src/definePlugin.ts
1093
+ /**
1094
+ * Merges the `output.mode` default into the output config and validates the combination.
1095
+ * Throws `KUBB_INVALID_PLUGIN_OPTIONS` when `mode: 'file'` is paired with a `group` option,
1096
+ * since a single-file output has nothing to group.
1097
+ *
1098
+ * An omitted `mode` follows the shape of `path`: an extension means a single file, anything
1099
+ * else is a directory. Plugin defaults such as `path: 'types'` name a directory, so they
1100
+ * generate without the caller spelling out `mode`.
1101
+ */
1102
+ function normalizeOutput({ output, group, pluginName }) {
1103
+ const mode = output.mode ?? (path.extname(output.path) ? "file" : "directory");
1104
+ if (mode === "file" && group) throw new Diagnostics.Error({
1105
+ code: Diagnostics.code.invalidPluginOptions,
1106
+ severity: "error",
1107
+ message: `Plugin "${pluginName}" resolves \`output.mode\` to 'file' but also configures a \`group\` option.`,
1108
+ help: "A single-file output has nothing to group. Remove the `group` option, give `output.path` an extensionless directory name, or set `output.mode: 'directory'` explicitly.",
1109
+ location: { kind: "config" },
1110
+ plugin: pluginName
1111
+ });
1112
+ return {
1113
+ ...output,
1114
+ mode
1115
+ };
1116
+ }
1117
+ /** Throws `KUBB_INVALID_PLUGIN_OPTIONS`, listing the allowed values, when `value` is not one of `allowed`. */
1118
+ function assertPluginOption({ plugin, option, value, allowed }) {
1119
+ if (allowed.includes(value)) return;
1120
+ const format = (item) => typeof item === "string" ? JSON.stringify(item) : String(item);
1121
+ const expected = allowed.map(format).join(", ");
1122
+ throw new Diagnostics.Error({
1123
+ code: Diagnostics.code.invalidPluginOptions,
1124
+ severity: "error",
1125
+ message: `Plugin "${plugin}" option \`${option}\` is ${format(value)}, but it must be one of ${expected}.`,
1126
+ help: `Set \`${option}\` to one of ${expected}.`,
1127
+ location: { kind: "config" },
1128
+ plugin
1129
+ });
1130
+ }
1131
+ function definePlugin(input) {
1132
+ if (typeof input === "function") return defineExtension({
1133
+ kind: "plugin",
1134
+ build: (options) => {
1135
+ const plugin = input(options);
1136
+ return {
1137
+ ...plugin,
1138
+ meta: resolveMeta(plugin)
1139
+ };
1140
+ }
1141
+ });
1142
+ const { meta, dependencies, enforce, hooks = {}, setup } = input;
1143
+ return defineExtension({
1144
+ kind: "plugin",
1145
+ meta,
1146
+ build: (options) => ({
1147
+ name: meta.name,
1148
+ meta,
1149
+ options,
1150
+ dependencies,
1151
+ enforce,
1152
+ hooks,
1153
+ setup
1154
+ })
1155
+ });
1156
+ }
1157
+ //#endregion
1158
+ //#region src/input.ts
1159
+ /**
1160
+ * Classifies an `input` value so callers branch on it once instead of repeating the checks.
1161
+ *
1162
+ * A non-string is a parsed spec (`object`). A string is `inline` when it holds OpenAPI content,
1163
+ * meaning it starts with `{` or `[`, spans multiple lines, or opens with a YAML `openapi:` or
1164
+ * `swagger:` key. Otherwise a string is a `url` when it parses as one, or a `file` path.
1165
+ */
1166
+ function getInputKind(input) {
1167
+ if (typeof input !== "string") return "object";
1168
+ const trimmed = input.trimStart();
1169
+ if (trimmed.startsWith("{") || trimmed.startsWith("[") || input.includes("\n") || /^(openapi|swagger)\s*:/i.test(trimmed)) return "inline";
1170
+ if (URL.canParse(input)) return "url";
1171
+ return "file";
1172
+ }
1173
+ /**
1174
+ * The v4 `input` wrapper keys. v4 typed `input` as `{ path }` or `{ data }`; v5 takes the value
1175
+ * directly, so the wrapper now matches the "already-parsed document" branch and silently yields
1176
+ * an empty build.
1177
+ */
1178
+ const legacyInputKeys = ["path", "data"];
1179
+ /**
1180
+ * Detects the v4 `{ path }` / `{ data }` wrapper so it fails loudly instead of being read as a
1181
+ * document. A real spec always carries more than these keys, so an object whose keys are drawn
1182
+ * only from them is the old shape rather than a document that happens to have a `path` property.
1183
+ */
1184
+ function isLegacyInput(input) {
1185
+ if (Array.isArray(input)) return input.some(isLegacyInput);
1186
+ if (typeof input !== "object" || input === null) return false;
1187
+ const keys = Object.keys(input);
1188
+ return keys.length > 0 && keys.every((key) => legacyInputKeys.includes(key));
1189
+ }
1190
+ /**
1191
+ * Normalizes `config.input` into an `AdapterSource` the adapter can parse.
1192
+ *
1193
+ * A parsed object and inline content become `{ type: 'data' }`; a URL is kept verbatim and a
1194
+ * local path is resolved against `config.root`, both as `{ type: 'path' }`.
1195
+ */
1196
+ function inputToAdapterSource(config) {
1197
+ const input = config.input;
1198
+ if (input && isLegacyInput(input)) throw new Diagnostics.Error({
1199
+ code: Diagnostics.code.legacyInput,
1200
+ severity: "error",
1201
+ message: "The `input` option uses the v4 `{ path }` / `{ data }` wrapper.",
1202
+ help: "Unwrap it: `input: { path: \"./petStore.yaml\" }` becomes `input: \"./petStore.yaml\"`, and `input: { data: spec }` becomes `input: spec`.",
1203
+ location: { kind: "config" }
1204
+ });
1205
+ if (!input) throw new Diagnostics.Error({
1206
+ code: Diagnostics.code.inputRequired,
1207
+ severity: "error",
1208
+ message: "An adapter is configured without an input.",
1209
+ help: "Set `input` to a file path, a URL, an inline spec (JSON/YAML string), or a parsed object in your Kubb config.",
1210
+ location: { kind: "config" }
1211
+ });
1212
+ if (typeof input !== "string") return {
1213
+ type: "data",
1214
+ data: input
1215
+ };
1216
+ const kind = getInputKind(input);
1217
+ if (kind === "inline") return {
1218
+ type: "data",
1219
+ data: input
1220
+ };
1221
+ if (kind === "url") return {
1222
+ type: "path",
1223
+ path: input
1224
+ };
1225
+ return {
1226
+ type: "path",
1227
+ path: resolve(config.root, input)
1228
+ };
1229
+ }
1230
+ //#endregion
1231
+ //#region src/Resolver.ts
1232
+ function isNamespace(value) {
1233
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1234
+ }
1235
+ /**
1236
+ * Shared brand for reaching a resolver's build options. `Resolver.merge` reads this instead of
1237
+ * relying on `instanceof`, which fails when a CommonJS config and the ESM CLI each load their own
1238
+ * copy of `@kubb/core`. `Symbol.for` resolves to one key across those copies, so the options stay
1239
+ * reachable and a `file` override is never dropped.
1240
+ */
1241
+ const resolverOptions = Symbol.for("@kubb/core/resolver/options");
1242
+ /**
1243
+ * Builds a nested file path from a dotted name. Splits on dots that precede a letter
1244
+ * (so version numbers embedded in operationIds like `v2025.0` stay intact), camelCases
1245
+ * every segment, and joins with `/`.
1246
+ *
1247
+ * Empty segments are dropped before joining. They arise when the name starts with a dot
1248
+ * followed by a letter (e.g. `..Schema` splits into `['..', 'Schema']` and `'..'` cases to
1249
+ * an empty string). Without this a leading `/` would form, which `path.resolve` reads as an
1250
+ * absolute path, letting generated files escape the configured output directory.
1251
+ *
1252
+ * @example Nested path from a dotted name
1253
+ * `toFilePath('pet.petId') // 'pet/petId'`
1254
+ */
1255
+ function toFilePath(name) {
1256
+ return name.split(/\.(?=[a-zA-Z])/).map((part) => camelCase(part)).filter(Boolean).join("/");
1257
+ }
1258
+ /** Throws `KUBB_PATH_TRAVERSAL` when `target` lies outside `parent`; `target === parent` stays allowed. */
1259
+ function assertInside({ target, parent, message, help }) {
1260
+ const parentWithSep = parent.endsWith(path.sep) ? parent : `${parent}${path.sep}`;
1261
+ if (target === parent || target.startsWith(parentWithSep)) return;
1262
+ throw new Diagnostics.Error({
1263
+ code: Diagnostics.code.pathTraversal,
1264
+ severity: "error",
1265
+ message,
1266
+ help,
1267
+ location: { kind: "config" }
1268
+ });
1269
+ }
1270
+ /**
1271
+ * Built-in `file.baseName`: casts the identifier with `toFilePath` and appends the extension.
1272
+ */
1273
+ function toBaseName({ name, extname }) {
1274
+ return `${toFilePath(name)}${extname}`;
1275
+ }
1276
+ /**
1277
+ * Base constraint for all plugin resolver objects.
1278
+ *
1279
+ * The built-in machinery lives under `default`. Generators call the top-level `name`, `file`,
1280
+ * and `imports`, and a plugin overrides `name` and `file` to set its conventions. Extend with
1281
+ * top-level helpers (`typeName`, …) and/or grouped namespaces (`query`, `schema`, …).
1282
+ *
1283
+ * @example Top-level helper
1284
+ * ```ts
1285
+ * type MyResolver = Resolver & {
1286
+ * typeName(name: string): string
1287
+ * }
1288
+ * ```
1289
+ *
1290
+ * @example Grouped namespace
1291
+ * ```ts
1292
+ * type MyResolver = Resolver & {
1293
+ * query: {
1294
+ * name(node: OperationNode): string
1295
+ * keyName(node: OperationNode): string
1296
+ * }
1297
+ * }
1298
+ * ```
1299
+ */
1300
+ var Resolver = class Resolver {
1301
+ static #patternCache = /* @__PURE__ */ new Map();
1302
+ static #optionsCache = /* @__PURE__ */ new WeakMap();
1303
+ pluginName;
1304
+ /** The built-in machinery, untouched by `name`/`file` overrides and built once since the driver reads it per node. */
1305
+ default;
1306
+ #options;
1307
+ #baseName;
1308
+ #filePath;
1309
+ constructor(options) {
1310
+ this.pluginName = options.pluginName;
1311
+ this.#options = options;
1312
+ this.#baseName = options.file?.baseName ? options.file.baseName.bind(this) : toBaseName;
1313
+ this.#filePath = options.file?.path ? options.file.path.bind(this) : void 0;
1314
+ this.default = {
1315
+ name: camelCase,
1316
+ options: this.#resolveOptions.bind(this),
1317
+ path: this.#resolvePath.bind(this),
1318
+ file: this.#resolveFile.bind(this),
1319
+ banner: this.#resolveBanner.bind(this),
1320
+ footer: this.#resolveFooter.bind(this)
1321
+ };
1322
+ this.#apply(options);
1323
+ }
1324
+ /** Exposes the raw build options so `Resolver.merge` can read them across `@kubb/core` copies. */
1325
+ get [resolverOptions]() {
1326
+ return this.#options;
1327
+ }
1328
+ name(name) {
1329
+ return this.default.name(name);
1330
+ }
1331
+ file(options) {
1332
+ return this.#resolveFile(options);
1333
+ }
1334
+ /**
1335
+ * Builds one `ImportNode` per unique schema referenced in the tree, in first-occurrence
1336
+ * order. Each ref's target resolves through `resolveRefName`, so collision- or macro-renamed
1337
+ * schemas (`targetName`) import the emitted name. Names and paths go through the top-level
1338
+ * `name` and `file`, so import entries follow the plugin's conventions, and a per-call
1339
+ * `name` override wins over both.
1340
+ *
1341
+ * The subtree scan runs through `collectImportedRefNames`, which memoizes by node identity, so a
1342
+ * schema shared across the ts, zod, and faker plugins is walked once and every plugin's resolver
1343
+ * reads the same ref set instead of re-scanning it per plugin.
1344
+ */
1345
+ imports(options) {
1346
+ const { node, root, output, group, extname = ".ts", name } = options;
1347
+ const resolveName = name ?? ((schemaName) => this.name(schemaName));
1348
+ return collectImportedRefNames(node).map((schemaName) => ast.factory.createImport({
1349
+ name: [resolveName(schemaName)],
1350
+ path: this.file({
1351
+ name: schemaName,
1352
+ extname,
1353
+ root,
1354
+ output,
1355
+ group
1356
+ }).path
1357
+ }));
1358
+ }
1359
+ /**
1360
+ * Folds each `override` over `base`, left to right, and returns a new resolver with helpers
1361
+ * re-bound. Top-level keys replace, and a namespace (or `file`) merges per method, so overriding
1362
+ * `query.name` keeps the base `query.keyName`. The last override wins per key. Used when applying
1363
+ * `setResolver` partial overrides, and to compose shared resolver fragments without spreading each
1364
+ * namespace by hand. Reads a resolver's options through the shared brand rather than `instanceof`,
1365
+ * so a `file` override survives even when `base` and `override` come from different `@kubb/core`
1366
+ * copies.
1367
+ *
1368
+ * @example Fold several partial overrides onto a resolver
1369
+ * ```ts
1370
+ * const resolver = Resolver.merge(defaultResolver, sharedNamingPatch, { name: (name) => name.toUpperCase() })
1371
+ * ```
1372
+ */
1373
+ static merge(base, ...overrides) {
1374
+ const merged = overrides.reduce((acc, override) => {
1375
+ const patch = resolverOptions in override ? override[resolverOptions] : override;
1376
+ for (const [key, value] of Object.entries(patch)) {
1377
+ if (value === void 0) continue;
1378
+ const current = acc[key];
1379
+ acc[key] = isNamespace(value) && isNamespace(current) ? {
1380
+ ...current,
1381
+ ...value
1382
+ } : value;
1383
+ }
1384
+ return acc;
1385
+ }, { ...base[resolverOptions] });
1386
+ return new Resolver(merged);
1387
+ }
1388
+ /**
1389
+ * Binds each entry of `options` onto the resolver, so `this.name`, `this.default`, and
1390
+ * `this.file` resolve there for top-level helpers and namespace methods alike. `default`
1391
+ * is skipped so it can't be shadowed.
1392
+ */
1393
+ #apply(options) {
1394
+ const root = this;
1395
+ const bind = (value) => typeof value === "function" ? value.bind(root) : value;
1396
+ for (const [key, value] of Object.entries(options)) {
1397
+ if (key === "pluginName" || key === "default" || key === "file" || value === void 0) continue;
1398
+ root[key] = isNamespace(value) ? Object.fromEntries(Object.entries(value).map(([method, member]) => [method, bind(member)])) : bind(value);
1399
+ }
1400
+ }
1401
+ static #testPattern(value, pattern) {
1402
+ if (typeof pattern === "string") {
1403
+ let regex = Resolver.#patternCache.get(pattern);
1404
+ regex ??= new RegExp(pattern);
1405
+ Resolver.#patternCache.set(pattern, regex);
1406
+ return regex.test(value);
1407
+ }
1408
+ return value.match(pattern) !== null;
1409
+ }
1410
+ static #matchesOperation(node, { type, pattern }) {
1411
+ if (type === "tag") return node.tags.some((tag) => Resolver.#testPattern(tag, pattern));
1412
+ if (type === "operationId") return Resolver.#testPattern(node.operationId, pattern);
1413
+ if (type === "path") return node.path !== void 0 && Resolver.#testPattern(node.path, pattern);
1414
+ if (type === "method") return node.method !== void 0 && Resolver.#testPattern(node.method.toLowerCase(), pattern);
1415
+ if (type === "contentType") return node.requestBody?.content?.some((c) => Resolver.#testPattern(c.contentType, pattern)) ?? false;
1416
+ return false;
1417
+ }
1418
+ /**
1419
+ * Returns `null` when the filter type doesn't apply to schemas, so include rules built
1420
+ * from operation filters (e.g. `tag`) don't exclude every schema.
1421
+ */
1422
+ static #matchesSchema(node, { type, pattern }) {
1423
+ if (type === "schemaName") return node.name ? Resolver.#testPattern(node.name, pattern) : false;
1424
+ return null;
1425
+ }
1426
+ static #computeOptions(node, { options, exclude = [], include, override = [] }) {
1427
+ if (operationDef.is(node)) {
1428
+ if (exclude.some((filter) => Resolver.#matchesOperation(node, filter))) return null;
1429
+ if (include && !include.some((filter) => Resolver.#matchesOperation(node, filter))) return null;
1430
+ return {
1431
+ ...options,
1432
+ ...override.find((filter) => Resolver.#matchesOperation(node, filter))?.options
1433
+ };
1434
+ }
1435
+ if (schemaDef.is(node)) {
1436
+ if (exclude.some((filter) => Resolver.#matchesSchema(node, filter) === true)) return null;
1437
+ if (include) {
1438
+ const applicable = include.map((filter) => Resolver.#matchesSchema(node, filter)).filter((result) => result !== null);
1439
+ if (applicable.length > 0 && !applicable.includes(true)) return null;
1440
+ }
1441
+ return {
1442
+ ...options,
1443
+ ...override.find((filter) => Resolver.#matchesSchema(node, filter) === true)?.options
1444
+ };
1445
+ }
1446
+ return options;
1447
+ }
1448
+ /**
1449
+ * Applies include/exclude filters and merges matching override options, caching the result
1450
+ * per `(options, node)` pair. Returns `null` when the node is filtered out.
1451
+ */
1452
+ #resolveOptions(node, context) {
1453
+ const { options } = context;
1454
+ if (typeof options !== "object" || options === null) return Resolver.#computeOptions(node, context);
1455
+ let byOptions = Resolver.#optionsCache.get(options);
1456
+ if (!byOptions) {
1457
+ byOptions = /* @__PURE__ */ new WeakMap();
1458
+ Resolver.#optionsCache.set(options, byOptions);
1459
+ }
1460
+ const cached = byOptions.get(node);
1461
+ if (cached) return cached.value;
1462
+ const result = Resolver.#computeOptions(node, context);
1463
+ byOptions.set(node, { value: result });
1464
+ return result;
1465
+ }
1466
+ /**
1467
+ * A custom `group.name` wins; otherwise `tag` groups use the camelCased tag and `path`
1468
+ * groups use the first non-traversal segment (`''` when none remain, placing the file in
1469
+ * the output root, kept safe by the caller's boundary check).
1470
+ */
1471
+ static #resolveGroupDir(group, groupValue) {
1472
+ if (group.name) return group.name({ group: groupValue });
1473
+ if (group.type === "tag") return camelCase(groupValue);
1474
+ const segment = groupValue.split("/").filter((part) => part !== "" && part !== "." && part !== "..")[0];
1475
+ return segment ? camelCase(segment) : "";
1476
+ }
1477
+ /**
1478
+ * `mode: 'file'` (default) resolves directly to `output.path`. `mode: 'directory'` resolves
1479
+ * to `output.path/{baseName}`, or into a subdirectory when `group` and a `tag`/`path` value
1480
+ * are provided.
1481
+ */
1482
+ #resolvePath({ baseName, tag, path: groupPath, root, output, group }) {
1483
+ if (output.mode !== "directory") return path.resolve(root, output.path);
1484
+ const outputDir = path.resolve(root, output.path);
1485
+ const result = group && (groupPath || tag) ? path.resolve(outputDir, Resolver.#resolveGroupDir(group, group.type === "path" ? groupPath : tag), baseName) : path.resolve(outputDir, baseName);
1486
+ assertInside({
1487
+ target: result,
1488
+ parent: outputDir,
1489
+ message: `Resolved path "${result}" is outside the output directory "${outputDir}".`,
1490
+ help: "This can stem from a path traversal in the OpenAPI specification or a misconfigured `group.name` function. Keep generated paths within the output directory."
1491
+ });
1492
+ return result;
1493
+ }
1494
+ /**
1495
+ * Resolves a resolver-supplied full path (`file.path`) against `root`, bypassing `output.path`
1496
+ * and `group`. The path may not escape `root`, which keeps a `file.path` that interpolates
1497
+ * spec-derived values from writing outside the project.
1498
+ */
1499
+ #resolveOverridePath(filePath, root) {
1500
+ const resolved = path.resolve(root, filePath);
1501
+ assertInside({
1502
+ target: resolved,
1503
+ parent: root,
1504
+ message: `Resolved path "${resolved}" is outside the project root "${root}".`,
1505
+ help: "A resolver `file.path` must return a path inside the project root."
1506
+ });
1507
+ return resolved;
1508
+ }
1509
+ /**
1510
+ * Builds a `FileNode`. When `#filePath` (the resolver's `file.path`) is set it owns the whole
1511
+ * path; otherwise the base name (from `#baseName`, the resolver's `file.baseName` or the
1512
+ * built-in `toBaseName`) is placed by the `output.path`/`group` layout. The resolved file starts
1513
+ * with empty `sources`, `imports`, and `exports`, which consumers populate separately.
1514
+ */
1515
+ #resolveFile(options) {
1516
+ const { name, extname, tag, path: groupPath, root, output, group } = options;
1517
+ const baseName = this.#baseName({
1518
+ name,
1519
+ extname
1520
+ });
1521
+ const filePath = this.#filePath ? this.#resolveOverridePath(this.#filePath({
1522
+ baseName,
1523
+ output
1524
+ }), root) : this.#resolvePath({
1525
+ baseName,
1526
+ tag,
1527
+ path: groupPath,
1528
+ root,
1529
+ output,
1530
+ group
1531
+ });
1532
+ return ast.factory.createFile({
1533
+ path: filePath,
1534
+ baseName: path.basename(filePath),
1535
+ meta: { pluginName: this.pluginName },
1536
+ sources: [],
1537
+ imports: [],
1538
+ exports: []
1539
+ });
1540
+ }
1541
+ /**
1542
+ * Missing fields default to empty/`false` so the `BannerMeta` shape stays stable even when
1543
+ * a caller (e.g. the barrel plugin) has no document metadata.
1544
+ */
1545
+ static #buildBannerMeta(meta, file) {
1546
+ return {
1547
+ title: meta?.title,
1548
+ description: meta?.description,
1549
+ version: meta?.version,
1550
+ baseURL: meta?.baseURL,
1551
+ circularNames: meta?.circularNames ?? [],
1552
+ enumNames: meta?.enumNames ?? [],
1553
+ filePath: file?.path ?? "",
1554
+ baseName: file?.baseName ?? "",
1555
+ isBarrel: file?.isBarrel ?? false,
1556
+ isAggregation: file?.isAggregation ?? false
1557
+ };
1558
+ }
1559
+ /**
1560
+ * Resolves a user-configured banner/footer value. `undefined` means not configured.
1561
+ */
1562
+ static #resolveUserText(value, meta, file) {
1563
+ if (typeof value === "function") return value(Resolver.#buildBannerMeta(meta, file));
1564
+ if (typeof value === "string") return value;
1565
+ }
1566
+ static #buildDefaultBanner({ title, version, config }) {
1567
+ const lines = [
1568
+ "/**",
1569
+ "* Generated by Kubb (https://kubb.dev/).",
1570
+ "* Do not edit manually."
1571
+ ];
1572
+ if (config.output.defaultBanner !== "simple") {
1573
+ const input = config.input;
1574
+ const source = typeof input === "string" ? getInputKind(input) === "inline" ? "text content" : path.basename(input) : input ? "text content" : "";
1575
+ if (source) lines.push(`* Source: ${source}`);
1576
+ if (title) lines.push(`* Title: ${title}`);
1577
+ if (version) lines.push(`* OpenAPI spec version: ${version}`);
1578
+ }
1579
+ return `${lines.join("\n")}\n*/\n`;
1580
+ }
1581
+ /**
1582
+ * A user-supplied `output.banner` overrides the default Kubb notice. When
1583
+ * `config.output.defaultBanner` is `false` and no user banner is set, returns `null`.
1584
+ */
1585
+ #resolveBanner(meta, { output, config, file }) {
1586
+ const userBanner = Resolver.#resolveUserText(output?.banner, meta, file);
1587
+ if (userBanner !== void 0) return userBanner;
1588
+ if (config.output.defaultBanner === false) return null;
1589
+ return Resolver.#buildDefaultBanner({
1590
+ title: meta?.title,
1591
+ version: meta?.version,
1592
+ config
1593
+ });
1594
+ }
1595
+ #resolveFooter(meta, { output, file }) {
1596
+ return Resolver.#resolveUserText(output?.footer, meta, file) ?? null;
1597
+ }
1598
+ };
1599
+ //#endregion
1600
+ //#region src/createResolver.ts
1601
+ /**
1602
+ * Defines a plugin resolver, the object that decides what every generated symbol and file
1603
+ * path is called. Override the top-level `name` and `file` to set the plugin's conventions,
1604
+ * and add your own naming helpers, top-level (`typeName`, …) or grouped in namespaces
1605
+ * (`query`, `schema`, …). Every method reaches sibling helpers and the built-in machinery
1606
+ * through `this.name`, `this.file`, and `this.default`.
1607
+ *
1608
+ * @example Custom identifier casing
1609
+ * ```ts
1610
+ * export const resolverTs = createResolver<PluginTs>({
1611
+ * pluginName: 'plugin-ts',
1612
+ * name(name) {
1613
+ * return ensureValidVarName(pascalCase(name))
1614
+ * },
1615
+ * })
1616
+ * ```
1617
+ *
1618
+ * @example Rename generated files with `file.baseName`
1619
+ * ```ts
1620
+ * export const resolverFaker = createResolver<PluginFaker>({
1621
+ * pluginName: 'plugin-faker',
1622
+ * name(name) {
1623
+ * return camelCase(name, { prefix: 'create' })
1624
+ * },
1625
+ * file: {
1626
+ * baseName({ name, extname }) {
1627
+ * return `${camelCase(name, { prefix: 'create' })}${extname}`
1628
+ * },
1629
+ * },
1630
+ * })
1631
+ * ```
1632
+ *
1633
+ * @example Own the full path with `file.path`
1634
+ * ```ts
1635
+ * export const resolverFaker = createResolver<PluginFaker>({
1636
+ * pluginName: 'plugin-faker',
1637
+ * file: {
1638
+ * path({ baseName, output }) {
1639
+ * return `${output.path}/mocks/${baseName}`
1640
+ * },
1641
+ * },
1642
+ * })
1643
+ * ```
1644
+ */
1645
+ function createResolver(options) {
1646
+ return new Resolver(options);
1647
+ }
1648
+ //#endregion
1649
+ //#region src/Hookable.ts
1650
+ /**
1651
+ * Typed hook emitter that awaits all async listeners before resolving.
1652
+ * Wraps Node's `EventEmitter` with full TypeScript hook-map inference.
1653
+ *
1654
+ * @example
1655
+ * ```ts
1656
+ * const hooks = new Hookable<{ build: [name: string] }>()
1657
+ * hooks.hook('build', async (name) => { console.log(name) })
1658
+ * await hooks.callHook('build', 'petstore') // all listeners awaited
1659
+ * ```
1660
+ */
1661
+ var Hookable = class {
1662
+ /**
1663
+ * Maximum number of listeners per hook before Node emits a memory-leak warning.
1664
+ * @default 10
1665
+ */
1666
+ constructor(maxListener = 10) {
1667
+ this.#emitter.setMaxListeners(maxListener);
1668
+ }
1669
+ #emitter = new EventEmitter();
1670
+ /**
1671
+ * Calls `hookName` and awaits all registered listeners sequentially.
1672
+ * Throws if any listener rejects, wrapping the cause in an error that names the hook.
1673
+ *
1674
+ * @example
1675
+ * ```ts
1676
+ * await hooks.callHook('build', 'petstore')
1677
+ * ```
1678
+ */
1679
+ callHook(hookName, ...hookArgs) {
1680
+ const listeners = this.#emitter.listeners(hookName);
1681
+ if (listeners.length === 0) return;
1682
+ return this.#emitAll(hookName, listeners, hookArgs);
1683
+ }
1684
+ async #emitAll(hookName, listeners, hookArgs) {
1685
+ for (const listener of listeners) try {
1686
+ await listener(...hookArgs);
1687
+ } catch (err) {
1688
+ throw new Error(`Error in async listener for "${hookName}"`, { cause: toError(err) });
1689
+ }
1690
+ }
1691
+ /**
1692
+ * Registers a persistent listener for `hookName` and returns a function that removes it.
1693
+ *
1694
+ * @example
1695
+ * ```ts
1696
+ * const unhook = hooks.hook('build', async (name) => { console.log(name) })
1697
+ * unhook() // removes it
1698
+ * ```
1699
+ */
1700
+ hook(hookName, handler) {
1701
+ this.#emitter.on(hookName, handler);
1702
+ return () => this.removeHook(hookName, handler);
1703
+ }
1704
+ /**
1705
+ * Registers every handler in `configHooks` at once and returns a function that removes them
1706
+ * all. Undefined entries are skipped, so a partial hook object registers only its present keys.
1707
+ *
1708
+ * @example
1709
+ * ```ts
1710
+ * const unhook = hooks.addHooks({ build: onBuild, done: onDone })
1711
+ * unhook() // removes both
1712
+ * ```
1713
+ */
1714
+ addHooks(configHooks) {
1715
+ const unhooks = Object.keys(configHooks).filter((name) => configHooks[name]).map((name) => this.hook(name, configHooks[name]));
1716
+ return () => {
1717
+ for (const unhook of unhooks) unhook();
1718
+ };
1719
+ }
1720
+ /**
1721
+ * Removes a previously registered listener.
1722
+ *
1723
+ * @example
1724
+ * ```ts
1725
+ * hooks.removeHook('build', handler)
1726
+ * ```
1727
+ */
1728
+ removeHook(hookName, handler) {
1729
+ this.#emitter.off(hookName, handler);
1730
+ }
1731
+ /**
1732
+ * Returns the number of listeners registered for `hookName`.
1733
+ *
1734
+ * @example
1735
+ * ```ts
1736
+ * hooks.hook('build', handler)
1737
+ * hooks.listenerCount('build') // 1
1738
+ * ```
1739
+ */
1740
+ listenerCount(hookName) {
1741
+ return this.#emitter.listenerCount(hookName);
1742
+ }
1743
+ /**
1744
+ * Raises or lowers the per-hook listener ceiling before Node warns about a memory leak.
1745
+ * Set this above the expected listener count when many listeners attach by design.
1746
+ *
1747
+ * @example
1748
+ * ```ts
1749
+ * hooks.setMaxListeners(40)
1750
+ * ```
1751
+ */
1752
+ setMaxListeners(max) {
1753
+ this.#emitter.setMaxListeners(max);
1754
+ }
1755
+ /**
1756
+ * Removes all listeners from every hook channel.
1757
+ *
1758
+ * @example
1759
+ * ```ts
1760
+ * hooks.removeAllHooks()
1761
+ * ```
1762
+ */
1763
+ removeAllHooks() {
1764
+ this.#emitter.removeAllListeners();
1765
+ }
1766
+ };
1767
+ //#endregion
1768
+ //#region \0@oxc-project+runtime@0.148.0/helpers/esm/usingCtx.js
1769
+ function _usingCtx() {
1770
+ var r = "function" == typeof SuppressedError ? SuppressedError : function(r, e) {
1771
+ var n = Error();
1772
+ return n.name = "SuppressedError", n.error = r, n.suppressed = e, n;
1773
+ };
1774
+ var e = {};
1775
+ var n = [];
1776
+ function using(r, e) {
1777
+ if (null != e) {
1778
+ if (Object(e) !== e) throw new TypeError("using declarations can only be used with objects, functions, null, or undefined.");
1779
+ if (r) var o = e[Symbol.asyncDispose || Symbol["for"]("Symbol.asyncDispose")];
1780
+ if (void 0 === o && (o = e[Symbol.dispose || Symbol["for"]("Symbol.dispose")], r)) var t = o;
1781
+ if ("function" != typeof o) throw new TypeError("Object is not disposable.");
1782
+ t && (o = function o() {
1783
+ try {
1784
+ t.call(e);
1785
+ } catch (r) {
1786
+ return Promise.reject(r);
1787
+ }
1788
+ }), n.push({
1789
+ v: e,
1790
+ d: o,
1791
+ a: r
1792
+ });
1793
+ } else r && n.push({
1794
+ d: e,
1795
+ a: r
1796
+ });
1797
+ return e;
1798
+ }
1799
+ return {
1800
+ e,
1801
+ u: using.bind(null, !1),
1802
+ a: using.bind(null, !0),
1803
+ d: function d() {
1804
+ var o;
1805
+ var t = this.e;
1806
+ var s = 0;
1807
+ function next() {
1808
+ for (; o = n.pop();) try {
1809
+ if (!o.a && 1 === s) return s = 0, n.push(o), Promise.resolve().then(next);
1810
+ if (o.d) {
1811
+ var r = o.d.call(o.v);
1812
+ if (o.a) return s |= 2, Promise.resolve(r).then(next, err);
1813
+ } else s |= 1;
1814
+ } catch (r) {
1815
+ return err(r);
1816
+ }
1817
+ if (1 === s) return t !== e ? Promise.reject(t) : Promise.resolve();
1818
+ if (t !== e) throw t;
1819
+ }
1820
+ function err(n) {
1821
+ return t = t !== e ? new r(n, t) : n, next();
1822
+ }
1823
+ return next();
1824
+ }
1825
+ };
1826
+ }
1827
+ function joinSources(file) {
1828
+ return file.sources.map((source) => extractStringsFromNodes(source.nodes)).filter(Boolean).join("\n\n");
1829
+ }
1830
+ /**
1831
+ * Reads a `copy` file and prints it through the parser's `copy` hook, or verbatim with `banner`/`footer` when there is none.
1832
+ */
1833
+ async function parseCopy(file, parser) {
1834
+ let content;
1835
+ try {
1836
+ content = await read(file.copy);
1837
+ } catch (err) {
1838
+ throw new Error(`[kubb] Could not copy file into output: ${file.copy}`, { cause: err });
1839
+ }
1840
+ if (parser?.copy) return parser.parse(ast.factory.createFile(parser.copy(file, content)));
1841
+ return [
1842
+ file.banner,
1843
+ content,
1844
+ file.footer
1845
+ ].filter((segment) => Boolean(segment)).map((segment) => segment.trimEnd()).join("\n");
1846
+ }
1847
+ function mergeFile(a, b) {
1848
+ return {
1849
+ ...a,
1850
+ banner: b.banner,
1851
+ footer: b.footer,
1852
+ copy: b.copy ?? a.copy,
1853
+ sources: a.sources.length ? b.sources.length ? [...a.sources, ...b.sources] : a.sources : b.sources,
1854
+ imports: a.imports.length ? b.imports.length ? [...a.imports, ...b.imports] : a.imports : b.imports,
1855
+ exports: a.exports.length ? b.exports.length ? [...a.exports, ...b.exports] : a.exports : b.exports
1856
+ };
1857
+ }
1858
+ function isIndexPath(path) {
1859
+ return path.endsWith("/index.ts") || path === "index.ts";
1860
+ }
1861
+ function compareFiles(a, b) {
1862
+ return a.path.length - b.path.length || Number(isIndexPath(a.path)) - Number(isIndexPath(b.path));
1863
+ }
1864
+ function isUnchanged({ stored, source, key, manifest }) {
1865
+ if (stored === null) return false;
1866
+ if (matchesStored({
1867
+ stored,
1868
+ source
1869
+ })) return true;
1870
+ return manifest?.isUpToDate({
1871
+ key,
1872
+ source,
1873
+ disk: stored
1874
+ }) ?? false;
1875
+ }
1876
+ /**
1877
+ * In-memory file store for generated files, and the writer that turns them into source
1878
+ * strings on `storage`. Files sharing a `path` are merged (sources/imports/exports
1879
+ * concatenated). The `files` getter is sorted by path length (barrel `index.ts` last
1880
+ * within a bucket).
1881
+ *
1882
+ * @example
1883
+ * ```ts
1884
+ * const manager = new FileManager()
1885
+ * manager.upsert(myFile)
1886
+ * manager.files // sorted view
1887
+ * await manager.write(manager.files, { storage: fsStorage() })
1888
+ * ```
1889
+ */
1890
+ var FileManager = class {
1891
+ hooks = new Hookable();
1892
+ #cache = /* @__PURE__ */ new Map();
1893
+ #sorted = null;
1894
+ add(...files) {
1895
+ return this.#store(files, false);
1896
+ }
1897
+ upsert(...files) {
1898
+ return this.#store(files, true);
1899
+ }
1900
+ /** Stores a generator result: a file array is upserted as is, an element renders through `renderer` first, falsy is a no-op. */
1901
+ async dispatch({ result, renderer }) {
1902
+ try {
1903
+ var _usingCtx$1 = _usingCtx();
1904
+ if (!result) return;
1905
+ if (Array.isArray(result)) {
1906
+ this.upsert(...result);
1907
+ return;
1908
+ }
1909
+ if (!renderer) return;
1910
+ const instance = _usingCtx$1.u(renderer());
1911
+ await instance.render(result);
1912
+ this.upsert(...instance.files);
1913
+ } catch (_) {
1914
+ _usingCtx$1.e = _;
1915
+ } finally {
1916
+ _usingCtx$1.d();
1917
+ }
1918
+ }
1919
+ #store(files, mergeExisting) {
1920
+ const batch = files.length > 1 ? this.#dedupe(files) : files;
1921
+ const resolved = [];
1922
+ for (const file of batch) {
1923
+ const existing = this.#cache.get(file.path);
1924
+ const merged = existing && mergeExisting ? ast.factory.createFile(mergeFile(existing, file)) : ast.factory.createFile(file);
1925
+ this.#cache.set(merged.path, merged);
1926
+ resolved.push(merged);
1927
+ }
1928
+ if (resolved.length > 0) this.#sorted = null;
1929
+ return resolved;
1930
+ }
1931
+ #dedupe(files) {
1932
+ const seen = /* @__PURE__ */ new Map();
1933
+ for (const file of files) {
1934
+ const prev = seen.get(file.path);
1935
+ seen.set(file.path, prev ? mergeFile(prev, file) : file);
1936
+ }
1937
+ return [...seen.values()];
1938
+ }
1939
+ /**
1940
+ * Releases all stored files and clears every `hooks` listener. Called by the core after
1941
+ * `kubb:build:end`.
1942
+ */
1943
+ dispose() {
1944
+ this.#cache.clear();
1945
+ this.#sorted = null;
1946
+ this.hooks.removeAllHooks();
1947
+ }
1948
+ /**
1949
+ * All stored files in stable sort order (shortest path first, barrel files
1950
+ * last within a length bucket). Returns a cached view, do not mutate.
1951
+ */
1952
+ get files() {
1953
+ return this.#sorted ??= [...this.#cache.values()].sort(compareFiles);
1954
+ }
1955
+ /**
1956
+ * Converts a file's AST sources (or its `copy` source) into the final on-disk string.
1957
+ */
1958
+ async parse(file, { parsers } = {}) {
1959
+ const parser = parsers?.get(file.extname);
1960
+ if (file.copy) return parseCopy(file, parser);
1961
+ if (!parser) return joinSources(file);
1962
+ return parser.parse(file);
1963
+ }
1964
+ /**
1965
+ * Parses and writes every file through a bounded pool of workers. A small spec runs all its files
1966
+ * at once; a spec with thousands of files keeps at most {@link FILE_CONCURRENCY} parsed sources in
1967
+ * memory rather than holding every source, while still overlapping each file's write with the
1968
+ * next file's parse. Each `update` carries the file's input position, so a consumer can present
1969
+ * the files in generation order even though they finish in whatever order they parse.
1970
+ *
1971
+ * A file the storage already holds is skipped, so a rebuild that generates identical output
1972
+ * writes nothing and leaves every mtime where it was.
1973
+ */
1974
+ async write(files, { storage, parsers, manifest, signal }) {
1975
+ if (files.length === 0) return;
1976
+ await this.hooks.callHook("start", files);
1977
+ const total = files.length;
1978
+ await inParallel({
1979
+ items: files,
1980
+ limit: 50,
1981
+ run: async (file, index) => {
1982
+ signal?.throwIfAborted();
1983
+ const source = await this.parse(file, { parsers });
1984
+ await this.hooks.callHook("update", {
1985
+ file,
1986
+ source,
1987
+ processed: index + 1,
1988
+ total,
1989
+ percentage: (index + 1) / total * 100
1990
+ });
1991
+ if (!source) return;
1992
+ signal?.throwIfAborted();
1993
+ const stored = await storage.readItem(file.path);
1994
+ if (isUnchanged({
1995
+ stored,
1996
+ source,
1997
+ key: file.path,
1998
+ manifest
1999
+ })) return;
2000
+ signal?.throwIfAborted();
2001
+ await storage.writeItem(file.path, source, { stored });
2002
+ manifest?.track({
2003
+ key: file.path,
2004
+ source
2005
+ });
2006
+ }
2007
+ });
2008
+ await this.hooks.callHook("end", files);
2009
+ }
2010
+ };
2011
+ //#endregion
2012
+ //#region src/Transform.ts
2013
+ /**
2014
+ * Holds an ordered list of macros per plugin, keyed by plugin name. Each plugin's macros run in
2015
+ * isolation on the original adapter node and are composed into a single `Visitor` that the
2016
+ * `@kubb/ast` `transform` primitive applies. `applyTo` is a per-plugin lookup, not a cross-plugin
2017
+ * chain, so plugin A's macros never see plugin B's output. When a plugin has no macros, `applyTo`
2018
+ * returns the original node reference, and `transform` does the same when the composed visitor
2019
+ * leaves the tree untouched, so callers can detect a no-op by identity.
2020
+ *
2021
+ * Registration order matches the order setup hooks fire, which the driver has already sorted by
2022
+ * `enforce` and dependency edges. The registry preserves that order. Macro `enforce` only reorders
2023
+ * within a single plugin's list.
2024
+ */
2025
+ var Transform = class {
2026
+ #macros = /* @__PURE__ */ new Map();
2027
+ #composed = /* @__PURE__ */ new Map();
2028
+ #memo = /* @__PURE__ */ new Map();
2029
+ /**
2030
+ * Appends `macro` to the plugin's list, after any macros already registered.
2031
+ */
2032
+ add(pluginName, macro) {
2033
+ const list = this.#macros.get(pluginName);
2034
+ if (list) list.push(macro);
2035
+ else this.#macros.set(pluginName, [macro]);
2036
+ this.#invalidate(pluginName);
2037
+ }
2038
+ /**
2039
+ * Replaces the plugin's macro list with `macros`.
2040
+ */
2041
+ set(pluginName, macros) {
2042
+ this.#macros.set(pluginName, [...macros]);
2043
+ this.#invalidate(pluginName);
2044
+ }
2045
+ /**
2046
+ * Runs the plugin's macros on `node`. Returns the original node reference when the plugin has no
2047
+ * macros, so callers can compare by identity to detect a no-op.
2048
+ */
2049
+ applyTo(pluginName, node) {
2050
+ const visitor = this.#visitorFor(pluginName);
2051
+ if (!visitor) return node;
2052
+ let memo = this.#memo.get(pluginName);
2053
+ if (!memo) {
2054
+ memo = /* @__PURE__ */ new WeakMap();
2055
+ this.#memo.set(pluginName, memo);
2056
+ }
2057
+ const cached = memo.get(node);
2058
+ if (cached) return cached;
2059
+ const result = transform(node, visitor);
2060
+ memo.set(node, result);
2061
+ return result;
2062
+ }
2063
+ /**
2064
+ * Clears every registration. Called from the driver's `dispose()` so macros do not leak across
2065
+ * builds.
2066
+ */
2067
+ dispose() {
2068
+ this.#macros.clear();
2069
+ this.#composed.clear();
2070
+ this.#memo.clear();
2071
+ }
2072
+ #invalidate(pluginName) {
2073
+ this.#composed.delete(pluginName);
2074
+ this.#memo.delete(pluginName);
2075
+ }
2076
+ #visitorFor(pluginName) {
2077
+ const macros = this.#macros.get(pluginName);
2078
+ if (!macros || macros.length === 0) return void 0;
2079
+ let composed = this.#composed.get(pluginName);
2080
+ if (!composed) {
2081
+ composed = composeMacros(macros);
2082
+ this.#composed.set(pluginName, composed);
2083
+ }
2084
+ return composed;
2085
+ }
2086
+ };
2087
+ //#endregion
2088
+ //#region src/nodeCache.ts
2089
+ /**
2090
+ * Builds an empty {@link NodeCache} backed by a plain `Map`. Called once per node in the generate
2091
+ * walk.
2092
+ */
2093
+ function createNodeCache() {
2094
+ const store = /* @__PURE__ */ new Map();
2095
+ return {
2096
+ readItem(key) {
2097
+ return store.get(key);
2098
+ },
2099
+ writeItem(key, value) {
2100
+ store.set(key, value);
2101
+ return value;
2102
+ },
2103
+ ensureItem(key, factory) {
2104
+ if (store.has(key)) return store.get(key);
2105
+ const value = factory();
2106
+ store.set(key, value);
2107
+ return value;
2108
+ }
2109
+ };
2110
+ }
2111
+ //#endregion
2112
+ //#region src/KubbDriver.ts
2113
+ const ENFORCE_ORDER = {
2114
+ pre: -1,
2115
+ post: 1
2116
+ };
2117
+ /** `include` filter types that select operations, and so prune the schemas they do not reach. */
2118
+ const OPERATION_FILTER_TYPES = /* @__PURE__ */ new Set([
2119
+ "tag",
2120
+ "operationId",
2121
+ "path",
2122
+ "method",
2123
+ "contentType"
2124
+ ]);
2125
+ const enforceWeight = (plugin) => plugin.enforce ? ENFORCE_ORDER[plugin.enforce] : 0;
2126
+ /**
2127
+ * The options bag a `NormalizedPlugin` starts with before a plugin refines it: a directory output
2128
+ * at the plugin root and empty filter lists.
2129
+ */
2130
+ const defaultPluginOptions = () => ({
2131
+ output: {
2132
+ path: ".",
2133
+ mode: "directory"
2134
+ },
2135
+ exclude: [],
2136
+ override: []
2137
+ });
2138
+ /**
2139
+ * Fills in the `output`, `exclude`, and `override` a `NormalizedPlugin` needs from a plugin's raw
2140
+ * options, running `output` through `normalizeOutput`. Idempotent, so the driver can apply it after
2141
+ * `setOptions` has already run without disturbing an already-normalized bag.
2142
+ */
2143
+ function normalizePluginOptions(rawOptions, pluginName) {
2144
+ const options = {
2145
+ ...defaultPluginOptions(),
2146
+ ...rawOptions ?? {}
2147
+ };
2148
+ const group = "group" in options ? options.group : void 0;
2149
+ options.output = normalizeOutput({
2150
+ output: options.output,
2151
+ group,
2152
+ pluginName
2153
+ });
2154
+ return options;
2155
+ }
2156
+ var KubbDriver = class {
2157
+ config;
2158
+ options;
2159
+ /**
2160
+ * The `InputNode` produced by the adapter. Set after adapter setup.
2161
+ */
2162
+ inputNode = null;
2163
+ adapter = null;
2164
+ /**
2165
+ * Raw adapter source so `adapter.parse()` can run lazily.
2166
+ * Intentionally outlives the build, cleared by `dispose()`.
2167
+ */
2168
+ #adapterSource = null;
2169
+ /**
2170
+ * Central file store for all generated files.
2171
+ * Plugins should use `this.addFile()` / `this.upsertFile()` (via their context) to
2172
+ * add files. This property gives direct read/write access when needed.
2173
+ */
2174
+ fileManager = new FileManager();
2175
+ plugins = /* @__PURE__ */ new Map();
2176
+ /**
2177
+ * Removers for every listener the driver added (plugin, generator) so `dispose()` can detach
2178
+ * them in one pass. External `hooks.hook(...)` listeners are not tracked.
2179
+ */
2180
+ #unhooks = [];
2181
+ /**
2182
+ * Transform registry. Plugins populate it during `kubb:plugin:setup` via `addMacro`/`setMacros`,
2183
+ * and `#runGenerators` reads it once per `(plugin, node)` pair through `applyTo`.
2184
+ */
2185
+ #transforms = new Transform();
2186
+ constructor(config, options) {
2187
+ this.config = config;
2188
+ this.options = options;
2189
+ this.adapter = config.adapter ?? null;
2190
+ }
2191
+ /**
2192
+ * Normalizes and checks every configured plugin, orders them, and registers their lifecycle handlers.
2193
+ * A plugin that another lists as a dependency runs first, then `enforce: 'pre'` before
2194
+ * `'post'`. When the config has an adapter, the adapter source is resolved from the input
2195
+ * so `run` can parse it later.
2196
+ */
2197
+ async setup() {
2198
+ this.options.signal?.throwIfAborted();
2199
+ for (const parser of this.config.parsers) if (parser.meta) checkCompatibility(parser.meta);
2200
+ const normalized = this.#sortPlugins(this.config.plugins.map((rawPlugin) => {
2201
+ if (rawPlugin.meta) checkCompatibility(rawPlugin.meta);
2202
+ const meta = resolveMeta(rawPlugin);
2203
+ return {
2204
+ name: meta.name,
2205
+ meta,
2206
+ dependencies: typeof rawPlugin.dependencies === "function" ? rawPlugin.dependencies(rawPlugin.options ?? {}, { config: this.config }) : rawPlugin.dependencies,
2207
+ enforce: rawPlugin.enforce,
2208
+ hooks: rawPlugin.hooks,
2209
+ setup: rawPlugin.setup,
2210
+ options: rawPlugin.options ?? defaultPluginOptions(),
2211
+ resolver: createResolver({ pluginName: meta.name })
2212
+ };
2213
+ }));
2214
+ const byName = new Map(normalized.map((plugin) => [plugin.name, plugin]));
2215
+ for (const plugin of normalized) checkDependencies({
2216
+ name: plugin.name,
2217
+ dependencies: plugin.dependencies,
2218
+ plugins: byName
2219
+ });
2220
+ for (const plugin of normalized) {
2221
+ this.#registerPlugin(plugin);
2222
+ this.plugins.set(plugin.name, plugin);
2223
+ }
2224
+ if (this.config.adapter) this.#adapterSource = inputToAdapterSource(this.config);
2225
+ }
2226
+ /**
2227
+ * Orders plugins so every dependency runs before its dependents (Kahn's algorithm), with
2228
+ * `enforce` (`'pre'` before normal before `'post'`) and declaration order as tiebreaks.
2229
+ * A pairwise `Array.sort` comparator cannot do this: dependency relations are not transitive
2230
+ * at the comparator level, so a chain where A depends on B and B depends on C could come out
2231
+ * wrong when A and C are never compared directly. Dependencies on plugins missing from the
2232
+ * config are ignored here and surface later through `requirePlugin`.
2233
+ */
2234
+ #sortPlugins(plugins) {
2235
+ const queue = [...plugins].sort((a, b) => enforceWeight(a) - enforceWeight(b));
2236
+ const names = new Set(queue.map((plugin) => plugin.name));
2237
+ const blockedBy = new Map(queue.map((plugin) => {
2238
+ const dependencies = Array.isArray(plugin.dependencies) ? plugin.dependencies : Object.keys(plugin.dependencies ?? {});
2239
+ return [plugin.name, new Set(dependencies.filter((name) => names.has(name) && name !== plugin.name))];
2240
+ }));
2241
+ const sorted = [];
2242
+ for (const _ of plugins) {
2243
+ const index = queue.findIndex((plugin) => blockedBy.get(plugin.name)?.size === 0);
2244
+ if (index === -1) throw new Diagnostics.Error({
2245
+ code: Diagnostics.code.invalidPluginOptions,
2246
+ severity: "error",
2247
+ message: `Plugin dependencies form a cycle: ${queue.map((plugin) => plugin.name).join(" → ")}.`,
2248
+ help: "Remove one of the `dependencies` entries so the plugins can be ordered.",
2249
+ location: { kind: "config" }
2250
+ });
2251
+ const [plugin] = queue.splice(index, 1);
2252
+ if (!plugin) break;
2253
+ sorted.push(plugin);
2254
+ for (const blockers of blockedBy.values()) blockers.delete(plugin.name);
2255
+ }
2256
+ return sorted;
2257
+ }
2258
+ get hooks() {
2259
+ return this.options.hooks;
2260
+ }
2261
+ /**
2262
+ * Parses the adapter source into `this.inputNode`. Idempotent, so repeated calls from
2263
+ * `run` do not re-parse.
2264
+ */
2265
+ async #parseInput() {
2266
+ if (this.inputNode || !this.adapter || !this.#adapterSource) return;
2267
+ this.options.signal?.throwIfAborted();
2268
+ this.inputNode = await this.adapter.parse(this.#adapterSource, { signal: this.options.signal });
2269
+ }
2270
+ /**
2271
+ * Registers a plugin's lifecycle hooks on the shared `Hookable` as pass-through listeners that
2272
+ * external tooling can observe via `hooks.hook(...)`. The returned remover is tracked for
2273
+ * `dispose`. `kubb:plugin:setup` is skipped here; `setupHooks` invokes it directly with a
2274
+ * plugin-scoped context.
2275
+ *
2276
+ * @internal
2277
+ */
2278
+ #registerPlugin(plugin) {
2279
+ const { hooks } = plugin;
2280
+ if (!hooks) return;
2281
+ const { "kubb:plugin:setup": _setup, ...configHooks } = hooks;
2282
+ this.#unhooks.push(this.hooks.addHooks(configHooks));
2283
+ }
2284
+ /**
2285
+ * Runs each plugin's `setup` and `kubb:plugin:setup` handler, in plugin order, with a context scoped to that
2286
+ * plugin so `addGenerator`, `setResolver`, `addMacro`, `setMacros`, and `setOptions` target its
2287
+ * `NormalizedPlugin` entry. Called once from `run` before the plugin execution loop begins, so
2288
+ * plugins can configure generators, resolvers, macros, and options before `buildStart`.
2289
+ */
2290
+ async setupHooks() {
2291
+ for (const plugin of this.plugins.values()) {
2292
+ const setupHook = plugin.hooks?.["kubb:plugin:setup"];
2293
+ if (!plugin.setup && !setupHook) continue;
2294
+ const ctx = {
2295
+ config: this.config,
2296
+ options: plugin.options ?? {},
2297
+ addGenerator: (...generators) => {
2298
+ plugin.generators = [...plugin.generators ?? [], ...generators];
2299
+ },
2300
+ setResolver: (resolver) => {
2301
+ plugin.resolver = Resolver.merge(createResolver({ pluginName: plugin.name }), resolver);
2302
+ },
2303
+ addMacro: (macro) => {
2304
+ this.#transforms.add(plugin.name, macro);
2305
+ },
2306
+ setMacros: (macros) => {
2307
+ this.#transforms.set(plugin.name, macros);
2308
+ },
2309
+ setOptions: (opts) => {
2310
+ plugin.options = normalizePluginOptions({
2311
+ ...plugin.options,
2312
+ ...opts
2313
+ }, plugin.name);
2314
+ },
2315
+ injectFile: (userFileNode) => {
2316
+ this.fileManager.add(ast.factory.createFile(userFileNode));
2317
+ },
2318
+ requirePlugin: ((name) => this.requirePlugin(name, { requiredBy: plugin.name }))
2319
+ };
2320
+ try {
2321
+ await kubbContext.run(ctx, async () => {
2322
+ if (plugin.setup) plugin.options = normalizePluginOptions(await plugin.setup(ctx.options, ctx), plugin.name);
2323
+ await setupHook?.(ctx);
2324
+ });
2325
+ } catch (caughtError) {
2326
+ const diagnostic = Diagnostics.from(caughtError);
2327
+ throw new Diagnostics.Error({
2328
+ ...diagnostic,
2329
+ plugin: diagnostic.plugin ?? plugin.name
2330
+ });
2331
+ }
2332
+ }
2333
+ }
2334
+ /** `true` once `addGenerator()` in `kubb:plugin:setup` registered a generator for the plugin. */
2335
+ hasHookGenerators(pluginName) {
2336
+ return (this.plugins.get(pluginName)?.generators?.length ?? 0) > 0;
2337
+ }
2338
+ /**
2339
+ * Runs the full plugin pipeline. Returns the diagnostics collected so far even
2340
+ * when an outer hook throws, since the orchestrator preserves partial state by capturing
2341
+ * the failure as a {@link Diagnostic} instead of propagating. Each plugin also
2342
+ * contributes a `timing` diagnostic for the run summary.
2343
+ */
2344
+ async run() {
2345
+ const { hooks, config, fileManager } = this;
2346
+ const diagnostics = [];
2347
+ const parsersMap = /* @__PURE__ */ new Map();
2348
+ for (const parser of config.parsers) if (parser.extNames) for (const ext of parser.extNames) parsersMap.set(ext, parser);
2349
+ const updateBuffer = [];
2350
+ const unhookWrites = fileManager.hooks.addHooks({
2351
+ start: async (files) => {
2352
+ await hooks.callHook("kubb:files:processing:start", { files });
2353
+ },
2354
+ update: ({ file, processed, total, percentage }) => {
2355
+ updateBuffer.push({
2356
+ file,
2357
+ processed,
2358
+ total,
2359
+ percentage,
2360
+ config
2361
+ });
2362
+ },
2363
+ end: async (files) => {
2364
+ updateBuffer.sort((a, b) => a.processed - b.processed);
2365
+ await hooks.callHook("kubb:files:processing:update", { files: updateBuffer });
2366
+ updateBuffer.length = 0;
2367
+ await hooks.callHook("kubb:files:processing:end", { files });
2368
+ }
2369
+ });
2370
+ return Diagnostics.scope((diagnostic) => diagnostics.push(diagnostic), async () => {
2371
+ try {
2372
+ this.options.signal?.throwIfAborted();
2373
+ const outputRoot = resolve(config.root, config.output.path);
2374
+ await this.#parseInput();
2375
+ await this.setupHooks();
2376
+ for (const plugin of this.plugins.values()) {
2377
+ this.options.signal?.throwIfAborted();
2378
+ plugin.options = normalizePluginOptions(plugin.options, plugin.name);
2379
+ }
2380
+ if (this.adapter && this.inputNode) {
2381
+ const buildStartContext = this.#withFiles({
2382
+ config,
2383
+ adapter: this.adapter,
2384
+ meta: this.inputNode.meta,
2385
+ getPlugin: this.getPlugin.bind(this)
2386
+ });
2387
+ await hooks.callHook("kubb:build:start", buildStartContext);
2388
+ }
2389
+ const generatorPlugins = [];
2390
+ for (const plugin of this.plugins.values()) {
2391
+ const context = this.getContext(plugin);
2392
+ const hrStart = process.hrtime();
2393
+ try {
2394
+ await hooks.callHook("kubb:plugin:start", { plugin });
2395
+ } catch (caughtError) {
2396
+ const error = toError(caughtError);
2397
+ const duration = getElapsedMs(hrStart);
2398
+ await this.#emitPluginEnd({
2399
+ plugin,
2400
+ duration,
2401
+ success: false,
2402
+ error
2403
+ });
2404
+ diagnostics.push({
2405
+ ...Diagnostics.from(error),
2406
+ plugin: plugin.name
2407
+ }, Diagnostics.performance({
2408
+ plugin: plugin.name,
2409
+ duration
2410
+ }));
2411
+ continue;
2412
+ }
2413
+ if (this.hasHookGenerators(plugin.name)) {
2414
+ generatorPlugins.push({
2415
+ plugin,
2416
+ context,
2417
+ hrStart
2418
+ });
2419
+ continue;
2420
+ }
2421
+ const duration = getElapsedMs(hrStart);
2422
+ diagnostics.push(Diagnostics.performance({
2423
+ plugin: plugin.name,
2424
+ duration
2425
+ }));
2426
+ await this.#emitPluginEnd({
2427
+ plugin,
2428
+ duration,
2429
+ success: true
2430
+ });
2431
+ }
2432
+ diagnostics.push(...await this.#runGenerators(generatorPlugins));
2433
+ await hooks.callHook("kubb:plugins:end", this.#withFiles({ config }));
2434
+ if (this.options.cleanPath) await config.storage.empty(this.options.cleanPath);
2435
+ await fileManager.write(fileManager.files, {
2436
+ storage: config.storage,
2437
+ parsers: parsersMap,
2438
+ manifest: this.options.manifest,
2439
+ signal: this.options.signal
2440
+ });
2441
+ await hooks.callHook("kubb:build:end", {
2442
+ files: this.fileManager.files,
2443
+ config,
2444
+ outputDir: outputRoot
2445
+ });
2446
+ return { diagnostics: Diagnostics.dedupe(diagnostics) };
2447
+ } catch (caughtError) {
2448
+ diagnostics.push(Diagnostics.from(caughtError));
2449
+ return { diagnostics: Diagnostics.dedupe(diagnostics) };
2450
+ } finally {
2451
+ unhookWrites();
2452
+ }
2453
+ });
2454
+ }
2455
+ /**
2456
+ * Widens `extra` with the files present at emit time and a bound `upsertFile`, the shape every
2457
+ * file-carrying hook context shares. Building it here in one place keeps the `files` and
2458
+ * `upsertFile` keys from being dropped by a stray spread at the call site.
2459
+ */
2460
+ #withFiles(extra) {
2461
+ return {
2462
+ ...extra,
2463
+ files: this.fileManager.files,
2464
+ upsertFile: (...files) => this.fileManager.upsert(...files)
2465
+ };
2466
+ }
2467
+ #emitPluginEnd({ plugin, duration, success, error }) {
2468
+ return this.hooks.callHook("kubb:plugin:end", this.#withFiles({
2469
+ plugin,
2470
+ duration,
2471
+ success,
2472
+ ...error ? { error } : {},
2473
+ config: this.config
2474
+ }));
2475
+ }
2476
+ /**
2477
+ * Runs schemas and operations through every plugin's generators. The walk is node-outer: each
2478
+ * schema is visited once and each operation once, and the node fans out to the matching
2479
+ * generators of every plugin in dependency order. A per-node cache (`createNodeCache`) is created
2480
+ * once per node and shared by all of that node's plugins, so node-derived work is computed once
2481
+ * and reused instead of recomputed per plugin. Each node still runs through the plugin's macros
2482
+ * (from `this.#transforms`) and its exclude/include/override filters before that plugin's
2483
+ * generator sees it, so plugins stay isolated. Schemas run before operations so file output
2484
+ * stays deterministic across runs. A generator with a `match` predicate that resolves `false`
2485
+ * for a node is skipped for that node, without calling `schema`/`operation`.
2486
+ *
2487
+ * A failing plugin is dropped from the remaining walk, contributes an error diagnostic, and no
2488
+ * longer aborts the other plugins. `kubb:plugin:end` and each plugin's `timing` diagnostic fire
2489
+ * in dependency order once the walk finishes, driving the CLI's `Plugins N/M` counter. The
2490
+ * `operations` batch fires once per plugin after the single operation walk.
2491
+ *
2492
+ * When `this.inputNode` is `null`, every entry still gets a `kubb:plugin:end` so
2493
+ * post-plugin listeners (the barrel writer and friends) complete.
2494
+ */
2495
+ async #runGenerators(entries) {
2496
+ const diagnostics = [];
2497
+ if (entries.length === 0) return diagnostics;
2498
+ if (!this.inputNode) {
2499
+ for (const { plugin, hrStart } of entries) {
2500
+ const duration = getElapsedMs(hrStart);
2501
+ diagnostics.push(Diagnostics.performance({
2502
+ plugin: plugin.name,
2503
+ duration
2504
+ }));
2505
+ await this.#emitPluginEnd({
2506
+ plugin,
2507
+ duration,
2508
+ success: true
2509
+ });
2510
+ }
2511
+ return diagnostics;
2512
+ }
2513
+ const transforms = this.#transforms;
2514
+ const { schemas, operations } = this.inputNode;
2515
+ const allowedSchemaNamesByPlugin = /* @__PURE__ */ new Map();
2516
+ for (const { plugin } of entries) {
2517
+ const { exclude, include, override } = plugin.options;
2518
+ if (!((include?.some(({ type }) => OPERATION_FILTER_TYPES.has(type)) ?? false) && !(include?.some(({ type }) => type === "schemaName") ?? false))) continue;
2519
+ const resolver = this.getResolver(plugin.name);
2520
+ const includedOps = operations.filter((operation) => resolver.default.options(operation, {
2521
+ options: plugin.options,
2522
+ exclude,
2523
+ include,
2524
+ override
2525
+ }) !== null);
2526
+ allowedSchemaNamesByPlugin.set(plugin.name, collectUsedSchemaNames(includedOps, schemas));
2527
+ }
2528
+ const states = entries.map(({ plugin, context, hrStart }) => {
2529
+ const generatorContext = {
2530
+ ...context,
2531
+ resolver: this.getResolver(plugin.name)
2532
+ };
2533
+ const { exclude, include, override } = plugin.options;
2534
+ const generators = plugin.generators ?? [];
2535
+ return {
2536
+ plugin,
2537
+ hrStart,
2538
+ generatorContext,
2539
+ exclude,
2540
+ include,
2541
+ override,
2542
+ optionsAreStatic: !exclude?.length && !include?.length && !override?.length,
2543
+ allowedSchemaNames: allowedSchemaNamesByPlugin.get(plugin.name) ?? null,
2544
+ schemaGenerators: generators.filter((generator) => generator.schema),
2545
+ operationGenerators: generators.filter((generator) => generator.operation),
2546
+ operationsGenerators: generators.filter((generator) => generator.operations),
2547
+ pluginOperations: [],
2548
+ error: null
2549
+ };
2550
+ });
2551
+ const resolveForPlugin = (state, node) => {
2552
+ const transformedNode = transforms.applyTo(state.plugin.name, node);
2553
+ if (state.optionsAreStatic) return {
2554
+ transformedNode,
2555
+ options: state.plugin.options
2556
+ };
2557
+ const options = state.generatorContext.resolver.default.options(transformedNode, {
2558
+ options: state.plugin.options,
2559
+ exclude: state.exclude,
2560
+ include: state.include,
2561
+ override: state.override
2562
+ });
2563
+ if (options === null) return null;
2564
+ return {
2565
+ transformedNode,
2566
+ options
2567
+ };
2568
+ };
2569
+ for (const node of schemas) {
2570
+ const cache = createNodeCache();
2571
+ for (const state of states) {
2572
+ if (state.error || !state.schemaGenerators.length) continue;
2573
+ try {
2574
+ const resolved = resolveForPlugin(state, node);
2575
+ if (!resolved) continue;
2576
+ const { transformedNode, options } = resolved;
2577
+ if (state.allowedSchemaNames !== null && transformedNode.name && !state.allowedSchemaNames.has(transformedNode.name)) continue;
2578
+ const ctx = {
2579
+ ...state.generatorContext,
2580
+ options,
2581
+ cache
2582
+ };
2583
+ await this.#dispatchNode({
2584
+ generators: state.schemaGenerators,
2585
+ node: transformedNode,
2586
+ ctx,
2587
+ generate: (generator) => generator.schema(transformedNode, ctx)
2588
+ });
2589
+ await this.hooks.callHook("kubb:generate:schema", transformedNode, ctx);
2590
+ } catch (caughtError) {
2591
+ state.error = toError(caughtError);
2592
+ }
2593
+ }
2594
+ }
2595
+ for (const node of operations) {
2596
+ const cache = createNodeCache();
2597
+ for (const state of states) {
2598
+ if (state.error || !state.operationGenerators.length && !state.operationsGenerators.length) continue;
2599
+ try {
2600
+ const resolved = resolveForPlugin(state, node);
2601
+ if (!resolved) continue;
2602
+ state.pluginOperations.push(resolved.transformedNode);
2603
+ if (state.operationGenerators.length) {
2604
+ const { transformedNode } = resolved;
2605
+ const ctx = {
2606
+ ...state.generatorContext,
2607
+ options: resolved.options,
2608
+ cache
2609
+ };
2610
+ await this.#dispatchNode({
2611
+ generators: state.operationGenerators,
2612
+ node: transformedNode,
2613
+ ctx,
2614
+ generate: (generator) => generator.operation(transformedNode, ctx)
2615
+ });
2616
+ await this.hooks.callHook("kubb:generate:operation", transformedNode, ctx);
2617
+ }
2618
+ } catch (caughtError) {
2619
+ state.error = toError(caughtError);
2620
+ }
2621
+ }
2622
+ }
2623
+ for (const state of states) {
2624
+ if (state.error || !state.operationsGenerators.length) continue;
2625
+ try {
2626
+ const ctx = {
2627
+ ...state.generatorContext,
2628
+ options: state.plugin.options,
2629
+ cache: createNodeCache()
2630
+ };
2631
+ for (const generator of state.operationsGenerators) await this.dispatch({
2632
+ result: await generator.operations(state.pluginOperations, ctx),
2633
+ renderer: generator.renderer
2634
+ });
2635
+ await this.hooks.callHook("kubb:generate:operations", state.pluginOperations, ctx);
2636
+ } catch (caughtError) {
2637
+ state.error = toError(caughtError);
2638
+ }
2639
+ }
2640
+ for (const state of states) {
2641
+ const duration = getElapsedMs(state.hrStart);
2642
+ await this.#emitPluginEnd({
2643
+ plugin: state.plugin,
2644
+ duration,
2645
+ success: !state.error,
2646
+ error: state.error ?? void 0
2647
+ });
2648
+ if (state.error) diagnostics.push({
2649
+ ...Diagnostics.from(state.error),
2650
+ plugin: state.plugin.name
2651
+ });
2652
+ diagnostics.push(Diagnostics.performance({
2653
+ plugin: state.plugin.name,
2654
+ duration
2655
+ }));
2656
+ }
2657
+ return diagnostics;
2658
+ }
2659
+ /** Runs `node` through the generators whose `match` accepts it; `generate` picks the method for the node kind. */
2660
+ async #dispatchNode({ generators, node, ctx, generate }) {
2661
+ for (const generator of generators) {
2662
+ if (!(generator.match ? await generator.match(node, ctx) : true)) continue;
2663
+ await this.dispatch({
2664
+ result: await generate(generator),
2665
+ renderer: generator.renderer
2666
+ });
2667
+ }
2668
+ }
2669
+ /** Stores whatever a generator method or `kubb:generate:*` hook returned, see {@link FileManager.dispatch}. */
2670
+ dispatch(params) {
2671
+ return this.fileManager.dispatch(params);
2672
+ }
2673
+ /**
2674
+ * Removes every listener the driver added. Listeners attached directly to `hooks` from outside
2675
+ * the driver survive. Called at the end of a build to prevent leaks across repeated builds.
2676
+ *
2677
+ * @internal
2678
+ */
2679
+ dispose() {
2680
+ for (const unhook of this.#unhooks) unhook();
2681
+ this.#unhooks.length = 0;
2682
+ this.#transforms.dispose();
2683
+ this.fileManager.dispose();
2684
+ this.inputNode = null;
2685
+ this.#adapterSource = null;
2686
+ }
2687
+ [Symbol.dispose]() {
2688
+ this.dispose();
2689
+ }
2690
+ getResolver(pluginName) {
2691
+ return this.plugins.get(pluginName)?.resolver ?? createResolver({ pluginName });
2692
+ }
2693
+ getContext(plugin) {
2694
+ const driver = this;
2695
+ const report = (diagnostic) => {
2696
+ Diagnostics.report({
2697
+ ...diagnostic,
2698
+ plugin: plugin.name
2699
+ });
2700
+ };
2701
+ return {
2702
+ config: driver.config,
2703
+ signal: driver.options.signal,
2704
+ get root() {
2705
+ return resolve(driver.config.root, driver.config.output.path);
2706
+ },
2707
+ hooks: driver.hooks,
2708
+ plugin,
2709
+ getPlugin: driver.getPlugin.bind(driver),
2710
+ requirePlugin: ((name) => driver.requirePlugin(name, { requiredBy: plugin.name })),
2711
+ getResolver: driver.getResolver.bind(driver),
2712
+ driver,
2713
+ addFile: async (...files) => {
2714
+ driver.fileManager.add(...files);
2715
+ },
2716
+ upsertFile: async (...files) => {
2717
+ driver.fileManager.upsert(...files);
2718
+ },
2719
+ get meta() {
2720
+ return driver.inputNode?.meta ?? {
2721
+ circularNames: [],
2722
+ enumNames: []
2723
+ };
2724
+ },
2725
+ get adapter() {
2726
+ return driver.adapter;
2727
+ },
2728
+ get resolver() {
2729
+ return driver.getResolver(plugin.name);
2730
+ },
2731
+ warn(message) {
2732
+ report({
2733
+ code: Diagnostics.code.pluginWarning,
2734
+ severity: "warning",
2735
+ message
2736
+ });
2737
+ },
2738
+ error(error) {
2739
+ const cause = typeof error === "string" ? void 0 : error;
2740
+ report({
2741
+ code: Diagnostics.code.pluginFailed,
2742
+ severity: "error",
2743
+ message: typeof error === "string" ? error : error.message,
2744
+ cause
2745
+ });
2746
+ },
2747
+ info(message) {
2748
+ report({
2749
+ code: Diagnostics.code.pluginInfo,
2750
+ severity: "info",
2751
+ message
2752
+ });
2753
+ }
2754
+ };
2755
+ }
2756
+ getPlugin(pluginName) {
2757
+ return this.plugins.get(pluginName);
2758
+ }
2759
+ requirePlugin(pluginName, context) {
2760
+ const plugin = this.getPlugin(pluginName);
2761
+ if (plugin) return plugin;
2762
+ throw pluginNotFoundError({
2763
+ pluginName,
2764
+ requiredBy: context?.requiredBy
2765
+ });
2766
+ }
2767
+ };
2768
+ /** The `KUBB_PLUGIN_NOT_FOUND` error `requirePlugin` throws, naming the plugin that needed it. */
2769
+ function pluginNotFoundError({ pluginName, requiredBy }) {
2770
+ const by = requiredBy ? ` by "${requiredBy}"` : "";
2771
+ const help = requiredBy ? ` (required by "${requiredBy}")` : "";
2772
+ return new Diagnostics.Error({
2773
+ code: Diagnostics.code.pluginNotFound,
2774
+ severity: "error",
2775
+ message: `Plugin "${pluginName}" is required${by} but not found. Make sure it is included in your Kubb config.`,
2776
+ help: `Add "${pluginName}" to the \`plugins\` array in kubb.config.ts${help}, or remove the dependency on it.`,
2777
+ location: { kind: "config" },
2778
+ ...requiredBy ? { plugin: requiredBy } : {}
2779
+ });
2780
+ }
2781
+ //#endregion
2782
+ export { clean as A, useConfig as C, formatMs as D, Diagnostics as E, write as F, toError as I, camelCase as L, isPathInside as M, read as N, getElapsedMs as O, toPosixPath as P, tryUseKubb as S, useOptions as T, kubbContext as _, _usingCtx as a, setOptions as b, Resolver as c, definePlugin as d, defineExtension as f, injectFile as g, addMacro as h, FileManager as i, exists as j, inParallel as k, getInputKind as l, addGenerator as m, pluginNotFoundError as n, Hookable as o, resolveMeta as p, createNodeCache as r, createResolver as s, KubbDriver as t, assertPluginOption as u, requirePlugin as v, useKubb as w, setResolver as x, setMacros as y };
2783
+
2784
+ //# sourceMappingURL=KubbDriver-DRobnIcp.js.map