unplugin-kubb 5.20.2 → 5.20.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/esbuild.js +1 -1
- package/dist/farm.js +1 -1
- package/dist/generateModule.d.ts +5 -0
- package/dist/generateModule.js +9 -2
- package/dist/generateModule.js.map +1 -1
- package/dist/index.js +1 -1
- package/dist/rolldown.js +1 -1
- package/dist/rollup.js +1 -1
- package/dist/rspack.js +1 -1
- package/dist/{unpluginFactory-NPE3mfCC.js → unpluginFactory-FlC69Sui.js} +29 -7
- package/dist/unpluginFactory-FlC69Sui.js.map +1 -0
- package/dist/unpluginFactory.d.ts +1 -1
- package/dist/unpluginFactory.js +1 -1
- package/dist/vite.js +1 -1
- package/dist/webpack.js +1 -1
- package/package.json +7 -7
- package/dist/unpluginFactory-NPE3mfCC.js.map +0 -1
package/dist/esbuild.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { n as unpluginFactory } from "./unpluginFactory-
|
|
1
|
+
import { n as unpluginFactory } from "./unpluginFactory-FlC69Sui.js";
|
|
2
2
|
import { createEsbuildPlugin } from "unplugin";
|
|
3
3
|
// src/esbuild.ts
|
|
4
4
|
var esbuild_default = createEsbuildPlugin(unpluginFactory);
|
package/dist/farm.js
CHANGED
package/dist/generateModule.d.ts
CHANGED
|
@@ -1,4 +1,9 @@
|
|
|
1
1
|
import { Hookable, KubbHooks, ProblemDiagnostic, UserConfig } from "@kubb/core";
|
|
2
|
+
/**
|
|
3
|
+
* The absolute path of a config's `input` file, or `undefined` when `input` is not a path. A
|
|
4
|
+
* relative `root` resolves from `cwd`, and `input` from `root`.
|
|
5
|
+
*/
|
|
6
|
+
export declare function resolveInput(config: UserConfig, cwd: string): string | undefined;
|
|
2
7
|
/**
|
|
3
8
|
* The config whose `input` is `fileName`, else the first one without an `input`. A config for
|
|
4
9
|
* another spec does not apply, so it returns `undefined` when no config fits. A relative `root`
|
package/dist/generateModule.js
CHANGED
|
@@ -19,12 +19,19 @@ const toModulePlugin = (plugin) => ({
|
|
|
19
19
|
}
|
|
20
20
|
});
|
|
21
21
|
/**
|
|
22
|
+
* The absolute path of a config's `input` file, or `undefined` when `input` is not a path. A
|
|
23
|
+
* relative `root` resolves from `cwd`, and `input` from `root`.
|
|
24
|
+
*/
|
|
25
|
+
function resolveInput(config, cwd) {
|
|
26
|
+
return typeof config.input === "string" ? path.resolve(cwd, config.root || ".", config.input) : void 0;
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
22
29
|
* The config whose `input` is `fileName`, else the first one without an `input`. A config for
|
|
23
30
|
* another spec does not apply, so it returns `undefined` when no config fits. A relative `root`
|
|
24
31
|
* resolves from `cwd`, and `input` from `root`.
|
|
25
32
|
*/
|
|
26
33
|
function selectConfig({ configs, fileName, cwd }) {
|
|
27
|
-
const matches = (config) =>
|
|
34
|
+
const matches = (config) => resolveInput(config, cwd) === path.resolve(fileName);
|
|
28
35
|
return configs.find(matches) ?? configs.find((config) => config.input === void 0);
|
|
29
36
|
}
|
|
30
37
|
/**
|
|
@@ -56,6 +63,6 @@ async function generateModule({ root, input, config, hooks }) {
|
|
|
56
63
|
sources: adapter.sources ?? []
|
|
57
64
|
};
|
|
58
65
|
}
|
|
59
|
-
export { generateModule, selectConfig };
|
|
66
|
+
export { generateModule, resolveInput, selectConfig };
|
|
60
67
|
|
|
61
68
|
//# sourceMappingURL=generateModule.js.map
|
|
@@ -1 +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 without an `input`. A config for\n * another spec does not apply, so it returns `undefined` when no config fits. A relative `root`\n * resolves from `cwd`, and `input` from `root`.\n */\nexport function selectConfig({ configs, fileName, cwd }: { configs: Array<UserConfig>; fileName: string; cwd: string }): UserConfig | undefined {\n const matches = (config: UserConfig) =>
|
|
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 absolute path of a config's `input` file, or `undefined` when `input` is not a path. A\n * relative `root` resolves from `cwd`, and `input` from `root`.\n */\nexport function resolveInput(config: UserConfig, cwd: string): string | undefined {\n return typeof config.input === 'string' ? path.resolve(cwd, config.root || '.', config.input) : undefined\n}\n\n/**\n * The config whose `input` is `fileName`, else the first one without an `input`. A config for\n * another spec does not apply, so it returns `undefined` when no config fits. A relative `root`\n * resolves from `cwd`, and `input` from `root`.\n */\nexport function selectConfig({ configs, fileName, cwd }: { configs: Array<UserConfig>; fileName: string; cwd: string }): UserConfig | undefined {\n const matches = (config: UserConfig) => resolveInput(config, cwd) === path.resolve(fileName)\n\n return configs.find(matches) ?? configs.find((config) => config.input === undefined)\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>; sources: Array<string> }> {\n const storage = memoryStorage()\n const adapter = config.adapter ?? adapterOas()\n const { diagnostics } = await createKubb(\n {\n root,\n input,\n output: { path: '.', barrel: false, format: false, lint: false },\n adapter,\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, sources: adapter.sources ?? [] }\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,QAAoB,KAAiC;CAChF,OAAO,OAAO,OAAO,UAAU,WAAW,KAAK,QAAQ,KAAK,OAAO,QAAQ,KAAK,OAAO,KAAK,IAAI,KAAA;AAClG;;;;;;AAOA,SAAgB,aAAa,EAAE,SAAS,UAAU,OAA8F;CAC9I,MAAM,WAAW,WAAuB,aAAa,QAAQ,GAAG,MAAM,KAAK,QAAQ,QAAQ;CAE3F,OAAO,QAAQ,KAAK,OAAO,KAAK,QAAQ,MAAM,WAAW,OAAO,UAAU,KAAA,CAAS;AACrF;;;;;;AAOA,eAAsB,eAAe,EACnC,MACA,OACA,QACA,SAOsF;CACtF,MAAM,UAAU,cAAc;CAC9B,MAAM,UAAU,OAAO,WAAW,WAAW;CAC7C,MAAM,EAAE,gBAAgB,MAAM,WAC5B;EACE;EACA;EACA,QAAQ;GAAE,MAAM;GAAK,QAAQ;GAAO,QAAQ;GAAO,MAAM;EAAM;EAC/D;EACA,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;EAAQ,SAAS,QAAQ,WAAW,CAAC;CAAE;AACxD"}
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { a as loadConfigFile, i as findConfigFile, n as unpluginFactory, r as configFileCandidates, t as applyDefaults } from "./unpluginFactory-
|
|
1
|
+
import { a as loadConfigFile, i as findConfigFile, n as unpluginFactory, r as configFileCandidates, t as applyDefaults } from "./unpluginFactory-FlC69Sui.js";
|
|
2
2
|
import { generateModule, selectConfig } from "./generateModule.js";
|
|
3
3
|
import { createUnplugin } from "unplugin";
|
|
4
4
|
// src/index.ts
|
package/dist/rolldown.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { n as unpluginFactory } from "./unpluginFactory-
|
|
1
|
+
import { n as unpluginFactory } from "./unpluginFactory-FlC69Sui.js";
|
|
2
2
|
import { createRolldownPlugin } from "unplugin";
|
|
3
3
|
// src/rolldown.ts
|
|
4
4
|
var rolldown_default = createRolldownPlugin(unpluginFactory);
|
package/dist/rollup.js
CHANGED
package/dist/rspack.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import "./rolldown-runtime-BowF1xt-.js";
|
|
2
|
-
import { generateModule, selectConfig } from "./generateModule.js";
|
|
2
|
+
import { generateModule, resolveInput, selectConfig } from "./generateModule.js";
|
|
3
3
|
import { stripTypes } from "./stripTypes.js";
|
|
4
4
|
import path, { basename, dirname, join, resolve } from "node:path";
|
|
5
5
|
import { adapterOas } from "@kubb/adapter-oas";
|
|
@@ -130,12 +130,16 @@ function applyDefaults(config) {
|
|
|
130
130
|
}
|
|
131
131
|
};
|
|
132
132
|
}
|
|
133
|
-
/** Spec files an import loads as a module, the extensions `openapi-import` registers too. */
|
|
133
|
+
/** Spec files an import loads as a module, the extensions `openapi-import` registers too. A config's `input` file loads whatever its name. */
|
|
134
134
|
const specFilePattern = /\.openapi\.ya?ml$/;
|
|
135
|
+
/** Ends the virtual id of a JSON spec module under Vite, so its JSON plugin skips it. */
|
|
136
|
+
const jsonModuleSuffix = ".kubb.js";
|
|
137
|
+
/** The spec file behind a module id, without the virtual prefix and suffix that a JSON spec gets under Vite. */
|
|
138
|
+
const toSpecFile = (id) => id.startsWith("\0") && id.endsWith(jsonModuleSuffix) ? id.slice(1, -8) : id;
|
|
135
139
|
/**
|
|
136
140
|
* Builds the Kubb unplugin for every unplugin bundler. `unplugin-kubb` runs the Kubb build once for
|
|
137
141
|
* each config with an `input` (only during `build` under Vite), and `unplugin-kubb:import` loads an
|
|
138
|
-
* imported {@link specFilePattern} file as one module. Without `config`, it loads `kubb.config.*`.
|
|
142
|
+
* imported config `input` file, or a {@link specFilePattern} file, as one module. Without `config`, it loads `kubb.config.*`.
|
|
139
143
|
*/
|
|
140
144
|
const unpluginFactory = (options, meta) => {
|
|
141
145
|
const name = "unplugin-kubb";
|
|
@@ -182,6 +186,7 @@ const unpluginFactory = (options, meta) => {
|
|
|
182
186
|
const firstError = failed.filter(Diagnostics.isProblem).find((diagnostic) => diagnostic.severity === "error");
|
|
183
187
|
throw fail(firstError, failedCount > 0 ? `Build Error with ${failedCount} failed plugins` : firstError?.message ?? "Build failed");
|
|
184
188
|
}
|
|
189
|
+
let inputs = /* @__PURE__ */ new Set();
|
|
185
190
|
let generation;
|
|
186
191
|
return [{
|
|
187
192
|
name,
|
|
@@ -197,8 +202,22 @@ const unpluginFactory = (options, meta) => {
|
|
|
197
202
|
}, {
|
|
198
203
|
name: `${name}:import`,
|
|
199
204
|
enforce: "pre",
|
|
200
|
-
|
|
201
|
-
|
|
205
|
+
async buildStart() {
|
|
206
|
+
const configs = await loadConfigs().catch(() => []);
|
|
207
|
+
inputs = new Set(configs.map((config) => resolveInput(config, process.cwd())).filter((input) => input !== void 0));
|
|
208
|
+
},
|
|
209
|
+
vite: { async resolveId(source, importer) {
|
|
210
|
+
if (!source.endsWith(".json")) return null;
|
|
211
|
+
const resolved = await this.resolve(source, importer, { skipSelf: true });
|
|
212
|
+
return resolved && inputs.has(resolved.id) ? `\0${resolved.id}${jsonModuleSuffix}` : null;
|
|
213
|
+
} },
|
|
214
|
+
loadInclude: (moduleId) => {
|
|
215
|
+
const id = toSpecFile(moduleId);
|
|
216
|
+
return inputs.has(path.resolve(id)) || specFilePattern.test(id);
|
|
217
|
+
},
|
|
218
|
+
esbuild: { loader: "js" },
|
|
219
|
+
async load(moduleId) {
|
|
220
|
+
const id = toSpecFile(moduleId);
|
|
202
221
|
try {
|
|
203
222
|
const config = selectConfig({
|
|
204
223
|
configs: await loadConfigs(),
|
|
@@ -218,7 +237,10 @@ const unpluginFactory = (options, meta) => {
|
|
|
218
237
|
config
|
|
219
238
|
});
|
|
220
239
|
if (errors.length) throw fail(errors[0], `${id}: ${errors[0].message}`);
|
|
221
|
-
return
|
|
240
|
+
return {
|
|
241
|
+
code: stripTypes(text, `${id}.ts`),
|
|
242
|
+
moduleType: "js"
|
|
243
|
+
};
|
|
222
244
|
} catch (error) {
|
|
223
245
|
if (meta.framework !== "webpack" && meta.framework !== "rspack") throw error;
|
|
224
246
|
this.error(error);
|
|
@@ -229,4 +251,4 @@ const unpluginFactory = (options, meta) => {
|
|
|
229
251
|
};
|
|
230
252
|
export { loadConfigFile as a, findConfigFile as i, unpluginFactory as n, configFileCandidates as r, applyDefaults as t };
|
|
231
253
|
|
|
232
|
-
//# sourceMappingURL=unpluginFactory-
|
|
254
|
+
//# sourceMappingURL=unpluginFactory-FlC69Sui.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"unpluginFactory-FlC69Sui.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\n/**\n * Extensions `kubb` ships at its own version, so they count as installed without being a direct\n * dependency. `constants.test.ts` checks it against the `kubb` package's dependencies.\n */\nexport const BUNDLED_PACKAGES: ReadonlyArray<string> = ['@kubb/adapter-oas', '@kubb/parser-ts', '@kubb/parser-md', '@kubb/plugin-barrel']\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 { basename, dirname, join, resolve } from 'node:path'\nimport process from 'node:process'\nimport { CONFIG_EXTENSIONS } from './constants.ts'\nimport { loadModule } from './loader.ts'\n\n// A config in one of these folders belongs to the folder above it.\nconst CONFIG_FOLDERS = ['.config', 'configs']\nconst SEARCH_FILES = ['', ...CONFIG_FOLDERS.map((folder) => `${folder}/`)].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. Each\n * `root` resolves from the folder the config belongs to: the file's folder, or the folder above\n * `.config/` and `configs/`. A missing `root` becomes that folder, so the CLI, the bundler, and\n * an editor read the same paths wherever they run.\n */\nexport async function loadConfigFile<T extends { root?: string }>({ file, cli }: { 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 const dir = CONFIG_FOLDERS.includes(basename(dirname(file))) ? dirname(dirname(file)) : dirname(file)\n return (Array.isArray(resolved) ? resolved : [resolved]).map((config) => ({ ...config, root: resolve(dir, config.root ?? '.') }))\n}\n","import path from 'node:path'\nimport { adapterOas } from '@kubb/adapter-oas'\nimport {\n cliReporter,\n createCliReporter,\n type Diagnostic,\n Diagnostics,\n fileReporter,\n Hookable,\n htmlReporter,\n jsonReporter,\n Kubb,\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 type { UnpluginFactory } from 'unplugin'\nimport { generateModule, resolveInput, selectConfig } from './generateModule.ts'\nimport { stripTypes } from './stripTypes.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 * - `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 (only the root barrel is off: plugins whose default `output` carries `barrel: { type: 'named' }` still get their own barrel)\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 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. A config's `input` file loads whatever its name. */\nconst specFilePattern = /\\.openapi\\.ya?ml$/\n\n/** Ends the virtual id of a JSON spec module under Vite, so its JSON plugin skips it. */\nconst jsonModuleSuffix = '.kubb.js'\n\n/** The spec file behind a module id, without the virtual prefix and suffix that a JSON spec gets under Vite. */\nconst toSpecFile = (id: string) => (id.startsWith('\\0') && id.endsWith(jsonModuleSuffix) ? id.slice(1, -jsonModuleSuffix.length) : id)\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 config `input` file, or a {@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 // The summary only lists a build's diagnostics, so a warning raised outside one, such as schemas the configs define differently, prints here.\n hooks.hook('kubb:warn', ({ message, info }) => console.warn(`[${name}] ${[message, info].filter(Boolean).join(' ')}`))\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 return loadConfigFile<UserConfig>({ file, cli: {} })\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 const configs = (await loadConfigs()).filter((config) => config.input).map(applyDefaults)\n // Every config builds, so a failing one does not hide the others' output or errors. The first failure fails the host build.\n let failed: Array<Diagnostic> | undefined\n for await (const { success, diagnostics } of Kubb.generate(configs, { hooks })) {\n if (!success) failed ??= diagnostics\n }\n if (!failed) return\n\n const failedCount = Diagnostics.failedPlugins(failed).length\n const firstError = failed.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 // The `input` files of every config, so an import of one loads as a spec module whatever its name.\n let inputs = new Set<string>()\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` cannot wait, so the configs are read here first. A missing config fails the import that needs it, not the start.\n async buildStart() {\n const configs = await loadConfigs().catch(() => [])\n inputs = new Set(configs.map((config) => resolveInput(config, process.cwd())).filter((input) => input !== undefined))\n },\n // Vite 7 and older run their JSON plugin on every `.json` id and ignore `moduleType`, so a JSON input gets a virtual id.\n vite: {\n async resolveId(source, importer) {\n if (!source.endsWith('.json')) return null\n const resolved = await this.resolve(source, importer, { skipSelf: true })\n return resolved && inputs.has(resolved.id) ? `\\0${resolved.id}${jsonModuleSuffix}` : null\n },\n },\n loadInclude: (moduleId) => {\n const id = toSpecFile(moduleId)\n return inputs.has(path.resolve(id)) || specFilePattern.test(id)\n },\n // The loaded module is JavaScript whatever the spec extension, so esbuild must not pick a `.json` loader.\n esbuild: { loader: 'js' },\n async load(moduleId) {\n const id = toSpecFile(moduleId)\n try {\n const config = selectConfig({ configs: await loadConfigs(), fileName: id, cwd: process.cwd() })\n if (!config) {\n throw new Diagnostics.Error({\n code: Diagnostics.code.unknown,\n severity: 'error',\n message: `[${name}] No Kubb config applies to ${id}`,\n help: 'Set `input` of a config to this spec, or add a config without `input` to serve every imported spec.',\n location: { kind: 'config' },\n })\n }\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 // `moduleType` keeps Rolldown and Vite from parsing a `.json` spec module as JSON.\n return { code: stripTypes(text, `${id}.ts`), moduleType: 'js' }\n } catch (error) {\n // unplugin's webpack and Rspack loader never settles when `load` throws, so report the error instead.\n if (meta.framework !== 'webpack' && meta.framework !== 'rspack') throw error\n this.error(error as Error)\n return 'export {}'\n }\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;;AC9CA,MAAM,iBAAiB,CAAC,WAAW,SAAS;AAC5C,MAAM,eAAe,CAAC,IAAI,GAAG,eAAe,KAAK,WAAW,GAAG,OAAO,EAAE,CAAC,CAAC,CAAC,SAAS,WAAW,CAAC,GAAG,OAAO,UAAU,GAAG,OAAO,YAAY,CAAC;;;;AAK3I,SAAgB,qBAAqB,KAA4B;CAC/D,OAAO,aAAa,SAAS,SAAS,kBAAkB,KAAK,cAAc,KAAK,KAAK,GAAG,OAAO,WAAW,CAAC,CAAC;AAC9G;;;;;AAMA,SAAgB,eAAe,MAAcA,UA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AK,WAAW,QAAQ;GAC9B,IAAI;IACF,MAAM,SAAS,aAAa;KAAE,SAAS,MAAM,YAAY;KAAG,UAAU;KAAI,KAAK,QAAQ,IAAI;IAAE,CAAC;IAC9F,IAAI,CAAC,QACH,MAAM,IAAI,YAAY,MAAM;KAC1B,MAAM,YAAY,KAAK;KACvB,UAAU;KACV,SAAS,IAAI,KAAK,8BAA8B;KAChD,MAAM;KACN,UAAU,EAAE,MAAM,SAAS;IAC7B,CAAC;IAEH,MAAM,EAAE,MAAM,WAAW,MAAM,eAAe;KAAE,MAAM,KAAK,QAAQ,EAAE;KAAG,OAAO;KAAI;IAAO,CAAC;IAC3F,IAAI,OAAO,QAAQ,MAAM,KAAK,OAAO,IAAI,GAAG,GAAG,IAAI,OAAO,EAAE,CAAE,SAAS;IAIvE,OAAO;KAAE,MAAM,WAAW,MAAM,GAAG,GAAG,IAAI;KAAG,YAAY;IAAK;GAChE,SAAS,OAAO;IAEd,IAAI,KAAK,cAAc,aAAa,KAAK,cAAc,UAAU,MAAM;IACvE,KAAK,MAAM,KAAc;IACzB,OAAO;GACT;EACF;CACF,CACF;AACF"}
|
|
@@ -21,6 +21,6 @@ export declare function applyDefaults<TInput>(config: UserConfig<TInput>): UserC
|
|
|
21
21
|
/**
|
|
22
22
|
* Builds the Kubb unplugin for every unplugin bundler. `unplugin-kubb` runs the Kubb build once for
|
|
23
23
|
* each config with an `input` (only during `build` under Vite), and `unplugin-kubb:import` loads an
|
|
24
|
-
* imported {@link specFilePattern} file as one module. Without `config`, it loads `kubb.config.*`.
|
|
24
|
+
* imported config `input` file, or a {@link specFilePattern} file, as one module. Without `config`, it loads `kubb.config.*`.
|
|
25
25
|
*/
|
|
26
26
|
export declare const unpluginFactory: UnpluginFactory<Options | undefined, true>;
|
package/dist/unpluginFactory.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export { t as applyDefaults, n as unpluginFactory } from "./unpluginFactory-
|
|
1
|
+
export { t as applyDefaults, n as unpluginFactory } from "./unpluginFactory-FlC69Sui.js";
|
package/dist/vite.js
CHANGED
package/dist/webpack.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { n as unpluginFactory } from "./unpluginFactory-
|
|
1
|
+
import { n as unpluginFactory } from "./unpluginFactory-FlC69Sui.js";
|
|
2
2
|
import { createWebpackPlugin } from "unplugin";
|
|
3
3
|
// 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.20.
|
|
3
|
+
"version": "5.20.3",
|
|
4
4
|
"description": "Integration of Kubb for Vite, webpack, Rollup, Rolldown, Rspack, esbuild, Farm, Nuxt, and Astro.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"astro",
|
|
@@ -105,11 +105,11 @@
|
|
|
105
105
|
"registry": "https://registry.npmjs.org/"
|
|
106
106
|
},
|
|
107
107
|
"dependencies": {
|
|
108
|
-
"@kubb/adapter-oas": "5.20.
|
|
109
|
-
"@kubb/core": "^5.20.
|
|
110
|
-
"@kubb/parser-md": "5.20.
|
|
111
|
-
"@kubb/parser-ts": "5.20.
|
|
112
|
-
"@kubb/plugin-barrel": "5.20.
|
|
108
|
+
"@kubb/adapter-oas": "5.20.3",
|
|
109
|
+
"@kubb/core": "^5.20.3",
|
|
110
|
+
"@kubb/parser-md": "5.20.3",
|
|
111
|
+
"@kubb/parser-ts": "5.20.3",
|
|
112
|
+
"@kubb/plugin-barrel": "5.20.3",
|
|
113
113
|
"jiti": "^2.7.0",
|
|
114
114
|
"unplugin": "^3.7.0",
|
|
115
115
|
"yuku-codegen": "^0.19.0",
|
|
@@ -118,7 +118,7 @@
|
|
|
118
118
|
"devDependencies": {
|
|
119
119
|
"@farmfe/core": "^1.7.11",
|
|
120
120
|
"@internals/shared": "0.0.1",
|
|
121
|
-
"@kubb/ast": "5.20.
|
|
121
|
+
"@kubb/ast": "5.20.3",
|
|
122
122
|
"@nuxt/kit": "^4.6.4",
|
|
123
123
|
"@nuxt/schema": "^4.6.4",
|
|
124
124
|
"@rspack/core": "^2.3.2",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"unpluginFactory-NPE3mfCC.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\n/**\n * Extensions `kubb` ships at its own version, so they count as installed without being a direct\n * dependency. `constants.test.ts` checks it against the `kubb` package's dependencies.\n */\nexport const BUNDLED_PACKAGES: ReadonlyArray<string> = ['@kubb/adapter-oas', '@kubb/parser-ts', '@kubb/parser-md', '@kubb/plugin-barrel']\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 { basename, dirname, join, resolve } from 'node:path'\nimport process from 'node:process'\nimport { CONFIG_EXTENSIONS } from './constants.ts'\nimport { loadModule } from './loader.ts'\n\n// A config in one of these folders belongs to the folder above it.\nconst CONFIG_FOLDERS = ['.config', 'configs']\nconst SEARCH_FILES = ['', ...CONFIG_FOLDERS.map((folder) => `${folder}/`)].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. Each\n * `root` resolves from the folder the config belongs to: the file's folder, or the folder above\n * `.config/` and `configs/`. A missing `root` becomes that folder, so the CLI, the bundler, and\n * an editor read the same paths wherever they run.\n */\nexport async function loadConfigFile<T extends { root?: string }>({ file, cli }: { 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 const dir = CONFIG_FOLDERS.includes(basename(dirname(file))) ? dirname(dirname(file)) : dirname(file)\n return (Array.isArray(resolved) ? resolved : [resolved]).map((config) => ({ ...config, root: resolve(dir, config.root ?? '.') }))\n}\n","import path from 'node:path'\nimport { adapterOas } from '@kubb/adapter-oas'\nimport {\n cliReporter,\n createCliReporter,\n type Diagnostic,\n Diagnostics,\n fileReporter,\n Hookable,\n htmlReporter,\n jsonReporter,\n Kubb,\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 type { UnpluginFactory } from 'unplugin'\nimport { generateModule, selectConfig } from './generateModule.ts'\nimport { stripTypes } from './stripTypes.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 * - `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 (only the root barrel is off: plugins whose default `output` carries `barrel: { type: 'named' }` still get their own barrel)\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 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 // The summary only lists a build's diagnostics, so a warning raised outside one, such as schemas the configs define differently, prints here.\n hooks.hook('kubb:warn', ({ message, info }) => console.warn(`[${name}] ${[message, info].filter(Boolean).join(' ')}`))\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 return loadConfigFile<UserConfig>({ file, cli: {} })\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 const configs = (await loadConfigs()).filter((config) => config.input).map(applyDefaults)\n // Every config builds, so a failing one does not hide the others' output or errors. The first failure fails the host build.\n let failed: Array<Diagnostic> | undefined\n for await (const { success, diagnostics } of Kubb.generate(configs, { hooks })) {\n if (!success) failed ??= diagnostics\n }\n if (!failed) return\n\n const failedCount = Diagnostics.failedPlugins(failed).length\n const firstError = failed.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 // 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 try {\n const config = selectConfig({ configs: await loadConfigs(), fileName: id, cwd: process.cwd() })\n if (!config) {\n throw new Diagnostics.Error({\n code: Diagnostics.code.unknown,\n severity: 'error',\n message: `[${name}] No Kubb config applies to ${id}`,\n help: 'Set `input` of a config to this spec, or add a config without `input` to serve every imported spec.',\n location: { kind: 'config' },\n })\n }\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 stripTypes(text, `${id}.ts`)\n } catch (error) {\n // unplugin's webpack and Rspack loader never settles when `load` throws, so report the error instead.\n if (meta.framework !== 'webpack' && meta.framework !== 'rspack') throw error\n this.error(error as Error)\n return 'export {}'\n }\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;;AC9CA,MAAM,iBAAiB,CAAC,WAAW,SAAS;AAC5C,MAAM,eAAe,CAAC,IAAI,GAAG,eAAe,KAAK,WAAW,GAAG,OAAO,EAAE,CAAC,CAAC,CAAC,SAAS,WAAW,CAAC,GAAG,OAAO,UAAU,GAAG,OAAO,YAAY,CAAC;;;;AAK3I,SAAgB,qBAAqB,KAA4B;CAC/D,OAAO,aAAa,SAAS,SAAS,kBAAkB,KAAK,cAAc,KAAK,KAAK,GAAG,OAAO,WAAW,CAAC,CAAC;AAC9G;;;;;A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