@kubb/core 5.5.6 → 5.6.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.
package/dist/index.cjs CHANGED
@@ -1,17 +1,18 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_usingCtx = require("./usingCtx-C_vhSf7M.cjs");
2
+ const require_nodeCache = require("./nodeCache-CllHsCcy.cjs");
3
3
  let node_async_hooks = require("node:async_hooks");
4
4
  let node_util = require("node:util");
5
5
  let node_process = require("node:process");
6
- node_process = require_usingCtx.__toESM(node_process, 1);
7
- let node_child_process = require("node:child_process");
6
+ node_process = require_nodeCache.__toESM(node_process, 1);
7
+ let tinyexec = require("tinyexec");
8
8
  let node_fs_promises = require("node:fs/promises");
9
9
  let node_path = require("node:path");
10
- node_path = require_usingCtx.__toESM(node_path, 1);
10
+ node_path = require_nodeCache.__toESM(node_path, 1);
11
11
  let _kubb_ast = require("@kubb/ast");
12
12
  let node_crypto = require("node:crypto");
13
13
  let node_fs = require("node:fs");
14
14
  let node_os = require("node:os");
15
+ let node_readline = require("node:readline");
15
16
  let node_url = require("node:url");
16
17
  //#region src/createAdapter.ts
17
18
  /**
@@ -78,18 +79,131 @@ function isCIEnvironment() {
78
79
  }
79
80
  //#endregion
80
81
  //#region ../../internals/utils/src/openInBrowser.ts
82
+ const ignore = () => {};
81
83
  /**
82
84
  * Opens a URL or local file in the default browser, unless running in CI.
83
85
  */
84
86
  function openInBrowser(target) {
85
87
  if (isCIEnvironment()) return;
86
- if (node_process.default.platform === "win32") (0, node_child_process.execFile)("cmd", [
87
- "/c",
88
- "start",
89
- "",
90
- target
91
- ], () => {});
92
- else (0, node_child_process.execFile)(node_process.default.platform === "darwin" ? "open" : "xdg-open", [target], () => {});
88
+ if (node_process.default.platform === "win32") {
89
+ (0, tinyexec.x)("cmd", [
90
+ "/c",
91
+ "start",
92
+ "",
93
+ target
94
+ ]).then(ignore, ignore);
95
+ return;
96
+ }
97
+ (0, tinyexec.x)(node_process.default.platform === "darwin" ? "open" : "xdg-open", [target]).then(ignore, ignore);
98
+ }
99
+ //#endregion
100
+ //#region ../../internals/utils/src/tools.ts
101
+ /**
102
+ * CLI command descriptors for each supported code formatter.
103
+ */
104
+ const formatters = {
105
+ prettier: {
106
+ command: "prettier",
107
+ args: (outputPath) => [
108
+ "--ignore-unknown",
109
+ "--write",
110
+ outputPath
111
+ ],
112
+ errorMessage: "Prettier not found"
113
+ },
114
+ biome: {
115
+ command: "biome",
116
+ args: (outputPath) => [
117
+ "format",
118
+ "--write",
119
+ outputPath
120
+ ],
121
+ errorMessage: "Biome not found"
122
+ },
123
+ oxfmt: {
124
+ command: "oxfmt",
125
+ args: (outputPath) => [outputPath],
126
+ errorMessage: "Oxfmt not found"
127
+ }
128
+ };
129
+ /**
130
+ * CLI command descriptors for each supported linter.
131
+ */
132
+ const linters = {
133
+ eslint: {
134
+ command: "eslint",
135
+ args: (outputPath) => [outputPath, "--fix"],
136
+ errorMessage: "Eslint not found"
137
+ },
138
+ biome: {
139
+ command: "biome",
140
+ args: (outputPath) => [
141
+ "lint",
142
+ "--fix",
143
+ outputPath
144
+ ],
145
+ errorMessage: "Biome not found"
146
+ },
147
+ oxlint: {
148
+ command: "oxlint",
149
+ args: (outputPath) => [
150
+ "--fix",
151
+ "--no-ignore",
152
+ outputPath
153
+ ],
154
+ errorMessage: "Oxlint not found"
155
+ }
156
+ };
157
+ /**
158
+ * Preference order for `format: 'auto'`, most-preferred first. Spelled out rather than taken from
159
+ * the table's key order, which is arbitrary and would silently change what `auto` picks.
160
+ */
161
+ const FORMATTER_PREFERENCE = [
162
+ "oxfmt",
163
+ "biome",
164
+ "prettier"
165
+ ];
166
+ /**
167
+ * Preference order for `lint: 'auto'`, most-preferred first.
168
+ */
169
+ const LINTER_PREFERENCE = [
170
+ "oxlint",
171
+ "biome",
172
+ "eslint"
173
+ ];
174
+ /**
175
+ * Whether `name` is on PATH or in a `node_modules/.bin` above `cwd` and answers `--version` with a zero exit.
176
+ */
177
+ async function isToolAvailable(name, cwd) {
178
+ return (0, tinyexec.x)(name, ["--version"], {
179
+ throwOnError: false,
180
+ nodeOptions: {
181
+ cwd,
182
+ stdio: "ignore"
183
+ }
184
+ }).then(({ exitCode }) => exitCode === 0, () => false);
185
+ }
186
+ /**
187
+ * Returns the first installed executable from `candidates`, or `null` when none are found.
188
+ *
189
+ * Not memoized: a long-running host that probes repeatedly should cache the result itself, and a
190
+ * `--watch` build should keep noticing a tool installed mid-session.
191
+ */
192
+ async function detectTool(candidates, cwd) {
193
+ for (const candidate of candidates) if (await isToolAvailable(candidate, cwd)) return candidate;
194
+ return null;
195
+ }
196
+ /**
197
+ * Tokenizes a shell command string, respecting single and double quotes.
198
+ *
199
+ * @example
200
+ * ```ts
201
+ * tokenize('git commit -m "initial commit"')
202
+ * // → ['git', 'commit', '-m', 'initial commit']
203
+ * ```
204
+ */
205
+ function tokenize(command) {
206
+ return (command.match(/[^\s"']+|"([^"]*)"|'([^']*)'/g) ?? []).map((token) => token.replace(/^["']|["']$/g, ""));
93
207
  }
94
208
  //#endregion
95
209
  //#region ../../internals/utils/src/time.ts
@@ -125,11 +239,134 @@ function formatMs(ms) {
125
239
  return `${Math.round(ms)}ms`;
126
240
  }
127
241
  //#endregion
242
+ //#region package.json
243
+ var version = "5.6.0";
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
128
365
  //#region src/Diagnostics.ts
129
366
  /**
130
367
  * Docs major version, derived from the package version so the link tracks the published major.
131
368
  */
132
- const docsMajor = "5.5.6".split(".")[0] ?? "5";
369
+ const docsMajor = version.split(".")[0] ?? "5";
133
370
  /**
134
371
  * Builds a type guard that narrows a {@link Diagnostic} to the variant for `kind`. A diagnostic
135
372
  * with no `kind` is treated as a `problem`.
@@ -177,137 +414,142 @@ const severityStyle = {
177
414
  warning: "yellow",
178
415
  info: "blue"
179
416
  };
417
+ const countKey = {
418
+ error: "errors",
419
+ warning: "warnings",
420
+ info: "infos"
421
+ };
180
422
  /**
181
423
  * Explanation for every {@link diagnosticCode}. Use {@link Diagnostics.explain} to look one up
182
424
  * and `Diagnostics.docsUrl` for the matching kubb.dev page.
183
425
  */
184
426
  const diagnosticCatalog = {
185
- [require_usingCtx.diagnosticCode.unknown]: {
427
+ [diagnosticCode.unknown]: {
186
428
  title: "Unknown error",
187
429
  cause: "An error was thrown without a stable Kubb code, so it is reported as-is.",
188
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."
189
431
  },
190
- [require_usingCtx.diagnosticCode.inputNotFound]: {
432
+ [diagnosticCode.inputNotFound]: {
191
433
  title: "Input not found",
192
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.",
193
435
  fix: "Check that the path exists and is readable, then set it as `input` or pass it on the CLI."
194
436
  },
195
- [require_usingCtx.diagnosticCode.inputRequestFailed]: {
437
+ [diagnosticCode.inputRequestFailed]: {
196
438
  title: "Input request failed",
197
439
  cause: "A URL set as `input` (or reached through a `$ref`) answered with a 4xx or 5xx status instead of the document.",
198
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."
199
441
  },
200
- [require_usingCtx.diagnosticCode.inputUnreachable]: {
442
+ [diagnosticCode.inputUnreachable]: {
201
443
  title: "Input unreachable",
202
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.",
203
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`."
204
446
  },
205
- [require_usingCtx.diagnosticCode.inputRequired]: {
447
+ [diagnosticCode.inputRequired]: {
206
448
  title: "Input required",
207
449
  cause: "An adapter is configured but no `input` was provided.",
208
450
  fix: "Set `input` to a file path, a URL, an inline spec (JSON/YAML string), or a parsed object in your Kubb config."
209
451
  },
210
- [require_usingCtx.diagnosticCode.legacyInput]: {
452
+ [diagnosticCode.legacyInput]: {
211
453
  title: "Legacy input shape",
212
454
  cause: "`input` is a `{ path }` or `{ data }` wrapper, which v4 used to point at a document and v5 reads as the document itself.",
213
455
  fix: "Unwrap it: `input: { path: \"./petStore.yaml\" }` becomes `input: \"./petStore.yaml\"`, and `input: { data: spec }` becomes `input: spec`."
214
456
  },
215
- [require_usingCtx.diagnosticCode.invalidDocument]: {
457
+ [diagnosticCode.invalidDocument]: {
216
458
  title: "Invalid document",
217
459
  cause: "The parsed `input` has no `openapi` or `swagger` version field, so it is not an OpenAPI or Swagger document.",
218
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."
219
461
  },
220
- [require_usingCtx.diagnosticCode.invalidSpec]: {
462
+ [diagnosticCode.invalidSpec]: {
221
463
  title: "Invalid spec",
222
464
  cause: "The document does not pass OpenAPI schema validation. Kubb still generates from it, but the output can be incomplete or wrong.",
223
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."
224
466
  },
225
- [require_usingCtx.diagnosticCode.refNotFound]: {
467
+ [diagnosticCode.refNotFound]: {
226
468
  title: "Reference not found",
227
469
  cause: "A `$ref` could not be resolved in the source document.",
228
470
  fix: "Add the missing definition (for example under `components.schemas`) or fix the `$ref`. Run `kubb validate` to check the spec."
229
471
  },
230
- [require_usingCtx.diagnosticCode.invalidServerVariable]: {
472
+ [diagnosticCode.invalidServerVariable]: {
231
473
  title: "Invalid server variable",
232
474
  cause: "A server variable value is not allowed by its `enum`.",
233
475
  fix: "Use one of the values listed in the server variable `enum`, or update the spec."
234
476
  },
235
- [require_usingCtx.diagnosticCode.pluginNotFound]: {
477
+ [diagnosticCode.pluginNotFound]: {
236
478
  title: "Plugin not found",
237
479
  cause: "A plugin that another plugin depends on is missing from the config.",
238
480
  fix: "Add the required plugin to the `plugins` array in kubb.config.ts, or remove the dependency on it."
239
481
  },
240
- [require_usingCtx.diagnosticCode.pluginFailed]: {
482
+ [diagnosticCode.pluginFailed]: {
241
483
  title: "Plugin failed",
242
484
  cause: "A plugin threw while generating, or reported an error through `ctx.error`.",
243
485
  fix: "Read the underlying error and check the plugin options and the schema or operation it failed on."
244
486
  },
245
- [require_usingCtx.diagnosticCode.pluginWarning]: {
487
+ [diagnosticCode.pluginWarning]: {
246
488
  title: "Plugin warning",
247
489
  cause: "A plugin reported a non-fatal warning through `ctx.warn`.",
248
490
  fix: "Review the message. It does not fail the build; adjust the plugin options or input if the warning is unwanted."
249
491
  },
250
- [require_usingCtx.diagnosticCode.pluginInfo]: {
492
+ [diagnosticCode.pluginInfo]: {
251
493
  title: "Plugin info",
252
494
  cause: "A plugin reported an informational message through `ctx.info`.",
253
495
  fix: "Informational only. No action is required."
254
496
  },
255
- [require_usingCtx.diagnosticCode.unsupportedFormat]: {
497
+ [diagnosticCode.unsupportedFormat]: {
256
498
  title: "Unsupported format",
257
499
  cause: "A schema uses a `format` Kubb does not map to a specific type, so it falls back to the base type.",
258
500
  fix: "Use a format Kubb supports, or handle the custom format with a parser or plugin."
259
501
  },
260
- [require_usingCtx.diagnosticCode.deprecated]: {
502
+ [diagnosticCode.deprecated]: {
261
503
  title: "Deprecated",
262
504
  cause: "A referenced schema or operation is marked `deprecated`.",
263
505
  fix: "Migrate off the deprecated definition if the warning is unwanted."
264
506
  },
265
- [require_usingCtx.diagnosticCode.adapterRequired]: {
507
+ [diagnosticCode.adapterRequired]: {
266
508
  title: "Adapter required",
267
509
  cause: "An action needs an adapter but none is configured.",
268
510
  fix: "Set `adapter` in kubb.config.ts, for example `adapterOas()`."
269
511
  },
270
- [require_usingCtx.diagnosticCode.pathTraversal]: {
512
+ [diagnosticCode.pathTraversal]: {
271
513
  title: "Path traversal",
272
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`.",
273
515
  fix: "Keep generated paths within the output directory. Review the `group.name` function and the names coming from the spec."
274
516
  },
275
- [require_usingCtx.diagnosticCode.cleanRoot]: {
517
+ [diagnosticCode.cleanRoot]: {
276
518
  title: "Clean targets the project root",
277
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.",
278
520
  fix: "Point `output.path` at a subdirectory such as `./src/gen` so clean only removes generated code, or disable `output.clean`."
279
521
  },
280
- [require_usingCtx.diagnosticCode.invalidPluginOptions]: {
522
+ [diagnosticCode.invalidPluginOptions]: {
281
523
  title: "Invalid plugin options",
282
524
  cause: "A plugin was configured with options that cannot be honored, for example `output.mode: 'file'` paired with a `group` option.",
283
525
  fix: "Fix the plugin options. A single-file output has nothing to group, so remove the `group` option or use `output.mode: 'directory'`."
284
526
  },
285
- [require_usingCtx.diagnosticCode.postGenerateFailed]: {
527
+ [diagnosticCode.postGenerateFailed]: {
286
528
  title: "Post-generate command failed",
287
529
  cause: "A post-generate command (`output.postGenerate`) exited with a non-zero status.",
288
530
  fix: "Check the command is installed and correct, and run it manually to see the error."
289
531
  },
290
- [require_usingCtx.diagnosticCode.formatFailed]: {
532
+ [diagnosticCode.formatFailed]: {
291
533
  title: "Format failed",
292
534
  cause: "The formatter pass over the generated files failed.",
293
535
  fix: "Check the formatter (oxfmt, biome, or prettier) is installed and its config is valid, then run it manually on the output."
294
536
  },
295
- [require_usingCtx.diagnosticCode.lintFailed]: {
537
+ [diagnosticCode.lintFailed]: {
296
538
  title: "Lint failed",
297
539
  cause: "The linter pass over the generated files failed.",
298
540
  fix: "Check the linter (oxlint, biome, or eslint) is installed and its config is valid, then run it manually on the output."
299
541
  },
300
- [require_usingCtx.diagnosticCode.barrelDuplicateExport]: {
542
+ [diagnosticCode.barrelDuplicateExport]: {
301
543
  title: "Duplicate barrel export",
302
544
  cause: "Two generated modules export the same name, so the barrel cannot re-export both.",
303
545
  fix: "Rename one of the colliding declarations, or configure the plugin resolver to produce distinct names."
304
546
  },
305
- [require_usingCtx.diagnosticCode.performance]: {
547
+ [diagnosticCode.performance]: {
306
548
  title: "Performance",
307
549
  cause: "Not a failure. Records a plugin’s elapsed time, summed into the run total.",
308
550
  fix: "No action. This is an informational metric."
309
551
  },
310
- [require_usingCtx.diagnosticCode.updateAvailable]: {
552
+ [diagnosticCode.updateAvailable]: {
311
553
  title: "Update available",
312
554
  cause: "A newer Kubb version is published on npm than the one running.",
313
555
  fix: "Update the `@kubb/*` packages, for example `npm install -g @kubb/cli`, to get the latest fixes."
@@ -327,7 +569,7 @@ var Diagnostics = class Diagnostics {
327
569
  /**
328
570
  * The diagnostic code catalog, exposed as `Diagnostics.code` (e.g. `Diagnostics.code.refNotFound`).
329
571
  */
330
- static code = require_usingCtx.diagnosticCode;
572
+ static code = diagnosticCode;
331
573
  /**
332
574
  * Type guard for a build {@link ProblemDiagnostic}.
333
575
  */
@@ -364,7 +606,9 @@ var Diagnostics = class Diagnostics {
364
606
  */
365
607
  static isError(error) {
366
608
  if (error instanceof Diagnostics.Error) return true;
367
- return error instanceof Error && error.name === "DiagnosticError" && "diagnostic" in error && typeof error.diagnostic === "object" && error.diagnostic !== null && typeof error.diagnostic?.code === "string";
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";
368
612
  }
369
613
  /**
370
614
  * Runs `fn` with `sink` as the active diagnostic sink for the whole async
@@ -408,9 +652,9 @@ var Diagnostics = class Diagnostics {
408
652
  current = current.cause;
409
653
  }
410
654
  return {
411
- code: require_usingCtx.diagnosticCode.unknown,
655
+ code: diagnosticCode.unknown,
412
656
  severity: "error",
413
- message: root ? root.message : require_usingCtx.getErrorMessage(error),
657
+ message: root ? root.message : require_nodeCache.getErrorMessage(error),
414
658
  cause: root
415
659
  };
416
660
  }
@@ -420,7 +664,7 @@ var Diagnostics = class Diagnostics {
420
664
  static performance({ plugin, duration }) {
421
665
  return {
422
666
  kind: "performance",
423
- code: require_usingCtx.diagnosticCode.performance,
667
+ code: diagnosticCode.performance,
424
668
  severity: "info",
425
669
  message: `${plugin} generated in ${Math.round(duration)}ms`,
426
670
  plugin,
@@ -433,7 +677,7 @@ var Diagnostics = class Diagnostics {
433
677
  static update({ currentVersion, latestVersion }) {
434
678
  return {
435
679
  kind: "update",
436
- code: require_usingCtx.diagnosticCode.updateAvailable,
680
+ code: diagnosticCode.updateAvailable,
437
681
  severity: "info",
438
682
  message: `Update available: v${currentVersion} → v${latestVersion}. Run \`npm install -g @kubb/cli\` to update.`,
439
683
  currentVersion,
@@ -452,35 +696,20 @@ var Diagnostics = class Diagnostics {
452
696
  * that carry a `plugin`.
453
697
  */
454
698
  static failedPlugins(diagnostics) {
455
- const names = /* @__PURE__ */ new Set();
456
- for (const diagnostic of diagnostics) if (diagnostic.severity === "error" && diagnostic.plugin) names.add(diagnostic.plugin);
457
- return [...names];
699
+ return [...new Set(diagnostics.flatMap((diagnostic) => diagnostic.severity === "error" && diagnostic.plugin ? [diagnostic.plugin] : []))];
458
700
  }
459
701
  /**
460
702
  * Counts `problem` diagnostics by severity for the run summary. `performance` and
461
703
  * `update` diagnostics are ignored.
462
704
  */
463
705
  static count(diagnostics) {
464
- let errors = 0;
465
- let warnings = 0;
466
- let infos = 0;
467
- for (const diagnostic of diagnostics) {
468
- if (!isProblem(diagnostic)) continue;
469
- if (diagnostic.severity === "error") {
470
- errors += 1;
471
- continue;
472
- }
473
- if (diagnostic.severity === "warning") {
474
- warnings += 1;
475
- continue;
476
- }
477
- infos += 1;
478
- }
479
- return {
480
- errors,
481
- warnings,
482
- infos
706
+ const counts = {
707
+ errors: 0,
708
+ warnings: 0,
709
+ infos: 0
483
710
  };
711
+ for (const diagnostic of diagnostics.filter(isProblem)) counts[countKey[diagnostic.severity]] += 1;
712
+ return counts;
484
713
  }
485
714
  /**
486
715
  * Drops duplicate `problem` diagnostics that share a code, location pointer, and
@@ -532,7 +761,7 @@ var Diagnostics = class Diagnostics {
532
761
  ...problem?.location ? { location: problem.location } : {},
533
762
  ...problem?.help ? { help: problem.help } : {},
534
763
  ...problem?.plugin ? { plugin: problem.plugin } : {},
535
- ...diagnostic.code === require_usingCtx.diagnosticCode.unknown ? {} : { docsUrl: Diagnostics.docsUrl(diagnostic.code) }
764
+ ...diagnostic.code === diagnosticCode.unknown ? {} : { docsUrl: Diagnostics.docsUrl(diagnostic.code) }
536
765
  };
537
766
  }
538
767
  /**
@@ -552,7 +781,7 @@ var Diagnostics = class Diagnostics {
552
781
  const details = [];
553
782
  if (problem?.location && "pointer" in problem.location) details.push(` ${(0, node_util.styleText)("dim", "at:")} ${(0, node_util.styleText)("cyan", problem.location.pointer)}`);
554
783
  if (problem?.help) details.push(` ${(0, node_util.styleText)("cyan", "fix:")} ${problem.help}`);
555
- if (code !== require_usingCtx.diagnosticCode.unknown) details.push(` ${(0, node_util.styleText)("dim", "see:")} ${(0, node_util.styleText)("cyan", Diagnostics.docsUrl(code))}`);
784
+ if (code !== diagnosticCode.unknown) details.push(` ${(0, node_util.styleText)("dim", "see:")} ${(0, node_util.styleText)("cyan", Diagnostics.docsUrl(code))}`);
556
785
  return {
557
786
  headline,
558
787
  details
@@ -581,7 +810,7 @@ var Diagnostics = class Diagnostics {
581
810
  function normalizeOutput({ output, group, pluginName }) {
582
811
  const mode = output.mode ?? (node_path.default.extname(output.path) ? "file" : "directory");
583
812
  if (mode === "file" && group) throw new Diagnostics.Error({
584
- code: require_usingCtx.diagnosticCode.invalidPluginOptions,
813
+ code: Diagnostics.code.invalidPluginOptions,
585
814
  severity: "error",
586
815
  message: `Plugin "${pluginName}" resolves \`output.mode\` to 'file' but also configures a \`group\` option.`,
587
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.",
@@ -706,7 +935,7 @@ const resolverOptions = Symbol.for("@kubb/core/resolver/options");
706
935
  /**
707
936
  * Builds a nested file path from a dotted name. Splits on dots that precede a letter
708
937
  * (so version numbers embedded in operationIds like `v2025.0` stay intact), camelCases
709
- * every earlier segment, applies `caseLast` to the final segment, and joins with `/`.
938
+ * every segment, and joins with `/`.
710
939
  *
711
940
  * Empty segments are dropped before joining. They arise when the name starts with a dot
712
941
  * followed by a letter (e.g. `..Schema` splits into `['..', 'Schema']` and `'..'` cases to
@@ -715,16 +944,21 @@ const resolverOptions = Symbol.for("@kubb/core/resolver/options");
715
944
  *
716
945
  * @example Nested path from a dotted name
717
946
  * `toFilePath('pet.petId') // 'pet/petId'`
718
- *
719
- * @example PascalCase the final segment
720
- * `toFilePath('pet.Pet', pascalCase) // 'pet/Pet'`
721
- *
722
- * @example Suffix applied to the final segment only
723
- * `toFilePath('tag.tag', (part) => camelCase(part, { suffix: 'schema' })) // 'tag/tagSchema'`
724
947
  */
725
- function toFilePath(name, caseLast = require_usingCtx.camelCase) {
726
- const parts = name.split(/\.(?=[a-zA-Z])/);
727
- return parts.map((part, i) => i === parts.length - 1 ? caseLast(part) : require_usingCtx.camelCase(part)).filter(Boolean).join("/");
948
+ function toFilePath(name) {
949
+ return name.split(/\.(?=[a-zA-Z])/).map((part) => require_nodeCache.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(node_path.default.sep) ? parent : `${parent}${node_path.default.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
+ });
728
962
  }
729
963
  /**
730
964
  * Built-in `file.baseName`: casts the identifier with `toFilePath` and appends the extension.
@@ -760,6 +994,8 @@ var Resolver = class Resolver {
760
994
  static #patternCache = /* @__PURE__ */ new Map();
761
995
  static #optionsCache = /* @__PURE__ */ new WeakMap();
762
996
  pluginName;
997
+ /** The built-in machinery, untouched by `name`/`file` overrides and built once since the driver reads it per node. */
998
+ default;
763
999
  #options;
764
1000
  #baseName;
765
1001
  #filePath;
@@ -768,25 +1004,19 @@ var Resolver = class Resolver {
768
1004
  this.#options = options;
769
1005
  this.#baseName = options.file?.baseName ? options.file.baseName.bind(this) : toBaseName;
770
1006
  this.#filePath = options.file?.path ? options.file.path.bind(this) : void 0;
771
- this.#apply(options);
772
- }
773
- /** Exposes the raw build options so `Resolver.merge` can read them across `@kubb/core` copies. */
774
- get [resolverOptions]() {
775
- return this.#options;
776
- }
777
- /**
778
- * The built-in resolution machinery. Always reaches the untouched defaults, even when a
779
- * plugin overrides the top-level `name` or `file`.
780
- */
781
- get default() {
782
- return {
783
- name: require_usingCtx.camelCase,
1007
+ this.default = {
1008
+ name: require_nodeCache.camelCase,
784
1009
  options: this.#resolveOptions.bind(this),
785
1010
  path: this.#resolvePath.bind(this),
786
1011
  file: this.#resolveFile.bind(this),
787
1012
  banner: this.#resolveBanner.bind(this),
788
1013
  footer: this.#resolveFooter.bind(this)
789
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;
790
1020
  }
791
1021
  name(name) {
792
1022
  return this.default.name(name);
@@ -933,9 +1163,9 @@ var Resolver = class Resolver {
933
1163
  */
934
1164
  static #resolveGroupDir(group, groupValue) {
935
1165
  if (group.name) return group.name({ group: groupValue });
936
- if (group.type === "tag") return require_usingCtx.camelCase(groupValue);
1166
+ if (group.type === "tag") return require_nodeCache.camelCase(groupValue);
937
1167
  const segment = groupValue.split("/").filter((part) => part !== "" && part !== "." && part !== "..")[0];
938
- return segment ? require_usingCtx.camelCase(segment) : "";
1168
+ return segment ? require_nodeCache.camelCase(segment) : "";
939
1169
  }
940
1170
  /**
941
1171
  * `mode: 'file'` (default) resolves directly to `output.path`. `mode: 'directory'` resolves
@@ -946,13 +1176,11 @@ var Resolver = class Resolver {
946
1176
  if (output.mode !== "directory") return node_path.default.resolve(root, output.path);
947
1177
  const outputDir = node_path.default.resolve(root, output.path);
948
1178
  const result = group && (groupPath || tag) ? node_path.default.resolve(outputDir, Resolver.#resolveGroupDir(group, group.type === "path" ? groupPath : tag), baseName) : node_path.default.resolve(outputDir, baseName);
949
- const outputDirWithSep = outputDir.endsWith(node_path.default.sep) ? outputDir : `${outputDir}${node_path.default.sep}`;
950
- if (result !== outputDir && !result.startsWith(outputDirWithSep)) throw new Diagnostics.Error({
951
- code: Diagnostics.code.pathTraversal,
952
- severity: "error",
1179
+ assertInside({
1180
+ target: result,
1181
+ parent: outputDir,
953
1182
  message: `Resolved path "${result}" is outside the output directory "${outputDir}".`,
954
- 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.",
955
- location: { kind: "config" }
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."
956
1184
  });
957
1185
  return result;
958
1186
  }
@@ -963,13 +1191,11 @@ var Resolver = class Resolver {
963
1191
  */
964
1192
  #resolveOverridePath(filePath, root) {
965
1193
  const resolved = node_path.default.resolve(root, filePath);
966
- const rootWithSep = root.endsWith(node_path.default.sep) ? root : `${root}${node_path.default.sep}`;
967
- if (resolved !== root && !resolved.startsWith(rootWithSep)) throw new Diagnostics.Error({
968
- code: Diagnostics.code.pathTraversal,
969
- severity: "error",
1194
+ assertInside({
1195
+ target: resolved,
1196
+ parent: root,
970
1197
  message: `Resolved path "${resolved}" is outside the project root "${root}".`,
971
- help: "A resolver `file.path` must return a path inside the project root.",
972
- location: { kind: "config" }
1198
+ help: "A resolver `file.path` must return a path inside the project root."
973
1199
  });
974
1200
  return resolved;
975
1201
  }
@@ -1194,21 +1420,27 @@ const ENFORCE_ORDER = {
1194
1420
  pre: -1,
1195
1421
  post: 1
1196
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
+ ]);
1197
1431
  const enforceWeight = (plugin) => plugin.enforce ? ENFORCE_ORDER[plugin.enforce] : 0;
1198
1432
  /**
1199
1433
  * The options bag a `NormalizedPlugin` starts with before a plugin refines it: a directory output
1200
1434
  * at the plugin root and empty filter lists.
1201
1435
  */
1202
- function defaultPluginOptions() {
1203
- return {
1204
- output: {
1205
- path: ".",
1206
- mode: "directory"
1207
- },
1208
- exclude: [],
1209
- override: []
1210
- };
1211
- }
1436
+ const defaultPluginOptions = () => ({
1437
+ output: {
1438
+ path: ".",
1439
+ mode: "directory"
1440
+ },
1441
+ exclude: [],
1442
+ override: []
1443
+ });
1212
1444
  /**
1213
1445
  * Fills in the `output`, `exclude`, and `override` a `NormalizedPlugin` needs from a plugin's raw
1214
1446
  * options, running `output` through `normalizeOutput`. Idempotent, so the driver can apply it after
@@ -1245,7 +1477,7 @@ var KubbDriver = class {
1245
1477
  * Plugins should use `this.addFile()` / `this.upsertFile()` (via their context) to
1246
1478
  * add files. This property gives direct read/write access when needed.
1247
1479
  */
1248
- fileManager = new require_usingCtx.FileManager();
1480
+ fileManager = new require_nodeCache.FileManager();
1249
1481
  plugins = /* @__PURE__ */ new Map();
1250
1482
  /**
1251
1483
  * Removers for every listener the driver added (plugin, generator) so `dispose()` can detach
@@ -1355,10 +1587,10 @@ var KubbDriver = class {
1355
1587
  config: this.config,
1356
1588
  options: plugin.options ?? {},
1357
1589
  addGenerator: (...generators) => {
1358
- for (const generator of generators) this.registerGenerator(plugin.name, generator);
1590
+ plugin.generators = [...plugin.generators ?? [], ...generators];
1359
1591
  },
1360
1592
  setResolver: (resolver) => {
1361
- this.setPluginResolver(plugin.name, resolver);
1593
+ plugin.resolver = Resolver.merge(createResolver({ pluginName: plugin.name }), resolver);
1362
1594
  },
1363
1595
  addMacro: (macro) => {
1364
1596
  this.#transforms.add(plugin.name, macro);
@@ -1367,18 +1599,10 @@ var KubbDriver = class {
1367
1599
  this.#transforms.set(plugin.name, macros);
1368
1600
  },
1369
1601
  setOptions: (opts) => {
1370
- plugin.options = {
1602
+ plugin.options = normalizePluginOptions({
1371
1603
  ...plugin.options,
1372
1604
  ...opts
1373
- };
1374
- if (plugin.options.output) {
1375
- const group = "group" in plugin.options ? plugin.options.group : void 0;
1376
- plugin.options.output = normalizeOutput({
1377
- output: plugin.options.output,
1378
- group,
1379
- pluginName: plugin.name
1380
- });
1381
- }
1605
+ }, plugin.name);
1382
1606
  },
1383
1607
  injectFile: (userFileNode) => {
1384
1608
  this.fileManager.add(_kubb_ast.ast.factory.createFile(userFileNode));
@@ -1386,29 +1610,7 @@ var KubbDriver = class {
1386
1610
  });
1387
1611
  }
1388
1612
  }
1389
- /**
1390
- * Appends a generator to its owning plugin so the generate loop can call it directly.
1391
- *
1392
- * The generator's `schema`, `operation`, and `operations` methods run per node during the AST
1393
- * walk in `#runGenerators`, and their result is routed through `dispatch`. Because a generator is
1394
- * bound to a plugin, generators from different plugins never cross-fire without a name check. The
1395
- * renderer comes from `generator.renderer`; set it to `null` (or leave it unset) to opt out of
1396
- * rendering.
1397
- *
1398
- * Call this method inside `addGenerator()` (in `kubb:plugin:setup`) to wire up a generator.
1399
- */
1400
- registerGenerator(pluginName, generator) {
1401
- const plugin = this.plugins.get(pluginName);
1402
- if (!plugin) return;
1403
- plugin.generators = plugin.generators ? [...plugin.generators, generator] : [generator];
1404
- }
1405
- /**
1406
- * Returns `true` when at least one generator was registered for the given plugin
1407
- * via `addGenerator()` in `kubb:plugin:setup`.
1408
- *
1409
- * Used by the build loop to decide whether to walk the AST and run the generators
1410
- * for a plugin.
1411
- */
1613
+ /** `true` once `addGenerator()` in `kubb:plugin:setup` registered a generator for the plugin. */
1412
1614
  hasHookGenerators(pluginName) {
1413
1615
  return (this.plugins.get(pluginName)?.generators?.length ?? 0) > 0;
1414
1616
  }
@@ -1470,7 +1672,7 @@ var KubbDriver = class {
1470
1672
  try {
1471
1673
  await hooks.callHook("kubb:plugin:start", { plugin });
1472
1674
  } catch (caughtError) {
1473
- const error = require_usingCtx.toError(caughtError);
1675
+ const error = require_nodeCache.toError(caughtError);
1474
1676
  const duration = getElapsedMs(hrStart);
1475
1677
  await this.#emitPluginEnd({
1476
1678
  plugin,
@@ -1591,7 +1793,7 @@ var KubbDriver = class {
1591
1793
  const allowedSchemaNamesByPlugin = /* @__PURE__ */ new Map();
1592
1794
  for (const { plugin } of entries) {
1593
1795
  const { exclude, include, override } = plugin.options;
1594
- if (!((include?.some(({ type }) => require_usingCtx.OPERATION_FILTER_TYPES.has(type)) ?? false) && !(include?.some(({ type }) => type === "schemaName") ?? false))) continue;
1796
+ if (!((include?.some(({ type }) => OPERATION_FILTER_TYPES.has(type)) ?? false) && !(include?.some(({ type }) => type === "schemaName") ?? false))) continue;
1595
1797
  const resolver = this.getResolver(plugin.name);
1596
1798
  const includedOps = operations.filter((operation) => resolver.default.options(operation, {
1597
1799
  options: plugin.options,
@@ -1643,7 +1845,7 @@ var KubbDriver = class {
1643
1845
  };
1644
1846
  };
1645
1847
  for (const node of schemas) {
1646
- const cache = require_usingCtx.createNodeCache();
1848
+ const cache = require_nodeCache.createNodeCache();
1647
1849
  for (const state of states) {
1648
1850
  if (state.error || !state.schemaGenerators.length) continue;
1649
1851
  try {
@@ -1656,21 +1858,20 @@ var KubbDriver = class {
1656
1858
  options,
1657
1859
  cache
1658
1860
  };
1659
- for (const generator of state.schemaGenerators) {
1660
- if (!(generator.match ? await generator.match(transformedNode, ctx) : true)) continue;
1661
- await this.dispatch({
1662
- result: await generator.schema(transformedNode, ctx),
1663
- renderer: generator.renderer
1664
- });
1665
- }
1861
+ await this.#dispatchNode({
1862
+ generators: state.schemaGenerators,
1863
+ node: transformedNode,
1864
+ ctx,
1865
+ generate: (generator) => generator.schema(transformedNode, ctx)
1866
+ });
1666
1867
  await this.hooks.callHook("kubb:generate:schema", transformedNode, ctx);
1667
1868
  } catch (caughtError) {
1668
- state.error = require_usingCtx.toError(caughtError);
1869
+ state.error = require_nodeCache.toError(caughtError);
1669
1870
  }
1670
1871
  }
1671
1872
  }
1672
1873
  for (const node of operations) {
1673
- const cache = require_usingCtx.createNodeCache();
1874
+ const cache = require_nodeCache.createNodeCache();
1674
1875
  for (const state of states) {
1675
1876
  if (state.error || !state.operationGenerators.length && !state.operationsGenerators.length) continue;
1676
1877
  try {
@@ -1678,22 +1879,22 @@ var KubbDriver = class {
1678
1879
  if (!resolved) continue;
1679
1880
  state.pluginOperations.push(resolved.transformedNode);
1680
1881
  if (state.operationGenerators.length) {
1882
+ const { transformedNode } = resolved;
1681
1883
  const ctx = {
1682
1884
  ...state.generatorContext,
1683
1885
  options: resolved.options,
1684
1886
  cache
1685
1887
  };
1686
- for (const generator of state.operationGenerators) {
1687
- if (!(generator.match ? await generator.match(resolved.transformedNode, ctx) : true)) continue;
1688
- await this.dispatch({
1689
- result: await generator.operation(resolved.transformedNode, ctx),
1690
- renderer: generator.renderer
1691
- });
1692
- }
1693
- await this.hooks.callHook("kubb:generate:operation", resolved.transformedNode, ctx);
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);
1694
1895
  }
1695
1896
  } catch (caughtError) {
1696
- state.error = require_usingCtx.toError(caughtError);
1897
+ state.error = require_nodeCache.toError(caughtError);
1697
1898
  }
1698
1899
  }
1699
1900
  }
@@ -1703,7 +1904,7 @@ var KubbDriver = class {
1703
1904
  const ctx = {
1704
1905
  ...state.generatorContext,
1705
1906
  options: state.plugin.options,
1706
- cache: require_usingCtx.createNodeCache()
1907
+ cache: require_nodeCache.createNodeCache()
1707
1908
  };
1708
1909
  for (const generator of state.operationsGenerators) await this.dispatch({
1709
1910
  result: await generator.operations(state.pluginOperations, ctx),
@@ -1711,7 +1912,7 @@ var KubbDriver = class {
1711
1912
  });
1712
1913
  await this.hooks.callHook("kubb:generate:operations", state.pluginOperations, ctx);
1713
1914
  } catch (caughtError) {
1714
- state.error = require_usingCtx.toError(caughtError);
1915
+ state.error = require_nodeCache.toError(caughtError);
1715
1916
  }
1716
1917
  }
1717
1918
  for (const state of states) {
@@ -1733,36 +1934,20 @@ var KubbDriver = class {
1733
1934
  }
1734
1935
  return diagnostics;
1735
1936
  }
1736
- /**
1737
- * Stores whatever a generator method or `kubb:generate:*` hook returned.
1738
- *
1739
- * - An `Array<FileNode>` goes straight into `fileManager` via `upsert`.
1740
- * - A renderer element runs through `renderer` (the renderer factory, e.g. JSX) and the
1741
- * produced files go to `fileManager.upsert`.
1742
- * - A falsy result is treated as a no-op. The generator wrote files itself via
1743
- * `ctx.upsertFile`.
1744
- *
1745
- * Pass `renderer` when the result may be a renderer element. Generators that only return
1746
- * `Array<FileNode>` do not need one.
1747
- */
1748
- async dispatch({ result, renderer }) {
1749
- try {
1750
- var _usingCtx$2 = require_usingCtx._usingCtx();
1751
- if (!result) return;
1752
- if (Array.isArray(result)) {
1753
- this.fileManager.upsert(...result);
1754
- return;
1755
- }
1756
- if (!renderer) return;
1757
- const instance = _usingCtx$2.u(renderer());
1758
- await instance.render(result);
1759
- this.fileManager.upsert(...instance.files);
1760
- } catch (_) {
1761
- _usingCtx$2.e = _;
1762
- } finally {
1763
- _usingCtx$2.d();
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
+ });
1764
1945
  }
1765
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
+ }
1766
1951
  /**
1767
1952
  * Removes every listener the driver added. Listeners attached directly to `hooks` from outside
1768
1953
  * the driver survive. Called at the end of a build to prevent leaks across repeated builds.
@@ -1780,15 +1965,6 @@ var KubbDriver = class {
1780
1965
  [Symbol.dispose]() {
1781
1966
  this.dispose();
1782
1967
  }
1783
- /**
1784
- * Merges `partial` onto a fresh default resolver and stores the result on `plugin.resolver`,
1785
- * which is the single source `getResolver` and `getPlugin(name).resolver` both read.
1786
- */
1787
- setPluginResolver(pluginName, partial) {
1788
- const plugin = this.plugins.get(pluginName);
1789
- if (!plugin) return;
1790
- plugin.resolver = Resolver.merge(createResolver({ pluginName }), partial);
1791
- }
1792
1968
  getResolver(pluginName) {
1793
1969
  return this.plugins.get(pluginName)?.resolver ?? createResolver({ pluginName });
1794
1970
  }
@@ -1916,7 +2092,7 @@ async function createOutputManifest({ storage, cache }) {
1916
2092
  async commit() {
1917
2093
  try {
1918
2094
  const next = { ...entries };
1919
- await require_usingCtx.inParallel({
2095
+ await require_nodeCache.inParallel({
1920
2096
  items: [...tracked],
1921
2097
  limit: 50,
1922
2098
  run: async ([key, source]) => {
@@ -1981,29 +2157,6 @@ function createStorage(build) {
1981
2157
  }
1982
2158
  //#endregion
1983
2159
  //#region src/storages/fsStorage.ts
1984
- const WRITE_CONCURRENCY = 50;
1985
- function createLimiter(concurrency) {
1986
- let active = 0;
1987
- const queue = [];
1988
- function next() {
1989
- if (active >= concurrency) return;
1990
- const run = queue.shift();
1991
- if (!run) return;
1992
- active++;
1993
- run();
1994
- }
1995
- return function limit(task) {
1996
- return new Promise((resolve, reject) => {
1997
- queue.push(() => {
1998
- task().then(resolve, reject).finally(() => {
1999
- active--;
2000
- next();
2001
- });
2002
- });
2003
- next();
2004
- });
2005
- };
2006
- }
2007
2160
  /**
2008
2161
  * Built-in filesystem storage driver.
2009
2162
  *
@@ -2017,8 +2170,7 @@ function createLimiter(concurrency) {
2017
2170
  * a formatter left behind
2018
2171
  * - missing parent directories are created automatically
2019
2172
  * - Bun's native file API is used when running under Bun
2020
- * - concurrent `writeItem` calls are capped at {@link WRITE_CONCURRENCY} in flight, so a caller
2021
- * can fire every file's write without pacing itself
2173
+ * - `FileManager.write` bounds in-flight writes, so this driver does not pace itself
2022
2174
  *
2023
2175
  * @example
2024
2176
  * ```ts
@@ -2032,51 +2184,43 @@ function createLimiter(concurrency) {
2032
2184
  * })
2033
2185
  * ```
2034
2186
  */
2035
- const fsStorage = createStorage(() => {
2036
- const limit = createLimiter(WRITE_CONCURRENCY);
2037
- return {
2038
- name: "fs",
2039
- async existsItem(key) {
2040
- try {
2041
- await (0, node_fs_promises.access)((0, node_path.resolve)(key));
2042
- return true;
2043
- } catch (_error) {
2044
- return false;
2045
- }
2046
- },
2047
- async readItem(key) {
2048
- try {
2049
- return await (0, node_fs_promises.readFile)((0, node_path.resolve)(key), "utf8");
2050
- } catch (_error) {
2051
- return null;
2052
- }
2053
- },
2054
- async writeItem(key, value, options) {
2055
- await limit(() => require_usingCtx.write((0, node_path.resolve)(key), value, {
2056
- sanity: false,
2057
- stored: options?.stored
2058
- }));
2059
- },
2060
- async removeItem(key) {
2061
- await (0, node_fs_promises.rm)((0, node_path.resolve)(key), { force: true });
2062
- },
2063
- async readKeys(base) {
2064
- const resolvedBase = (0, node_path.resolve)(base ?? process.cwd());
2065
- const keys = [];
2066
- try {
2067
- for await (const entry of (0, node_fs_promises.glob)("**/*", {
2068
- cwd: resolvedBase,
2069
- withFileTypes: true
2070
- })) if (entry.isFile()) keys.push(require_usingCtx.toPosixPath((0, node_path.relative)(resolvedBase, (0, node_path.join)(entry.parentPath, entry.name))));
2071
- } catch (_error) {}
2072
- return keys;
2073
- },
2074
- async empty(base) {
2075
- if (!base) return;
2076
- await require_usingCtx.clean((0, node_path.resolve)(base));
2187
+ const fsStorage = createStorage(() => ({
2188
+ name: "fs",
2189
+ async existsItem(key) {
2190
+ return require_nodeCache.exists((0, node_path.resolve)(key));
2191
+ },
2192
+ async readItem(key) {
2193
+ try {
2194
+ return await (0, node_fs_promises.readFile)((0, node_path.resolve)(key), "utf8");
2195
+ } catch (_error) {
2196
+ return null;
2077
2197
  }
2078
- };
2079
- });
2198
+ },
2199
+ async writeItem(key, value, options) {
2200
+ await require_nodeCache.write((0, node_path.resolve)(key), value, {
2201
+ sanity: false,
2202
+ stored: options?.stored
2203
+ });
2204
+ },
2205
+ async removeItem(key) {
2206
+ await (0, node_fs_promises.rm)((0, node_path.resolve)(key), { force: true });
2207
+ },
2208
+ async readKeys(base) {
2209
+ const resolvedBase = (0, node_path.resolve)(base ?? process.cwd());
2210
+ const keys = [];
2211
+ try {
2212
+ for await (const entry of (0, node_fs_promises.glob)("**/*", {
2213
+ cwd: resolvedBase,
2214
+ withFileTypes: true
2215
+ })) if (entry.isFile()) keys.push(require_nodeCache.toPosixPath((0, node_path.relative)(resolvedBase, (0, node_path.join)(entry.parentPath, entry.name))));
2216
+ } catch (_error) {}
2217
+ return keys;
2218
+ },
2219
+ async empty(base) {
2220
+ if (!base) return;
2221
+ await require_nodeCache.clean((0, node_path.resolve)(base));
2222
+ }
2223
+ }));
2080
2224
  //#endregion
2081
2225
  //#region src/storages/cacheStorage.ts
2082
2226
  /**
@@ -2132,7 +2276,202 @@ const cacheStorage = createStorage(({ root = process.cwd() }) => {
2132
2276
  };
2133
2277
  });
2134
2278
  //#endregion
2279
+ //#region src/output/runHook.ts
2280
+ const KILL_GRACE_MS = 2e3;
2281
+ async function settle(proc, hooks, id, commandWithArgs) {
2282
+ let childError = null;
2283
+ let lineError = null;
2284
+ let lines = Promise.resolve();
2285
+ let killTimer;
2286
+ proc.process?.once("error", (error) => {
2287
+ childError = error;
2288
+ killTimer = setTimeout(() => proc.kill("SIGKILL"), KILL_GRACE_MS).unref();
2289
+ });
2290
+ if (hooks.listenerCount("kubb:hook:line") > 0) for (const input of [proc.process?.stdout, proc.process?.stderr]) {
2291
+ if (!input) continue;
2292
+ (0, node_readline.createInterface)({ input }).on("line", (line) => {
2293
+ lines = lines.then(() => hooks.callHook("kubb:hook:line", {
2294
+ id,
2295
+ line
2296
+ })).catch((error) => {
2297
+ lineError ??= require_nodeCache.toError(error);
2298
+ });
2299
+ });
2300
+ }
2301
+ const output = await Promise.resolve(proc).catch(() => null);
2302
+ clearTimeout(killTimer);
2303
+ await lines;
2304
+ const error = childError ?? lineError;
2305
+ if (error) return {
2306
+ success: false,
2307
+ error
2308
+ };
2309
+ if (output?.exitCode === 0) return {
2310
+ success: true,
2311
+ error: null
2312
+ };
2313
+ return {
2314
+ success: false,
2315
+ error: /* @__PURE__ */ new Error(`Hook execute failed: ${commandWithArgs}`),
2316
+ stdout: output?.stdout,
2317
+ stderr: output?.stderr
2318
+ };
2319
+ }
2320
+ /**
2321
+ * Spawns a command and returns its outcome, announcing it through `kubb:hook:start`,
2322
+ * `kubb:hook:line` (one per stdout or stderr line, only while a listener is attached) and
2323
+ * `kubb:hook:end`. A non-zero exit, a spawn failure, an abort or a throwing line listener returns
2324
+ * `success: false` instead of throwing. The failure travels on the result and `kubb:hook:end`
2325
+ * only, and the caller emits `kubb:success` or a diagnostic, so nothing is reported twice.
2326
+ */
2327
+ async function runHook({ hooks, command, args = [], name, cwd = node_process.default.cwd(), signal }) {
2328
+ const id = (0, node_crypto.randomUUID)();
2329
+ await hooks.callHook("kubb:hook:start", {
2330
+ id,
2331
+ command,
2332
+ name,
2333
+ args
2334
+ });
2335
+ const result = await settle((0, tinyexec.x)(command, [...args], {
2336
+ signal,
2337
+ throwOnError: false,
2338
+ nodeOptions: {
2339
+ cwd,
2340
+ windowsHide: true,
2341
+ stdio: [
2342
+ "ignore",
2343
+ "pipe",
2344
+ "pipe"
2345
+ ],
2346
+ detached: node_process.default.platform !== "win32"
2347
+ }
2348
+ }), hooks, id, [command, ...args].join(" "));
2349
+ await hooks.callHook("kubb:hook:end", {
2350
+ id,
2351
+ command,
2352
+ name,
2353
+ args,
2354
+ ...result
2355
+ });
2356
+ return result;
2357
+ }
2358
+ //#endregion
2359
+ //#region src/output/runOutputPasses.ts
2360
+ /**
2361
+ * Format and lint are one pass over the output directory that differs only in these values.
2362
+ * `label` and `verb` are spelled out: deriving them from `kind` gives "lintter" and "lintting".
2363
+ */
2364
+ const TOOL_PASSES = [{
2365
+ kind: "format",
2366
+ label: "formatter",
2367
+ verb: "Formatting",
2368
+ tools: formatters,
2369
+ preference: FORMATTER_PREFERENCE,
2370
+ code: Diagnostics.code.formatFailed
2371
+ }, {
2372
+ kind: "lint",
2373
+ label: "linter",
2374
+ verb: "Linting",
2375
+ tools: linters,
2376
+ preference: LINTER_PREFERENCE,
2377
+ code: Diagnostics.code.lintFailed
2378
+ }];
2379
+ /**
2380
+ * Resolves `auto` to an installed tool and runs it. Returns the failure instead of throwing.
2381
+ */
2382
+ async function runToolPass({ pass, setting, outputPath, hooks, cwd, signal }) {
2383
+ const detected = setting === "auto" ? await detectTool(pass.preference, cwd) : setting;
2384
+ if (!detected) {
2385
+ await hooks.callHook("kubb:warn", { message: `No ${pass.label} found (${pass.preference.join(", ")}). Skipping ${pass.verb.toLowerCase()}.` });
2386
+ return null;
2387
+ }
2388
+ if (setting === "auto") await hooks.callHook("kubb:info", { message: `Auto-detected ${pass.label}: ${(0, node_util.styleText)("dim", detected)}` });
2389
+ const tool = pass.tools[detected];
2390
+ if (!tool || !(0, node_fs.existsSync)(outputPath)) return null;
2391
+ const result = await runHook({
2392
+ hooks,
2393
+ command: tool.command,
2394
+ args: tool.args(outputPath),
2395
+ cwd,
2396
+ signal
2397
+ });
2398
+ if (result.success) {
2399
+ await hooks.callHook("kubb:success", { message: `${pass.verb} with ${(0, node_util.styleText)("dim", detected)} on ${(0, node_util.styleText)("dim", outputPath)} successfully` });
2400
+ return null;
2401
+ }
2402
+ return result.error;
2403
+ }
2404
+ /**
2405
+ * Runs `output.format`, `output.lint` and `output.postGenerate` over the generated output and
2406
+ * returns the diagnostics they produced. Each failure is emitted through `Diagnostics.emit` and
2407
+ * returned, so it reaches the summary, the reporters and the exit code; the passes keep going so
2408
+ * one failing tool does not hide the next. `Kubb.generate()` runs this after an error-free build
2409
+ * unless the host passes its own `processOutput`.
2410
+ *
2411
+ * @example
2412
+ * ```ts
2413
+ * const diagnostics = await runOutputPasses({ config, outputPath: '/repo/src/gen', hooks })
2414
+ * ```
2415
+ */
2416
+ async function runOutputPasses({ config, outputPath, hooks, signal }) {
2417
+ const diagnostics = [];
2418
+ const report = async (code, label, error) => {
2419
+ const diagnostic = {
2420
+ code,
2421
+ severity: "error",
2422
+ message: `${label} failed: ${error.message}`,
2423
+ help: "Check that the tool is installed and that the command and its config are correct.",
2424
+ location: { kind: "config" },
2425
+ cause: error
2426
+ };
2427
+ diagnostics.push(diagnostic);
2428
+ await Diagnostics.emit(hooks, diagnostic);
2429
+ };
2430
+ for (const pass of TOOL_PASSES) {
2431
+ const setting = config.output[pass.kind];
2432
+ if (!setting) continue;
2433
+ await hooks.callHook(`kubb:${pass.kind}:start`);
2434
+ const error = await runToolPass({
2435
+ pass,
2436
+ setting,
2437
+ outputPath,
2438
+ hooks,
2439
+ cwd: config.root,
2440
+ signal
2441
+ });
2442
+ if (error) await report(pass.code, pass.label, error);
2443
+ await hooks.callHook(`kubb:${pass.kind}:end`);
2444
+ signal?.throwIfAborted();
2445
+ }
2446
+ const commands = config.output.postGenerate ?? [];
2447
+ if (commands.length === 0) return diagnostics;
2448
+ await hooks.callHook("kubb:hooks:start");
2449
+ for (const entry of commands) {
2450
+ const { command, name } = typeof entry === "string" ? {
2451
+ command: entry,
2452
+ name: void 0
2453
+ } : entry;
2454
+ const [executable, ...args] = tokenize(command);
2455
+ if (!executable) continue;
2456
+ const result = await runHook({
2457
+ hooks,
2458
+ command: executable,
2459
+ args,
2460
+ name,
2461
+ cwd: config.root,
2462
+ signal
2463
+ });
2464
+ if (result.success) await hooks.callHook("kubb:success", { message: `${(0, node_util.styleText)("dim", name ?? command)} successfully executed` });
2465
+ if (!result.success) await report(Diagnostics.code.postGenerateFailed, "Post-generate command", result.error);
2466
+ signal?.throwIfAborted();
2467
+ }
2468
+ await hooks.callHook("kubb:hooks:end");
2469
+ return diagnostics;
2470
+ }
2471
+ //#endregion
2135
2472
  //#region src/createKubb.ts
2473
+ /** Upper bound of listeners one plugin adds to a hook, sizing the emitter ceiling for large plugin sets. */
2474
+ const HOOK_LISTENERS_PER_PLUGIN = 4;
2136
2475
  function resolveConfig(userConfig) {
2137
2476
  return {
2138
2477
  ...userConfig,
@@ -2150,11 +2489,18 @@ function resolveConfig(userConfig) {
2150
2489
  };
2151
2490
  }
2152
2491
  /**
2492
+ * Only the fs storage writes `output.path`, so only then do the passes have fresh files to run
2493
+ * over; a memory or custom storage would leave them formatting whatever an earlier run left there.
2494
+ */
2495
+ function writesOutputDirectory(storage) {
2496
+ return storage.name === "fs";
2497
+ }
2498
+ /**
2153
2499
  * Whether anything runs over the output directory after the files are written. Only then can the
2154
2500
  * bytes on disk stop matching what Kubb wrote, which is what the manifest exists to track.
2155
2501
  */
2156
- function hasOutputPasses(output) {
2157
- return Boolean(output.format || output.lint || output.postGenerate?.length);
2502
+ function hasOutputPasses({ output, storage }) {
2503
+ return writesOutputDirectory(storage) && Boolean(output.format || output.lint || output.postGenerate?.length);
2158
2504
  }
2159
2505
  /**
2160
2506
  * Kubb code-generation instance bound to a single config entry. Resolves the user
@@ -2177,17 +2523,15 @@ var Kubb = class {
2177
2523
  hooks;
2178
2524
  config;
2179
2525
  #driver = null;
2180
- #storage = null;
2181
2526
  #manifest = null;
2182
2527
  #signal;
2183
2528
  constructor(userConfig, options = {}) {
2184
2529
  this.config = resolveConfig(userConfig);
2185
- this.hooks = options.hooks ?? new require_usingCtx.Hookable();
2530
+ this.hooks = options.hooks ?? new require_nodeCache.Hookable();
2186
2531
  this.#signal = options.signal;
2187
2532
  }
2188
2533
  get storage() {
2189
- if (!this.#storage) throw new Error("[kubb] setup() must be called before accessing storage");
2190
- return this.#storage;
2534
+ return this.config.storage;
2191
2535
  }
2192
2536
  get driver() {
2193
2537
  if (!this.#driver) throw new Error("[kubb] setup() must be called before accessing driver");
@@ -2200,7 +2544,7 @@ var Kubb = class {
2200
2544
  const signal = this.#signal;
2201
2545
  signal?.throwIfAborted();
2202
2546
  const config = this.config;
2203
- const manifest = hasOutputPasses(config.output) ? await createOutputManifest({
2547
+ const manifest = hasOutputPasses(config) ? await createOutputManifest({
2204
2548
  storage: config.storage,
2205
2549
  cache: cacheStorage({ root: config.root })
2206
2550
  }) : void 0;
@@ -2209,10 +2553,10 @@ var Kubb = class {
2209
2553
  manifest,
2210
2554
  signal
2211
2555
  });
2212
- this.hooks.setMaxListeners(Math.max(10, config.plugins.length * 4));
2556
+ this.hooks.setMaxListeners(Math.max(10, config.plugins.length * HOOK_LISTENERS_PER_PLUGIN));
2213
2557
  if (config.output.clean) {
2214
2558
  const cleanPath = (0, node_path.resolve)(config.root, config.output.path);
2215
- if (require_usingCtx.isPathInside(config.root, cleanPath)) throw new Diagnostics.Error({
2559
+ if (require_nodeCache.isPathInside(config.root, cleanPath)) throw new Diagnostics.Error({
2216
2560
  code: Diagnostics.code.cleanRoot,
2217
2561
  severity: "error",
2218
2562
  message: `output.clean cannot delete "${cleanPath}" because it is the project root or a parent of it.`,
@@ -2223,7 +2567,6 @@ var Kubb = class {
2223
2567
  }
2224
2568
  await driver.setup();
2225
2569
  this.#driver = driver;
2226
- this.#storage = config.storage;
2227
2570
  this.#manifest = manifest ?? null;
2228
2571
  }
2229
2572
  /**
@@ -2245,7 +2588,7 @@ var Kubb = class {
2245
2588
  */
2246
2589
  async safeBuild() {
2247
2590
  try {
2248
- var _usingCtx$1 = require_usingCtx._usingCtx();
2591
+ var _usingCtx$1 = require_nodeCache._usingCtx();
2249
2592
  this.#signal?.throwIfAborted();
2250
2593
  if (!this.#driver) await this.setup();
2251
2594
  const self = _usingCtx$1.u(this);
@@ -2310,9 +2653,12 @@ var Kubb = class {
2310
2653
  diagnostics
2311
2654
  };
2312
2655
  }
2313
- const outputDiagnostics = options.processOutput ? await options.processOutput({
2656
+ const processOutput = options.processOutput ?? runOutputPasses;
2657
+ const outputDiagnostics = writesOutputDirectory(config.storage) ? await processOutput({
2314
2658
  config,
2315
- outputPath: (0, node_path.resolve)(config.root, config.output.path)
2659
+ outputPath: (0, node_path.resolve)(config.root, config.output.path),
2660
+ hooks,
2661
+ signal
2316
2662
  }) : [];
2317
2663
  const finalDiagnostics = [...diagnostics, ...outputDiagnostics];
2318
2664
  const failed = Diagnostics.hasError(outputDiagnostics);
@@ -2633,7 +2979,7 @@ const fileReporter = createReporter({
2633
2979
  Date.now()
2634
2980
  ].filter(Boolean).join("-")}.log`;
2635
2981
  const pathName = (0, node_path.resolve)(node_process.default.cwd(), ".kubb", baseName);
2636
- await require_usingCtx.write(pathName, `${content}\n`);
2982
+ await require_nodeCache.write(pathName, `${content}\n`);
2637
2983
  console.error(`Debug log written to ${(0, node_path.relative)(node_process.default.cwd(), pathName)}`);
2638
2984
  }
2639
2985
  });
@@ -2678,11 +3024,11 @@ const htmlReporter = createReporter({
2678
3024
  ].filter(Boolean).join("-");
2679
3025
  const pathName = (0, node_path.resolve)(process.cwd(), ".kubb", baseName);
2680
3026
  const assets = new URL("./html/", require("url").pathToFileURL(__filename).href);
2681
- const [html, ui] = await Promise.all([require_usingCtx.read((0, node_url.fileURLToPath)(new URL("index.html", assets))), require_usingCtx.read((0, node_url.fileURLToPath)(new URL("ui.iife.js", assets)))]);
3027
+ const [html, ui] = await Promise.all([require_nodeCache.read((0, node_url.fileURLToPath)(new URL("index.html", assets))), require_nodeCache.read((0, node_url.fileURLToPath)(new URL("ui.iife.js", assets)))]);
2682
3028
  await Promise.all([
2683
- require_usingCtx.write((0, node_path.resolve)(pathName, "index.html"), html),
2684
- require_usingCtx.write((0, node_path.resolve)(pathName, "ui.iife.js"), ui),
2685
- require_usingCtx.write((0, node_path.resolve)(pathName, "data.js"), serializeReport(result))
3029
+ require_nodeCache.write((0, node_path.resolve)(pathName, "index.html"), html),
3030
+ require_nodeCache.write((0, node_path.resolve)(pathName, "ui.iife.js"), ui),
3031
+ require_nodeCache.write((0, node_path.resolve)(pathName, "data.js"), serializeReport(result))
2686
3032
  ]);
2687
3033
  const reportPath = (0, node_path.resolve)(pathName, "index.html");
2688
3034
  console.error(`HTML report written to ${(0, node_path.relative)(process.cwd(), reportPath)}`);
@@ -2840,7 +3186,7 @@ const memoryStorage = createStorage(() => {
2840
3186
  });
2841
3187
  //#endregion
2842
3188
  exports.Diagnostics = Diagnostics;
2843
- exports.Hookable = require_usingCtx.Hookable;
3189
+ exports.Hookable = require_nodeCache.Hookable;
2844
3190
  exports.KubbDriver = KubbDriver;
2845
3191
  exports.Resolver = Resolver;
2846
3192
  exports.applyConfigDefaults = applyConfigDefaults;
@@ -2864,5 +3210,7 @@ exports.jsonReporter = jsonReporter;
2864
3210
  exports.logLevel = logLevel;
2865
3211
  exports.memoryStorage = memoryStorage;
2866
3212
  exports.resolveCacheDir = resolveCacheDir;
3213
+ exports.runHook = runHook;
3214
+ exports.runOutputPasses = runOutputPasses;
2867
3215
 
2868
3216
  //# sourceMappingURL=index.cjs.map