@kubb/core 5.6.2 → 5.6.3

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.
package/dist/index.js CHANGED
@@ -1,12 +1,10 @@
1
1
  import "./rolldown-runtime-C0LytTxp.js";
2
- import { a as inParallel, c as isPathInside, d as write, f as getErrorMessage, i as Hookable, l as read, m as camelCase, n as FileManager, o as clean, p as toError, r as _usingCtx, s as exists, t as createNodeCache, u as toPosixPath } from "./nodeCache-CumrOPh-.js";
3
- import { AsyncLocalStorage } from "node:async_hooks";
2
+ import { S as toError, _ as exists, a as _usingCtx, b as toPosixPath, c as Resolver, d as definePlugin, f as Diagnostics, g as clean, h as inParallel, l as getInputKind, m as getElapsedMs, o as Hookable, p as formatMs, s as createResolver, t as KubbDriver, u as assertPluginOption, v as isPathInside, x as write, y as read } from "./KubbDriver-BZBnKODj.js";
4
3
  import { stripVTControlCharacters, styleText } from "node:util";
5
4
  import process$1 from "node:process";
6
5
  import { x } from "tinyexec";
7
6
  import { glob, readFile, rm } from "node:fs/promises";
8
- import path, { join, relative, resolve } from "node:path";
9
- import { ast, collectImportedRefNames, collectUsedSchemaNames, composeMacros, operationDef, schemaDef, transform } from "@kubb/ast";
7
+ import { join, relative, resolve } from "node:path";
10
8
  import { hash, randomUUID } from "node:crypto";
11
9
  import { chmodSync, existsSync, mkdirSync } from "node:fs";
12
10
  import { homedir, tmpdir } from "node:os";
@@ -206,1850 +204,6 @@ function tokenize(command) {
206
204
  return (command.match(/[^\s"']+|"([^"]*)"|'([^']*)'/g) ?? []).map((token) => token.replace(/^["']|["']$/g, ""));
207
205
  }
208
206
  //#endregion
209
- //#region ../../internals/utils/src/time.ts
210
- /**
211
- * Calculates elapsed time in milliseconds from a high-resolution `process.hrtime` start time.
212
- * Rounds to 2 decimal places for sub-millisecond precision without noise.
213
- *
214
- * @example
215
- * ```ts
216
- * const start = process.hrtime()
217
- * doWork()
218
- * getElapsedMs(start) // 42.35
219
- * ```
220
- */
221
- function getElapsedMs(hrStart) {
222
- const [seconds, nanoseconds] = process.hrtime(hrStart);
223
- const ms = seconds * 1e3 + nanoseconds / 1e6;
224
- return Math.round(ms * 100) / 100;
225
- }
226
- /**
227
- * Converts a millisecond duration into a human-readable string (`ms`, `s`, or `m s`).
228
- *
229
- * @example
230
- * ```ts
231
- * formatMs(250) // '250ms'
232
- * formatMs(1500) // '1.50s'
233
- * formatMs(90000) // '1m 30.0s'
234
- * ```
235
- */
236
- function formatMs(ms) {
237
- if (ms >= 6e4) return `${Math.floor(ms / 6e4)}m ${(ms % 6e4 / 1e3).toFixed(1)}s`;
238
- if (ms >= 1e3) return `${(ms / 1e3).toFixed(2)}s`;
239
- return `${Math.round(ms)}ms`;
240
- }
241
- //#endregion
242
- //#region package.json
243
- var version = "5.6.2";
244
- //#endregion
245
- //#region src/constants.ts
246
- /**
247
- * Stable codes Kubb attaches to a `Diagnostic`. Each maps to a known failure mode
248
- * and stays stable so it can be referenced in tooling and (later) docs. Reference
249
- * these instead of inlining the string at a throw site.
250
- */
251
- const diagnosticCode = {
252
- /**
253
- * Fallback for an unstructured error with no specific code.
254
- */
255
- unknown: "KUBB_UNKNOWN",
256
- /**
257
- * The file or URL set as `input` could not be read.
258
- */
259
- inputNotFound: "KUBB_INPUT_NOT_FOUND",
260
- /**
261
- * A URL set as `input` (or referenced by a `$ref`) answered with a 4xx or 5xx status
262
- * instead of the document.
263
- */
264
- inputRequestFailed: "KUBB_INPUT_REQUEST_FAILED",
265
- /**
266
- * A URL set as `input` (or referenced by a `$ref`) never answered, so the request failed
267
- * before a status was returned.
268
- */
269
- inputUnreachable: "KUBB_INPUT_UNREACHABLE",
270
- /**
271
- * An adapter was configured without an `input`.
272
- */
273
- inputRequired: "KUBB_INPUT_REQUIRED",
274
- /**
275
- * `input` uses the v4 `{ path }` / `{ data }` wrapper, which v5 reads as a parsed
276
- * document instead of a pointer to one.
277
- */
278
- legacyInput: "KUBB_LEGACY_INPUT",
279
- /**
280
- * The parsed `input` carries no `openapi` or `swagger` version, so it is not a
281
- * document the adapter can read.
282
- */
283
- invalidDocument: "KUBB_INVALID_DOCUMENT",
284
- /** The document fails OpenAPI schema validation. Reported as a warning. */
285
- invalidSpec: "KUBB_INVALID_SPEC",
286
- /**
287
- * A `$ref` (or equivalent reference) could not be resolved in the source document.
288
- */
289
- refNotFound: "KUBB_REF_NOT_FOUND",
290
- /**
291
- * A server variable value is not allowed by its `enum`.
292
- */
293
- invalidServerVariable: "KUBB_INVALID_SERVER_VARIABLE",
294
- /**
295
- * A required plugin is missing from the config.
296
- */
297
- pluginNotFound: "KUBB_PLUGIN_NOT_FOUND",
298
- /**
299
- * A plugin threw while generating.
300
- */
301
- pluginFailed: "KUBB_PLUGIN_FAILED",
302
- /**
303
- * A plugin reported a non-fatal warning through `ctx.warn`.
304
- */
305
- pluginWarning: "KUBB_PLUGIN_WARNING",
306
- /**
307
- * A plugin reported an informational message through `ctx.info`.
308
- */
309
- pluginInfo: "KUBB_PLUGIN_INFO",
310
- /**
311
- * A schema uses a `format` Kubb does not map to a specific type. Reserved for
312
- * adapters to emit as a `warning`.
313
- */
314
- unsupportedFormat: "KUBB_UNSUPPORTED_FORMAT",
315
- /**
316
- * A referenced schema or operation is marked `deprecated`. Reserved for adapters
317
- * to emit as an `info`.
318
- */
319
- deprecated: "KUBB_DEPRECATED",
320
- /**
321
- * An adapter is required but the config has none. The build cannot read the input
322
- * without one.
323
- */
324
- adapterRequired: "KUBB_ADAPTER_REQUIRED",
325
- /**
326
- * A resolved output path escapes the output directory, which can stem from a path
327
- * traversal in the spec or a misconfigured `group.name`.
328
- */
329
- pathTraversal: "KUBB_PATH_TRAVERSAL",
330
- /**
331
- * `output.clean` is enabled but `output.path` resolves to the project root or a parent of it,
332
- * so cleaning would delete kubb.config and every source file.
333
- */
334
- cleanRoot: "KUBB_CLEAN_ROOT",
335
- /**
336
- * A plugin's options are invalid, for example `output.mode: 'file'` paired with a `group` option.
337
- */
338
- invalidPluginOptions: "KUBB_INVALID_PLUGIN_OPTIONS",
339
- /**
340
- * A post-generate command (`output.postGenerate`) exited with a failure.
341
- */
342
- postGenerateFailed: "KUBB_POST_GENERATE_FAILED",
343
- /**
344
- * The formatter pass over the generated files failed.
345
- */
346
- formatFailed: "KUBB_FORMAT_FAILED",
347
- /**
348
- * The linter pass over the generated files failed.
349
- */
350
- lintFailed: "KUBB_LINT_FAILED",
351
- /**
352
- * A barrel tries to re-export the same name from more than one module.
353
- */
354
- barrelDuplicateExport: "KUBB_BARREL_DUPLICATE_EXPORT",
355
- /**
356
- * Not a failure. Carries a plugin's elapsed time, summed into the run total.
357
- */
358
- performance: "KUBB_PERFORMANCE",
359
- /**
360
- * Not a failure. A newer Kubb version is available on npm.
361
- */
362
- updateAvailable: "KUBB_UPDATE_AVAILABLE"
363
- };
364
- //#endregion
365
- //#region src/Diagnostics.ts
366
- /**
367
- * Docs major version, derived from the package version so the link tracks the published major.
368
- */
369
- const docsMajor = version.split(".")[0] ?? "5";
370
- /**
371
- * Builds a type guard that narrows a {@link Diagnostic} to the variant for `kind`. A diagnostic
372
- * with no `kind` is treated as a `problem`.
373
- */
374
- function isKind(kind) {
375
- return (diagnostic) => (diagnostic.kind ?? "problem") === kind;
376
- }
377
- /**
378
- * Returns `true` when the diagnostic is a build {@link ProblemDiagnostic}.
379
- *
380
- * @example
381
- * ```ts
382
- * if (isProblem(diagnostic)) {
383
- * console.log(diagnostic.location)
384
- * }
385
- * ```
386
- */
387
- const isProblem = isKind("problem");
388
- /**
389
- * Returns `true` when the diagnostic is a per-plugin {@link PerformanceDiagnostic}.
390
- *
391
- * @example
392
- * ```ts
393
- * const timings = diagnostics.filter(isPerformance)
394
- * ```
395
- */
396
- const isPerformance = isKind("performance");
397
- /**
398
- * Returns `true` when the diagnostic is a version-update {@link UpdateDiagnostic}.
399
- *
400
- * @example
401
- * ```ts
402
- * if (isUpdate(diagnostic)) {
403
- * console.log(diagnostic.latestVersion)
404
- * }
405
- * ```
406
- */
407
- const isUpdate = isKind("update");
408
- /**
409
- * Accent color per severity. The color tints the `[CODE]` tag (red error, yellow warning,
410
- * blue info).
411
- */
412
- const severityStyle = {
413
- error: "red",
414
- warning: "yellow",
415
- info: "blue"
416
- };
417
- const countKey = {
418
- error: "errors",
419
- warning: "warnings",
420
- info: "infos"
421
- };
422
- /**
423
- * Explanation for every {@link diagnosticCode}. Use {@link Diagnostics.explain} to look one up
424
- * and `Diagnostics.docsUrl` for the matching kubb.dev page.
425
- */
426
- const diagnosticCatalog = {
427
- [diagnosticCode.unknown]: {
428
- title: "Unknown error",
429
- cause: "An error was thrown without a stable Kubb code, so it is reported as-is.",
430
- 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."
431
- },
432
- [diagnosticCode.inputNotFound]: {
433
- title: "Input not found",
434
- 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.",
435
- fix: "Check that the path exists and is readable, then set it as `input` or pass it on the CLI."
436
- },
437
- [diagnosticCode.inputRequestFailed]: {
438
- title: "Input request failed",
439
- cause: "A URL set as `input` (or reached through a `$ref`) answered with a 4xx or 5xx status instead of the document.",
440
- 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."
441
- },
442
- [diagnosticCode.inputUnreachable]: {
443
- title: "Input unreachable",
444
- 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.",
445
- 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`."
446
- },
447
- [diagnosticCode.inputRequired]: {
448
- title: "Input required",
449
- cause: "An adapter is configured but no `input` was provided.",
450
- fix: "Set `input` to a file path, a URL, an inline spec (JSON/YAML string), or a parsed object in your Kubb config."
451
- },
452
- [diagnosticCode.legacyInput]: {
453
- title: "Legacy input shape",
454
- cause: "`input` is a `{ path }` or `{ data }` wrapper, which v4 used to point at a document and v5 reads as the document itself.",
455
- fix: "Unwrap it: `input: { path: \"./petStore.yaml\" }` becomes `input: \"./petStore.yaml\"`, and `input: { data: spec }` becomes `input: spec`."
456
- },
457
- [diagnosticCode.invalidDocument]: {
458
- title: "Invalid document",
459
- cause: "The parsed `input` has no `openapi` or `swagger` version field, so it is not an OpenAPI or Swagger document.",
460
- 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."
461
- },
462
- [diagnosticCode.invalidSpec]: {
463
- title: "Invalid spec",
464
- cause: "The document does not pass OpenAPI schema validation. Kubb still generates from it, but the output can be incomplete or wrong.",
465
- 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."
466
- },
467
- [diagnosticCode.refNotFound]: {
468
- title: "Reference not found",
469
- cause: "A `$ref` could not be resolved in the source document.",
470
- fix: "Add the missing definition (for example under `components.schemas`) or fix the `$ref`. Run `kubb validate` to check the spec."
471
- },
472
- [diagnosticCode.invalidServerVariable]: {
473
- title: "Invalid server variable",
474
- cause: "A server variable value is not allowed by its `enum`.",
475
- fix: "Use one of the values listed in the server variable `enum`, or update the spec."
476
- },
477
- [diagnosticCode.pluginNotFound]: {
478
- title: "Plugin not found",
479
- cause: "A plugin that another plugin depends on is missing from the config.",
480
- fix: "Add the required plugin to the `plugins` array in kubb.config.ts, or remove the dependency on it."
481
- },
482
- [diagnosticCode.pluginFailed]: {
483
- title: "Plugin failed",
484
- cause: "A plugin threw while generating, or reported an error through `ctx.error`.",
485
- fix: "Read the underlying error and check the plugin options and the schema or operation it failed on."
486
- },
487
- [diagnosticCode.pluginWarning]: {
488
- title: "Plugin warning",
489
- cause: "A plugin reported a non-fatal warning through `ctx.warn`.",
490
- fix: "Review the message. It does not fail the build; adjust the plugin options or input if the warning is unwanted."
491
- },
492
- [diagnosticCode.pluginInfo]: {
493
- title: "Plugin info",
494
- cause: "A plugin reported an informational message through `ctx.info`.",
495
- fix: "Informational only. No action is required."
496
- },
497
- [diagnosticCode.unsupportedFormat]: {
498
- title: "Unsupported format",
499
- cause: "A schema uses a `format` Kubb does not map to a specific type, so it falls back to the base type.",
500
- fix: "Use a format Kubb supports, or handle the custom format with a parser or plugin."
501
- },
502
- [diagnosticCode.deprecated]: {
503
- title: "Deprecated",
504
- cause: "A referenced schema or operation is marked `deprecated`.",
505
- fix: "Migrate off the deprecated definition if the warning is unwanted."
506
- },
507
- [diagnosticCode.adapterRequired]: {
508
- title: "Adapter required",
509
- cause: "An action needs an adapter but none is configured.",
510
- fix: "Set `adapter` in kubb.config.ts, for example `adapterOas()`."
511
- },
512
- [diagnosticCode.pathTraversal]: {
513
- title: "Path traversal",
514
- cause: "A resolved output path escaped the output directory, which can stem from a path traversal in the spec or a misconfigured `group.name`.",
515
- fix: "Keep generated paths within the output directory. Review the `group.name` function and the names coming from the spec."
516
- },
517
- [diagnosticCode.cleanRoot]: {
518
- title: "Clean targets the project root",
519
- 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.",
520
- fix: "Point `output.path` at a subdirectory such as `./src/gen` so clean only removes generated code, or disable `output.clean`."
521
- },
522
- [diagnosticCode.invalidPluginOptions]: {
523
- title: "Invalid plugin options",
524
- cause: "A plugin was configured with options that cannot be honored, for example `output.mode: 'file'` paired with a `group` option.",
525
- fix: "Fix the plugin options. A single-file output has nothing to group, so remove the `group` option or use `output.mode: 'directory'`."
526
- },
527
- [diagnosticCode.postGenerateFailed]: {
528
- title: "Post-generate command failed",
529
- cause: "A post-generate command (`output.postGenerate`) exited with a non-zero status.",
530
- fix: "Check the command is installed and correct, and run it manually to see the error."
531
- },
532
- [diagnosticCode.formatFailed]: {
533
- title: "Format failed",
534
- cause: "The formatter pass over the generated files failed.",
535
- fix: "Check the formatter (oxfmt, biome, or prettier) is installed and its config is valid, then run it manually on the output."
536
- },
537
- [diagnosticCode.lintFailed]: {
538
- title: "Lint failed",
539
- cause: "The linter pass over the generated files failed.",
540
- fix: "Check the linter (oxlint, biome, or eslint) is installed and its config is valid, then run it manually on the output."
541
- },
542
- [diagnosticCode.barrelDuplicateExport]: {
543
- title: "Duplicate barrel export",
544
- cause: "Two generated modules export the same name, so the barrel cannot re-export both.",
545
- fix: "Rename one of the colliding declarations, or configure the plugin resolver to produce distinct names."
546
- },
547
- [diagnosticCode.performance]: {
548
- title: "Performance",
549
- cause: "Not a failure. Records a plugin’s elapsed time, summed into the run total.",
550
- fix: "No action. This is an informational metric."
551
- },
552
- [diagnosticCode.updateAvailable]: {
553
- title: "Update available",
554
- cause: "A newer Kubb version is published on npm than the one running.",
555
- fix: "Update the `@kubb/*` packages, for example `npm install -g @kubb/cli`, to get the latest fixes."
556
- }
557
- };
558
- /**
559
- * Static helpers for working with {@link Diagnostic}s, plus the run-scoped sink
560
- * that lets deep code report a diagnostic without threading a callback.
561
- *
562
- * The sink lives in a single `AsyncLocalStorage` in the `@kubb/core` bundle.
563
- * `Diagnostics.scope` activates it for a run, so anything inside that run (the
564
- * adapter parse, a generator) reports through `Diagnostics.report` and lands
565
- * in the same run.
566
- */
567
- var Diagnostics = class Diagnostics {
568
- static #reporterStorage = new AsyncLocalStorage();
569
- /**
570
- * The diagnostic code catalog, exposed as `Diagnostics.code` (e.g. `Diagnostics.code.refNotFound`).
571
- */
572
- static code = diagnosticCode;
573
- /**
574
- * Type guard for a build {@link ProblemDiagnostic}.
575
- */
576
- static isProblem = isProblem;
577
- /**
578
- * Type guard for a version-update {@link UpdateDiagnostic}.
579
- */
580
- static isUpdate = isUpdate;
581
- /**
582
- * Type guard for a per-plugin {@link PerformanceDiagnostic}.
583
- */
584
- static isPerformance = isPerformance;
585
- /**
586
- * An `Error` that carries a {@link Diagnostic}, so structured problems can flow
587
- * through the existing throw/catch paths while keeping their code and location.
588
- *
589
- * @example
590
- * ```ts
591
- * throw new Diagnostics.Error({ code: diagnosticCode.refNotFound, severity: 'error', message: `Could not find ${ref}`, location: { kind: 'schema', pointer: ref, ref } })
592
- * ```
593
- */
594
- static Error = class DiagnosticError extends Error {
595
- diagnostic;
596
- constructor(diagnostic) {
597
- super(diagnostic.message, { cause: diagnostic.cause });
598
- this.name = "DiagnosticError";
599
- this.diagnostic = diagnostic;
600
- }
601
- };
602
- /**
603
- * Structural check for a {@link Diagnostics.Error}, including one thrown from a duplicated
604
- * `@kubb/core` copy where `instanceof` fails. Matches on the `name` and a `diagnostic`
605
- * that carries a `code`.
606
- */
607
- static isError(error) {
608
- if (error instanceof Diagnostics.Error) return true;
609
- if (!(error instanceof Error) || error.name !== "DiagnosticError") return false;
610
- const { diagnostic } = error;
611
- return typeof diagnostic === "object" && diagnostic !== null && typeof diagnostic.code === "string";
612
- }
613
- /**
614
- * Runs `fn` with `sink` as the active diagnostic sink for the whole async
615
- * subtree, so {@link Diagnostics.report} reaches it from anywhere inside.
616
- */
617
- static scope(sink, fn) {
618
- return Diagnostics.#reporterStorage.run(sink, fn);
619
- }
620
- /**
621
- * Collects a diagnostic into the active build via the run-scoped sink, without throwing.
622
- * Returns `true` when a run consumed it, `false` when called outside a {@link Diagnostics.scope}
623
- * (so callers can fall back to throwing). Use a `warning`/`info` severity for non-fatal issues.
624
- * For rendering a diagnostic live on the hook bus, use {@link Diagnostics.emit} instead.
625
- */
626
- static report(diagnostic) {
627
- const sink = Diagnostics.#reporterStorage.getStore();
628
- if (!sink) return false;
629
- sink(diagnostic);
630
- return true;
631
- }
632
- /**
633
- * Emits a diagnostic on the run's `kubb:diagnostic` hook so the loggers render it live.
634
- * Use it instead of calling `hooks.callHook('kubb:diagnostic', ...)` directly. To collect a
635
- * diagnostic into the build result from deep in a run, use {@link Diagnostics.report} instead.
636
- */
637
- static async emit(hooks, diagnostic) {
638
- await hooks.callHook("kubb:diagnostic", { diagnostic });
639
- }
640
- /**
641
- * Coerces any thrown value into a {@link ProblemDiagnostic}. A {@link Diagnostics.Error}
642
- * keeps its structured data, and anything else becomes a `KUBB_UNKNOWN` error.
643
- */
644
- static from(error) {
645
- const seen = /* @__PURE__ */ new Set();
646
- let current = error;
647
- let root;
648
- while (current instanceof Error && !seen.has(current)) {
649
- if (Diagnostics.isError(current)) return current.diagnostic;
650
- seen.add(current);
651
- root = current;
652
- current = current.cause;
653
- }
654
- return {
655
- code: diagnosticCode.unknown,
656
- severity: "error",
657
- message: root ? root.message : getErrorMessage(error),
658
- cause: root
659
- };
660
- }
661
- /**
662
- * Builds a per-plugin performance record. Reporters sum these into the run total.
663
- */
664
- static performance({ plugin, duration }) {
665
- return {
666
- kind: "performance",
667
- code: diagnosticCode.performance,
668
- severity: "info",
669
- message: `${plugin} generated in ${Math.round(duration)}ms`,
670
- plugin,
671
- duration
672
- };
673
- }
674
- /**
675
- * Builds the version-update notice shown when a newer Kubb is published on npm.
676
- */
677
- static update({ currentVersion, latestVersion }) {
678
- return {
679
- kind: "update",
680
- code: diagnosticCode.updateAvailable,
681
- severity: "info",
682
- message: `Update available: v${currentVersion} → v${latestVersion}. Run \`npm install -g @kubb/cli\` to update.`,
683
- currentVersion,
684
- latestVersion
685
- };
686
- }
687
- /**
688
- * True when any diagnostic is an error, the severity that fails a build. Non-error
689
- * diagnostics are ignored.
690
- */
691
- static hasError(diagnostics) {
692
- return diagnostics.some((diagnostic) => diagnostic.severity === "error");
693
- }
694
- /**
695
- * Names of the plugins that failed, deduped, derived from the error diagnostics
696
- * that carry a `plugin`.
697
- */
698
- static failedPlugins(diagnostics) {
699
- return [...new Set(diagnostics.flatMap((diagnostic) => diagnostic.severity === "error" && diagnostic.plugin ? [diagnostic.plugin] : []))];
700
- }
701
- /**
702
- * Counts `problem` diagnostics by severity for the run summary. `performance` and
703
- * `update` diagnostics are ignored.
704
- */
705
- static count(diagnostics) {
706
- const counts = {
707
- errors: 0,
708
- warnings: 0,
709
- infos: 0
710
- };
711
- for (const diagnostic of diagnostics.filter(isProblem)) counts[countKey[diagnostic.severity]] += 1;
712
- return counts;
713
- }
714
- /**
715
- * Drops duplicate `problem` diagnostics that share a code, location pointer, and
716
- * plugin, so the same issue reported across several passes is shown once. Non-problem
717
- * diagnostics are always kept.
718
- */
719
- static dedupe(diagnostics) {
720
- const seen = /* @__PURE__ */ new Set();
721
- const result = [];
722
- for (const diagnostic of diagnostics) {
723
- if (!isProblem(diagnostic)) {
724
- result.push(diagnostic);
725
- continue;
726
- }
727
- const pointer = diagnostic.location && "pointer" in diagnostic.location ? diagnostic.location.pointer : "";
728
- const key = `${diagnostic.code} ${pointer} ${diagnostic.plugin ?? ""}`;
729
- if (seen.has(key)) continue;
730
- seen.add(key);
731
- result.push(diagnostic);
732
- }
733
- return result;
734
- }
735
- /**
736
- * Builds the kubb.dev docs URL for a diagnostic code, e.g.
737
- * `KUBB_REF_NOT_FOUND` → `https://kubb.dev/docs/5.x/reference/diagnostics#kubb-ref-not-found`.
738
- */
739
- static docsUrl(code) {
740
- const slug = code.toLowerCase().replaceAll("_", "-");
741
- return `https://kubb.dev/docs/${docsMajor}.x/reference/diagnostics#${slug}`;
742
- }
743
- /**
744
- * The catalog entry for a code: its title, cause, and fix. Mirrors the kubb.dev
745
- * `/reference/diagnostics#<slug>` section.
746
- */
747
- static explain(code) {
748
- return diagnosticCatalog[code];
749
- }
750
- /**
751
- * Reduces a diagnostic to its JSON-safe fields plus a `docsUrl`, for machine-readable
752
- * consumers. The `cause`, `kind`, and `duration` are dropped, and absent optional
753
- * fields are omitted rather than set to `undefined`.
754
- */
755
- static serialize(diagnostic) {
756
- const problem = isProblem(diagnostic) ? diagnostic : void 0;
757
- return {
758
- code: diagnostic.code,
759
- severity: diagnostic.severity,
760
- message: diagnostic.message,
761
- ...problem?.location ? { location: problem.location } : {},
762
- ...problem?.help ? { help: problem.help } : {},
763
- ...problem?.plugin ? { plugin: problem.plugin } : {},
764
- ...diagnostic.code === diagnosticCode.unknown ? {} : { docsUrl: Diagnostics.docsUrl(diagnostic.code) }
765
- };
766
- }
767
- /**
768
- * Renders a {@link Diagnostic} for terminal output as its parts: the `headline`
769
- * (`[CODE] plugin: message`, with the code in the severity color) and the indented `details`
770
- * rows (`at:` pointer, `fix:` help, `see:` docs link).
771
- *
772
- * Hosts compose these to fit their gutter: a clack logger passes `[headline, ...details]` as the
773
- * message with no gutter symbol, while plain text outputs use {@link Diagnostics.formatLines}.
774
- */
775
- static format(diagnostic) {
776
- const { code, severity, message } = diagnostic;
777
- const color = severityStyle[severity];
778
- const problem = isProblem(diagnostic) ? diagnostic : void 0;
779
- const tag = styleText(color, styleText("bold", `[${code}]`));
780
- const headline = problem?.plugin ? `${tag} ${problem.plugin}: ${message}` : `${tag}: ${message}`;
781
- const details = [];
782
- if (problem?.location && "pointer" in problem.location) details.push(` ${styleText("dim", "at:")} ${styleText("cyan", problem.location.pointer)}`);
783
- if (problem?.help) details.push(` ${styleText("cyan", "fix:")} ${problem.help}`);
784
- if (code !== diagnosticCode.unknown) details.push(` ${styleText("dim", "see:")} ${styleText("cyan", Diagnostics.docsUrl(code))}`);
785
- return {
786
- headline,
787
- details
788
- };
789
- }
790
- /**
791
- * The self-contained block form of {@link Diagnostics.format}: the `headline` followed by the
792
- * indented detail rows. Used where there is no gutter (plain and file output).
793
- */
794
- static formatLines(diagnostic) {
795
- const { headline, details } = Diagnostics.format(diagnostic);
796
- return [headline, ...details];
797
- }
798
- };
799
- //#endregion
800
- //#region src/definePlugin.ts
801
- /**
802
- * Merges the `output.mode` default into the output config and validates the combination.
803
- * Throws `KUBB_INVALID_PLUGIN_OPTIONS` when `mode: 'file'` is paired with a `group` option,
804
- * since a single-file output has nothing to group.
805
- *
806
- * An omitted `mode` follows the shape of `path`: an extension means a single file, anything
807
- * else is a directory. Plugin defaults such as `path: 'types'` name a directory, so they
808
- * generate without the caller spelling out `mode`.
809
- */
810
- function normalizeOutput({ output, group, pluginName }) {
811
- const mode = output.mode ?? (path.extname(output.path) ? "file" : "directory");
812
- if (mode === "file" && group) throw new Diagnostics.Error({
813
- code: Diagnostics.code.invalidPluginOptions,
814
- severity: "error",
815
- message: `Plugin "${pluginName}" resolves \`output.mode\` to 'file' but also configures a \`group\` option.`,
816
- 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.",
817
- location: { kind: "config" },
818
- plugin: pluginName
819
- });
820
- return {
821
- ...output,
822
- mode
823
- };
824
- }
825
- /**
826
- * Wraps a plugin factory and returns a function that accepts user options and
827
- * yields a typed `Plugin`. Lifecycle handlers go inside a single `hooks` object.
828
- *
829
- * Pass a `PluginFactoryOptions` type parameter to get a typed `ctx` inside
830
- * `kubb:plugin:setup`. Plugin names should follow the `plugin-<feature>`
831
- * convention (`plugin-react-query`, `plugin-zod`, ...).
832
- *
833
- * @example
834
- * ```ts
835
- * import { definePlugin } from '@kubb/core'
836
- *
837
- * export const pluginTs = definePlugin((options: { prefix?: string } = {}) => ({
838
- * name: 'plugin-ts',
839
- * hooks: {
840
- * 'kubb:plugin:setup'(ctx) {
841
- * ctx.setResolver(resolverTs)
842
- * },
843
- * },
844
- * }))
845
- * ```
846
- */
847
- function definePlugin(factory) {
848
- return (options) => factory(options ?? {});
849
- }
850
- //#endregion
851
- //#region src/input.ts
852
- /**
853
- * Classifies an `input` value so callers branch on it once instead of repeating the checks.
854
- *
855
- * A non-string is a parsed spec (`object`). A string is `inline` when it holds OpenAPI content,
856
- * meaning it starts with `{` or `[`, spans multiple lines, or opens with a YAML `openapi:` or
857
- * `swagger:` key. Otherwise a string is a `url` when it parses as one, or a `file` path.
858
- */
859
- function getInputKind(input) {
860
- if (typeof input !== "string") return "object";
861
- const trimmed = input.trimStart();
862
- if (trimmed.startsWith("{") || trimmed.startsWith("[") || input.includes("\n") || /^(openapi|swagger)\s*:/i.test(trimmed)) return "inline";
863
- if (URL.canParse(input)) return "url";
864
- return "file";
865
- }
866
- /**
867
- * The v4 `input` wrapper keys. v4 typed `input` as `{ path }` or `{ data }`; v5 takes the value
868
- * directly, so the wrapper now matches the "already-parsed document" branch and silently yields
869
- * an empty build.
870
- */
871
- const legacyInputKeys = ["path", "data"];
872
- /**
873
- * Detects the v4 `{ path }` / `{ data }` wrapper so it fails loudly instead of being read as a
874
- * document. A real spec always carries more than these keys, so an object whose keys are drawn
875
- * only from them is the old shape rather than a document that happens to have a `path` property.
876
- */
877
- function isLegacyInput(input) {
878
- if (Array.isArray(input)) return input.some(isLegacyInput);
879
- if (typeof input !== "object" || input === null) return false;
880
- const keys = Object.keys(input);
881
- return keys.length > 0 && keys.every((key) => legacyInputKeys.includes(key));
882
- }
883
- /**
884
- * Normalizes `config.input` into an `AdapterSource` the adapter can parse.
885
- *
886
- * A parsed object and inline content become `{ type: 'data' }`; a URL is kept verbatim and a
887
- * local path is resolved against `config.root`, both as `{ type: 'path' }`.
888
- */
889
- function inputToAdapterSource(config) {
890
- const input = config.input;
891
- if (input && isLegacyInput(input)) throw new Diagnostics.Error({
892
- code: Diagnostics.code.legacyInput,
893
- severity: "error",
894
- message: "The `input` option uses the v4 `{ path }` / `{ data }` wrapper.",
895
- help: "Unwrap it: `input: { path: \"./petStore.yaml\" }` becomes `input: \"./petStore.yaml\"`, and `input: { data: spec }` becomes `input: spec`.",
896
- location: { kind: "config" }
897
- });
898
- if (!input) throw new Diagnostics.Error({
899
- code: Diagnostics.code.inputRequired,
900
- severity: "error",
901
- message: "An adapter is configured without an input.",
902
- help: "Set `input` to a file path, a URL, an inline spec (JSON/YAML string), or a parsed object in your Kubb config.",
903
- location: { kind: "config" }
904
- });
905
- if (typeof input !== "string") return {
906
- type: "data",
907
- data: input
908
- };
909
- const kind = getInputKind(input);
910
- if (kind === "inline") return {
911
- type: "data",
912
- data: input
913
- };
914
- if (kind === "url") return {
915
- type: "path",
916
- path: input
917
- };
918
- return {
919
- type: "path",
920
- path: resolve(config.root, input)
921
- };
922
- }
923
- //#endregion
924
- //#region src/Resolver.ts
925
- function isNamespace(value) {
926
- return typeof value === "object" && value !== null && !Array.isArray(value);
927
- }
928
- /**
929
- * Shared brand for reaching a resolver's build options. `Resolver.merge` reads this instead of
930
- * relying on `instanceof`, which fails when a CommonJS config and the ESM CLI each load their own
931
- * copy of `@kubb/core`. `Symbol.for` resolves to one key across those copies, so the options stay
932
- * reachable and a `file` override is never dropped.
933
- */
934
- const resolverOptions = Symbol.for("@kubb/core/resolver/options");
935
- /**
936
- * Builds a nested file path from a dotted name. Splits on dots that precede a letter
937
- * (so version numbers embedded in operationIds like `v2025.0` stay intact), camelCases
938
- * every segment, and joins with `/`.
939
- *
940
- * Empty segments are dropped before joining. They arise when the name starts with a dot
941
- * followed by a letter (e.g. `..Schema` splits into `['..', 'Schema']` and `'..'` cases to
942
- * an empty string). Without this a leading `/` would form, which `path.resolve` reads as an
943
- * absolute path, letting generated files escape the configured output directory.
944
- *
945
- * @example Nested path from a dotted name
946
- * `toFilePath('pet.petId') // 'pet/petId'`
947
- */
948
- function toFilePath(name) {
949
- return name.split(/\.(?=[a-zA-Z])/).map((part) => camelCase(part)).filter(Boolean).join("/");
950
- }
951
- /** Throws `KUBB_PATH_TRAVERSAL` when `target` lies outside `parent`; `target === parent` stays allowed. */
952
- function assertInside({ target, parent, message, help }) {
953
- const parentWithSep = parent.endsWith(path.sep) ? parent : `${parent}${path.sep}`;
954
- if (target === parent || target.startsWith(parentWithSep)) return;
955
- throw new Diagnostics.Error({
956
- code: Diagnostics.code.pathTraversal,
957
- severity: "error",
958
- message,
959
- help,
960
- location: { kind: "config" }
961
- });
962
- }
963
- /**
964
- * Built-in `file.baseName`: casts the identifier with `toFilePath` and appends the extension.
965
- */
966
- function toBaseName({ name, extname }) {
967
- return `${toFilePath(name)}${extname}`;
968
- }
969
- /**
970
- * Base constraint for all plugin resolver objects.
971
- *
972
- * The built-in machinery lives under `default`. Generators call the top-level `name`, `file`,
973
- * and `imports`, and a plugin overrides `name` and `file` to set its conventions. Extend with
974
- * top-level helpers (`typeName`, …) and/or grouped namespaces (`query`, `schema`, …).
975
- *
976
- * @example Top-level helper
977
- * ```ts
978
- * type MyResolver = Resolver & {
979
- * typeName(name: string): string
980
- * }
981
- * ```
982
- *
983
- * @example Grouped namespace
984
- * ```ts
985
- * type MyResolver = Resolver & {
986
- * query: {
987
- * name(node: OperationNode): string
988
- * keyName(node: OperationNode): string
989
- * }
990
- * }
991
- * ```
992
- */
993
- var Resolver = class Resolver {
994
- static #patternCache = /* @__PURE__ */ new Map();
995
- static #optionsCache = /* @__PURE__ */ new WeakMap();
996
- pluginName;
997
- /** The built-in machinery, untouched by `name`/`file` overrides and built once since the driver reads it per node. */
998
- default;
999
- #options;
1000
- #baseName;
1001
- #filePath;
1002
- constructor(options) {
1003
- this.pluginName = options.pluginName;
1004
- this.#options = options;
1005
- this.#baseName = options.file?.baseName ? options.file.baseName.bind(this) : toBaseName;
1006
- this.#filePath = options.file?.path ? options.file.path.bind(this) : void 0;
1007
- this.default = {
1008
- name: camelCase,
1009
- options: this.#resolveOptions.bind(this),
1010
- path: this.#resolvePath.bind(this),
1011
- file: this.#resolveFile.bind(this),
1012
- banner: this.#resolveBanner.bind(this),
1013
- footer: this.#resolveFooter.bind(this)
1014
- };
1015
- this.#apply(options);
1016
- }
1017
- /** Exposes the raw build options so `Resolver.merge` can read them across `@kubb/core` copies. */
1018
- get [resolverOptions]() {
1019
- return this.#options;
1020
- }
1021
- name(name) {
1022
- return this.default.name(name);
1023
- }
1024
- file(options) {
1025
- return this.#resolveFile(options);
1026
- }
1027
- /**
1028
- * Builds one `ImportNode` per unique schema referenced in the tree, in first-occurrence
1029
- * order. Each ref's target resolves through `resolveRefName`, so collision- or macro-renamed
1030
- * schemas (`targetName`) import the emitted name. Names and paths go through the top-level
1031
- * `name` and `file`, so import entries follow the plugin's conventions, and a per-call
1032
- * `name` override wins over both.
1033
- *
1034
- * The subtree scan runs through `collectImportedRefNames`, which memoizes by node identity, so a
1035
- * schema shared across the ts, zod, and faker plugins is walked once and every plugin's resolver
1036
- * reads the same ref set instead of re-scanning it per plugin.
1037
- */
1038
- imports(options) {
1039
- const { node, root, output, group, extname = ".ts", name } = options;
1040
- const resolveName = name ?? ((schemaName) => this.name(schemaName));
1041
- return collectImportedRefNames(node).map((schemaName) => ast.factory.createImport({
1042
- name: [resolveName(schemaName)],
1043
- path: this.file({
1044
- name: schemaName,
1045
- extname,
1046
- root,
1047
- output,
1048
- group
1049
- }).path
1050
- }));
1051
- }
1052
- /**
1053
- * Folds each `override` over `base`, left to right, and returns a new resolver with helpers
1054
- * re-bound. Top-level keys replace, and a namespace (or `file`) merges per method, so overriding
1055
- * `query.name` keeps the base `query.keyName`. The last override wins per key. Used when applying
1056
- * `setResolver` partial overrides, and to compose shared resolver fragments without spreading each
1057
- * namespace by hand. Reads a resolver's options through the shared brand rather than `instanceof`,
1058
- * so a `file` override survives even when `base` and `override` come from different `@kubb/core`
1059
- * copies.
1060
- *
1061
- * @example Fold several partial overrides onto a resolver
1062
- * ```ts
1063
- * const resolver = Resolver.merge(defaultResolver, sharedNamingPatch, { name: (name) => name.toUpperCase() })
1064
- * ```
1065
- */
1066
- static merge(base, ...overrides) {
1067
- const merged = overrides.reduce((acc, override) => {
1068
- const patch = resolverOptions in override ? override[resolverOptions] : override;
1069
- for (const [key, value] of Object.entries(patch)) {
1070
- if (value === void 0) continue;
1071
- const current = acc[key];
1072
- acc[key] = isNamespace(value) && isNamespace(current) ? {
1073
- ...current,
1074
- ...value
1075
- } : value;
1076
- }
1077
- return acc;
1078
- }, { ...base[resolverOptions] });
1079
- return new Resolver(merged);
1080
- }
1081
- /**
1082
- * Binds each entry of `options` onto the resolver, so `this.name`, `this.default`, and
1083
- * `this.file` resolve there for top-level helpers and namespace methods alike. `default`
1084
- * is skipped so it can't be shadowed.
1085
- */
1086
- #apply(options) {
1087
- const root = this;
1088
- const bind = (value) => typeof value === "function" ? value.bind(root) : value;
1089
- for (const [key, value] of Object.entries(options)) {
1090
- if (key === "pluginName" || key === "default" || key === "file" || value === void 0) continue;
1091
- root[key] = isNamespace(value) ? Object.fromEntries(Object.entries(value).map(([method, member]) => [method, bind(member)])) : bind(value);
1092
- }
1093
- }
1094
- static #testPattern(value, pattern) {
1095
- if (typeof pattern === "string") {
1096
- let regex = Resolver.#patternCache.get(pattern);
1097
- regex ??= new RegExp(pattern);
1098
- Resolver.#patternCache.set(pattern, regex);
1099
- return regex.test(value);
1100
- }
1101
- return value.match(pattern) !== null;
1102
- }
1103
- static #matchesOperation(node, { type, pattern }) {
1104
- if (type === "tag") return node.tags.some((tag) => Resolver.#testPattern(tag, pattern));
1105
- if (type === "operationId") return Resolver.#testPattern(node.operationId, pattern);
1106
- if (type === "path") return node.path !== void 0 && Resolver.#testPattern(node.path, pattern);
1107
- if (type === "method") return node.method !== void 0 && Resolver.#testPattern(node.method.toLowerCase(), pattern);
1108
- if (type === "contentType") return node.requestBody?.content?.some((c) => Resolver.#testPattern(c.contentType, pattern)) ?? false;
1109
- return false;
1110
- }
1111
- /**
1112
- * Returns `null` when the filter type doesn't apply to schemas, so include rules built
1113
- * from operation filters (e.g. `tag`) don't exclude every schema.
1114
- */
1115
- static #matchesSchema(node, { type, pattern }) {
1116
- if (type === "schemaName") return node.name ? Resolver.#testPattern(node.name, pattern) : false;
1117
- return null;
1118
- }
1119
- static #computeOptions(node, { options, exclude = [], include, override = [] }) {
1120
- if (operationDef.is(node)) {
1121
- if (exclude.some((filter) => Resolver.#matchesOperation(node, filter))) return null;
1122
- if (include && !include.some((filter) => Resolver.#matchesOperation(node, filter))) return null;
1123
- return {
1124
- ...options,
1125
- ...override.find((filter) => Resolver.#matchesOperation(node, filter))?.options
1126
- };
1127
- }
1128
- if (schemaDef.is(node)) {
1129
- if (exclude.some((filter) => Resolver.#matchesSchema(node, filter) === true)) return null;
1130
- if (include) {
1131
- const applicable = include.map((filter) => Resolver.#matchesSchema(node, filter)).filter((result) => result !== null);
1132
- if (applicable.length > 0 && !applicable.includes(true)) return null;
1133
- }
1134
- return {
1135
- ...options,
1136
- ...override.find((filter) => Resolver.#matchesSchema(node, filter) === true)?.options
1137
- };
1138
- }
1139
- return options;
1140
- }
1141
- /**
1142
- * Applies include/exclude filters and merges matching override options, caching the result
1143
- * per `(options, node)` pair. Returns `null` when the node is filtered out.
1144
- */
1145
- #resolveOptions(node, context) {
1146
- const { options } = context;
1147
- if (typeof options !== "object" || options === null) return Resolver.#computeOptions(node, context);
1148
- let byOptions = Resolver.#optionsCache.get(options);
1149
- if (!byOptions) {
1150
- byOptions = /* @__PURE__ */ new WeakMap();
1151
- Resolver.#optionsCache.set(options, byOptions);
1152
- }
1153
- const cached = byOptions.get(node);
1154
- if (cached) return cached.value;
1155
- const result = Resolver.#computeOptions(node, context);
1156
- byOptions.set(node, { value: result });
1157
- return result;
1158
- }
1159
- /**
1160
- * A custom `group.name` wins; otherwise `tag` groups use the camelCased tag and `path`
1161
- * groups use the first non-traversal segment (`''` when none remain, placing the file in
1162
- * the output root, kept safe by the caller's boundary check).
1163
- */
1164
- static #resolveGroupDir(group, groupValue) {
1165
- if (group.name) return group.name({ group: groupValue });
1166
- if (group.type === "tag") return camelCase(groupValue);
1167
- const segment = groupValue.split("/").filter((part) => part !== "" && part !== "." && part !== "..")[0];
1168
- return segment ? camelCase(segment) : "";
1169
- }
1170
- /**
1171
- * `mode: 'file'` (default) resolves directly to `output.path`. `mode: 'directory'` resolves
1172
- * to `output.path/{baseName}`, or into a subdirectory when `group` and a `tag`/`path` value
1173
- * are provided.
1174
- */
1175
- #resolvePath({ baseName, tag, path: groupPath, root, output, group }) {
1176
- if (output.mode !== "directory") return path.resolve(root, output.path);
1177
- const outputDir = path.resolve(root, output.path);
1178
- const result = group && (groupPath || tag) ? path.resolve(outputDir, Resolver.#resolveGroupDir(group, group.type === "path" ? groupPath : tag), baseName) : path.resolve(outputDir, baseName);
1179
- assertInside({
1180
- target: result,
1181
- parent: outputDir,
1182
- message: `Resolved path "${result}" is outside the output directory "${outputDir}".`,
1183
- 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."
1184
- });
1185
- return result;
1186
- }
1187
- /**
1188
- * Resolves a resolver-supplied full path (`file.path`) against `root`, bypassing `output.path`
1189
- * and `group`. The path may not escape `root`, which keeps a `file.path` that interpolates
1190
- * spec-derived values from writing outside the project.
1191
- */
1192
- #resolveOverridePath(filePath, root) {
1193
- const resolved = path.resolve(root, filePath);
1194
- assertInside({
1195
- target: resolved,
1196
- parent: root,
1197
- message: `Resolved path "${resolved}" is outside the project root "${root}".`,
1198
- help: "A resolver `file.path` must return a path inside the project root."
1199
- });
1200
- return resolved;
1201
- }
1202
- /**
1203
- * Builds a `FileNode`. When `#filePath` (the resolver's `file.path`) is set it owns the whole
1204
- * path; otherwise the base name (from `#baseName`, the resolver's `file.baseName` or the
1205
- * built-in `toBaseName`) is placed by the `output.path`/`group` layout. The resolved file starts
1206
- * with empty `sources`, `imports`, and `exports`, which consumers populate separately.
1207
- */
1208
- #resolveFile(options) {
1209
- const { name, extname, tag, path: groupPath, root, output, group } = options;
1210
- const baseName = this.#baseName({
1211
- name,
1212
- extname
1213
- });
1214
- const filePath = this.#filePath ? this.#resolveOverridePath(this.#filePath({
1215
- baseName,
1216
- output
1217
- }), root) : this.#resolvePath({
1218
- baseName,
1219
- tag,
1220
- path: groupPath,
1221
- root,
1222
- output,
1223
- group
1224
- });
1225
- return ast.factory.createFile({
1226
- path: filePath,
1227
- baseName: path.basename(filePath),
1228
- meta: { pluginName: this.pluginName },
1229
- sources: [],
1230
- imports: [],
1231
- exports: []
1232
- });
1233
- }
1234
- /**
1235
- * Missing fields default to empty/`false` so the `BannerMeta` shape stays stable even when
1236
- * a caller (e.g. the barrel plugin) has no document metadata.
1237
- */
1238
- static #buildBannerMeta(meta, file) {
1239
- return {
1240
- title: meta?.title,
1241
- description: meta?.description,
1242
- version: meta?.version,
1243
- baseURL: meta?.baseURL,
1244
- circularNames: meta?.circularNames ?? [],
1245
- enumNames: meta?.enumNames ?? [],
1246
- filePath: file?.path ?? "",
1247
- baseName: file?.baseName ?? "",
1248
- isBarrel: file?.isBarrel ?? false,
1249
- isAggregation: file?.isAggregation ?? false
1250
- };
1251
- }
1252
- /**
1253
- * Resolves a user-configured banner/footer value. `undefined` means not configured.
1254
- */
1255
- static #resolveUserText(value, meta, file) {
1256
- if (typeof value === "function") return value(Resolver.#buildBannerMeta(meta, file));
1257
- if (typeof value === "string") return value;
1258
- }
1259
- static #buildDefaultBanner({ title, version, config }) {
1260
- const lines = [
1261
- "/**",
1262
- "* Generated by Kubb (https://kubb.dev/).",
1263
- "* Do not edit manually."
1264
- ];
1265
- if (config.output.defaultBanner !== "simple") {
1266
- const input = config.input;
1267
- const source = typeof input === "string" ? getInputKind(input) === "inline" ? "text content" : path.basename(input) : input ? "text content" : "";
1268
- if (source) lines.push(`* Source: ${source}`);
1269
- if (title) lines.push(`* Title: ${title}`);
1270
- if (version) lines.push(`* OpenAPI spec version: ${version}`);
1271
- }
1272
- return `${lines.join("\n")}\n*/\n`;
1273
- }
1274
- /**
1275
- * A user-supplied `output.banner` overrides the default Kubb notice. When
1276
- * `config.output.defaultBanner` is `false` and no user banner is set, returns `null`.
1277
- */
1278
- #resolveBanner(meta, { output, config, file }) {
1279
- const userBanner = Resolver.#resolveUserText(output?.banner, meta, file);
1280
- if (userBanner !== void 0) return userBanner;
1281
- if (config.output.defaultBanner === false) return null;
1282
- return Resolver.#buildDefaultBanner({
1283
- title: meta?.title,
1284
- version: meta?.version,
1285
- config
1286
- });
1287
- }
1288
- #resolveFooter(meta, { output, file }) {
1289
- return Resolver.#resolveUserText(output?.footer, meta, file) ?? null;
1290
- }
1291
- };
1292
- //#endregion
1293
- //#region src/createResolver.ts
1294
- /**
1295
- * Defines a plugin resolver, the object that decides what every generated symbol and file
1296
- * path is called. Override the top-level `name` and `file` to set the plugin's conventions,
1297
- * and add your own naming helpers, top-level (`typeName`, …) or grouped in namespaces
1298
- * (`query`, `schema`, …). Every method reaches sibling helpers and the built-in machinery
1299
- * through `this.name`, `this.file`, and `this.default`.
1300
- *
1301
- * @example Custom identifier casing
1302
- * ```ts
1303
- * export const resolverTs = createResolver<PluginTs>({
1304
- * pluginName: 'plugin-ts',
1305
- * name(name) {
1306
- * return ensureValidVarName(pascalCase(name))
1307
- * },
1308
- * })
1309
- * ```
1310
- *
1311
- * @example Rename generated files with `file.baseName`
1312
- * ```ts
1313
- * export const resolverFaker = createResolver<PluginFaker>({
1314
- * pluginName: 'plugin-faker',
1315
- * name(name) {
1316
- * return camelCase(name, { prefix: 'create' })
1317
- * },
1318
- * file: {
1319
- * baseName({ name, extname }) {
1320
- * return `${camelCase(name, { prefix: 'create' })}${extname}`
1321
- * },
1322
- * },
1323
- * })
1324
- * ```
1325
- *
1326
- * @example Own the full path with `file.path`
1327
- * ```ts
1328
- * export const resolverFaker = createResolver<PluginFaker>({
1329
- * pluginName: 'plugin-faker',
1330
- * file: {
1331
- * path({ baseName, output }) {
1332
- * return `${output.path}/mocks/${baseName}`
1333
- * },
1334
- * },
1335
- * })
1336
- * ```
1337
- */
1338
- function createResolver(options) {
1339
- return new Resolver(options);
1340
- }
1341
- //#endregion
1342
- //#region src/Transform.ts
1343
- /**
1344
- * Holds an ordered list of macros per plugin, keyed by plugin name. Each plugin's macros run in
1345
- * isolation on the original adapter node and are composed into a single `Visitor` that the
1346
- * `@kubb/ast` `transform` primitive applies. `applyTo` is a per-plugin lookup, not a cross-plugin
1347
- * chain, so plugin A's macros never see plugin B's output. When a plugin has no macros, `applyTo`
1348
- * returns the original node reference, and `transform` does the same when the composed visitor
1349
- * leaves the tree untouched, so callers can detect a no-op by identity.
1350
- *
1351
- * Registration order matches the order setup hooks fire, which the driver has already sorted by
1352
- * `enforce` and dependency edges. The registry preserves that order. Macro `enforce` only reorders
1353
- * within a single plugin's list.
1354
- */
1355
- var Transform = class {
1356
- #macros = /* @__PURE__ */ new Map();
1357
- #composed = /* @__PURE__ */ new Map();
1358
- #memo = /* @__PURE__ */ new Map();
1359
- /**
1360
- * Appends `macro` to the plugin's list, after any macros already registered.
1361
- */
1362
- add(pluginName, macro) {
1363
- const list = this.#macros.get(pluginName);
1364
- if (list) list.push(macro);
1365
- else this.#macros.set(pluginName, [macro]);
1366
- this.#invalidate(pluginName);
1367
- }
1368
- /**
1369
- * Replaces the plugin's macro list with `macros`.
1370
- */
1371
- set(pluginName, macros) {
1372
- this.#macros.set(pluginName, [...macros]);
1373
- this.#invalidate(pluginName);
1374
- }
1375
- /**
1376
- * Runs the plugin's macros on `node`. Returns the original node reference when the plugin has no
1377
- * macros, so callers can compare by identity to detect a no-op.
1378
- */
1379
- applyTo(pluginName, node) {
1380
- const visitor = this.#visitorFor(pluginName);
1381
- if (!visitor) return node;
1382
- let memo = this.#memo.get(pluginName);
1383
- if (!memo) {
1384
- memo = /* @__PURE__ */ new WeakMap();
1385
- this.#memo.set(pluginName, memo);
1386
- }
1387
- const cached = memo.get(node);
1388
- if (cached) return cached;
1389
- const result = transform(node, visitor);
1390
- memo.set(node, result);
1391
- return result;
1392
- }
1393
- /**
1394
- * Clears every registration. Called from the driver's `dispose()` so macros do not leak across
1395
- * builds.
1396
- */
1397
- dispose() {
1398
- this.#macros.clear();
1399
- this.#composed.clear();
1400
- this.#memo.clear();
1401
- }
1402
- #invalidate(pluginName) {
1403
- this.#composed.delete(pluginName);
1404
- this.#memo.delete(pluginName);
1405
- }
1406
- #visitorFor(pluginName) {
1407
- const macros = this.#macros.get(pluginName);
1408
- if (!macros || macros.length === 0) return void 0;
1409
- let composed = this.#composed.get(pluginName);
1410
- if (!composed) {
1411
- composed = composeMacros(macros);
1412
- this.#composed.set(pluginName, composed);
1413
- }
1414
- return composed;
1415
- }
1416
- };
1417
- //#endregion
1418
- //#region src/KubbDriver.ts
1419
- const ENFORCE_ORDER = {
1420
- pre: -1,
1421
- post: 1
1422
- };
1423
- /** `include` filter types that select operations, and so prune the schemas they do not reach. */
1424
- const OPERATION_FILTER_TYPES = /* @__PURE__ */ new Set([
1425
- "tag",
1426
- "operationId",
1427
- "path",
1428
- "method",
1429
- "contentType"
1430
- ]);
1431
- const enforceWeight = (plugin) => plugin.enforce ? ENFORCE_ORDER[plugin.enforce] : 0;
1432
- /**
1433
- * The options bag a `NormalizedPlugin` starts with before a plugin refines it: a directory output
1434
- * at the plugin root and empty filter lists.
1435
- */
1436
- const defaultPluginOptions = () => ({
1437
- output: {
1438
- path: ".",
1439
- mode: "directory"
1440
- },
1441
- exclude: [],
1442
- override: []
1443
- });
1444
- /**
1445
- * Fills in the `output`, `exclude`, and `override` a `NormalizedPlugin` needs from a plugin's raw
1446
- * options, running `output` through `normalizeOutput`. Idempotent, so the driver can apply it after
1447
- * `setOptions` has already run without disturbing an already-normalized bag.
1448
- */
1449
- function normalizePluginOptions(rawOptions, pluginName) {
1450
- const options = {
1451
- ...defaultPluginOptions(),
1452
- ...rawOptions ?? {}
1453
- };
1454
- const group = "group" in options ? options.group : void 0;
1455
- options.output = normalizeOutput({
1456
- output: options.output,
1457
- group,
1458
- pluginName
1459
- });
1460
- return options;
1461
- }
1462
- var KubbDriver = class {
1463
- config;
1464
- options;
1465
- /**
1466
- * The `InputNode` produced by the adapter. Set after adapter setup.
1467
- */
1468
- inputNode = null;
1469
- adapter = null;
1470
- /**
1471
- * Raw adapter source so `adapter.parse()` can run lazily.
1472
- * Intentionally outlives the build, cleared by `dispose()`.
1473
- */
1474
- #adapterSource = null;
1475
- /**
1476
- * Central file store for all generated files.
1477
- * Plugins should use `this.addFile()` / `this.upsertFile()` (via their context) to
1478
- * add files. This property gives direct read/write access when needed.
1479
- */
1480
- fileManager = new FileManager();
1481
- plugins = /* @__PURE__ */ new Map();
1482
- /**
1483
- * Removers for every listener the driver added (plugin, generator) so `dispose()` can detach
1484
- * them in one pass. External `hooks.hook(...)` listeners are not tracked.
1485
- */
1486
- #unhooks = [];
1487
- /**
1488
- * Transform registry. Plugins populate it during `kubb:plugin:setup` via `addMacro`/`setMacros`,
1489
- * and `#runGenerators` reads it once per `(plugin, node)` pair through `applyTo`.
1490
- */
1491
- #transforms = new Transform();
1492
- constructor(config, options) {
1493
- this.config = config;
1494
- this.options = options;
1495
- this.adapter = config.adapter ?? null;
1496
- }
1497
- /**
1498
- * Normalizes every configured plugin, orders them, and registers their lifecycle handlers.
1499
- * A plugin that another lists as a dependency runs first, then `enforce: 'pre'` before
1500
- * `'post'`. When the config has an adapter, the adapter source is resolved from the input
1501
- * so `run` can parse it later.
1502
- */
1503
- async setup() {
1504
- this.options.signal?.throwIfAborted();
1505
- const normalized = this.#sortPlugins(this.config.plugins.map((rawPlugin) => {
1506
- return {
1507
- name: rawPlugin.name,
1508
- dependencies: rawPlugin.dependencies,
1509
- enforce: rawPlugin.enforce,
1510
- hooks: rawPlugin.hooks,
1511
- options: rawPlugin.options ?? defaultPluginOptions(),
1512
- resolver: createResolver({ pluginName: rawPlugin.name })
1513
- };
1514
- }));
1515
- for (const plugin of normalized) {
1516
- this.#registerPlugin(plugin);
1517
- this.plugins.set(plugin.name, plugin);
1518
- }
1519
- if (this.config.adapter) this.#adapterSource = inputToAdapterSource(this.config);
1520
- }
1521
- /**
1522
- * Orders plugins so every dependency runs before its dependents (Kahn's algorithm), with
1523
- * `enforce` (`'pre'` before normal before `'post'`) and declaration order as tiebreaks.
1524
- * A pairwise `Array.sort` comparator cannot do this: dependency relations are not transitive
1525
- * at the comparator level, so a chain where A depends on B and B depends on C could come out
1526
- * wrong when A and C are never compared directly. Dependencies on plugins missing from the
1527
- * config are ignored here and surface later through `requirePlugin`.
1528
- */
1529
- #sortPlugins(plugins) {
1530
- const queue = [...plugins].sort((a, b) => enforceWeight(a) - enforceWeight(b));
1531
- const names = new Set(queue.map((plugin) => plugin.name));
1532
- const blockedBy = new Map(queue.map((plugin) => [plugin.name, new Set(plugin.dependencies?.filter((name) => names.has(name) && name !== plugin.name))]));
1533
- const sorted = [];
1534
- for (const _ of plugins) {
1535
- const index = queue.findIndex((plugin) => blockedBy.get(plugin.name)?.size === 0);
1536
- if (index === -1) throw new Diagnostics.Error({
1537
- code: Diagnostics.code.invalidPluginOptions,
1538
- severity: "error",
1539
- message: `Plugin dependencies form a cycle: ${queue.map((plugin) => plugin.name).join(" → ")}.`,
1540
- help: "Remove one of the `dependencies` entries so the plugins can be ordered.",
1541
- location: { kind: "config" }
1542
- });
1543
- const [plugin] = queue.splice(index, 1);
1544
- if (!plugin) break;
1545
- sorted.push(plugin);
1546
- for (const blockers of blockedBy.values()) blockers.delete(plugin.name);
1547
- }
1548
- return sorted;
1549
- }
1550
- get hooks() {
1551
- return this.options.hooks;
1552
- }
1553
- /**
1554
- * Parses the adapter source into `this.inputNode`. Idempotent, so repeated calls from
1555
- * `run` do not re-parse.
1556
- */
1557
- async #parseInput() {
1558
- if (this.inputNode || !this.adapter || !this.#adapterSource) return;
1559
- this.options.signal?.throwIfAborted();
1560
- this.inputNode = await this.adapter.parse(this.#adapterSource, { signal: this.options.signal });
1561
- }
1562
- /**
1563
- * Registers a plugin's lifecycle hooks on the shared `Hookable` as pass-through listeners that
1564
- * external tooling can observe via `hooks.hook(...)`. The returned remover is tracked for
1565
- * `dispose`. `kubb:plugin:setup` is skipped here; `setupHooks` invokes it directly with a
1566
- * plugin-scoped context.
1567
- *
1568
- * @internal
1569
- */
1570
- #registerPlugin(plugin) {
1571
- const { hooks } = plugin;
1572
- if (!hooks) return;
1573
- const { "kubb:plugin:setup": _setup, ...configHooks } = hooks;
1574
- this.#unhooks.push(this.hooks.addHooks(configHooks));
1575
- }
1576
- /**
1577
- * Runs each plugin's `kubb:plugin:setup` handler, in plugin order, with a context scoped to that
1578
- * plugin so `addGenerator`, `setResolver`, `addMacro`, `setMacros`, and `setOptions` target its
1579
- * `NormalizedPlugin` entry. Called once from `run` before the plugin execution loop begins, so
1580
- * plugins can configure generators, resolvers, macros, and options before `buildStart`.
1581
- */
1582
- async setupHooks() {
1583
- for (const plugin of this.plugins.values()) {
1584
- const setup = plugin.hooks?.["kubb:plugin:setup"];
1585
- if (!setup) continue;
1586
- await setup({
1587
- config: this.config,
1588
- options: plugin.options ?? {},
1589
- addGenerator: (...generators) => {
1590
- plugin.generators = [...plugin.generators ?? [], ...generators];
1591
- },
1592
- setResolver: (resolver) => {
1593
- plugin.resolver = Resolver.merge(createResolver({ pluginName: plugin.name }), resolver);
1594
- },
1595
- addMacro: (macro) => {
1596
- this.#transforms.add(plugin.name, macro);
1597
- },
1598
- setMacros: (macros) => {
1599
- this.#transforms.set(plugin.name, macros);
1600
- },
1601
- setOptions: (opts) => {
1602
- plugin.options = normalizePluginOptions({
1603
- ...plugin.options,
1604
- ...opts
1605
- }, plugin.name);
1606
- },
1607
- injectFile: (userFileNode) => {
1608
- this.fileManager.add(ast.factory.createFile(userFileNode));
1609
- }
1610
- });
1611
- }
1612
- }
1613
- /** `true` once `addGenerator()` in `kubb:plugin:setup` registered a generator for the plugin. */
1614
- hasHookGenerators(pluginName) {
1615
- return (this.plugins.get(pluginName)?.generators?.length ?? 0) > 0;
1616
- }
1617
- /**
1618
- * Runs the full plugin pipeline. Returns the diagnostics collected so far even
1619
- * when an outer hook throws, since the orchestrator preserves partial state by capturing
1620
- * the failure as a {@link Diagnostic} instead of propagating. Each plugin also
1621
- * contributes a `timing` diagnostic for the run summary.
1622
- */
1623
- async run() {
1624
- const { hooks, config, fileManager } = this;
1625
- const diagnostics = [];
1626
- const parsersMap = /* @__PURE__ */ new Map();
1627
- for (const parser of config.parsers) if (parser.extNames) for (const ext of parser.extNames) parsersMap.set(ext, parser);
1628
- const updateBuffer = [];
1629
- const unhookWrites = fileManager.hooks.addHooks({
1630
- start: async (files) => {
1631
- await hooks.callHook("kubb:files:processing:start", { files });
1632
- },
1633
- update: ({ file, processed, total, percentage }) => {
1634
- updateBuffer.push({
1635
- file,
1636
- processed,
1637
- total,
1638
- percentage,
1639
- config
1640
- });
1641
- },
1642
- end: async (files) => {
1643
- updateBuffer.sort((a, b) => a.processed - b.processed);
1644
- await hooks.callHook("kubb:files:processing:update", { files: updateBuffer });
1645
- updateBuffer.length = 0;
1646
- await hooks.callHook("kubb:files:processing:end", { files });
1647
- }
1648
- });
1649
- return Diagnostics.scope((diagnostic) => diagnostics.push(diagnostic), async () => {
1650
- try {
1651
- this.options.signal?.throwIfAborted();
1652
- const outputRoot = resolve(config.root, config.output.path);
1653
- await this.#parseInput();
1654
- await this.setupHooks();
1655
- for (const plugin of this.plugins.values()) {
1656
- this.options.signal?.throwIfAborted();
1657
- plugin.options = normalizePluginOptions(plugin.options, plugin.name);
1658
- }
1659
- if (this.adapter && this.inputNode) {
1660
- const buildStartContext = this.#withFiles({
1661
- config,
1662
- adapter: this.adapter,
1663
- meta: this.inputNode.meta,
1664
- getPlugin: this.getPlugin.bind(this)
1665
- });
1666
- await hooks.callHook("kubb:build:start", buildStartContext);
1667
- }
1668
- const generatorPlugins = [];
1669
- for (const plugin of this.plugins.values()) {
1670
- const context = this.getContext(plugin);
1671
- const hrStart = process.hrtime();
1672
- try {
1673
- await hooks.callHook("kubb:plugin:start", { plugin });
1674
- } catch (caughtError) {
1675
- const error = toError(caughtError);
1676
- const duration = getElapsedMs(hrStart);
1677
- await this.#emitPluginEnd({
1678
- plugin,
1679
- duration,
1680
- success: false,
1681
- error
1682
- });
1683
- diagnostics.push({
1684
- ...Diagnostics.from(error),
1685
- plugin: plugin.name
1686
- }, Diagnostics.performance({
1687
- plugin: plugin.name,
1688
- duration
1689
- }));
1690
- continue;
1691
- }
1692
- if (this.hasHookGenerators(plugin.name)) {
1693
- generatorPlugins.push({
1694
- plugin,
1695
- context,
1696
- hrStart
1697
- });
1698
- continue;
1699
- }
1700
- const duration = getElapsedMs(hrStart);
1701
- diagnostics.push(Diagnostics.performance({
1702
- plugin: plugin.name,
1703
- duration
1704
- }));
1705
- await this.#emitPluginEnd({
1706
- plugin,
1707
- duration,
1708
- success: true
1709
- });
1710
- }
1711
- diagnostics.push(...await this.#runGenerators(generatorPlugins));
1712
- await hooks.callHook("kubb:plugins:end", this.#withFiles({ config }));
1713
- await fileManager.write(fileManager.files, {
1714
- storage: config.storage,
1715
- parsers: parsersMap,
1716
- manifest: this.options.manifest,
1717
- signal: this.options.signal
1718
- });
1719
- await hooks.callHook("kubb:build:end", {
1720
- files: this.fileManager.files,
1721
- config,
1722
- outputDir: outputRoot
1723
- });
1724
- return { diagnostics: Diagnostics.dedupe(diagnostics) };
1725
- } catch (caughtError) {
1726
- diagnostics.push(Diagnostics.from(caughtError));
1727
- return { diagnostics: Diagnostics.dedupe(diagnostics) };
1728
- } finally {
1729
- unhookWrites();
1730
- }
1731
- });
1732
- }
1733
- /**
1734
- * Widens `extra` with the files present at emit time and a bound `upsertFile`, the shape every
1735
- * file-carrying hook context shares. Building it here in one place keeps the `files` and
1736
- * `upsertFile` keys from being dropped by a stray spread at the call site.
1737
- */
1738
- #withFiles(extra) {
1739
- return {
1740
- ...extra,
1741
- files: this.fileManager.files,
1742
- upsertFile: (...files) => this.fileManager.upsert(...files)
1743
- };
1744
- }
1745
- #emitPluginEnd({ plugin, duration, success, error }) {
1746
- return this.hooks.callHook("kubb:plugin:end", this.#withFiles({
1747
- plugin,
1748
- duration,
1749
- success,
1750
- ...error ? { error } : {},
1751
- config: this.config
1752
- }));
1753
- }
1754
- /**
1755
- * Runs schemas and operations through every plugin's generators. The walk is node-outer: each
1756
- * schema is visited once and each operation once, and the node fans out to the matching
1757
- * generators of every plugin in dependency order. A per-node cache (`createNodeCache`) is created
1758
- * once per node and shared by all of that node's plugins, so node-derived work is computed once
1759
- * and reused instead of recomputed per plugin. Each node still runs through the plugin's macros
1760
- * (from `this.#transforms`) and its exclude/include/override filters before that plugin's
1761
- * generator sees it, so plugins stay isolated. Schemas run before operations so file output
1762
- * stays deterministic across runs. A generator with a `match` predicate that resolves `false`
1763
- * for a node is skipped for that node, without calling `schema`/`operation`.
1764
- *
1765
- * A failing plugin is dropped from the remaining walk, contributes an error diagnostic, and no
1766
- * longer aborts the other plugins. `kubb:plugin:end` and each plugin's `timing` diagnostic fire
1767
- * in dependency order once the walk finishes, driving the CLI's `Plugins N/M` counter. The
1768
- * `operations` batch fires once per plugin after the single operation walk.
1769
- *
1770
- * When `this.inputNode` is `null`, every entry still gets a `kubb:plugin:end` so
1771
- * post-plugin listeners (the barrel writer and friends) complete.
1772
- */
1773
- async #runGenerators(entries) {
1774
- const diagnostics = [];
1775
- if (entries.length === 0) return diagnostics;
1776
- if (!this.inputNode) {
1777
- for (const { plugin, hrStart } of entries) {
1778
- const duration = getElapsedMs(hrStart);
1779
- diagnostics.push(Diagnostics.performance({
1780
- plugin: plugin.name,
1781
- duration
1782
- }));
1783
- await this.#emitPluginEnd({
1784
- plugin,
1785
- duration,
1786
- success: true
1787
- });
1788
- }
1789
- return diagnostics;
1790
- }
1791
- const transforms = this.#transforms;
1792
- const { schemas, operations } = this.inputNode;
1793
- const allowedSchemaNamesByPlugin = /* @__PURE__ */ new Map();
1794
- for (const { plugin } of entries) {
1795
- const { exclude, include, override } = plugin.options;
1796
- if (!((include?.some(({ type }) => OPERATION_FILTER_TYPES.has(type)) ?? false) && !(include?.some(({ type }) => type === "schemaName") ?? false))) continue;
1797
- const resolver = this.getResolver(plugin.name);
1798
- const includedOps = operations.filter((operation) => resolver.default.options(operation, {
1799
- options: plugin.options,
1800
- exclude,
1801
- include,
1802
- override
1803
- }) !== null);
1804
- allowedSchemaNamesByPlugin.set(plugin.name, collectUsedSchemaNames(includedOps, schemas));
1805
- }
1806
- const states = entries.map(({ plugin, context, hrStart }) => {
1807
- const generatorContext = {
1808
- ...context,
1809
- resolver: this.getResolver(plugin.name)
1810
- };
1811
- const { exclude, include, override } = plugin.options;
1812
- const generators = plugin.generators ?? [];
1813
- return {
1814
- plugin,
1815
- hrStart,
1816
- generatorContext,
1817
- exclude,
1818
- include,
1819
- override,
1820
- optionsAreStatic: !exclude?.length && !include?.length && !override?.length,
1821
- allowedSchemaNames: allowedSchemaNamesByPlugin.get(plugin.name) ?? null,
1822
- schemaGenerators: generators.filter((generator) => generator.schema),
1823
- operationGenerators: generators.filter((generator) => generator.operation),
1824
- operationsGenerators: generators.filter((generator) => generator.operations),
1825
- pluginOperations: [],
1826
- error: null
1827
- };
1828
- });
1829
- const resolveForPlugin = (state, node) => {
1830
- const transformedNode = transforms.applyTo(state.plugin.name, node);
1831
- if (state.optionsAreStatic) return {
1832
- transformedNode,
1833
- options: state.plugin.options
1834
- };
1835
- const options = state.generatorContext.resolver.default.options(transformedNode, {
1836
- options: state.plugin.options,
1837
- exclude: state.exclude,
1838
- include: state.include,
1839
- override: state.override
1840
- });
1841
- if (options === null) return null;
1842
- return {
1843
- transformedNode,
1844
- options
1845
- };
1846
- };
1847
- for (const node of schemas) {
1848
- const cache = createNodeCache();
1849
- for (const state of states) {
1850
- if (state.error || !state.schemaGenerators.length) continue;
1851
- try {
1852
- const resolved = resolveForPlugin(state, node);
1853
- if (!resolved) continue;
1854
- const { transformedNode, options } = resolved;
1855
- if (state.allowedSchemaNames !== null && transformedNode.name && !state.allowedSchemaNames.has(transformedNode.name)) continue;
1856
- const ctx = {
1857
- ...state.generatorContext,
1858
- options,
1859
- cache
1860
- };
1861
- await this.#dispatchNode({
1862
- generators: state.schemaGenerators,
1863
- node: transformedNode,
1864
- ctx,
1865
- generate: (generator) => generator.schema(transformedNode, ctx)
1866
- });
1867
- await this.hooks.callHook("kubb:generate:schema", transformedNode, ctx);
1868
- } catch (caughtError) {
1869
- state.error = toError(caughtError);
1870
- }
1871
- }
1872
- }
1873
- for (const node of operations) {
1874
- const cache = createNodeCache();
1875
- for (const state of states) {
1876
- if (state.error || !state.operationGenerators.length && !state.operationsGenerators.length) continue;
1877
- try {
1878
- const resolved = resolveForPlugin(state, node);
1879
- if (!resolved) continue;
1880
- state.pluginOperations.push(resolved.transformedNode);
1881
- if (state.operationGenerators.length) {
1882
- const { transformedNode } = resolved;
1883
- const ctx = {
1884
- ...state.generatorContext,
1885
- options: resolved.options,
1886
- cache
1887
- };
1888
- await this.#dispatchNode({
1889
- generators: state.operationGenerators,
1890
- node: transformedNode,
1891
- ctx,
1892
- generate: (generator) => generator.operation(transformedNode, ctx)
1893
- });
1894
- await this.hooks.callHook("kubb:generate:operation", transformedNode, ctx);
1895
- }
1896
- } catch (caughtError) {
1897
- state.error = toError(caughtError);
1898
- }
1899
- }
1900
- }
1901
- for (const state of states) {
1902
- if (state.error || !state.operationsGenerators.length) continue;
1903
- try {
1904
- const ctx = {
1905
- ...state.generatorContext,
1906
- options: state.plugin.options,
1907
- cache: createNodeCache()
1908
- };
1909
- for (const generator of state.operationsGenerators) await this.dispatch({
1910
- result: await generator.operations(state.pluginOperations, ctx),
1911
- renderer: generator.renderer
1912
- });
1913
- await this.hooks.callHook("kubb:generate:operations", state.pluginOperations, ctx);
1914
- } catch (caughtError) {
1915
- state.error = toError(caughtError);
1916
- }
1917
- }
1918
- for (const state of states) {
1919
- const duration = getElapsedMs(state.hrStart);
1920
- await this.#emitPluginEnd({
1921
- plugin: state.plugin,
1922
- duration,
1923
- success: !state.error,
1924
- error: state.error ?? void 0
1925
- });
1926
- if (state.error) diagnostics.push({
1927
- ...Diagnostics.from(state.error),
1928
- plugin: state.plugin.name
1929
- });
1930
- diagnostics.push(Diagnostics.performance({
1931
- plugin: state.plugin.name,
1932
- duration
1933
- }));
1934
- }
1935
- return diagnostics;
1936
- }
1937
- /** Runs `node` through the generators whose `match` accepts it; `generate` picks the method for the node kind. */
1938
- async #dispatchNode({ generators, node, ctx, generate }) {
1939
- for (const generator of generators) {
1940
- if (!(generator.match ? await generator.match(node, ctx) : true)) continue;
1941
- await this.dispatch({
1942
- result: await generate(generator),
1943
- renderer: generator.renderer
1944
- });
1945
- }
1946
- }
1947
- /** Stores whatever a generator method or `kubb:generate:*` hook returned, see {@link FileManager.dispatch}. */
1948
- dispatch(params) {
1949
- return this.fileManager.dispatch(params);
1950
- }
1951
- /**
1952
- * Removes every listener the driver added. Listeners attached directly to `hooks` from outside
1953
- * the driver survive. Called at the end of a build to prevent leaks across repeated builds.
1954
- *
1955
- * @internal
1956
- */
1957
- dispose() {
1958
- for (const unhook of this.#unhooks) unhook();
1959
- this.#unhooks.length = 0;
1960
- this.#transforms.dispose();
1961
- this.fileManager.dispose();
1962
- this.inputNode = null;
1963
- this.#adapterSource = null;
1964
- }
1965
- [Symbol.dispose]() {
1966
- this.dispose();
1967
- }
1968
- getResolver(pluginName) {
1969
- return this.plugins.get(pluginName)?.resolver ?? createResolver({ pluginName });
1970
- }
1971
- getContext(plugin) {
1972
- const driver = this;
1973
- const report = (diagnostic) => {
1974
- Diagnostics.report({
1975
- ...diagnostic,
1976
- plugin: plugin.name
1977
- });
1978
- };
1979
- return {
1980
- config: driver.config,
1981
- signal: driver.options.signal,
1982
- get root() {
1983
- return resolve(driver.config.root, driver.config.output.path);
1984
- },
1985
- hooks: driver.hooks,
1986
- plugin,
1987
- getPlugin: driver.getPlugin.bind(driver),
1988
- requirePlugin: ((name) => driver.requirePlugin(name, { requiredBy: plugin.name })),
1989
- getResolver: driver.getResolver.bind(driver),
1990
- driver,
1991
- addFile: async (...files) => {
1992
- driver.fileManager.add(...files);
1993
- },
1994
- upsertFile: async (...files) => {
1995
- driver.fileManager.upsert(...files);
1996
- },
1997
- get meta() {
1998
- return driver.inputNode?.meta ?? {
1999
- circularNames: [],
2000
- enumNames: []
2001
- };
2002
- },
2003
- get adapter() {
2004
- return driver.adapter;
2005
- },
2006
- get resolver() {
2007
- return driver.getResolver(plugin.name);
2008
- },
2009
- warn(message) {
2010
- report({
2011
- code: Diagnostics.code.pluginWarning,
2012
- severity: "warning",
2013
- message
2014
- });
2015
- },
2016
- error(error) {
2017
- const cause = typeof error === "string" ? void 0 : error;
2018
- report({
2019
- code: Diagnostics.code.pluginFailed,
2020
- severity: "error",
2021
- message: typeof error === "string" ? error : error.message,
2022
- cause
2023
- });
2024
- },
2025
- info(message) {
2026
- report({
2027
- code: Diagnostics.code.pluginInfo,
2028
- severity: "info",
2029
- message
2030
- });
2031
- }
2032
- };
2033
- }
2034
- getPlugin(pluginName) {
2035
- return this.plugins.get(pluginName);
2036
- }
2037
- requirePlugin(pluginName, context) {
2038
- const plugin = this.getPlugin(pluginName);
2039
- if (plugin) return plugin;
2040
- const requiredBy = context?.requiredBy;
2041
- const by = requiredBy ? ` by "${requiredBy}"` : "";
2042
- const help = requiredBy ? ` (required by "${requiredBy}")` : "";
2043
- throw new Diagnostics.Error({
2044
- code: Diagnostics.code.pluginNotFound,
2045
- severity: "error",
2046
- message: `Plugin "${pluginName}" is required${by} but not found. Make sure it is included in your Kubb config.`,
2047
- help: `Add "${pluginName}" to the \`plugins\` array in kubb.config.ts${help}, or remove the dependency on it.`,
2048
- location: { kind: "config" }
2049
- });
2050
- }
2051
- };
2052
- //#endregion
2053
207
  //#region src/outputManifest.ts
2054
208
  /**
2055
209
  * Bumped when the stored shape changes, so an older cache is discarded instead of misread.
@@ -2548,23 +702,21 @@ var Kubb = class {
2548
702
  storage: config.storage,
2549
703
  cache: cacheStorage({ root: config.root })
2550
704
  }) : void 0;
705
+ this.hooks.setMaxListeners(Math.max(10, config.plugins.length * HOOK_LISTENERS_PER_PLUGIN));
706
+ const cleanPath = config.output.clean ? resolve(config.root, config.output.path) : void 0;
707
+ if (cleanPath && isPathInside(config.root, cleanPath)) throw new Diagnostics.Error({
708
+ code: Diagnostics.code.cleanRoot,
709
+ severity: "error",
710
+ message: `output.clean cannot delete "${cleanPath}" because it is the project root or a parent of it.`,
711
+ help: "Point `output.path` at a subdirectory such as `./src/gen` so clean only removes generated code.",
712
+ location: { kind: "config" }
713
+ });
2551
714
  const driver = new KubbDriver(config, {
2552
715
  hooks: this.hooks,
2553
716
  manifest,
2554
- signal
717
+ signal,
718
+ cleanPath
2555
719
  });
2556
- this.hooks.setMaxListeners(Math.max(10, config.plugins.length * HOOK_LISTENERS_PER_PLUGIN));
2557
- if (config.output.clean) {
2558
- const cleanPath = resolve(config.root, config.output.path);
2559
- if (isPathInside(config.root, cleanPath)) throw new Diagnostics.Error({
2560
- code: Diagnostics.code.cleanRoot,
2561
- severity: "error",
2562
- message: `output.clean cannot delete "${cleanPath}" because it is the project root or a parent of it.`,
2563
- help: "Point `output.path` at a subdirectory such as `./src/gen` so clean only removes generated code.",
2564
- location: { kind: "config" }
2565
- });
2566
- await config.storage.empty(cleanPath);
2567
- }
2568
720
  await driver.setup();
2569
721
  this.#driver = driver;
2570
722
  this.#manifest = manifest ?? null;
@@ -3224,6 +1376,6 @@ const memoryStorage = createStorage(() => {
3224
1376
  };
3225
1377
  });
3226
1378
  //#endregion
3227
- export { Diagnostics, Hookable, KubbDriver, Resolver, applyConfigDefaults, cacheStorage, cliReporter, createAdapter, createCliReporter, createKubb, createRenderer, createReporter, createResolver, createStorage, defineGenerator, defineParser, definePlugin, fileReporter, fsStorage, getInputKind, htmlReporter, jsonReporter, kubbStorage, logLevel, memoryStorage, resolveCacheDir, resolveKubbDir, runHook, runOutputPasses };
1379
+ export { Diagnostics, Hookable, KubbDriver, Resolver, applyConfigDefaults, assertPluginOption, cacheStorage, cliReporter, createAdapter, createCliReporter, createKubb, createRenderer, createReporter, createResolver, createStorage, defineGenerator, defineParser, definePlugin, fileReporter, fsStorage, getInputKind, htmlReporter, jsonReporter, kubbStorage, logLevel, memoryStorage, resolveCacheDir, resolveKubbDir, runHook, runOutputPasses };
3228
1380
 
3229
1381
  //# sourceMappingURL=index.js.map