@kubb/core 5.6.3 → 5.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -4,6 +4,7 @@ import { styleText } from "node:util";
4
4
  import { access, mkdir, readFile, rm, writeFile } from "node:fs/promises";
5
5
  import path, { dirname, isAbsolute, relative, resolve } from "node:path";
6
6
  import { ast, collectImportedRefNames, collectUsedSchemaNames, composeMacros, extractStringsFromNodes, operationDef, schemaDef, transform } from "@kubb/ast";
7
+ import { satisfies } from "verkit";
7
8
  import { EventEmitter } from "node:events";
8
9
  //#region ../../internals/utils/src/casing.ts
9
10
  /**
@@ -329,7 +330,7 @@ function formatMs(ms) {
329
330
  }
330
331
  //#endregion
331
332
  //#region package.json
332
- var version = "5.6.3";
333
+ var version = "5.7.0";
333
334
  //#endregion
334
335
  //#region src/constants.ts
335
336
  /**
@@ -385,6 +386,18 @@ const diagnosticCode = {
385
386
  */
386
387
  pluginNotFound: "KUBB_PLUGIN_NOT_FOUND",
387
388
  /**
389
+ * The running Kubb or Node.js version is outside a plugin's `meta.compatibility`.
390
+ */
391
+ incompatibleExtension: "KUBB_INCOMPATIBLE_EXTENSION",
392
+ /**
393
+ * A required entry in a plugin's `dependencies` record is missing from the config.
394
+ */
395
+ missingDependency: "KUBB_MISSING_DEPENDENCY",
396
+ /**
397
+ * A dependency's `meta.version` is outside the range a plugin's `dependencies` record declares.
398
+ */
399
+ incompatibleDependency: "KUBB_INCOMPATIBLE_DEPENDENCY",
400
+ /**
388
401
  * A plugin threw while generating.
389
402
  */
390
403
  pluginFailed: "KUBB_PLUGIN_FAILED",
@@ -397,6 +410,10 @@ const diagnosticCode = {
397
410
  */
398
411
  pluginInfo: "KUBB_PLUGIN_INFO",
399
412
  /**
413
+ * A `kubb/kit` composable was called outside a plugin's `setup` and `kubb:plugin:setup`.
414
+ */
415
+ noContext: "KUBB_NO_CONTEXT",
416
+ /**
400
417
  * A schema uses a `format` Kubb does not map to a specific type. Reserved for
401
418
  * adapters to emit as a `warning`.
402
419
  */
@@ -568,6 +585,21 @@ const diagnosticCatalog = {
568
585
  cause: "A plugin that another plugin depends on is missing from the config.",
569
586
  fix: "Add the required plugin to the `plugins` array in kubb.config.ts, or remove the dependency on it."
570
587
  },
588
+ [diagnosticCode.incompatibleExtension]: {
589
+ title: "Incompatible extension",
590
+ cause: "A plugin sets `meta.compatibility.kubb` or `meta.compatibility.node` to a range the running Kubb or Node.js version does not satisfy.",
591
+ fix: "Upgrade Kubb or Node.js to a version in the range, or install a version of the plugin that supports your current Kubb and Node.js."
592
+ },
593
+ [diagnosticCode.missingDependency]: {
594
+ title: "Missing dependency",
595
+ cause: "A plugin lists another plugin in its `dependencies` record without `optional: true`, and the config does not include it.",
596
+ fix: "Add the missing plugin to the `plugins` array in kubb.config.ts."
597
+ },
598
+ [diagnosticCode.incompatibleDependency]: {
599
+ title: "Incompatible dependency",
600
+ cause: "A plugin's `dependencies` record sets a `version` range, and the configured plugin's `meta.version` falls outside it.",
601
+ fix: "Install a version of the dependency inside the range, or a version of the dependent plugin that supports the installed dependency."
602
+ },
571
603
  [diagnosticCode.pluginFailed]: {
572
604
  title: "Plugin failed",
573
605
  cause: "A plugin threw while generating, or reported an error through `ctx.error`.",
@@ -583,6 +615,11 @@ const diagnosticCatalog = {
583
615
  cause: "A plugin reported an informational message through `ctx.info`.",
584
616
  fix: "Informational only. No action is required."
585
617
  },
618
+ [diagnosticCode.noContext]: {
619
+ title: "No plugin context",
620
+ cause: "A `kubb/kit` composable such as `useKubb()` or `addGenerator()` ran outside the `setup` and `kubb:plugin:setup` of a plugin, so there is no plugin to apply it to.",
621
+ fix: "Call the composable inside `setup` or `kubb:plugin:setup`, including in code that setup awaits."
622
+ },
586
623
  [diagnosticCode.unsupportedFormat]: {
587
624
  title: "Unsupported format",
588
625
  cause: "A schema uses a `format` Kubb does not map to a specific type, so it falls back to the base type.",
@@ -886,6 +923,172 @@ var Diagnostics = class Diagnostics {
886
923
  }
887
924
  };
888
925
  //#endregion
926
+ //#region src/composables.ts
927
+ /**
928
+ * Holds the setup context of the plugin whose `setup` or `kubb:plugin:setup` is running. `KubbDriver` sets it for each plugin.
929
+ */
930
+ const kubbContext = new AsyncLocalStorage();
931
+ function requireContext(caller) {
932
+ const ctx = kubbContext.getStore();
933
+ if (ctx) return ctx;
934
+ throw new Diagnostics.Error({
935
+ code: Diagnostics.code.noContext,
936
+ severity: "error",
937
+ message: `\`${caller}()\` was called outside a plugin setup.`,
938
+ help: `Call \`${caller}()\` inside \`setup\` or \`kubb:plugin:setup\`, including in code that setup awaits.`
939
+ });
940
+ }
941
+ /**
942
+ * Returns the context of the plugin whose `kubb:plugin:setup` is running. It stays available after an `await`.
943
+ * Throws `KUBB_NO_CONTEXT` outside setup.
944
+ */
945
+ function useKubb() {
946
+ return requireContext("useKubb");
947
+ }
948
+ /**
949
+ * Returns the same context as {@link useKubb}, or `undefined` outside `setup` and `kubb:plugin:setup`.
950
+ */
951
+ function tryUseKubb() {
952
+ return kubbContext.getStore();
953
+ }
954
+ /**
955
+ * Registers generators on the plugin being set up, like `ctx.addGenerator`.
956
+ *
957
+ * @example
958
+ * `addGenerator(typeGenerator, enumGenerator)`
959
+ */
960
+ function addGenerator(...generators) {
961
+ requireContext("addGenerator").addGenerator(...generators);
962
+ }
963
+ /**
964
+ * Sets the resolver of the plugin being set up, like `ctx.setResolver`.
965
+ */
966
+ function setResolver(resolver) {
967
+ requireContext("setResolver").setResolver(resolver);
968
+ }
969
+ /**
970
+ * Adds a macro to the plugin being set up, like `ctx.addMacro`.
971
+ */
972
+ function addMacro(macro) {
973
+ requireContext("addMacro").addMacro(macro);
974
+ }
975
+ /**
976
+ * Replaces the macros of the plugin being set up, like `ctx.setMacros`.
977
+ */
978
+ function setMacros(macros) {
979
+ requireContext("setMacros").setMacros(macros);
980
+ }
981
+ /**
982
+ * Adds a raw file to the build output, like `ctx.injectFile`.
983
+ */
984
+ function injectFile(file) {
985
+ requireContext("injectFile").injectFile(file);
986
+ }
987
+ /**
988
+ * Returns the options the user passed to the plugin being set up, like `ctx.options`.
989
+ */
990
+ function useOptions() {
991
+ return requireContext("useOptions").options;
992
+ }
993
+ /**
994
+ * Sets the resolved options of the plugin being set up, like `ctx.setOptions`.
995
+ */
996
+ function setOptions(options) {
997
+ requireContext("setOptions").setOptions(options);
998
+ }
999
+ /**
1000
+ * Returns the resolved build configuration, like `ctx.config`.
1001
+ */
1002
+ function useConfig() {
1003
+ return requireContext("useConfig").config;
1004
+ }
1005
+ /**
1006
+ * Returns another plugin from the config, typed through `Kubb.PluginRegistry`, like `ctx.requirePlugin`.
1007
+ */
1008
+ function requirePlugin(name) {
1009
+ return requireContext("requirePlugin").requirePlugin(name);
1010
+ }
1011
+ //#endregion
1012
+ //#region src/defineExtension.ts
1013
+ /**
1014
+ * Returns `meta`, or `{ name }` for an extension that only sets the deprecated `name`. Throws `KUBB_INVALID_PLUGIN_OPTIONS` when it has neither.
1015
+ */
1016
+ function resolveMeta({ name, meta }) {
1017
+ if (meta) return meta;
1018
+ if (name) return { name };
1019
+ throw new Diagnostics.Error({
1020
+ code: Diagnostics.code.invalidPluginOptions,
1021
+ severity: "error",
1022
+ message: "An extension has neither `meta.name` nor `name`.",
1023
+ help: "Set `meta: { name }` on the plugin or parser.",
1024
+ location: { kind: "config" }
1025
+ });
1026
+ }
1027
+ /**
1028
+ * Throws `KUBB_INCOMPATIBLE_EXTENSION` when the running Kubb or Node.js version is outside `meta.compatibility`.
1029
+ */
1030
+ function checkCompatibility(meta) {
1031
+ const checks = [{
1032
+ target: "Kubb",
1033
+ range: meta.compatibility?.kubb,
1034
+ version
1035
+ }, {
1036
+ target: "Node.js",
1037
+ range: meta.compatibility?.node,
1038
+ version: process.versions.node
1039
+ }];
1040
+ for (const { target, range, version } of checks) {
1041
+ if (!range || satisfies(version, range, { includePrerelease: true })) continue;
1042
+ throw new Diagnostics.Error({
1043
+ code: Diagnostics.code.incompatibleExtension,
1044
+ severity: "error",
1045
+ message: `"${meta.name}" requires ${target} ${range}, but ${version} is running.`,
1046
+ help: `Use a ${target} version that satisfies ${range}, or a version of "${meta.name}" that supports ${target} ${version}.`,
1047
+ location: { kind: "config" },
1048
+ plugin: meta.name
1049
+ });
1050
+ }
1051
+ }
1052
+ /**
1053
+ * Throws `KUBB_MISSING_DEPENDENCY` for a missing required entry in a `dependencies` record, and
1054
+ * `KUBB_INCOMPATIBLE_DEPENDENCY` when an entry's `meta.version` is out of range. Arrays are not checked.
1055
+ */
1056
+ function checkDependencies({ name, dependencies, plugins }) {
1057
+ if (!dependencies || Array.isArray(dependencies)) return;
1058
+ for (const [dependencyName, dependency] of Object.entries(dependencies)) {
1059
+ const target = plugins.get(dependencyName);
1060
+ if (!target) {
1061
+ if (dependency?.optional) continue;
1062
+ throw new Diagnostics.Error({
1063
+ code: Diagnostics.code.missingDependency,
1064
+ severity: "error",
1065
+ message: `Plugin "${dependencyName}" is required by "${name}" but not found.`,
1066
+ help: `Add "${dependencyName}" to the \`plugins\` array in kubb.config.ts.`,
1067
+ location: { kind: "config" },
1068
+ plugin: name
1069
+ });
1070
+ }
1071
+ const range = dependency?.version;
1072
+ const version = target.meta?.version;
1073
+ if (!range || !version || satisfies(version, range, { includePrerelease: true })) continue;
1074
+ throw new Diagnostics.Error({
1075
+ code: Diagnostics.code.incompatibleDependency,
1076
+ severity: "error",
1077
+ message: `"${name}" requires "${dependencyName}" ${range}, but ${version} is configured.`,
1078
+ help: `Install a version of "${dependencyName}" that satisfies ${range}.`,
1079
+ location: { kind: "config" },
1080
+ plugin: name
1081
+ });
1082
+ }
1083
+ }
1084
+ function defineExtension({ kind, meta, build }) {
1085
+ const factory = (options) => build(options ?? {});
1086
+ return Object.assign(factory, meta ? {
1087
+ kind,
1088
+ meta
1089
+ } : { kind });
1090
+ }
1091
+ //#endregion
889
1092
  //#region src/definePlugin.ts
890
1093
  /**
891
1094
  * Merges the `output.mode` default into the output config and validates the combination.
@@ -925,30 +1128,31 @@ function assertPluginOption({ plugin, option, value, allowed }) {
925
1128
  plugin
926
1129
  });
927
1130
  }
928
- /**
929
- * Wraps a plugin factory and returns a function that accepts user options and
930
- * yields a typed `Plugin`. Lifecycle handlers go inside a single `hooks` object.
931
- *
932
- * Pass a `PluginFactoryOptions` type parameter to get a typed `ctx` inside
933
- * `kubb:plugin:setup`. Plugin names should follow the `plugin-<feature>`
934
- * convention (`plugin-react-query`, `plugin-zod`, ...).
935
- *
936
- * @example
937
- * ```ts
938
- * import { definePlugin } from '@kubb/core'
939
- *
940
- * export const pluginTs = definePlugin((options: { prefix?: string } = {}) => ({
941
- * name: 'plugin-ts',
942
- * hooks: {
943
- * 'kubb:plugin:setup'(ctx) {
944
- * ctx.setResolver(resolverTs)
945
- * },
946
- * },
947
- * }))
948
- * ```
949
- */
950
- function definePlugin(factory) {
951
- return (options) => factory(options ?? {});
1131
+ function definePlugin(input) {
1132
+ if (typeof input === "function") return defineExtension({
1133
+ kind: "plugin",
1134
+ build: (options) => {
1135
+ const plugin = input(options);
1136
+ return {
1137
+ ...plugin,
1138
+ meta: resolveMeta(plugin)
1139
+ };
1140
+ }
1141
+ });
1142
+ const { meta, dependencies, enforce, hooks = {}, setup } = input;
1143
+ return defineExtension({
1144
+ kind: "plugin",
1145
+ meta,
1146
+ build: (options) => ({
1147
+ name: meta.name,
1148
+ meta,
1149
+ options,
1150
+ dependencies,
1151
+ enforce,
1152
+ hooks,
1153
+ setup
1154
+ })
1155
+ });
952
1156
  }
953
1157
  //#endregion
954
1158
  //#region src/input.ts
@@ -1985,23 +2189,34 @@ var KubbDriver = class {
1985
2189
  this.adapter = config.adapter ?? null;
1986
2190
  }
1987
2191
  /**
1988
- * Normalizes every configured plugin, orders them, and registers their lifecycle handlers.
2192
+ * Normalizes and checks every configured plugin, orders them, and registers their lifecycle handlers.
1989
2193
  * A plugin that another lists as a dependency runs first, then `enforce: 'pre'` before
1990
2194
  * `'post'`. When the config has an adapter, the adapter source is resolved from the input
1991
2195
  * so `run` can parse it later.
1992
2196
  */
1993
2197
  async setup() {
1994
2198
  this.options.signal?.throwIfAborted();
2199
+ for (const parser of this.config.parsers) if (parser.meta) checkCompatibility(parser.meta);
1995
2200
  const normalized = this.#sortPlugins(this.config.plugins.map((rawPlugin) => {
2201
+ if (rawPlugin.meta) checkCompatibility(rawPlugin.meta);
2202
+ const meta = resolveMeta(rawPlugin);
1996
2203
  return {
1997
- name: rawPlugin.name,
1998
- dependencies: rawPlugin.dependencies,
2204
+ name: meta.name,
2205
+ meta,
2206
+ dependencies: typeof rawPlugin.dependencies === "function" ? rawPlugin.dependencies(rawPlugin.options ?? {}, { config: this.config }) : rawPlugin.dependencies,
1999
2207
  enforce: rawPlugin.enforce,
2000
2208
  hooks: rawPlugin.hooks,
2209
+ setup: rawPlugin.setup,
2001
2210
  options: rawPlugin.options ?? defaultPluginOptions(),
2002
- resolver: createResolver({ pluginName: rawPlugin.name })
2211
+ resolver: createResolver({ pluginName: meta.name })
2003
2212
  };
2004
2213
  }));
2214
+ const byName = new Map(normalized.map((plugin) => [plugin.name, plugin]));
2215
+ for (const plugin of normalized) checkDependencies({
2216
+ name: plugin.name,
2217
+ dependencies: plugin.dependencies,
2218
+ plugins: byName
2219
+ });
2005
2220
  for (const plugin of normalized) {
2006
2221
  this.#registerPlugin(plugin);
2007
2222
  this.plugins.set(plugin.name, plugin);
@@ -2019,7 +2234,10 @@ var KubbDriver = class {
2019
2234
  #sortPlugins(plugins) {
2020
2235
  const queue = [...plugins].sort((a, b) => enforceWeight(a) - enforceWeight(b));
2021
2236
  const names = new Set(queue.map((plugin) => plugin.name));
2022
- const blockedBy = new Map(queue.map((plugin) => [plugin.name, new Set(plugin.dependencies?.filter((name) => names.has(name) && name !== plugin.name))]));
2237
+ const blockedBy = new Map(queue.map((plugin) => {
2238
+ const dependencies = Array.isArray(plugin.dependencies) ? plugin.dependencies : Object.keys(plugin.dependencies ?? {});
2239
+ return [plugin.name, new Set(dependencies.filter((name) => names.has(name) && name !== plugin.name))];
2240
+ }));
2023
2241
  const sorted = [];
2024
2242
  for (const _ of plugins) {
2025
2243
  const index = queue.findIndex((plugin) => blockedBy.get(plugin.name)?.size === 0);
@@ -2064,41 +2282,45 @@ var KubbDriver = class {
2064
2282
  this.#unhooks.push(this.hooks.addHooks(configHooks));
2065
2283
  }
2066
2284
  /**
2067
- * Runs each plugin's `kubb:plugin:setup` handler, in plugin order, with a context scoped to that
2285
+ * Runs each plugin's `setup` and `kubb:plugin:setup` handler, in plugin order, with a context scoped to that
2068
2286
  * plugin so `addGenerator`, `setResolver`, `addMacro`, `setMacros`, and `setOptions` target its
2069
2287
  * `NormalizedPlugin` entry. Called once from `run` before the plugin execution loop begins, so
2070
2288
  * plugins can configure generators, resolvers, macros, and options before `buildStart`.
2071
2289
  */
2072
2290
  async setupHooks() {
2073
2291
  for (const plugin of this.plugins.values()) {
2074
- const setup = plugin.hooks?.["kubb:plugin:setup"];
2075
- if (!setup) continue;
2292
+ const setupHook = plugin.hooks?.["kubb:plugin:setup"];
2293
+ if (!plugin.setup && !setupHook) continue;
2294
+ const ctx = {
2295
+ config: this.config,
2296
+ options: plugin.options ?? {},
2297
+ addGenerator: (...generators) => {
2298
+ plugin.generators = [...plugin.generators ?? [], ...generators];
2299
+ },
2300
+ setResolver: (resolver) => {
2301
+ plugin.resolver = Resolver.merge(createResolver({ pluginName: plugin.name }), resolver);
2302
+ },
2303
+ addMacro: (macro) => {
2304
+ this.#transforms.add(plugin.name, macro);
2305
+ },
2306
+ setMacros: (macros) => {
2307
+ this.#transforms.set(plugin.name, macros);
2308
+ },
2309
+ setOptions: (opts) => {
2310
+ plugin.options = normalizePluginOptions({
2311
+ ...plugin.options,
2312
+ ...opts
2313
+ }, plugin.name);
2314
+ },
2315
+ injectFile: (userFileNode) => {
2316
+ this.fileManager.add(ast.factory.createFile(userFileNode));
2317
+ },
2318
+ requirePlugin: ((name) => this.requirePlugin(name, { requiredBy: plugin.name }))
2319
+ };
2076
2320
  try {
2077
- await setup({
2078
- config: this.config,
2079
- options: plugin.options ?? {},
2080
- addGenerator: (...generators) => {
2081
- plugin.generators = [...plugin.generators ?? [], ...generators];
2082
- },
2083
- setResolver: (resolver) => {
2084
- plugin.resolver = Resolver.merge(createResolver({ pluginName: plugin.name }), resolver);
2085
- },
2086
- addMacro: (macro) => {
2087
- this.#transforms.add(plugin.name, macro);
2088
- },
2089
- setMacros: (macros) => {
2090
- this.#transforms.set(plugin.name, macros);
2091
- },
2092
- setOptions: (opts) => {
2093
- plugin.options = normalizePluginOptions({
2094
- ...plugin.options,
2095
- ...opts
2096
- }, plugin.name);
2097
- },
2098
- injectFile: (userFileNode) => {
2099
- this.fileManager.add(ast.factory.createFile(userFileNode));
2100
- },
2101
- requirePlugin: ((name) => this.requirePlugin(name, { requiredBy: plugin.name }))
2321
+ await kubbContext.run(ctx, async () => {
2322
+ if (plugin.setup) plugin.options = normalizePluginOptions(await plugin.setup(ctx.options, ctx), plugin.name);
2323
+ await setupHook?.(ctx);
2102
2324
  });
2103
2325
  } catch (caughtError) {
2104
2326
  const diagnostic = Diagnostics.from(caughtError);
@@ -2557,6 +2779,6 @@ function pluginNotFoundError({ pluginName, requiredBy }) {
2557
2779
  });
2558
2780
  }
2559
2781
  //#endregion
2560
- export { camelCase as C, toError as S, exists as _, _usingCtx as a, toPosixPath as b, Resolver as c, definePlugin as d, Diagnostics as f, clean as g, inParallel as h, FileManager as i, getInputKind as l, getElapsedMs as m, pluginNotFoundError as n, Hookable as o, formatMs as p, createNodeCache as r, createResolver as s, KubbDriver as t, assertPluginOption as u, isPathInside as v, write as x, read as y };
2782
+ export { clean as A, useConfig as C, formatMs as D, Diagnostics as E, write as F, toError as I, camelCase as L, isPathInside as M, read as N, getElapsedMs as O, toPosixPath as P, tryUseKubb as S, useOptions as T, kubbContext as _, _usingCtx as a, setOptions as b, Resolver as c, definePlugin as d, defineExtension as f, injectFile as g, addMacro as h, FileManager as i, exists as j, inParallel as k, getInputKind as l, addGenerator as m, pluginNotFoundError as n, Hookable as o, resolveMeta as p, createNodeCache as r, createResolver as s, KubbDriver as t, assertPluginOption as u, requirePlugin as v, useKubb as w, setResolver as x, setMacros as y };
2561
2783
 
2562
- //# sourceMappingURL=KubbDriver-BZBnKODj.js.map
2784
+ //# sourceMappingURL=KubbDriver-DRobnIcp.js.map