@kubb/core 5.8.4 → 5.9.1

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.
@@ -4,10 +4,10 @@ import { AsyncLocalStorage } from "node:async_hooks";
4
4
  import { styleText } from "node:util";
5
5
  import { access, mkdir, readFile, rm, writeFile } from "node:fs/promises";
6
6
  import path, { dirname, isAbsolute, relative, resolve } from "node:path";
7
- import { ast, collectImportedRefNames, collectUsedSchemaNames, composeMacros, extractStringsFromNodes, operationDef, schemaDef, transform } from "@kubb/ast";
7
+ import { ast, collectImportedRefNames, collectUsedSchemaNames, composeMacros, extractStringsFromNodes, transform } from "@kubb/ast";
8
8
  import { EventEmitter } from "node:events";
9
9
  //#region package.json
10
- var version = "5.8.4";
10
+ var version = "5.9.1";
11
11
  //#endregion
12
12
  //#region ../../internals/utils/src/casing.ts
13
13
  /**
@@ -65,74 +65,34 @@ function getErrorMessage(value) {
65
65
  }
66
66
  //#endregion
67
67
  //#region ../../internals/utils/src/runtime.ts
68
+ const isBun = typeof Bun !== "undefined";
69
+ const isDeno = "Deno" in globalThis;
68
70
  /**
69
- * Detects the JavaScript runtime executing the current process and exposes its name and version.
71
+ * The JavaScript runtime executing the current process: its name, version and whether it is Bun.
70
72
  *
71
- * Prefer the shared {@link runtime} instance over constructing your own.
73
+ * @example
74
+ * ```ts
75
+ * runtime.name // 'bun' when run with `bun kubb`, 'node' otherwise
76
+ * ```
72
77
  */
73
- var Runtime = class {
74
- /**
75
- * `true` when the current process is running under Bun.
76
- *
77
- * Detection keys off the global `Bun` object rather than `process.versions`,
78
- * because Bun polyfills `process.versions.node` for Node compatibility and would
79
- * otherwise look like Node.
80
- *
81
- * @example
82
- * ```ts
83
- * if (runtime.isBun) {
84
- * await Bun.write(path, data)
85
- * }
86
- * ```
87
- */
88
- get isBun() {
89
- return typeof Bun !== "undefined";
90
- }
91
- /**
92
- * `true` when the current process is running under Deno.
93
- */
94
- get isDeno() {
95
- return typeof globalThis.Deno !== "undefined";
96
- }
97
- /**
98
- * `true` when the current process is running under Node.
99
- *
100
- * Bun and Deno are excluded first so a polyfilled `process` does not register as Node.
101
- */
102
- get isNode() {
103
- return !this.isBun && !this.isDeno && typeof process !== "undefined" && process.versions?.node != null;
104
- }
105
- /**
106
- * Name of the runtime executing the current process.
107
- *
108
- * @example
109
- * ```ts
110
- * runtime.name // 'bun' when run with `bun kubb`, 'node' otherwise
111
- * ```
112
- */
113
- get name() {
114
- if (this.isBun) return "bun";
115
- if (this.isDeno) return "deno";
116
- return "node";
117
- }
118
- /**
119
- * Version of the active runtime, or an empty string when it cannot be read.
120
- *
121
- * @example
122
- * ```ts
123
- * runtime.version // '1.3.11' under Bun, '22.22.2' under Node
124
- * ```
125
- */
126
- get version() {
127
- if (this.isBun) return process.versions.bun ?? "";
128
- if (this.isDeno) return globalThis.Deno?.version?.deno ?? "";
129
- return process.versions?.node ?? "";
130
- }
78
+ const runtime = {
79
+ isBun,
80
+ ...detect()
131
81
  };
132
- /**
133
- * Shared {@link Runtime} instance describing the JavaScript runtime executing the current process.
134
- */
135
- const runtime = new Runtime();
82
+ function detect() {
83
+ if (isBun) return {
84
+ name: "bun",
85
+ version: process.versions.bun ?? ""
86
+ };
87
+ if (isDeno) return {
88
+ name: "deno",
89
+ version: globalThis.Deno?.version?.deno ?? ""
90
+ };
91
+ return {
92
+ name: "node",
93
+ version: process.versions?.node ?? ""
94
+ };
95
+ }
136
96
  //#endregion
137
97
  //#region ../../internals/utils/src/fs.ts
138
98
  /**
@@ -401,6 +361,10 @@ const diagnosticCode = {
401
361
  * A plugin threw while generating.
402
362
  */
403
363
  pluginFailed: "KUBB_PLUGIN_FAILED",
364
+ /** An adapter threw while parsing the input. */
365
+ adapterFailed: "KUBB_ADAPTER_FAILED",
366
+ /** A parser threw while printing a generated file. */
367
+ parserFailed: "KUBB_PARSER_FAILED",
404
368
  /**
405
369
  * A plugin reported a non-fatal warning through `ctx.warn`.
406
370
  */
@@ -520,6 +484,11 @@ const severityStyle = {
520
484
  warning: "yellow",
521
485
  info: "blue"
522
486
  };
487
+ const failedCode = {
488
+ plugin: diagnosticCode.pluginFailed,
489
+ adapter: diagnosticCode.adapterFailed,
490
+ parser: diagnosticCode.parserFailed
491
+ };
523
492
  const countKey = {
524
493
  error: "errors",
525
494
  warning: "warnings",
@@ -603,7 +572,17 @@ const diagnosticCatalog = {
603
572
  [diagnosticCode.pluginFailed]: {
604
573
  title: "Plugin failed",
605
574
  cause: "A plugin threw while generating, or reported an error through `ctx.error`.",
606
- fix: "Read the underlying error and check the plugin options and the schema or operation it failed on."
575
+ fix: "Read the underlying error and check the plugin options and the schema or operation it failed on. If the plugin crashed, rerun with `--verbose` for the stack trace and report it to the plugin maintainers, at the `report:` link when one is shown."
576
+ },
577
+ [diagnosticCode.adapterFailed]: {
578
+ title: "Adapter failed",
579
+ cause: "The adapter threw an unexpected error while parsing the input.",
580
+ fix: "This is likely a bug in the adapter. Rerun with `--verbose` for the stack trace and report it to the adapter maintainers, at the `report:` link when one is shown."
581
+ },
582
+ [diagnosticCode.parserFailed]: {
583
+ title: "Parser failed",
584
+ cause: "A parser threw an unexpected error while printing a generated file.",
585
+ fix: "This is likely a bug in the parser. Rerun with `--verbose` for the stack trace and report it to the parser maintainers, at the `report:` link when one is shown."
607
586
  },
608
587
  [diagnosticCode.pluginWarning]: {
609
588
  title: "Plugin warning",
@@ -785,6 +764,29 @@ var Diagnostics = class Diagnostics {
785
764
  };
786
765
  }
787
766
  /**
767
+ * Coerces an error thrown by a plugin, adapter, or parser into a diagnostic attributed to it.
768
+ * A structured {@link Diagnostics.Error} keeps its code. Any other error is a crash: it gets the
769
+ * kind's `*_FAILED` code and the extension's `meta.issues` link, so the user reports it to the
770
+ * extension's maintainers instead of to Kubb.
771
+ */
772
+ static fromExtension(error, { kind, extension }) {
773
+ const diagnostic = Diagnostics.from(error);
774
+ const name = extension.meta?.name ?? extension.name;
775
+ const owner = kind === "plugin" ? { plugin: diagnostic.plugin ?? name } : {};
776
+ if (diagnostic.code !== diagnosticCode.unknown || diagnostic.cause?.name === "AbortError") return {
777
+ ...diagnostic,
778
+ ...owner
779
+ };
780
+ const issues = extension.meta?.issues;
781
+ return {
782
+ ...diagnostic,
783
+ ...owner,
784
+ code: failedCode[kind],
785
+ message: kind === "plugin" ? diagnostic.message : `${kind} "${name}" crashed: ${diagnostic.message}`,
786
+ ...issues ? { issues } : {}
787
+ };
788
+ }
789
+ /**
788
790
  * Builds a per-plugin performance record. Reporters sum these into the run total.
789
791
  */
790
792
  static performance({ plugin, duration }) {
@@ -887,13 +889,14 @@ var Diagnostics = class Diagnostics {
887
889
  ...problem?.location ? { location: problem.location } : {},
888
890
  ...problem?.help ? { help: problem.help } : {},
889
891
  ...problem?.plugin ? { plugin: problem.plugin } : {},
892
+ ...problem?.issues ? { issues: problem.issues } : {},
890
893
  ...diagnostic.code === diagnosticCode.unknown ? {} : { docsUrl: Diagnostics.docsUrl(diagnostic.code) }
891
894
  };
892
895
  }
893
896
  /**
894
897
  * Renders a {@link Diagnostic} for terminal output as its parts: the `headline`
895
898
  * (`[CODE] plugin: message`, with the code in the severity color) and the indented `details`
896
- * rows (`at:` pointer, `fix:` help, `see:` docs link).
899
+ * rows (`at:` pointer, `fix:` help, `see:` docs link, `report:` issue tracker).
897
900
  *
898
901
  * Hosts compose these to fit their gutter: a clack logger passes `[headline, ...details]` as the
899
902
  * message with no gutter symbol, while plain text outputs use {@link Diagnostics.formatLines}.
@@ -908,6 +911,7 @@ var Diagnostics = class Diagnostics {
908
911
  if (problem?.location && "pointer" in problem.location) details.push(` ${styleText("dim", "at:")} ${styleText("cyan", problem.location.pointer)}`);
909
912
  if (problem?.help) details.push(` ${styleText("cyan", "fix:")} ${problem.help}`);
910
913
  if (code !== diagnosticCode.unknown) details.push(` ${styleText("dim", "see:")} ${styleText("cyan", Diagnostics.docsUrl(code))}`);
914
+ if (problem?.issues) details.push(` ${styleText("dim", "report:")} ${styleText("cyan", problem.issues)}`);
911
915
  return {
912
916
  headline,
913
917
  details
@@ -1467,7 +1471,7 @@ var Resolver = class Resolver {
1467
1471
  return null;
1468
1472
  }
1469
1473
  static #computeOptions(node, { options, exclude = [], include, override = [] }) {
1470
- if (operationDef.is(node)) {
1474
+ if (node.kind === "Operation") {
1471
1475
  if (exclude.some((filter) => Resolver.#matchesOperation(node, filter))) return null;
1472
1476
  if (include && !include.some((filter) => Resolver.#matchesOperation(node, filter))) return null;
1473
1477
  return {
@@ -1475,7 +1479,7 @@ var Resolver = class Resolver {
1475
1479
  ...override.find((filter) => Resolver.#matchesOperation(node, filter))?.options
1476
1480
  };
1477
1481
  }
1478
- if (schemaDef.is(node)) {
1482
+ if (node.kind === "Schema") {
1479
1483
  if (exclude.some((filter) => Resolver.#matchesSchema(node, filter) === true)) return null;
1480
1484
  if (include) {
1481
1485
  const applicable = include.map((filter) => Resolver.#matchesSchema(node, filter)).filter((result) => result !== null);
@@ -1870,6 +1874,17 @@ function _usingCtx() {
1870
1874
  function joinSources(file) {
1871
1875
  return file.sources.map((source) => extractStringsFromNodes(source.nodes)).filter(Boolean).join("\n\n");
1872
1876
  }
1877
+ /** Runs a parser call and turns a crash into a `KUBB_PARSER_FAILED` diagnostic that names the parser. */
1878
+ function runParser(parser, print) {
1879
+ try {
1880
+ return print();
1881
+ } catch (error) {
1882
+ throw new Diagnostics.Error(Diagnostics.fromExtension(error, {
1883
+ kind: "parser",
1884
+ extension: parser
1885
+ }));
1886
+ }
1887
+ }
1873
1888
  /**
1874
1889
  * Reads a `copy` file and prints it through the parser's `copy` hook, or verbatim with `banner`/`footer` when there is none.
1875
1890
  */
@@ -1880,7 +1895,7 @@ async function parseCopy(file, parser) {
1880
1895
  } catch (err) {
1881
1896
  throw new Error(`[kubb] Could not copy file into output: ${file.copy}`, { cause: err });
1882
1897
  }
1883
- if (parser?.copy) return parser.parse(ast.factory.createFile(parser.copy(file, content)));
1898
+ if (parser?.copy) return runParser(parser, () => parser.parse(ast.factory.createFile(parser.copy(file, content))));
1884
1899
  return [
1885
1900
  file.banner,
1886
1901
  content,
@@ -2002,7 +2017,7 @@ var FileManager = class {
2002
2017
  const parser = parsers?.get(file.extname);
2003
2018
  if (file.copy) return parseCopy(file, parser);
2004
2019
  if (!parser) return joinSources(file);
2005
- return parser.parse(file);
2020
+ return runParser(parser, () => parser.parse(file));
2006
2021
  }
2007
2022
  /**
2008
2023
  * Parses and writes every file through a bounded pool of workers. A small spec runs all its files
@@ -2308,7 +2323,14 @@ var KubbDriver = class {
2308
2323
  async #parseInput() {
2309
2324
  if (this.inputNode || !this.adapter || !this.#adapterSource) return;
2310
2325
  this.options.signal?.throwIfAborted();
2311
- this.inputNode = await this.adapter.parse(this.#adapterSource, { signal: this.options.signal });
2326
+ try {
2327
+ this.inputNode = await this.adapter.parse(this.#adapterSource, { signal: this.options.signal });
2328
+ } catch (caughtError) {
2329
+ throw new Diagnostics.Error(Diagnostics.fromExtension(caughtError, {
2330
+ kind: "adapter",
2331
+ extension: this.adapter
2332
+ }));
2333
+ }
2312
2334
  }
2313
2335
  /**
2314
2336
  * Registers a plugin's lifecycle hooks on the shared `Hookable` as pass-through listeners that
@@ -2366,18 +2388,13 @@ var KubbDriver = class {
2366
2388
  await setupHook?.(ctx);
2367
2389
  });
2368
2390
  } catch (caughtError) {
2369
- const diagnostic = Diagnostics.from(caughtError);
2370
- throw new Diagnostics.Error({
2371
- ...diagnostic,
2372
- plugin: diagnostic.plugin ?? plugin.name
2373
- });
2391
+ throw new Diagnostics.Error(Diagnostics.fromExtension(caughtError, {
2392
+ kind: "plugin",
2393
+ extension: plugin
2394
+ }));
2374
2395
  }
2375
2396
  }
2376
2397
  }
2377
- /** `true` once `addGenerator()` in `kubb:plugin:setup` registered a generator for the plugin. */
2378
- hasHookGenerators(pluginName) {
2379
- return (this.plugins.get(pluginName)?.generators?.length ?? 0) > 0;
2380
- }
2381
2398
  /**
2382
2399
  * Runs the full plugin pipeline. Returns the diagnostics collected so far even
2383
2400
  * when an outer hook throws, since the orchestrator preserves partial state by capturing
@@ -2444,16 +2461,16 @@ var KubbDriver = class {
2444
2461
  success: false,
2445
2462
  error
2446
2463
  });
2447
- diagnostics.push({
2448
- ...Diagnostics.from(error),
2449
- plugin: plugin.name
2450
- }, Diagnostics.performance({
2464
+ diagnostics.push(Diagnostics.fromExtension(error, {
2465
+ kind: "plugin",
2466
+ extension: plugin
2467
+ }), Diagnostics.performance({
2451
2468
  plugin: plugin.name,
2452
2469
  duration
2453
2470
  }));
2454
2471
  continue;
2455
2472
  }
2456
- if (this.hasHookGenerators(plugin.name)) {
2473
+ if ((plugin.generators?.length ?? 0) > 0) {
2457
2474
  generatorPlugins.push({
2458
2475
  plugin,
2459
2476
  context,
@@ -2671,7 +2688,7 @@ var KubbDriver = class {
2671
2688
  options: state.plugin.options,
2672
2689
  cache: createNodeCache()
2673
2690
  };
2674
- for (const generator of state.operationsGenerators) await this.dispatch({
2691
+ for (const generator of state.operationsGenerators) await this.fileManager.dispatch({
2675
2692
  result: await generator.operations(state.pluginOperations, ctx),
2676
2693
  renderer: generator.renderer
2677
2694
  });
@@ -2688,10 +2705,10 @@ var KubbDriver = class {
2688
2705
  success: !state.error,
2689
2706
  error: state.error ?? void 0
2690
2707
  });
2691
- if (state.error) diagnostics.push({
2692
- ...Diagnostics.from(state.error),
2693
- plugin: state.plugin.name
2694
- });
2708
+ if (state.error) diagnostics.push(Diagnostics.fromExtension(state.error, {
2709
+ kind: "plugin",
2710
+ extension: state.plugin
2711
+ }));
2695
2712
  diagnostics.push(Diagnostics.performance({
2696
2713
  plugin: state.plugin.name,
2697
2714
  duration
@@ -2703,16 +2720,12 @@ var KubbDriver = class {
2703
2720
  async #dispatchNode({ generators, node, ctx, generate }) {
2704
2721
  for (const generator of generators) {
2705
2722
  if (!(generator.match ? await generator.match(node, ctx) : true)) continue;
2706
- await this.dispatch({
2723
+ await this.fileManager.dispatch({
2707
2724
  result: await generate(generator),
2708
2725
  renderer: generator.renderer
2709
2726
  });
2710
2727
  }
2711
2728
  }
2712
- /** Stores whatever a generator method or `kubb:generate:*` hook returned, see {@link FileManager.dispatch}. */
2713
- dispatch(params) {
2714
- return this.fileManager.dispatch(params);
2715
- }
2716
2729
  /**
2717
2730
  * Removes every listener the driver added. Listeners attached directly to `hooks` from outside
2718
2731
  * the driver survive. Called at the end of a build to prevent leaks across repeated builds.
@@ -2824,4 +2837,4 @@ function pluginNotFoundError({ pluginName, requiredBy }) {
2824
2837
  //#endregion
2825
2838
  export { getElapsedMs as A, useOptions as C, resolveMeta as D, defineExtension as E, read as F, toPosixPath as I, write as L, clean as M, exists as N, Diagnostics as O, isPathInside as P, toError as R, useKubb as S, createExtensionFactory as T, setMacros as _, _usingCtx as a, tryUseKubb as b, Resolver as c, definePlugin as d, addGenerator as f, requirePlugin as g, kubbContext as h, FileManager as i, inParallel as j, formatMs as k, getInputKind as l, injectFile as m, pluginNotFoundError as n, Hookable as o, addMacro as p, createNodeCache as r, createResolver as s, KubbDriver as t, assertPluginOption as u, setOptions as v, checkCompatibility as w, useConfig as x, setResolver as y, camelCase as z };
2826
2839
 
2827
- //# sourceMappingURL=KubbDriver-DbOEJvzz.js.map
2840
+ //# sourceMappingURL=KubbDriver-GBBjs4Pb.js.map