unplugin-kubb 5.12.5 → 5.12.6

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/README.md CHANGED
@@ -115,15 +115,25 @@ export default defineConfig({
115
115
  })
116
116
  ```
117
117
 
118
+ ## Import a spec
119
+
120
+ Import a `*.openapi.yaml` or `*.openapi.yml` file to get the output of every plugin in your config as one module. This also works in the Vite dev server.
121
+
122
+ ```ts
123
+ import { getPetById, petSchema } from './petStore.openapi.yaml'
124
+ ```
125
+
126
+ For types in `tsc` and your editor, add [`openapi-import`](https://github.com/kubb-labs/openapi-import).
127
+
118
128
  ## Options
119
129
 
120
130
  ### config
121
131
 
122
- Define the options for Kubb.
132
+ Your Kubb config. Without it, the plugin loads `kubb.config.ts` like the CLI does.
123
133
 
124
134
  ```typescript [Options]
125
135
  type Options = {
126
- config: UserConfig
136
+ config?: UserConfig
127
137
  }
128
138
  ```
129
139
 
package/dist/esbuild.js CHANGED
@@ -1,4 +1,4 @@
1
- import { unpluginFactory } from "./unpluginFactory.js";
1
+ import { n as unpluginFactory } from "./unpluginFactory-DUew0Jfa.js";
2
2
  import { createEsbuildPlugin } from "unplugin";
3
3
  //#region src/esbuild.ts
4
4
  var esbuild_default = createEsbuildPlugin(unpluginFactory);
package/dist/farm.js CHANGED
@@ -1,4 +1,4 @@
1
- import { unpluginFactory } from "./unpluginFactory.js";
1
+ import { n as unpluginFactory } from "./unpluginFactory-DUew0Jfa.js";
2
2
  import { createFarmPlugin } from "unplugin";
3
3
  //#region src/farm.ts
4
4
  var farm_default = createFarmPlugin(unpluginFactory);
@@ -0,0 +1,24 @@
1
+ import { Hookable, KubbHooks, ProblemDiagnostic, UserConfig } from "@kubb/core";
2
+ //#region src/generateModule.d.ts
3
+ /**
4
+ * The config whose `input` is `fileName`, else the first one. Like Kubb, `root` resolves from
5
+ * `cwd` and `input` from `root`.
6
+ */
7
+ export declare function selectConfig(configs: Array<UserConfig>, fileName: string, cwd: string): UserConfig | undefined;
8
+ /**
9
+ * Generates the output of every plugin in `config` for one spec as one TypeScript module, without
10
+ * writing files. Only `config`'s adapter and plugins are used. `text` is empty when `errors` is not.
11
+ * The `*.openapi.yaml` loader and the `openapi-import` content mapper share it.
12
+ */
13
+ export declare function generateModule({ root, input, config, hooks }: {
14
+ /** Folder of the spec; relative imports in the module resolve from here. */
15
+ root: string;
16
+ input: UserConfig['input'];
17
+ config: UserConfig;
18
+ hooks?: Hookable<KubbHooks>;
19
+ }): Promise<{
20
+ text: string;
21
+ errors: Array<ProblemDiagnostic>;
22
+ }>;
23
+ //#endregion
24
+ //# sourceMappingURL=generateModule.d.ts.map
@@ -0,0 +1,59 @@
1
+ import "./rolldown-runtime-C0LytTxp.js";
2
+ import path from "node:path";
3
+ import { adapterOas } from "@kubb/adapter-oas";
4
+ import { Diagnostics, createKubb, memoryStorage } from "@kubb/core";
5
+ import { parserTs } from "@kubb/parser-ts";
6
+ import { pluginBarrelName } from "@kubb/plugin-barrel";
7
+ //#region src/generateModule.ts
8
+ const moduleFile = "index.ts";
9
+ const toModulePlugin = (plugin) => ({
10
+ ...plugin,
11
+ options: {
12
+ ...plugin.options,
13
+ output: {
14
+ ...plugin.options?.output,
15
+ path: moduleFile,
16
+ mode: "file"
17
+ },
18
+ group: void 0
19
+ }
20
+ });
21
+ /**
22
+ * The config whose `input` is `fileName`, else the first one. Like Kubb, `root` resolves from
23
+ * `cwd` and `input` from `root`.
24
+ */
25
+ function selectConfig(configs, fileName, cwd) {
26
+ const matches = (config) => typeof config.input === "string" && path.resolve(cwd, config.root || ".", config.input) === path.resolve(fileName);
27
+ return configs.find(matches) ?? configs[0];
28
+ }
29
+ /**
30
+ * Generates the output of every plugin in `config` for one spec as one TypeScript module, without
31
+ * writing files. Only `config`'s adapter and plugins are used. `text` is empty when `errors` is not.
32
+ * The `*.openapi.yaml` loader and the `openapi-import` content mapper share it.
33
+ */
34
+ async function generateModule({ root, input, config, hooks }) {
35
+ const storage = memoryStorage();
36
+ const { diagnostics } = await createKubb({
37
+ root,
38
+ input,
39
+ output: {
40
+ path: ".",
41
+ barrel: false,
42
+ format: false,
43
+ lint: false
44
+ },
45
+ adapter: config.adapter ?? adapterOas(),
46
+ parsers: [parserTs()],
47
+ plugins: (config.plugins ?? []).filter((plugin) => plugin.name !== pluginBarrelName).map(toModulePlugin),
48
+ storage
49
+ }, { hooks }).safeBuild();
50
+ const errors = diagnostics.filter(Diagnostics.isProblem).filter((diagnostic) => diagnostic.severity === "error");
51
+ return {
52
+ text: errors.length ? "" : await storage.readItem(path.resolve(root, moduleFile)) ?? "",
53
+ errors
54
+ };
55
+ }
56
+ //#endregion
57
+ export { generateModule, selectConfig };
58
+
59
+ //# sourceMappingURL=generateModule.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"generateModule.js","names":[],"sources":["../src/generateModule.ts"],"sourcesContent":["import path from 'node:path'\nimport { adapterOas } from '@kubb/adapter-oas'\nimport {\n createKubb,\n Diagnostics,\n type Hookable,\n type KubbHooks,\n memoryStorage,\n type Output,\n type Plugin,\n type ProblemDiagnostic,\n type UserConfig,\n} from '@kubb/core'\nimport { parserTs } from '@kubb/parser-ts'\nimport { pluginBarrelName } from '@kubb/plugin-barrel'\n\n// Every plugin writes to this one file, so Kubb merges their output and drops the imports between them.\nconst moduleFile = 'index.ts'\n\nconst toModulePlugin = (plugin: Plugin): Plugin => ({\n ...plugin,\n options: {\n ...plugin.options,\n // An explicit `mode: 'directory'` would otherwise survive and write under `index.ts/`.\n output: { ...(plugin.options as { output?: Output } | undefined)?.output, path: moduleFile, mode: 'file' },\n group: undefined,\n },\n})\n\n/**\n * The config whose `input` is `fileName`, else the first one. Like Kubb, `root` resolves from\n * `cwd` and `input` from `root`.\n */\nexport function selectConfig(configs: Array<UserConfig>, fileName: string, cwd: string): UserConfig | undefined {\n const matches = (config: UserConfig) => typeof config.input === 'string' && path.resolve(cwd, config.root || '.', config.input) === path.resolve(fileName)\n\n return configs.find(matches) ?? configs[0]\n}\n\n/**\n * Generates the output of every plugin in `config` for one spec as one TypeScript module, without\n * writing files. Only `config`'s adapter and plugins are used. `text` is empty when `errors` is not.\n * The `*.openapi.yaml` loader and the `openapi-import` content mapper share it.\n */\nexport async function generateModule({\n root,\n input,\n config,\n hooks,\n}: {\n /** Folder of the spec; relative imports in the module resolve from here. */\n root: string\n input: UserConfig['input']\n config: UserConfig\n hooks?: Hookable<KubbHooks>\n}): Promise<{ text: string; errors: Array<ProblemDiagnostic> }> {\n const storage = memoryStorage()\n const { diagnostics } = await createKubb(\n {\n root,\n input,\n output: { path: '.', barrel: false, format: false, lint: false },\n adapter: config.adapter ?? adapterOas(),\n parsers: [parserTs()],\n plugins: (config.plugins ?? []).filter((plugin) => plugin.name !== pluginBarrelName).map(toModulePlugin),\n storage,\n },\n { hooks },\n ).safeBuild()\n const errors = diagnostics.filter(Diagnostics.isProblem).filter((diagnostic) => diagnostic.severity === 'error')\n // Files written elsewhere (a bundled client runtime) are left out; no output is an empty module.\n const text = errors.length ? '' : ((await storage.readItem(path.resolve(root, moduleFile))) ?? '')\n\n return { text, errors }\n}\n"],"mappings":";;;;;;;AAiBA,MAAM,aAAa;AAEnB,MAAM,kBAAkB,YAA4B;CAClD,GAAG;CACH,SAAS;EACP,GAAG,OAAO;EAEV,QAAQ;GAAE,GAAI,OAAO,SAA6C;GAAQ,MAAM;GAAY,MAAM;EAAO;EACzG,OAAO,KAAA;CACT;AACF;;;;;AAMA,SAAgB,aAAa,SAA4B,UAAkB,KAAqC;CAC9G,MAAM,WAAW,WAAuB,OAAO,OAAO,UAAU,YAAY,KAAK,QAAQ,KAAK,OAAO,QAAQ,KAAK,OAAO,KAAK,MAAM,KAAK,QAAQ,QAAQ;CAEzJ,OAAO,QAAQ,KAAK,OAAO,KAAK,QAAQ;AAC1C;;;;;;AAOA,eAAsB,eAAe,EACnC,MACA,OACA,QACA,SAO8D;CAC9D,MAAM,UAAU,cAAc;CAC9B,MAAM,EAAE,gBAAgB,MAAM,WAC5B;EACE;EACA;EACA,QAAQ;GAAE,MAAM;GAAK,QAAQ;GAAO,QAAQ;GAAO,MAAM;EAAM;EAC/D,SAAS,OAAO,WAAW,WAAW;EACtC,SAAS,CAAC,SAAS,CAAC;EACpB,UAAU,OAAO,WAAW,CAAC,EAAA,CAAG,QAAQ,WAAW,OAAO,SAAS,gBAAgB,CAAC,CAAC,IAAI,cAAc;EACvG;CACF,GACA,EAAE,MAAM,CACV,CAAC,CAAC,UAAU;CACZ,MAAM,SAAS,YAAY,OAAO,YAAY,SAAS,CAAC,CAAC,QAAQ,eAAe,WAAW,aAAa,OAAO;CAI/G,OAAO;EAAE,MAFI,OAAO,SAAS,KAAO,MAAM,QAAQ,SAAS,KAAK,QAAQ,MAAM,UAAU,CAAC,KAAM;EAEhF;CAAO;AACxB"}
package/dist/index.d.ts CHANGED
@@ -1,6 +1,23 @@
1
1
  import { Options, applyDefaults, unpluginFactory } from "./unpluginFactory.js";
2
+ import { generateModule, selectConfig } from "./generateModule.js";
3
+ //#region ../../internals/shared/src/config.d.ts
4
+ /**
5
+ * Every config file path the Kubb CLI checks in `dir`, in the order it checks them.
6
+ */
7
+ export declare function configFileCandidates(dir: string): Array<string>;
8
+ /**
9
+ * The first Kubb config file in `cwd` or the nearest parent folder that has one: `.kubbrc` before
10
+ * `kubb.config`, the folder itself before its `.config/` and `configs/`, and {@link CONFIG_EXTENSIONS} in order.
11
+ */
12
+ export declare function findConfigFile(cwd?: string): string | undefined;
13
+ /**
14
+ * Loads a Kubb config module, calls it with `cli` when it exports a function, and returns its
15
+ * configs as a list, so a single config and a `defineConfig([...])` array read the same.
16
+ */
17
+ export declare function loadConfigFile<T>(file: string, cli: unknown): Promise<Array<T>>;
18
+ //#endregion
2
19
  //#region src/index.d.ts
3
- declare const plugin: import("unplugin").UnpluginInstance<Options | undefined, boolean>;
20
+ declare const plugin: import("unplugin").UnpluginInstance<Options | undefined, true>;
4
21
  //#endregion
5
- export { type Options, applyDefaults, plugin as default, plugin as unplugin, unpluginFactory };
22
+ export { type Options, applyDefaults, plugin as default, plugin as unplugin, generateModule, selectConfig, unpluginFactory };
6
23
  //# sourceMappingURL=index.d.ts.map
package/dist/index.js CHANGED
@@ -1,8 +1,9 @@
1
- import { applyDefaults, unpluginFactory } from "./unpluginFactory.js";
1
+ import { a as loadConfigFile, i as findConfigFile, n as unpluginFactory, r as configFileCandidates, t as applyDefaults } from "./unpluginFactory-DUew0Jfa.js";
2
+ import { generateModule, selectConfig } from "./generateModule.js";
2
3
  import { createUnplugin } from "unplugin";
3
4
  //#region src/index.ts
4
5
  const plugin = /* #__PURE__ */ createUnplugin(unpluginFactory);
5
6
  //#endregion
6
- export { applyDefaults, plugin as default, plugin as unplugin, unpluginFactory };
7
+ export { applyDefaults, configFileCandidates, plugin as default, plugin as unplugin, findConfigFile, generateModule, loadConfigFile, selectConfig, unpluginFactory };
7
8
 
8
9
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../src/index.ts"],"sourcesContent":["import { createUnplugin } from 'unplugin'\nimport { unpluginFactory } from './unpluginFactory.ts'\n\nexport { applyDefaults, type Options, unpluginFactory } from './unpluginFactory.ts'\n\nconst plugin = /* #__PURE__ */ createUnplugin(unpluginFactory)\n\nexport { plugin as unplugin, plugin as default }\n"],"mappings":";;;AAKA,MAAM,SAAyB,+BAAe,eAAe"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../src/index.ts"],"sourcesContent":["import { createUnplugin } from 'unplugin'\nimport { unpluginFactory } from './unpluginFactory.ts'\n\nexport { configFileCandidates, findConfigFile, loadConfigFile } from '@internals/shared'\nexport { generateModule, selectConfig } from './generateModule.ts'\nexport { applyDefaults, type Options, unpluginFactory } from './unpluginFactory.ts'\n\nconst plugin = /* #__PURE__ */ createUnplugin(unpluginFactory)\n\nexport { plugin as unplugin, plugin as default }\n"],"mappings":";;;;AAOA,MAAM,SAAyB,+BAAe,eAAe"}
package/dist/rolldown.js CHANGED
@@ -1,4 +1,4 @@
1
- import { unpluginFactory } from "./unpluginFactory.js";
1
+ import { n as unpluginFactory } from "./unpluginFactory-DUew0Jfa.js";
2
2
  import { createRolldownPlugin } from "unplugin";
3
3
  //#region src/rolldown.ts
4
4
  var rolldown_default = createRolldownPlugin(unpluginFactory);
package/dist/rollup.js CHANGED
@@ -1,4 +1,4 @@
1
- import { unpluginFactory } from "./unpluginFactory.js";
1
+ import { n as unpluginFactory } from "./unpluginFactory-DUew0Jfa.js";
2
2
  import { createRollupPlugin } from "unplugin";
3
3
  //#region src/rollup.ts
4
4
  var rollup_default = createRollupPlugin(unpluginFactory);
package/dist/rspack.js CHANGED
@@ -1,4 +1,4 @@
1
- import { unpluginFactory } from "./unpluginFactory.js";
1
+ import { n as unpluginFactory } from "./unpluginFactory-DUew0Jfa.js";
2
2
  import { createRspackPlugin } from "unplugin";
3
3
  //#region src/rspack.ts
4
4
  var rspack_default = createRspackPlugin(unpluginFactory);
@@ -0,0 +1,222 @@
1
+ import "./rolldown-runtime-C0LytTxp.js";
2
+ import { generateModule, selectConfig } from "./generateModule.js";
3
+ import path, { dirname, join, resolve } from "node:path";
4
+ import { adapterOas } from "@kubb/adapter-oas";
5
+ import { Diagnostics, Hookable, cliReporter, createCliReporter, createKubb, fileReporter, htmlReporter, jsonReporter, logLevel } from "@kubb/core";
6
+ import { parserMd } from "@kubb/parser-md";
7
+ import { parserTs, parserTsx } from "@kubb/parser-ts";
8
+ import { pluginBarrel, pluginBarrelName } from "@kubb/plugin-barrel";
9
+ import { existsSync } from "node:fs";
10
+ import process$1 from "node:process";
11
+ import { readFile } from "node:fs/promises";
12
+ import { createJiti } from "jiti";
13
+ import ts from "@typescript/typescript6";
14
+ //#region ../../internals/shared/src/constants.ts
15
+ /** File extensions a Kubb config file may use. */
16
+ const CONFIG_EXTENSIONS = [
17
+ ".ts",
18
+ ".mts",
19
+ ".cts",
20
+ ".js",
21
+ ".mjs",
22
+ ".cjs"
23
+ ];
24
+ //#endregion
25
+ //#region ../../internals/shared/src/loader.ts
26
+ /**
27
+ * jiti options for loading Kubb config modules: the automatic JSX runtime pointed at
28
+ * `@kubb/renderer-jsx`, and `moduleCache` off so a re-load re-evaluates the file.
29
+ */
30
+ const JITI_OPTIONS = {
31
+ jsx: {
32
+ runtime: "automatic",
33
+ importSource: "@kubb/renderer-jsx"
34
+ },
35
+ moduleCache: false
36
+ };
37
+ /**
38
+ * Plain JavaScript files. jiti hands these to Node's native `import()`, whose module cache never
39
+ * lets go of a file, so `moduleCache: false` alone would keep returning the first version of it.
40
+ */
41
+ const JAVASCRIPT_EXTENSION = /\.[cm]?jsx?$/;
42
+ const jiti = createJiti(import.meta.url, JITI_OPTIONS);
43
+ /**
44
+ * Loads a Kubb TypeScript or JavaScript config module via jiti.
45
+ *
46
+ * jiti transpiles TypeScript and the `@kubb/renderer-jsx` JSX runtime on the fly. Every load
47
+ * re-evaluates the file, so a config edited on disk is picked up by the next load.
48
+ *
49
+ * @example
50
+ * ```ts
51
+ * const config = await loadModule('/abs/kubb.config.ts', { default: true })
52
+ * ```
53
+ */
54
+ async function loadModule(filePath, options) {
55
+ if (!JAVASCRIPT_EXTENSION.test(filePath)) return options?.default ? jiti.import(filePath, { default: true }) : jiti.import(filePath);
56
+ const mod = await jiti.evalModule(await readFile(filePath, "utf8"), {
57
+ filename: filePath,
58
+ async: true,
59
+ forceTranspile: true
60
+ });
61
+ return options?.default ? mod?.default ?? mod : mod;
62
+ }
63
+ //#endregion
64
+ //#region ../../internals/shared/src/config.ts
65
+ const SEARCH_FILES = [
66
+ "",
67
+ ".config/",
68
+ "configs/"
69
+ ].flatMap((prefix) => [`${prefix}.kubbrc`, `${prefix}kubb.config`]);
70
+ /**
71
+ * Every config file path the Kubb CLI checks in `dir`, in the order it checks them.
72
+ */
73
+ function configFileCandidates(dir) {
74
+ return SEARCH_FILES.flatMap((file) => CONFIG_EXTENSIONS.map((extension) => join(dir, `${file}${extension}`)));
75
+ }
76
+ /**
77
+ * The first Kubb config file in `cwd` or the nearest parent folder that has one: `.kubbrc` before
78
+ * `kubb.config`, the folder itself before its `.config/` and `configs/`, and {@link CONFIG_EXTENSIONS} in order.
79
+ */
80
+ function findConfigFile(cwd = process$1.cwd()) {
81
+ for (let dir = resolve(cwd);; dir = dirname(dir)) {
82
+ const found = configFileCandidates(dir).find((file) => existsSync(file));
83
+ if (found || dirname(dir) === dir) return found;
84
+ }
85
+ }
86
+ /**
87
+ * Loads a Kubb config module, calls it with `cli` when it exports a function, and returns its
88
+ * configs as a list, so a single config and a `defineConfig([...])` array read the same.
89
+ */
90
+ async function loadConfigFile(file, cli) {
91
+ const loaded = await loadModule(file, { default: true });
92
+ const resolved = await (typeof loaded === "function" ? loaded(cli) : loaded);
93
+ return Array.isArray(resolved) ? resolved : [resolved];
94
+ }
95
+ //#endregion
96
+ //#region src/unpluginFactory.ts
97
+ /**
98
+ * Applies the defaults `defineConfig` and the unplugin share to a single user config when not set.
99
+ *
100
+ * - `root` defaults to `process.cwd()`
101
+ * - `adapter` defaults to `adapterOas()`
102
+ * - `parsers` defaults to `[parserTs(), parserTsx(), parserMd()]`
103
+ * - `reporters` defaults to `[cliReporter, jsonReporter, fileReporter, htmlReporter]`
104
+ * - `plugins` gets `pluginBarrel()` appended when none is already present
105
+ * - `output.barrel` defaults to `false` when not set (`pluginBarrel` is always present after the step above, but generates nothing until configured)
106
+ * - `output.format` and `output.lint` default to `false`
107
+ */
108
+ function applyDefaults(config) {
109
+ const plugins = config.plugins ?? [];
110
+ return {
111
+ ...config,
112
+ root: config.root || process.cwd(),
113
+ adapter: config.adapter ?? adapterOas(),
114
+ parsers: config.parsers?.length ? config.parsers : [
115
+ parserTs(),
116
+ parserTsx(),
117
+ parserMd()
118
+ ],
119
+ reporters: config.reporters?.length ? config.reporters : [
120
+ cliReporter,
121
+ jsonReporter,
122
+ fileReporter,
123
+ htmlReporter
124
+ ],
125
+ plugins: plugins.some((plugin) => plugin.name === pluginBarrelName) ? plugins : [...plugins, pluginBarrel()],
126
+ output: {
127
+ barrel: false,
128
+ format: false,
129
+ lint: false,
130
+ ...config.output
131
+ }
132
+ };
133
+ }
134
+ /** Spec files an import loads as a module, the extensions `openapi-import` registers too. */
135
+ const specFilePattern = /\.openapi\.ya?ml$/;
136
+ /**
137
+ * Builds the Kubb unplugin for every unplugin bundler. `unplugin-kubb` runs the Kubb build once for
138
+ * each config with an `input` (only during `build` under Vite), and `unplugin-kubb:import` loads an
139
+ * imported {@link specFilePattern} file as one module. Without `config`, it loads `kubb.config.*`.
140
+ */
141
+ const unpluginFactory = (options, meta) => {
142
+ const name = "unplugin-kubb";
143
+ const hooks = new Hookable();
144
+ const reporter = createCliReporter();
145
+ hooks.hook("kubb:generation:end", ({ config, diagnostics = [], filesCreated = 0, status = "success", hrStart = process.hrtime() }) => reporter.report({
146
+ config,
147
+ diagnostics,
148
+ filesCreated,
149
+ status,
150
+ hrStart
151
+ }, { logLevel: logLevel.info }));
152
+ const fail = (problem, message) => new Diagnostics.Error({
153
+ ...problem ?? {
154
+ code: Diagnostics.code.unknown,
155
+ severity: "error"
156
+ },
157
+ message: `[${name}] ${message}`
158
+ });
159
+ async function readConfigs() {
160
+ if (options?.config) return [options.config];
161
+ const file = findConfigFile();
162
+ if (!file) throw new Diagnostics.Error({
163
+ code: Diagnostics.code.inputRequired,
164
+ severity: "error",
165
+ message: `[${name}] Config is not set`,
166
+ help: "Pass your Kubb config as the `config` option of the plugin, or add a `kubb.config.ts`.",
167
+ location: { kind: "config" }
168
+ });
169
+ return (await loadConfigFile(file, {})).map((config) => config.root ? {
170
+ ...config,
171
+ root: path.resolve(path.dirname(file), config.root)
172
+ } : config);
173
+ }
174
+ let loaded;
175
+ const loadConfigs = () => loaded ??= readConfigs();
176
+ async function runBuild() {
177
+ for (const config of (await loadConfigs()).filter((config) => config.input)) {
178
+ const result = await createKubb(applyDefaults(config), { hooks }).generate();
179
+ if (result.success) continue;
180
+ const failedCount = Diagnostics.failedPlugins(result.diagnostics).length;
181
+ const firstError = result.diagnostics.filter(Diagnostics.isProblem).find((diagnostic) => diagnostic.severity === "error");
182
+ throw fail(firstError, failedCount > 0 ? `Build Error with ${failedCount} failed plugins` : firstError?.message ?? "Build failed");
183
+ }
184
+ }
185
+ let generation;
186
+ return [{
187
+ name,
188
+ enforce: "pre",
189
+ apply: meta.framework === "vite" ? "build" : void 0,
190
+ async buildStart() {
191
+ generation ??= runBuild().catch((error) => {
192
+ generation = void 0;
193
+ throw error;
194
+ });
195
+ await generation;
196
+ }
197
+ }, {
198
+ name: `${name}:import`,
199
+ enforce: "pre",
200
+ loadInclude: (id) => specFilePattern.test(id),
201
+ async load(id) {
202
+ const config = selectConfig(await loadConfigs(), id, process.cwd());
203
+ const { text, errors } = await generateModule({
204
+ root: path.dirname(id),
205
+ input: id,
206
+ config
207
+ });
208
+ if (errors.length) throw fail(errors[0], `${id}: ${errors[0].message}`);
209
+ return ts.transpileModule(text, {
210
+ fileName: `${id}.ts`,
211
+ compilerOptions: {
212
+ module: ts.ModuleKind.ESNext,
213
+ target: ts.ScriptTarget.ESNext
214
+ }
215
+ }).outputText;
216
+ }
217
+ }];
218
+ };
219
+ //#endregion
220
+ export { loadConfigFile as a, findConfigFile as i, unpluginFactory as n, configFileCandidates as r, applyDefaults as t };
221
+
222
+ //# sourceMappingURL=unpluginFactory-DUew0Jfa.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"unpluginFactory-DUew0Jfa.js","names":["process"],"sources":["../../../internals/shared/src/constants.ts","../../../internals/shared/src/loader.ts","../../../internals/shared/src/config.ts","../src/unpluginFactory.ts"],"sourcesContent":["export const KUBB_CONFIG_FILENAME = 'kubb.config.ts' as const\n\n/** File extensions a Kubb config file may use. */\nexport const CONFIG_EXTENSIONS = ['.ts', '.mts', '.cts', '.js', '.mjs', '.cjs'] as const\n\nexport const KUBB_PACKAGE_NAME = 'kubb' as const\n\nexport const initDefaults = {\n inputPath: './openapi.yaml',\n outputPath: './src/gen',\n plugins: ['plugin-ts'],\n} as const\n","import { readFile } from 'node:fs/promises'\nimport { createJiti } from 'jiti'\n\n/**\n * jiti options for loading Kubb config modules: the automatic JSX runtime pointed at\n * `@kubb/renderer-jsx`, and `moduleCache` off so a re-load re-evaluates the file.\n */\nconst JITI_OPTIONS = {\n jsx: { runtime: 'automatic', importSource: '@kubb/renderer-jsx' },\n moduleCache: false,\n} satisfies Parameters<typeof createJiti>[1]\n\n/**\n * Plain JavaScript files. jiti hands these to Node's native `import()`, whose module cache never\n * lets go of a file, so `moduleCache: false` alone would keep returning the first version of it.\n */\nconst JAVASCRIPT_EXTENSION = /\\.[cm]?jsx?$/\n\n/**\n * Per-call options for {@link loadModule}.\n */\ntype LoadModuleOptions = {\n /**\n * Return the module's default export instead of the full namespace.\n */\n default?: boolean\n}\n\nconst jiti = createJiti(import.meta.url, JITI_OPTIONS)\n\n/**\n * Loads a Kubb TypeScript or JavaScript config module via jiti.\n *\n * jiti transpiles TypeScript and the `@kubb/renderer-jsx` JSX runtime on the fly. Every load\n * re-evaluates the file, so a config edited on disk is picked up by the next load.\n *\n * @example\n * ```ts\n * const config = await loadModule('/abs/kubb.config.ts', { default: true })\n * ```\n */\nexport async function loadModule<T = unknown>(filePath: string, options?: LoadModuleOptions): Promise<T> {\n if (!JAVASCRIPT_EXTENSION.test(filePath)) {\n return (options?.default ? jiti.import(filePath, { default: true }) : jiti.import(filePath)) as Promise<T>\n }\n\n // Transpiled through jiti instead, so every load re-evaluates the file as it is on disk now.\n // A TypeScript file it imports reloads too. A plain JavaScript file it imports still goes\n // through Node's `import()` and stays cached until the process restarts.\n const mod = (await jiti.evalModule(await readFile(filePath, 'utf8'), { filename: filePath, async: true, forceTranspile: true })) as\n | { default?: unknown }\n | undefined\n return (options?.default ? (mod?.default ?? mod) : mod) as T\n}\n","import { existsSync } from 'node:fs'\nimport { dirname, join, resolve } from 'node:path'\nimport process from 'node:process'\nimport { CONFIG_EXTENSIONS } from './constants.ts'\nimport { loadModule } from './loader.ts'\n\nconst SEARCH_FILES = ['', '.config/', 'configs/'].flatMap((prefix) => [`${prefix}.kubbrc`, `${prefix}kubb.config`])\n\n/**\n * Every config file path the Kubb CLI checks in `dir`, in the order it checks them.\n */\nexport function configFileCandidates(dir: string): Array<string> {\n return SEARCH_FILES.flatMap((file) => CONFIG_EXTENSIONS.map((extension) => join(dir, `${file}${extension}`)))\n}\n\n/**\n * The first Kubb config file in `cwd` or the nearest parent folder that has one: `.kubbrc` before\n * `kubb.config`, the folder itself before its `.config/` and `configs/`, and {@link CONFIG_EXTENSIONS} in order.\n */\nexport function findConfigFile(cwd: string = process.cwd()): string | undefined {\n for (let dir = resolve(cwd); ; dir = dirname(dir)) {\n const found = configFileCandidates(dir).find((file) => existsSync(file))\n if (found || dirname(dir) === dir) return found\n }\n}\n\n/**\n * Loads a Kubb config module, calls it with `cli` when it exports a function, and returns its\n * configs as a list, so a single config and a `defineConfig([...])` array read the same.\n */\nexport async function loadConfigFile<T>(file: string, cli: unknown): Promise<Array<T>> {\n const loaded = await loadModule<unknown>(file, { default: true })\n const resolved = (await (typeof loaded === 'function' ? loaded(cli) : loaded)) as T | Array<T>\n return Array.isArray(resolved) ? resolved : [resolved]\n}\n","import path from 'node:path'\nimport { adapterOas } from '@kubb/adapter-oas'\nimport {\n cliReporter,\n type Config,\n createCliReporter,\n createKubb,\n Diagnostics,\n fileReporter,\n Hookable,\n htmlReporter,\n jsonReporter,\n type KubbHooks,\n logLevel,\n type ProblemDiagnostic,\n type UserConfig,\n} from '@kubb/core'\nimport { parserMd } from '@kubb/parser-md'\nimport { parserTs, parserTsx } from '@kubb/parser-ts'\nimport { pluginBarrel, pluginBarrelName } from '@kubb/plugin-barrel'\nimport { findConfigFile, loadConfigFile } from '@internals/shared'\nimport ts from '@typescript/typescript6'\nimport type { UnpluginFactory } from 'unplugin'\nimport { generateModule, selectConfig } from './generateModule.ts'\n\nexport type Options = {\n /**\n * Kubb config passed to the unplugin entry point. When not set, the plugin loads\n * `kubb.config.*` the way the Kubb CLI finds it, from the current working directory up.\n */\n config?: UserConfig\n}\n\n/**\n * Applies the defaults `defineConfig` and the unplugin share to a single user config when not set.\n *\n * - `root` defaults to `process.cwd()`\n * - `adapter` defaults to `adapterOas()`\n * - `parsers` defaults to `[parserTs(), parserTsx(), parserMd()]`\n * - `reporters` defaults to `[cliReporter, jsonReporter, fileReporter, htmlReporter]`\n * - `plugins` gets `pluginBarrel()` appended when none is already present\n * - `output.barrel` defaults to `false` when not set (`pluginBarrel` is always present after the step above, but generates nothing until configured)\n * - `output.format` and `output.lint` default to `false`\n */\nexport function applyDefaults<TInput>(config: UserConfig<TInput>): UserConfig<TInput> {\n const plugins = config.plugins ?? []\n\n return {\n ...config,\n root: config.root || process.cwd(),\n adapter: config.adapter ?? adapterOas(),\n parsers: config.parsers?.length ? config.parsers : [parserTs(), parserTsx(), parserMd()],\n reporters: config.reporters?.length ? config.reporters : [cliReporter, jsonReporter, fileReporter, htmlReporter],\n plugins: plugins.some((plugin) => plugin.name === pluginBarrelName) ? plugins : [...plugins, pluginBarrel()],\n output: { barrel: false, format: false, lint: false, ...config.output },\n }\n}\n\n/** Spec files an import loads as a module, the extensions `openapi-import` registers too. */\nconst specFilePattern = /\\.openapi\\.ya?ml$/\n\n/**\n * Builds the Kubb unplugin for every unplugin bundler. `unplugin-kubb` runs the Kubb build once for\n * each config with an `input` (only during `build` under Vite), and `unplugin-kubb:import` loads an\n * imported {@link specFilePattern} file as one module. Without `config`, it loads `kubb.config.*`.\n */\nexport const unpluginFactory: UnpluginFactory<Options | undefined, true> = (options, meta) => {\n const name = 'unplugin-kubb' as const\n const hooks = new Hookable<KubbHooks>()\n const reporter = createCliReporter()\n\n hooks.hook('kubb:generation:end', ({ config, diagnostics = [], filesCreated = 0, status = 'success', hrStart = process.hrtime() }) =>\n reporter.report({ config, diagnostics, filesCreated, status, hrStart }, { logLevel: logLevel.info }),\n )\n\n // Throw: webpack, Rspack, esbuild, and Farm contexts have no `this.error`. Keep the problem's code,\n // help and location, so the bundler shows the same diagnostic.\n const fail = (problem: ProblemDiagnostic | undefined, message: string) =>\n new Diagnostics.Error({ ...(problem ?? { code: Diagnostics.code.unknown, severity: 'error' }), message: `[${name}] ${message}` })\n\n async function readConfigs(): Promise<Array<UserConfig>> {\n if (options?.config) return [options.config]\n\n const file = findConfigFile()\n if (!file) {\n throw new Diagnostics.Error({\n code: Diagnostics.code.inputRequired,\n severity: 'error',\n message: `[${name}] Config is not set`,\n help: 'Pass your Kubb config as the `config` option of the plugin, or add a `kubb.config.ts`.',\n location: { kind: 'config' },\n })\n }\n // `UserConfig.root` is relative to the config file, which may sit in a parent of the bundler's cwd.\n const configs = await loadConfigFile<UserConfig>(file, {})\n return configs.map((config) => (config.root ? { ...config, root: path.resolve(path.dirname(file), config.root) } : config))\n }\n\n // Loaded once per instance, like the generation below: restart the build after editing the config file.\n let loaded: ReturnType<typeof readConfigs> | undefined\n const loadConfigs = () => (loaded ??= readConfigs())\n\n async function runBuild() {\n for (const config of (await loadConfigs()).filter((config) => config.input)) {\n const result = await createKubb(applyDefaults(config) as Config, { hooks }).generate()\n if (result.success) continue\n\n const failedCount = Diagnostics.failedPlugins(result.diagnostics).length\n const firstError = result.diagnostics.filter(Diagnostics.isProblem).find((diagnostic) => diagnostic.severity === 'error')\n throw fail(firstError, failedCount > 0 ? `Build Error with ${failedCount} failed plugins` : (firstError?.message ?? 'Build failed'))\n }\n }\n\n // A rerun with `output.clean` loops webpack and Rspack watchers, so generate once per instance.\n let generation: Promise<void> | undefined\n\n return [\n {\n name,\n enforce: 'pre',\n apply: meta.framework === 'vite' ? 'build' : undefined,\n async buildStart() {\n generation ??= runBuild().catch((error: unknown) => {\n generation = undefined\n throw error\n })\n await generation\n },\n },\n {\n name: `${name}:import`,\n enforce: 'pre',\n loadInclude: (id) => specFilePattern.test(id),\n async load(id) {\n const config = selectConfig(await loadConfigs(), id, process.cwd())!\n const { text, errors } = await generateModule({ root: path.dirname(id), input: id, config })\n if (errors.length) throw fail(errors[0], `${id}: ${errors[0]!.message}`)\n\n // Bundlers do not strip types from a `.yaml` module, so hand them JavaScript.\n return ts.transpileModule(text, { fileName: `${id}.ts`, compilerOptions: { module: ts.ModuleKind.ESNext, target: ts.ScriptTarget.ESNext } }).outputText\n },\n },\n ]\n}\n"],"mappings":";;;;;;;;;;;;;;;AAGA,MAAa,oBAAoB;CAAC;CAAO;CAAQ;CAAQ;CAAO;CAAQ;AAAM;;;;;;;ACI9E,MAAM,eAAe;CACnB,KAAK;EAAE,SAAS;EAAa,cAAc;CAAqB;CAChE,aAAa;AACf;;;;;AAMA,MAAM,uBAAuB;AAY7B,MAAM,OAAO,WAAW,YAAY,KAAK,YAAY;;;;;;;;;;;;AAarD,eAAsB,WAAwB,UAAkB,SAAyC;CACvG,IAAI,CAAC,qBAAqB,KAAK,QAAQ,GACrC,OAAQ,SAAS,UAAU,KAAK,OAAO,UAAU,EAAE,SAAS,KAAK,CAAC,IAAI,KAAK,OAAO,QAAQ;CAM5F,MAAM,MAAO,MAAM,KAAK,WAAW,MAAM,SAAS,UAAU,MAAM,GAAG;EAAE,UAAU;EAAU,OAAO;EAAM,gBAAgB;CAAK,CAAC;CAG9H,OAAQ,SAAS,UAAW,KAAK,WAAW,MAAO;AACrD;;;AC/CA,MAAM,eAAe;CAAC;CAAI;CAAY;AAAU,CAAC,CAAC,SAAS,WAAW,CAAC,GAAG,OAAO,UAAU,GAAG,OAAO,YAAY,CAAC;;;;AAKlH,SAAgB,qBAAqB,KAA4B;CAC/D,OAAO,aAAa,SAAS,SAAS,kBAAkB,KAAK,cAAc,KAAK,KAAK,GAAG,OAAO,WAAW,CAAC,CAAC;AAC9G;;;;;AAMA,SAAgB,eAAe,MAAcA,UAAQ,IAAI,GAAuB;CAC9E,KAAK,IAAI,MAAM,QAAQ,GAAG,IAAK,MAAM,QAAQ,GAAG,GAAG;EACjD,MAAM,QAAQ,qBAAqB,GAAG,CAAC,CAAC,MAAM,SAAS,WAAW,IAAI,CAAC;E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,cAAc,OAAO,gBAAgB,KAAK,EAAE;EAC5C,MAAM,KAAK,IAAI;GACb,MAAM,SAAS,aAAa,MAAM,YAAY,GAAG,IAAI,QAAQ,IAAI,CAAC;GAClE,MAAM,EAAE,MAAM,WAAW,MAAM,eAAe;IAAE,MAAM,KAAK,QAAQ,EAAE;IAAG,OAAO;IAAI;GAAO,CAAC;GAC3F,IAAI,OAAO,QAAQ,MAAM,KAAK,OAAO,IAAI,GAAG,GAAG,IAAI,OAAO,EAAE,CAAE,SAAS;GAGvE,OAAO,GAAG,gBAAgB,MAAM;IAAE,UAAU,GAAG,GAAG;IAAM,iBAAiB;KAAE,QAAQ,GAAG,WAAW;KAAQ,QAAQ,GAAG,aAAa;IAAO;GAAE,CAAC,CAAC,CAAC;EAC/I;CACF,CACF;AACF"}
@@ -3,7 +3,8 @@ import { UnpluginFactory } from "unplugin";
3
3
  //#region src/unpluginFactory.d.ts
4
4
  export type Options = {
5
5
  /**
6
- * Kubb config passed to the unplugin entry point.
6
+ * Kubb config passed to the unplugin entry point. When not set, the plugin loads
7
+ * `kubb.config.*` the way the Kubb CLI finds it, from the current working directory up.
7
8
  */
8
9
  config?: UserConfig;
9
10
  };
@@ -20,12 +21,10 @@ export type Options = {
20
21
  */
21
22
  export declare function applyDefaults<TInput>(config: UserConfig<TInput>): UserConfig<TInput>;
22
23
  /**
23
- * Builds the Kubb unplugin for any unplugin-supported bundler (Vite, Rollup, Webpack, esbuild).
24
- *
25
- * Runs the Kubb build during the first `buildStart` with {@link applyDefaults} applied to the
26
- * config and prints the same summary `kubb generate` does. Under Vite it only applies during
27
- * `build`. A missing config or a failed generation fails the host build.
24
+ * Builds the Kubb unplugin for every unplugin bundler. `unplugin-kubb` runs the Kubb build once for
25
+ * each config with an `input` (only during `build` under Vite), and `unplugin-kubb:import` loads an
26
+ * imported {@link specFilePattern} file as one module. Without `config`, it loads `kubb.config.*`.
28
27
  */
29
- export declare const unpluginFactory: UnpluginFactory<Options | undefined>;
28
+ export declare const unpluginFactory: UnpluginFactory<Options | undefined, true>;
30
29
  //#endregion
31
30
  //# sourceMappingURL=unpluginFactory.d.ts.map
@@ -1,102 +1 @@
1
- import "./rolldown-runtime-C0LytTxp.js";
2
- import { adapterOas } from "@kubb/adapter-oas";
3
- import { Diagnostics, Hookable, cliReporter, createCliReporter, createKubb, fileReporter, htmlReporter, jsonReporter, logLevel } from "@kubb/core";
4
- import { parserMd } from "@kubb/parser-md";
5
- import { parserTs, parserTsx } from "@kubb/parser-ts";
6
- import { pluginBarrel, pluginBarrelName } from "@kubb/plugin-barrel";
7
- //#region src/unpluginFactory.ts
8
- /**
9
- * Applies the defaults `defineConfig` and the unplugin share to a single user config when not set.
10
- *
11
- * - `root` defaults to `process.cwd()`
12
- * - `adapter` defaults to `adapterOas()`
13
- * - `parsers` defaults to `[parserTs(), parserTsx(), parserMd()]`
14
- * - `reporters` defaults to `[cliReporter, jsonReporter, fileReporter, htmlReporter]`
15
- * - `plugins` gets `pluginBarrel()` appended when none is already present
16
- * - `output.barrel` defaults to `false` when not set (`pluginBarrel` is always present after the step above, but generates nothing until configured)
17
- * - `output.format` and `output.lint` default to `false`
18
- */
19
- function applyDefaults(config) {
20
- const plugins = config.plugins ?? [];
21
- return {
22
- ...config,
23
- root: config.root || process.cwd(),
24
- adapter: config.adapter ?? adapterOas(),
25
- parsers: config.parsers?.length ? config.parsers : [
26
- parserTs(),
27
- parserTsx(),
28
- parserMd()
29
- ],
30
- reporters: config.reporters?.length ? config.reporters : [
31
- cliReporter,
32
- jsonReporter,
33
- fileReporter,
34
- htmlReporter
35
- ],
36
- plugins: plugins.some((plugin) => plugin.name === pluginBarrelName) ? plugins : [...plugins, pluginBarrel()],
37
- output: {
38
- barrel: false,
39
- format: false,
40
- lint: false,
41
- ...config.output
42
- }
43
- };
44
- }
45
- /**
46
- * Builds the Kubb unplugin for any unplugin-supported bundler (Vite, Rollup, Webpack, esbuild).
47
- *
48
- * Runs the Kubb build during the first `buildStart` with {@link applyDefaults} applied to the
49
- * config and prints the same summary `kubb generate` does. Under Vite it only applies during
50
- * `build`. A missing config or a failed generation fails the host build.
51
- */
52
- const unpluginFactory = (options, meta) => {
53
- const name = "unplugin-kubb";
54
- const hooks = new Hookable();
55
- const reporter = createCliReporter();
56
- hooks.hook("kubb:generation:end", ({ config, diagnostics = [], filesCreated = 0, status = "success", hrStart = process.hrtime() }) => reporter.report({
57
- config,
58
- diagnostics,
59
- filesCreated,
60
- status,
61
- hrStart
62
- }, { logLevel: logLevel.info }));
63
- async function runBuild() {
64
- if (!options?.config) throw new Diagnostics.Error({
65
- code: Diagnostics.code.inputRequired,
66
- severity: "error",
67
- message: `[${name}] Config is not set`,
68
- help: "Pass your Kubb config as the `config` option of the plugin.",
69
- location: { kind: "config" }
70
- });
71
- const result = await createKubb(applyDefaults(options.config), { hooks }).generate();
72
- if (!result.success) {
73
- const failedCount = Diagnostics.failedPlugins(result.diagnostics).length;
74
- const firstError = result.diagnostics.filter(Diagnostics.isProblem).find((diagnostic) => diagnostic.severity === "error");
75
- const message = failedCount > 0 ? `Build Error with ${failedCount} failed plugins` : firstError?.message ?? "Build failed";
76
- throw new Diagnostics.Error({
77
- ...firstError ?? {
78
- code: Diagnostics.code.unknown,
79
- severity: "error"
80
- },
81
- message: `[${name}] ${message}`
82
- });
83
- }
84
- }
85
- let generation;
86
- return {
87
- name,
88
- enforce: "pre",
89
- apply: meta.framework === "vite" ? "build" : void 0,
90
- async buildStart() {
91
- generation ??= runBuild().catch((error) => {
92
- generation = void 0;
93
- throw error;
94
- });
95
- await generation;
96
- }
97
- };
98
- };
99
- //#endregion
100
- export { applyDefaults, unpluginFactory };
101
-
102
- //# sourceMappingURL=unpluginFactory.js.map
1
+ export { t as applyDefaults, n as unpluginFactory } from "./unpluginFactory-DUew0Jfa.js";
package/dist/vite.js CHANGED
@@ -1,4 +1,4 @@
1
- import { unpluginFactory } from "./unpluginFactory.js";
1
+ import { n as unpluginFactory } from "./unpluginFactory-DUew0Jfa.js";
2
2
  import { createVitePlugin } from "unplugin";
3
3
  //#region src/vite.ts
4
4
  var vite_default = createVitePlugin(unpluginFactory);
package/dist/webpack.js CHANGED
@@ -1,4 +1,4 @@
1
- import { unpluginFactory } from "./unpluginFactory.js";
1
+ import { n as unpluginFactory } from "./unpluginFactory-DUew0Jfa.js";
2
2
  import { createWebpackPlugin } from "unplugin";
3
3
  //#region src/webpack.ts
4
4
  var webpack_default = createWebpackPlugin(unpluginFactory);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "unplugin-kubb",
3
- "version": "5.12.5",
3
+ "version": "5.12.6",
4
4
  "description": "Integration of Kubb for Vite, webpack, Rollup, Rolldown, Rspack, esbuild, Farm, Nuxt, and Astro.",
5
5
  "keywords": [
6
6
  "astro",
@@ -105,16 +105,19 @@
105
105
  "registry": "https://registry.npmjs.org/"
106
106
  },
107
107
  "dependencies": {
108
- "@kubb/adapter-oas": "5.12.5",
109
- "@kubb/core": "5.12.5",
110
- "@kubb/parser-md": "5.12.5",
111
- "@kubb/parser-ts": "5.12.5",
112
- "@kubb/plugin-barrel": "5.12.5",
108
+ "@kubb/adapter-oas": "5.12.6",
109
+ "@kubb/core": "5.12.6",
110
+ "@kubb/parser-md": "5.12.6",
111
+ "@kubb/parser-ts": "5.12.6",
112
+ "@kubb/plugin-barrel": "5.12.6",
113
+ "@typescript/typescript6": "^6.0.2",
114
+ "jiti": "^2.7.0",
113
115
  "unplugin": "^3.4.0"
114
116
  },
115
117
  "devDependencies": {
116
118
  "@farmfe/core": "^1.7.11",
117
- "@kubb/ast": "5.12.5",
119
+ "@internals/shared": "0.0.1",
120
+ "@kubb/ast": "5.12.6",
118
121
  "@nuxt/kit": "^4.6.2",
119
122
  "@nuxt/schema": "^4.6.2",
120
123
  "@rspack/core": "^2.2.9",
@@ -1 +0,0 @@
1
- {"version":3,"file":"unpluginFactory.js","names":[],"sources":["../src/unpluginFactory.ts"],"sourcesContent":["import { adapterOas } from '@kubb/adapter-oas'\nimport {\n cliReporter,\n type Config,\n createCliReporter,\n createKubb,\n Diagnostics,\n fileReporter,\n Hookable,\n htmlReporter,\n jsonReporter,\n type KubbHooks,\n logLevel,\n type UserConfig,\n} from '@kubb/core'\nimport { parserMd } from '@kubb/parser-md'\nimport { parserTs, parserTsx } from '@kubb/parser-ts'\nimport { pluginBarrel, pluginBarrelName } from '@kubb/plugin-barrel'\nimport type { UnpluginFactory } from 'unplugin'\n\nexport type Options = {\n /**\n * Kubb config passed to the unplugin entry point.\n */\n config?: UserConfig\n}\n\n/**\n * Applies the defaults `defineConfig` and the unplugin share to a single user config when not set.\n *\n * - `root` defaults to `process.cwd()`\n * - `adapter` defaults to `adapterOas()`\n * - `parsers` defaults to `[parserTs(), parserTsx(), parserMd()]`\n * - `reporters` defaults to `[cliReporter, jsonReporter, fileReporter, htmlReporter]`\n * - `plugins` gets `pluginBarrel()` appended when none is already present\n * - `output.barrel` defaults to `false` when not set (`pluginBarrel` is always present after the step above, but generates nothing until configured)\n * - `output.format` and `output.lint` default to `false`\n */\nexport function applyDefaults<TInput>(config: UserConfig<TInput>): UserConfig<TInput> {\n const plugins = config.plugins ?? []\n\n return {\n ...config,\n root: config.root || process.cwd(),\n adapter: config.adapter ?? adapterOas(),\n parsers: config.parsers?.length ? config.parsers : [parserTs(), parserTsx(), parserMd()],\n reporters: config.reporters?.length ? config.reporters : [cliReporter, jsonReporter, fileReporter, htmlReporter],\n plugins: plugins.some((plugin) => plugin.name === pluginBarrelName) ? plugins : [...plugins, pluginBarrel()],\n output: { barrel: false, format: false, lint: false, ...config.output },\n }\n}\n\n/**\n * Builds the Kubb unplugin for any unplugin-supported bundler (Vite, Rollup, Webpack, esbuild).\n *\n * Runs the Kubb build during the first `buildStart` with {@link applyDefaults} applied to the\n * config and prints the same summary `kubb generate` does. Under Vite it only applies during\n * `build`. A missing config or a failed generation fails the host build.\n */\nexport const unpluginFactory: UnpluginFactory<Options | undefined> = (options, meta) => {\n const name = 'unplugin-kubb' as const\n const hooks = new Hookable<KubbHooks>()\n const reporter = createCliReporter()\n\n hooks.hook('kubb:generation:end', ({ config, diagnostics = [], filesCreated = 0, status = 'success', hrStart = process.hrtime() }) =>\n reporter.report({ config, diagnostics, filesCreated, status, hrStart }, { logLevel: logLevel.info }),\n )\n\n // Throw: webpack, Rspack, esbuild, and Farm contexts have no `this.error`.\n async function runBuild() {\n if (!options?.config) {\n throw new Diagnostics.Error({\n code: Diagnostics.code.inputRequired,\n severity: 'error',\n message: `[${name}] Config is not set`,\n help: 'Pass your Kubb config as the `config` option of the plugin.',\n location: { kind: 'config' },\n })\n }\n\n const kubb = createKubb(applyDefaults(options.config) as Config, { hooks })\n const result = await kubb.generate()\n\n if (!result.success) {\n const failedCount = Diagnostics.failedPlugins(result.diagnostics).length\n const firstError = result.diagnostics.filter(Diagnostics.isProblem).find((diagnostic) => diagnostic.severity === 'error')\n const message = failedCount > 0 ? `Build Error with ${failedCount} failed plugins` : (firstError?.message ?? 'Build failed')\n\n // Keep the first error's code, help, and location, so the bundler shows the same diagnostic.\n throw new Diagnostics.Error({\n ...(firstError ?? { code: Diagnostics.code.unknown, severity: 'error' }),\n message: `[${name}] ${message}`,\n })\n }\n }\n\n // A rerun with `output.clean` loops webpack and Rspack watchers, so generate once per instance.\n let generation: Promise<void> | undefined\n\n return {\n name,\n enforce: 'pre',\n apply: meta.framework === 'vite' ? 'build' : undefined,\n async buildStart() {\n generation ??= runBuild().catch((error: unknown) => {\n generation = undefined\n throw error\n })\n await generation\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAsCA,SAAgB,cAAsB,QAAgD;CACpF,MAAM,UAAU,OAAO,WAAW,CAAC;CAEnC,OAAO;EACL,GAAG;EACH,MAAM,OAAO,QAAQ,QAAQ,IAAI;EACjC,SAAS,OAAO,WAAW,WAAW;EACtC,SAAS,OAAO,SAAS,SAAS,OAAO,UAAU;GAAC,SAAS;GAAG,UAAU;GAAG,SAAS;EAAC;EACvF,WAAW,OAAO,WAA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