@kubb/mcp 5.6.2 → 5.6.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/index.cjs +46 -19
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +2 -1
- package/dist/index.js +45 -18
- package/dist/index.js.map +1 -1
- package/package.json +6 -7
package/dist/index.cjs
CHANGED
|
@@ -21,24 +21,26 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
|
|
|
21
21
|
enumerable: true
|
|
22
22
|
}) : target, mod));
|
|
23
23
|
//#endregion
|
|
24
|
-
let _tmcp_adapter_valibot = require("@tmcp/adapter-valibot");
|
|
25
24
|
let _tmcp_transport_stdio = require("@tmcp/transport-stdio");
|
|
26
25
|
let tmcp = require("tmcp");
|
|
26
|
+
let tmcp_adapter = require("tmcp/adapter");
|
|
27
|
+
let zod_locales = require("zod/locales");
|
|
28
|
+
let zod_mini = require("zod/mini");
|
|
29
|
+
zod_mini = __toESM(zod_mini, 1);
|
|
27
30
|
let node_path = require("node:path");
|
|
28
31
|
node_path = __toESM(node_path, 1);
|
|
32
|
+
let node_fs_promises = require("node:fs/promises");
|
|
29
33
|
let jiti = require("jiti");
|
|
30
34
|
let _kubb_core = require("@kubb/core");
|
|
31
35
|
let tmcp_tool = require("tmcp/tool");
|
|
32
36
|
let tmcp_utils = require("tmcp/utils");
|
|
33
|
-
let valibot = require("valibot");
|
|
34
|
-
valibot = __toESM(valibot, 1);
|
|
35
37
|
let node_fs = require("node:fs");
|
|
36
38
|
node_fs = __toESM(node_fs, 1);
|
|
37
39
|
let node_process = require("node:process");
|
|
38
40
|
node_process = __toESM(node_process, 1);
|
|
39
41
|
let _kubb_adapter_oas = require("@kubb/adapter-oas");
|
|
40
42
|
//#region package.json
|
|
41
|
-
var version = "5.6.
|
|
43
|
+
var version = "5.6.3";
|
|
42
44
|
//#endregion
|
|
43
45
|
//#region ../../internals/shared/src/constants.ts
|
|
44
46
|
const KUBB_CONFIG_FILENAME = "kubb.config.ts";
|
|
@@ -173,9 +175,15 @@ const JITI_OPTIONS = {
|
|
|
173
175
|
moduleCache: false
|
|
174
176
|
};
|
|
175
177
|
/**
|
|
178
|
+
* Plain JavaScript files. jiti hands these to Node's native `import()`, whose module cache never
|
|
179
|
+
* lets go of a file, so `moduleCache: false` alone would keep returning the first version of it.
|
|
180
|
+
*/
|
|
181
|
+
const JAVASCRIPT_EXTENSION = /\.[cm]?jsx?$/;
|
|
182
|
+
/**
|
|
176
183
|
* Creates a jiti-based loader for Kubb's TypeScript and JavaScript config modules.
|
|
177
184
|
*
|
|
178
|
-
* jiti transpiles TypeScript and the `@kubb/renderer-jsx` JSX runtime on the fly.
|
|
185
|
+
* jiti transpiles TypeScript and the `@kubb/renderer-jsx` JSX runtime on the fly. Every load
|
|
186
|
+
* re-evaluates the file, so a config edited on disk is picked up by the next load.
|
|
179
187
|
*
|
|
180
188
|
* @example
|
|
181
189
|
* ```ts
|
|
@@ -184,8 +192,14 @@ const JITI_OPTIONS = {
|
|
|
184
192
|
*/
|
|
185
193
|
function createModuleLoader() {
|
|
186
194
|
const jiti$1 = (0, jiti.createJiti)(require("url").pathToFileURL(__filename).href, JITI_OPTIONS);
|
|
187
|
-
return { load(filePath, options) {
|
|
188
|
-
return options?.default ? jiti$1.import(filePath, { default: true }) : jiti$1.import(filePath);
|
|
195
|
+
return { async load(filePath, options) {
|
|
196
|
+
if (!JAVASCRIPT_EXTENSION.test(filePath)) return options?.default ? jiti$1.import(filePath, { default: true }) : jiti$1.import(filePath);
|
|
197
|
+
const mod = await jiti$1.evalModule(await (0, node_fs_promises.readFile)(filePath, "utf8"), {
|
|
198
|
+
filename: filePath,
|
|
199
|
+
async: true,
|
|
200
|
+
forceTranspile: true
|
|
201
|
+
});
|
|
202
|
+
return options?.default ? mod?.default ?? mod : mod;
|
|
189
203
|
} };
|
|
190
204
|
}
|
|
191
205
|
//#endregion
|
|
@@ -319,15 +333,15 @@ async function resolveUserConfig(config, options) {
|
|
|
319
333
|
}
|
|
320
334
|
//#endregion
|
|
321
335
|
//#region src/tools/generate.ts
|
|
322
|
-
const generateSchema =
|
|
323
|
-
config:
|
|
324
|
-
input:
|
|
325
|
-
output:
|
|
326
|
-
logLevel:
|
|
336
|
+
const generateSchema = zod_mini.object({
|
|
337
|
+
config: zod_mini.optional(zod_mini.string().check(zod_mini.minLength(1), zod_mini.describe(`Path to kubb.config file (supports ${CONFIG_EXTENSIONS.join(", ")}). If not provided, will look for kubb.config.* in current directory`))),
|
|
338
|
+
input: zod_mini.optional(zod_mini.string().check(zod_mini.minLength(1), zod_mini.describe("Path to OpenAPI/Swagger spec file (overrides config)"))),
|
|
339
|
+
output: zod_mini.optional(zod_mini.string().check(zod_mini.minLength(1), zod_mini.describe("Output directory path (overrides config)"))),
|
|
340
|
+
logLevel: zod_mini._default(zod_mini.enum([
|
|
327
341
|
"silent",
|
|
328
342
|
"info",
|
|
329
343
|
"verbose"
|
|
330
|
-
])
|
|
344
|
+
]).check(zod_mini.describe("Log level for build output")), "info")
|
|
331
345
|
});
|
|
332
346
|
const generateTool = (0, tmcp_tool.defineTool)({
|
|
333
347
|
name: "generate",
|
|
@@ -427,10 +441,10 @@ const generateTool = (0, tmcp_tool.defineTool)({
|
|
|
427
441
|
});
|
|
428
442
|
//#endregion
|
|
429
443
|
//#region src/tools/init.ts
|
|
430
|
-
const initSchema =
|
|
431
|
-
input:
|
|
432
|
-
output:
|
|
433
|
-
plugins:
|
|
444
|
+
const initSchema = zod_mini.object({
|
|
445
|
+
input: zod_mini.optional(zod_mini.string().check(zod_mini.minLength(1), zod_mini.describe("Path to OpenAPI spec (default: ./openapi.yaml)"))),
|
|
446
|
+
output: zod_mini.optional(zod_mini.string().check(zod_mini.minLength(1), zod_mini.describe("Output directory (default: ./src/gen)"))),
|
|
447
|
+
plugins: zod_mini.optional(zod_mini.string().check(zod_mini.minLength(1), zod_mini.describe("Comma-separated list of plugins: plugin-ts,plugin-zod,...")))
|
|
434
448
|
});
|
|
435
449
|
const initTool = (0, tmcp_tool.defineTool)({
|
|
436
450
|
name: "init",
|
|
@@ -451,7 +465,7 @@ const initTool = (0, tmcp_tool.defineTool)({
|
|
|
451
465
|
});
|
|
452
466
|
//#endregion
|
|
453
467
|
//#region src/tools/validate.ts
|
|
454
|
-
const validateSchema =
|
|
468
|
+
const validateSchema = zod_mini.object({ input: zod_mini.string().check(zod_mini.minLength(1), zod_mini.describe("Path or URL to the OpenAPI/Swagger specification")) });
|
|
455
469
|
const validateTool = (0, tmcp_tool.defineTool)({
|
|
456
470
|
name: "validate",
|
|
457
471
|
description: "Validate an OpenAPI/Swagger specification file or URL",
|
|
@@ -468,17 +482,30 @@ const validateTool = (0, tmcp_tool.defineTool)({
|
|
|
468
482
|
//#endregion
|
|
469
483
|
//#region src/server.ts
|
|
470
484
|
/**
|
|
485
|
+
* Describes each tool's input to MCP clients. `@tmcp/adapter-zod` imports the full `zod` build, so
|
|
486
|
+
* this converts with Zod Mini instead. `io: 'input'` keeps fields with a default optional.
|
|
487
|
+
*/
|
|
488
|
+
var ZodMiniJsonSchemaAdapter = class extends tmcp_adapter.JsonSchemaAdapter {
|
|
489
|
+
async toJsonSchema(schema) {
|
|
490
|
+
return zod_mini.toJSONSchema(schema, {
|
|
491
|
+
target: "draft-7",
|
|
492
|
+
io: "input"
|
|
493
|
+
});
|
|
494
|
+
}
|
|
495
|
+
};
|
|
496
|
+
/**
|
|
471
497
|
* Builds the Kubb MCP server with the generate, validate, and init tools registered.
|
|
472
498
|
*
|
|
473
499
|
* @example
|
|
474
500
|
* `const server = createMcpServer()`
|
|
475
501
|
*/
|
|
476
502
|
function createMcpServer() {
|
|
503
|
+
zod_mini.config((0, zod_locales.en)());
|
|
477
504
|
const server = new tmcp.McpServer({
|
|
478
505
|
name: "Kubb",
|
|
479
506
|
version
|
|
480
507
|
}, {
|
|
481
|
-
adapter: new
|
|
508
|
+
adapter: new ZodMiniJsonSchemaAdapter(),
|
|
482
509
|
capabilities: { tools: {} }
|
|
483
510
|
});
|
|
484
511
|
server.tools([
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["jiti","createJiti","resolve","relative","isAbsolute","path","existsSync","v","defineTool","Hookable","Diagnostics","tool","path","createKubb","v","defineTool","path","process","fs","tool","v","defineTool","adapterOas","tool","Diagnostics","McpServer","ValibotJsonSchemaAdapter","StdioTransport"],"sources":["../package.json","../../../internals/shared/src/constants.ts","../../../internals/shared/src/init.ts","../../../internals/shared/src/loader.ts","../../../internals/utils/src/fs.ts","../../../internals/utils/src/promise.ts","../src/utils.ts","../src/tools/generate.ts","../src/tools/init.ts","../src/tools/validate.ts","../src/server.ts"],"sourcesContent":["","import type { PluginOption } from './types.ts'\n\nexport 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\nexport const availablePlugins: Array<PluginOption> = [\n {\n value: 'plugin-ts',\n label: 'TypeScript',\n hint: 'Recommended',\n packageName: '@kubb/plugin-ts',\n importName: 'pluginTs',\n category: 'types',\n },\n {\n value: 'plugin-axios',\n label: 'Axios Client',\n packageName: '@kubb/plugin-axios',\n importName: 'pluginAxios',\n category: 'client',\n },\n {\n value: 'plugin-fetch',\n label: 'Fetch Client',\n packageName: '@kubb/plugin-fetch',\n importName: 'pluginFetch',\n category: 'client',\n },\n {\n value: 'plugin-react-query',\n label: 'React Query / TanStack Query',\n packageName: '@kubb/plugin-react-query',\n importName: 'pluginReactQuery',\n category: 'framework',\n },\n {\n value: 'plugin-vue-query',\n label: 'Vue Query',\n packageName: '@kubb/plugin-vue-query',\n importName: 'pluginVueQuery',\n category: 'framework',\n },\n {\n value: 'plugin-zod',\n label: 'Zod Schemas',\n packageName: '@kubb/plugin-zod',\n importName: 'pluginZod',\n category: 'validation',\n },\n {\n value: 'plugin-faker',\n label: 'Faker.js Mocks',\n packageName: '@kubb/plugin-faker',\n importName: 'pluginFaker',\n category: 'mocks',\n },\n {\n value: 'plugin-msw',\n label: 'MSW Handlers',\n packageName: '@kubb/plugin-msw',\n importName: 'pluginMsw',\n category: 'mocks',\n },\n {\n value: 'plugin-cypress',\n label: 'Cypress Tests',\n packageName: '@kubb/plugin-cypress',\n importName: 'pluginCypress',\n category: 'testing',\n },\n {\n value: 'plugin-mcp',\n label: 'MCP Server (AI / Model Context Protocol)',\n packageName: '@kubb/plugin-mcp',\n importName: 'pluginMcp',\n category: 'ai',\n },\n {\n value: 'plugin-redoc',\n label: 'ReDoc Documentation',\n packageName: '@kubb/plugin-redoc',\n importName: 'pluginRedoc',\n category: 'documentation',\n },\n]\n","import { availablePlugins, KUBB_PACKAGE_NAME } from './constants.ts'\nimport type { PluginOption } from './types.ts'\n\n/**\n * Resolves a comma-separated plugin flag (e.g. `--plugins plugin-ts,plugin-zod`) into the\n * matching known plugin options. Unrecognized names are dropped, and a missing flag yields\n * an empty list.\n */\nexport function resolvePlugins(pluginsFlag: string | undefined): Array<PluginOption> {\n if (!pluginsFlag) {\n return []\n }\n const requested = pluginsFlag\n .split(',')\n .map((value) => value.trim())\n .filter(Boolean)\n return availablePlugins.filter((plugin) => requested.includes(plugin.value))\n}\n\nexport function generateConfigFile({\n selectedPlugins,\n inputPath,\n outputPath,\n}: {\n selectedPlugins: Array<PluginOption>\n inputPath: string\n outputPath: string\n}): string {\n const imports = selectedPlugins.map((plugin) => `import { ${plugin.importName} } from '${plugin.packageName}'`).join('\\n')\n\n const pluginConfigs = selectedPlugins.map((plugin) => ` ${plugin.importName}(),`).join('\\n')\n\n return `import { defineConfig } from 'kubb/config'\n${imports}\n\nexport default defineConfig({\n input: '${inputPath}',\n output: {\n path: '${outputPath}',\n clean: true,\n },\n plugins: [\n${pluginConfigs}\n ],\n})\n`\n}\n\n/**\n * Turns package names into install specifiers for the wizard.\n *\n * `kubb` is pinned to the exact version of the running CLI, since both ship from the same release\n * and resolving `kubb@beta` separately can land on a different version than the CLI doing the\n * scaffolding. Plugins release from their own repo on their own cadence, so they follow the\n * release channel of the CLI through its dist-tag.\n */\nexport function resolveInstallVersions({ packages, version }: { packages: Array<string>; version: string }): Array<string> {\n const prerelease = version.match(/-([a-z]+)/)?.[1]\n const tag = prerelease ?? 'latest'\n\n return packages.map((name) => (name === KUBB_PACKAGE_NAME ? `${name}@${version}` : `${name}@${tag}`))\n}\n","import { 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 * Per-call options for {@link ModuleLoader.load}.\n */\ntype LoadModuleOptions = {\n /**\n * Return the module's default export instead of the full namespace.\n */\n default?: boolean\n}\n\n/**\n * Loads `.ts`/`.js` modules via jiti.\n */\ntype ModuleLoader = {\n load<T = unknown>(filePath: string, options?: LoadModuleOptions): Promise<T>\n}\n\n/**\n * Creates a jiti-based loader for Kubb's TypeScript and JavaScript config modules.\n *\n * jiti transpiles TypeScript and the `@kubb/renderer-jsx` JSX runtime on the fly.\n *\n * @example\n * ```ts\n * const config = await createModuleLoader().load('/abs/kubb.config.ts', { default: true })\n * ```\n */\nexport function createModuleLoader(): ModuleLoader {\n const jiti = createJiti(import.meta.url, JITI_OPTIONS)\n\n return {\n load<T>(filePath: string, options?: LoadModuleOptions) {\n return (options?.default ? jiti.import(filePath, { default: true }) : jiti.import(filePath)) as Promise<T>\n },\n }\n}\n","import { access, mkdir, readFile, rm, writeFile } from 'node:fs/promises'\nimport { dirname, isAbsolute, relative, resolve } from 'node:path'\nimport { runtime } from './runtime.ts'\n\n/**\n * Resolves to `true` when the file or directory at `path` exists.\n * Uses `Bun.file().exists()` when running under Bun, `fs.access` otherwise.\n *\n * @example\n * ```ts\n * if (await exists('./kubb.config.ts')) {\n * const content = await read('./kubb.config.ts')\n * }\n * ```\n */\nexport async function exists(path: string): Promise<boolean> {\n if (runtime.isBun) {\n return Bun.file(path).exists()\n }\n return access(path).then(\n () => true,\n () => false,\n )\n}\n\n/**\n * Reads the file at `path` as a UTF-8 string.\n * Uses `Bun.file().text()` when running under Bun, `fs.readFile` otherwise.\n *\n * @example\n * ```ts\n * const source = await read('./src/Pet.ts')\n * ```\n */\nexport async function read(path: string): Promise<string> {\n if (runtime.isBun) {\n return Bun.file(path).text()\n }\n return readFile(path, { encoding: 'utf8' })\n}\n\ntype WriteOptions = {\n /**\n * Previously read content, or `null` when the file does not exist.\n * Omitting this value reads the file before writing.\n */\n stored?: string | null\n /**\n * When `true`, re-reads the file immediately after writing and throws if the\n * content does not match — useful for catching write failures on unreliable file systems.\n */\n sanity?: boolean\n}\n\n/**\n * Whether `stored` already holds `source`, comparing on the trimmed text rather than the exact\n * bytes. Surrounding whitespace is what a formatter adds and what editors strip, and neither is a\n * reason to rewrite the file.\n *\n * Both sides are trimmed, so a storage that keeps bytes verbatim settles on the same answer as one\n * that normalizes what it stores. Trimming only `stored` would leave a source with leading\n * whitespace rewritten on every build, since the stored copy keeps the whitespace the comparison\n * has already dropped.\n */\nexport function matchesStored({ stored, source }: { stored: string; source: string }): boolean {\n return stored.trim() === source.trim()\n}\n\n/**\n * Writes `data` to `path`, trimming surrounding whitespace and ending the file with a single newline\n * the way prettier, biome, and oxfmt all do.\n * Skips the write when the trimmed content is empty, or when the file already holds that content.\n * Creates any missing parent directories automatically.\n * When `sanity` is `true`, re-reads the file after writing and throws if the content does not match.\n *\n * @example\n * ```ts\n * await write('./src/Pet.ts', source) // writes and returns the trimmed content plus a newline\n * await write('./src/Pet.ts', source) // null — file unchanged\n * await write('./src/Pet.ts', ' ') // null — empty content skipped\n * ```\n */\nexport async function write(path: string, data: string, options: WriteOptions = {}): Promise<string | null> {\n const trimmed = data.trim()\n if (trimmed === '') return null\n\n const content = `${trimmed}\\n`\n const resolved = resolve(path)\n let stored = options.stored\n\n if (stored === undefined) {\n if (runtime.isBun) {\n const file = Bun.file(resolved)\n stored = (await file.exists()) ? await file.text() : null\n } else {\n try {\n stored = await readFile(resolved, { encoding: 'utf-8' })\n } catch {\n /* file doesn't exist yet */\n stored = null\n }\n }\n }\n if (matchesStored({ stored: stored ?? '', source: trimmed })) return null\n\n if (runtime.isBun) {\n await Bun.write(resolved, content)\n return content\n }\n\n // Creating the directory up front costs a syscall per file, and every file after the first in a\n // directory pays it for nothing. Write first and only fall back when the directory is missing,\n // which also stays correct when something removed it mid-run.\n try {\n await writeFile(resolved, content, { encoding: 'utf-8' })\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error\n\n await mkdir(dirname(resolved), { recursive: true })\n await writeFile(resolved, content, { encoding: 'utf-8' })\n }\n\n if (options.sanity) {\n const savedData = await readFile(resolved, { encoding: 'utf-8' })\n if (savedData !== content) {\n throw new Error(`Sanity check failed for ${path}\\n\\nData[${data.length}]:\\n${data}\\n\\nSaved[${savedData.length}]:\\n${savedData}\\n`)\n }\n return savedData\n }\n\n return content\n}\n\n/**\n * Recursively removes `path`. Silently succeeds when `path` does not exist.\n *\n * @example\n * ```ts\n * await clean('./dist')\n * ```\n */\nexport async function clean(path: string): Promise<void> {\n return rm(path, { recursive: true, force: true })\n}\n\n/**\n * Converts a filesystem path to use POSIX (`/`) separators.\n *\n * Most of the codebase compares and composes paths as strings (prefix matching, joining for\n * import specifiers, splitting on `/`). On POSIX `path.resolve` already returns `/`-separated\n * paths, but on Windows it returns `\\`-separated paths, which breaks every such comparison.\n *\n * Routing every path that crosses a module boundary through `toPosixPath` keeps the rest of the\n * code platform-agnostic. The conversion runs unconditionally so Windows-specific behavior is\n * exercisable from POSIX CI.\n *\n * @example\n * toPosixPath('C:\\\\repo\\\\src\\\\pet.ts') // 'C:/repo/src/pet.ts'\n */\nexport function toPosixPath(filePath: string): string {\n return filePath.replaceAll('\\\\', '/')\n}\n\n/**\n * Strips the file extension from a path or file name.\n * Only removes the last `.ext` segment when the dot is not part of a directory name.\n *\n * @example\n * trimExtName('petStore.ts') // 'petStore'\n * trimExtName('/src/models/pet.ts') // '/src/models/pet'\n * trimExtName('/project.v2/gen/pet.ts') // '/project.v2/gen/pet'\n * trimExtName('noExtension') // 'noExtension'\n */\nexport function trimExtName(text: string): string {\n const dotIndex = text.lastIndexOf('.')\n if (dotIndex > 0 && !text.includes('/', dotIndex)) {\n return text.slice(0, dotIndex)\n }\n return text\n}\n\n/**\n * Resolves to `true` when `path` is `parent` itself or nested inside it. Both sides are resolved\n * to absolute paths first, so relative and `..`-containing inputs compare correctly.\n *\n * Guards a destructive or an out-of-tree operation: before wiping an output directory, check that\n * it does not contain the project root, and before loading a path a caller supplied, check that it\n * did not escape the directory it is allowed to read from.\n *\n * @example\n * isPathInside('./src/gen', '.') // true — nested inside the root\n * isPathInside('.', '.') // true — the same directory counts as inside\n * isPathInside('.', './src/gen') // false — the root is not inside its own output\n * isPathInside('../other', '.') // false — escapes the root\n */\nexport function isPathInside(path: string, parent: string): boolean {\n const resolvedPath = resolve(path)\n const resolvedParent = resolve(parent)\n if (resolvedPath === resolvedParent) {\n return true\n }\n\n const rel = relative(resolvedParent, resolvedPath)\n\n return rel !== '' && !rel.startsWith('..') && !isAbsolute(rel)\n}\n","/** A value that may already be resolved or still pending.\n *\n * @example\n * ```ts\n * function load(id: string): PossiblePromise<string> {\n * return cache.get(id) ?? fetchRemote(id)\n * }\n * ```\n */\nexport type PossiblePromise<T> = Promise<T> | T\n\n/** Returns `true` when `result` is a thenable `Promise`.\n *\n * @example\n * ```ts\n * isPromise(Promise.resolve(1)) // true\n * isPromise(42) // false\n * ```\n */\nexport function isPromise<T>(result: PossiblePromise<T>): result is Promise<T> {\n return result !== null && result !== undefined && typeof (result as Record<string, unknown>)['then'] === 'function'\n}\n\ntype Store<TKey, TValue> = {\n has(key: TKey): boolean\n get(key: TKey): TValue | undefined\n set(key: TKey, value: TValue): unknown\n}\n\n/**\n * Wraps `factory` with a keyed cache backed by the provided store.\n *\n * Pass a `WeakMap` for object keys (results are GC-eligible when the key is\n * collected) or a `Map` for primitive keys. For multi-argument functions,\n * nest two `memoize` calls — the outer keyed by the first argument, the\n * inner (created once per outer miss) keyed by the second.\n *\n * Because the cache is owned by the caller, it can be shared, inspected, or\n * cleared independently of the memoized function.\n *\n * @example Single WeakMap key\n * ```ts\n * const cache = new WeakMap<SchemaNode, Set<string>>()\n * const getRefs = memoize(cache, (node) => collectRefs(node))\n * ```\n *\n * @example Single Map key (primitive)\n * ```ts\n * const cache = new Map<string, Resolver>()\n * const getResolver = memoize(cache, (name) => buildResolver(name))\n * ```\n *\n * @example Two-level (object + primitive)\n * ```ts\n * const outer = new WeakMap<Params[], Map<string, Params[]>>()\n * const fn = memoize(outer, (params) => memoize(new Map(), (key) => transform(params, key)))\n * fn(params)('camelcase')\n * ```\n */\nexport function memoize<TKey, TValue>(store: Store<TKey, TValue>, factory: (key: TKey) => TValue): (key: TKey) => TValue {\n return (key: TKey): TValue => {\n if (store.has(key)) return store.get(key)!\n const value = factory(key)\n store.set(key, value)\n return value\n }\n}\n\ntype ParallelOptions<TItem> = {\n /**\n * Items to work through, handed out in order.\n */\n items: ReadonlyArray<TItem>\n /**\n * How many items may be in flight at once.\n */\n limit: number\n /**\n * Runs once per item, with the item's position so a caller can report progress.\n */\n run(item: TItem, index: number): Promise<void>\n}\n\n/**\n * Runs `run` over every item with at most `limit` in flight. Workers share one iterator, so each\n * takes the next item the moment it frees up instead of waiting for a batch to drain.\n *\n * @example\n * ```ts\n * await inParallel({ items: files, limit: 50, run: (file) => storage.writeItem(file.path, file.source) })\n * ```\n */\nexport async function inParallel<TItem>({ items, limit, run }: ParallelOptions<TItem>): Promise<void> {\n const queue = items.entries()\n\n const worker = async (): Promise<void> => {\n for (const [index, item] of queue) await run(item, index)\n }\n\n await Promise.all(Array.from({ length: Math.min(limit, items.length) }, () => worker()))\n}\n","import { existsSync } from 'node:fs'\nimport path from 'node:path'\nimport { CONFIG_EXTENSIONS, createModuleLoader } from '@internals/shared'\nimport { isPathInside, isPromise } from '@internals/utils'\nimport type { CLIOptions, Config, PossibleConfig, SerializedDiagnostic } from '@kubb/core'\n\nconst CONFIG_FILE_NAMES = CONFIG_EXTENSIONS.map((extension) => `kubb.config${extension}`)\n\n/**\n * Renders serialized diagnostics as a plain-text block for an AI assistant. Each entry\n * keeps the stable `code`, the source pointer, the suggested fix, and the docs link, so\n * the agent can act on the problem rather than parsing a bare message. No ANSI styling,\n * unlike the CLI renderer.\n */\nexport function formatDiagnostics(diagnostics: ReadonlyArray<SerializedDiagnostic>): string {\n return diagnostics.map((diagnostic) => formatDiagnostic(diagnostic)).join('\\n\\n')\n}\n\nfunction formatDiagnostic(diagnostic: SerializedDiagnostic): string {\n const { code, message, location, help, plugin, docsUrl } = diagnostic\n const lines = [plugin ? `[${code}] ${plugin}: ${message}` : `[${code}]: ${message}`]\n\n if (location && 'pointer' in location) {\n lines.push(` at: ${location.pointer}`)\n }\n if (help) {\n lines.push(` fix: ${help}`)\n }\n if (docsUrl) {\n lines.push(` see: ${docsUrl}`)\n }\n\n return lines.join('\\n')\n}\n\ntype NotifyFunction = (type: string, message: string, data?: Record<string, unknown>) => Promise<void>\n\nconst loader = createModuleLoader()\n\n// No cache: the MCP server is long-running, so every tool call re-reads the config to pick up edits.\nfunction loadModule(filePath: string): Promise<unknown> {\n return loader.load(filePath, { default: true })\n}\n\n/**\n * Loads the user's Kubb config and returns it with the directory it was found in.\n *\n * When `configPath` is given it must use an allowed extension and resolve inside\n * the current working directory, otherwise loading throws. When omitted, the\n * known `kubb.config.*` file names are tried in the current directory. Every\n * outcome is reported through `notify` before the function returns or throws.\n */\nexport async function loadUserConfig(configPath: string | undefined, { notify }: { notify: NotifyFunction }): Promise<{ userConfig: Config; cwd: string }> {\n if (configPath) {\n const ext = path.extname(configPath)\n if (!CONFIG_EXTENSIONS.some((extension) => extension === ext)) {\n const msg = `Invalid config file extension \"${ext}\". Allowed: ${CONFIG_EXTENSIONS.join(', ')}`\n await notify('CONFIG_ERROR', msg)\n throw new Error(msg)\n }\n const base = path.resolve(process.cwd())\n const resolvedConfigPath = path.resolve(base, configPath)\n if (!isPathInside(resolvedConfigPath, base)) {\n const msg = 'Invalid config file path: must be within the current working directory'\n await notify('CONFIG_ERROR', msg)\n throw new Error(msg)\n }\n const cwd = path.dirname(resolvedConfigPath)\n try {\n const userConfig = (await loadModule(resolvedConfigPath)) as Config\n await notify('CONFIG_LOADED', `Loaded config from ${resolvedConfigPath}`)\n return { userConfig, cwd }\n } catch (error) {\n const msg = `Failed to load config: ${error instanceof Error ? error.message : String(error)}`\n await notify('CONFIG_ERROR', msg)\n throw new Error(msg)\n }\n }\n\n const cwd = process.cwd()\n\n for (const configFileName of CONFIG_FILE_NAMES) {\n const configFilePath = path.resolve(process.cwd(), configFileName)\n if (!existsSync(configFilePath)) continue\n try {\n const userConfig = (await loadModule(configFilePath)) as Config\n await notify('CONFIG_LOADED', `Loaded ${configFileName} from current directory`)\n return { userConfig, cwd }\n } catch (err) {\n await notify('CONFIG_ERROR', `Failed to load ${configFileName}: ${err instanceof Error ? err.message : String(err)}`)\n }\n }\n\n await notify('CONFIG_ERROR', 'No config file found')\n throw new Error(`No config file found. Please provide a config path or create one of: ${CONFIG_FILE_NAMES.join(', ')}`)\n}\n\n/**\n * Inputs forwarded to a config when it is defined as a function.\n */\ntype ResolveUserConfigOptions = {\n /**\n * Path of the loaded config, passed through to the config function as `config`.\n */\n configPath?: string\n /**\n * Log level passed through to the config function.\n */\n logLevel?: CLIOptions['logLevel']\n}\n\n/**\n * Normalizes a possible config into a single resolved `Config`.\n *\n * Calls the config when it is a function, awaits it when it is a promise, and\n * picks the first entry when it resolves to an array.\n */\nexport async function resolveUserConfig(config: PossibleConfig<CLIOptions>, options: ResolveUserConfigOptions): Promise<Config> {\n const result = typeof config === 'function' ? config({ logLevel: options.logLevel, config: options.configPath }) : config\n const resolved = isPromise(result) ? await result : result\n\n return (Array.isArray(resolved) ? resolved[0] : resolved) as Config\n}\n","import path from 'node:path'\nimport { CONFIG_EXTENSIONS } from '@internals/shared'\nimport { type Config, createKubb, type Diagnostic, Diagnostics, type KubbHooks, Hookable } from '@kubb/core'\nimport { defineTool } from 'tmcp/tool'\nimport { tool } from 'tmcp/utils'\nimport * as v from 'valibot'\nimport { formatDiagnostics, loadUserConfig, resolveUserConfig } from '../utils.ts'\n\nconst generateSchema = v.object({\n config: v.optional(\n v.pipe(\n v.string(),\n v.minLength(1),\n v.description(`Path to kubb.config file (supports ${CONFIG_EXTENSIONS.join(', ')}). If not provided, will look for kubb.config.* in current directory`),\n ),\n ),\n input: v.optional(v.pipe(v.string(), v.minLength(1), v.description('Path to OpenAPI/Swagger spec file (overrides config)'))),\n output: v.optional(v.pipe(v.string(), v.minLength(1), v.description('Output directory path (overrides config)'))),\n logLevel: v.optional(v.pipe(v.picklist(['silent', 'info', 'verbose']), v.description('Log level for build output')), 'info'),\n})\n\nexport const generateTool = defineTool(\n {\n name: 'generate',\n description: 'Generate OpenAPI spec helpers using Kubb configuration',\n schema: generateSchema,\n },\n async function generate(schema: v.InferInput<typeof generateSchema>) {\n const { config: configPath, input, output, logLevel } = schema\n\n try {\n const hooks = new Hookable<KubbHooks>()\n const messages: Array<string> = []\n\n const notify = async (type: string, message: string, data?: Record<string, unknown>) => {\n messages.push(data ? `${type}: ${message} ${JSON.stringify(data)}` : `${type}: ${message}`)\n }\n\n hooks.hook('kubb:info', async ({ message }: { message: string }) => {\n await notify('INFO', message)\n })\n\n hooks.hook('kubb:success', async ({ message }: { message: string }) => {\n await notify('SUCCESS', message)\n })\n\n hooks.hook('kubb:error', async ({ error }: { error: Error }) => {\n await notify('ERROR', error.message)\n })\n\n hooks.hook('kubb:warn', async ({ message }: { message: string }) => {\n await notify('WARN', message)\n })\n\n hooks.hook('kubb:diagnostic', async ({ diagnostic }: { diagnostic: Diagnostic }) => {\n await notify('DIAGNOSTIC', diagnostic.message, Diagnostics.serialize(diagnostic))\n })\n\n hooks.hook('kubb:plugin:start', async ({ plugin }) => {\n await notify('PLUGIN_START', `Plugin starting: ${plugin.name}`)\n })\n\n hooks.hook('kubb:plugin:end', async ({ plugin, duration }) => {\n await notify('PLUGIN_END', `Plugin finished: ${plugin.name}`, { duration })\n })\n\n hooks.hook('kubb:files:processing:start', async () => {\n await notify('FILES_START', 'Starting file processing')\n })\n\n hooks.hook('kubb:files:processing:update', async ({ files }: { files: Array<{ file: { name: string } }> }) => {\n await notify('FILES_UPDATE', `Processing ${files.length} files`)\n })\n\n hooks.hook('kubb:files:processing:end', async () => {\n await notify('FILES_END', 'File processing complete')\n })\n\n hooks.hook('kubb:generation:start', async () => {\n await notify('GENERATION_START', 'Generation started')\n })\n\n hooks.hook('kubb:setup:start', async () => {\n await notify('SETUP_START', 'Setting up Kubb')\n })\n\n hooks.hook('kubb:setup:end', async () => {\n await notify('SETUP_END', 'Kubb setup complete')\n await notify('BUILD_START', 'Starting build')\n })\n\n hooks.hook('kubb:generation:end', async () => {\n await notify('GENERATION_END', 'Generation ended')\n })\n\n let userConfig: Config\n let cwd: string\n\n try {\n const configResult = await loadUserConfig(configPath, { notify })\n userConfig = configResult.userConfig\n cwd = configResult.cwd\n\n if (Array.isArray(userConfig)) {\n throw new Error('Array type in kubb.config.ts is not supported in this tool. Please provide a single configuration object.')\n }\n\n userConfig = await resolveUserConfig(userConfig, {\n configPath,\n logLevel,\n })\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error)\n return tool.error(errorMessage)\n }\n\n const config: Config = {\n ...userConfig,\n root: path.resolve(cwd, userConfig.root ?? '.'),\n input: input ?? userConfig.input,\n output: output\n ? {\n ...userConfig.output,\n path: output,\n }\n : userConfig.output,\n }\n\n await notify('CONFIG_READY', 'Configuration ready')\n\n const kubb = createKubb(config, { hooks })\n const result = await kubb.generate()\n await notify('BUILD_END', `Build complete - Generated ${result.files.length} files`)\n\n const problems = result.diagnostics.filter(Diagnostics.isProblem)\n const errors = problems.filter((diagnostic) => diagnostic.severity === 'error')\n if (errors.length > 0) {\n await notify('BUILD_FAILED', `Build failed with ${errors.length} diagnostic(s)`)\n\n const serialized = problems.map((diagnostic) => Diagnostics.serialize(diagnostic))\n return tool.error(`Build failed:\\n${formatDiagnostics(serialized)}\\n\\n\\`\\`\\`json\\n${JSON.stringify(serialized, null, 2)}\\n\\`\\`\\``)\n }\n\n await notify('BUILD_SUCCESS', `Build completed successfully - Generated ${result.files.length} files`)\n\n return tool.text(`Build completed successfully!\\n\\nGenerated ${result.files.length} files\\n\\n${messages.join('\\n')}`)\n } catch (caughtError) {\n const serialized = Diagnostics.serialize(Diagnostics.from(caughtError))\n return tool.error(`Build error:\\n${formatDiagnostics([serialized])}\\n\\n\\`\\`\\`json\\n${JSON.stringify(serialized, null, 2)}\\n\\`\\`\\``)\n }\n },\n)\n","import fs from 'node:fs'\nimport path from 'node:path'\nimport process from 'node:process'\nimport { generateConfigFile, KUBB_CONFIG_FILENAME, resolvePlugins } from '@internals/shared'\nimport { defineTool } from 'tmcp/tool'\nimport { tool } from 'tmcp/utils'\nimport * as v from 'valibot'\n\nconst initSchema = v.object({\n input: v.optional(v.pipe(v.string(), v.minLength(1), v.description('Path to OpenAPI spec (default: ./openapi.yaml)'))),\n output: v.optional(v.pipe(v.string(), v.minLength(1), v.description('Output directory (default: ./src/gen)'))),\n plugins: v.optional(v.pipe(v.string(), v.minLength(1), v.description('Comma-separated list of plugins: plugin-ts,plugin-zod,...'))),\n})\n\nexport const initTool = defineTool(\n {\n name: 'init',\n description: 'Scaffold a kubb.config.ts in the current directory (non-interactive). Does not install packages.',\n schema: initSchema,\n },\n async ({ input = './openapi.yaml', output = './src/gen', plugins }) => {\n const selected = resolvePlugins(plugins)\n const content = generateConfigFile({ selectedPlugins: selected, inputPath: input, outputPath: output })\n const dest = path.join(process.cwd(), KUBB_CONFIG_FILENAME)\n if (fs.existsSync(dest)) {\n return tool.error(`${KUBB_CONFIG_FILENAME} already exists at ${dest}. Delete it first before running init again.`)\n }\n fs.writeFileSync(dest, content, 'utf-8')\n const packageList = ['kubb', ...selected.map((p) => p.packageName)].join(' ')\n return tool.text(`Created kubb.config.ts\\n\\nInstall packages:\\n npm install ${packageList}\\n\\nThen run:\\n npx kubb generate`)\n },\n)\n","import { adapterOas } from '@kubb/adapter-oas'\nimport { Diagnostics } from '@kubb/core'\nimport { defineTool } from 'tmcp/tool'\nimport { tool } from 'tmcp/utils'\nimport * as v from 'valibot'\nimport { formatDiagnostics } from '../utils.ts'\n\nconst validateSchema = v.object({\n input: v.pipe(v.string(), v.minLength(1), v.description('Path or URL to the OpenAPI/Swagger specification')),\n})\n\nexport const validateTool = defineTool(\n {\n name: 'validate',\n description: 'Validate an OpenAPI/Swagger specification file or URL',\n schema: validateSchema,\n },\n async ({ input }) => {\n try {\n await adapterOas().validate(input, { throwOnError: true })\n return tool.text(`Validation successful: ${input}`)\n } catch (err) {\n const serialized = Diagnostics.serialize(Diagnostics.from(err))\n return tool.error(`Validation failed:\\n${formatDiagnostics([serialized])}\\n\\n\\`\\`\\`json\\n${JSON.stringify(serialized, null, 2)}\\n\\`\\`\\``)\n }\n },\n)\n","import { ValibotJsonSchemaAdapter } from '@tmcp/adapter-valibot'\nimport { StdioTransport } from '@tmcp/transport-stdio'\nimport { McpServer } from 'tmcp'\nimport { version } from '../package.json'\nimport { generateTool } from './tools/generate.ts'\nimport { initTool } from './tools/init.ts'\nimport { validateTool } from './tools/validate.ts'\n\n/**\n * Builds the Kubb MCP server with the generate, validate, and init tools registered.\n *\n * @example\n * `const server = createMcpServer()`\n */\nexport function createMcpServer() {\n const server = new McpServer({ name: 'Kubb', version }, { adapter: new ValibotJsonSchemaAdapter(), capabilities: { tools: {} } })\n server.tools([generateTool, validateTool, initTool])\n return server\n}\n\n/**\n * Starts the Kubb MCP server over stdio, the transport every local MCP client\n * (Claude, Copilot, editors) uses when it launches the server as a subprocess.\n */\nexport function startServer(): void {\n new StdioTransport(createMcpServer()).listen()\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACEA,MAAa,uBAAuB;;AAGpC,MAAa,oBAAoB;CAAC;CAAO;CAAQ;CAAQ;CAAO;CAAQ;AAAM;AAU9E,MAAa,mBAAwC;CACnD;EACE,OAAO;EACP,OAAO;EACP,MAAM;EACN,aAAa;EACb,YAAY;EACZ,UAAU;CACZ;CACA;EACE,OAAO;EACP,OAAO;EACP,aAAa;EACb,YAAY;EACZ,UAAU;CACZ;CACA;EACE,OAAO;EACP,OAAO;EACP,aAAa;EACb,YAAY;EACZ,UAAU;CACZ;CACA;EACE,OAAO;EACP,OAAO;EACP,aAAa;EACb,YAAY;EACZ,UAAU;CACZ;CACA;EACE,OAAO;EACP,OAAO;EACP,aAAa;EACb,YAAY;EACZ,UAAU;CACZ;CACA;EACE,OAAO;EACP,OAAO;EACP,aAAa;EACb,YAAY;EACZ,UAAU;CACZ;CACA;EACE,OAAO;EACP,OAAO;EACP,aAAa;EACb,YAAY;EACZ,UAAU;CACZ;CACA;EACE,OAAO;EACP,OAAO;EACP,aAAa;EACb,YAAY;EACZ,UAAU;CACZ;CACA;EACE,OAAO;EACP,OAAO;EACP,aAAa;EACb,YAAY;EACZ,UAAU;CACZ;CACA;EACE,OAAO;EACP,OAAO;EACP,aAAa;EACb,YAAY;EACZ,UAAU;CACZ;CACA;EACE,OAAO;EACP,OAAO;EACP,aAAa;EACb,YAAY;EACZ,UAAU;CACZ;AACF;;;;;;;;ACtFA,SAAgB,eAAe,aAAsD;CACnF,IAAI,CAAC,aACH,OAAO,CAAC;CAEV,MAAM,YAAY,YACf,MAAM,GAAG,CAAC,CACV,KAAK,UAAU,MAAM,KAAK,CAAC,CAA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AAAA,WAAAA,CAAW,CAAC,CAAC,SAAS,OAAO,EAAE,cAAc,KAAK,CAAC;EACzD,OAAOC,WAAAA,KAAK,KAAK,0BAA0B,OAAO;CACpD,SAAS,KAAK;EACZ,MAAM,aAAaC,WAAAA,YAAY,UAAUA,WAAAA,YAAY,KAAK,GAAG,CAAC;EAC9D,OAAOD,WAAAA,KAAK,MAAM,uBAAuB,kBAAkB,CAAC,UAAU,CAAC,EAAE,kBAAkB,KAAK,UAAU,YAAY,MAAM,CAAC,EAAE,SAAS;CAC1I;AACF,CACF;;;;;;;;;ACZA,SAAgB,kBAAkB;CAChC,MAAM,SAAS,IAAIE,KAAAA,UAAU;EAAE,MAAM;EAAQ;CAAQ,GAAG;EAAE,SAAS,IAAIC,sBAAAA,yBAAyB;EAAG,cAAc,EAAE,OAAO,CAAC,EAAE;CAAE,CAAC;CAChI,OAAO,MAAM;EAAC;EAAc;EAAc;CAAQ,CAAC;CACnD,OAAO;AACT;;;;;AAMA,SAAgB,cAAoB;CAClC,IAAIC,sBAAAA,eAAe,gBAAgB,CAAC,CAAC,CAAC,OAAO;AAC/C"}
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["jiti","createJiti","readFile","resolve","relative","isAbsolute","path","existsSync","z","defineTool","Hookable","Diagnostics","tool","path","createKubb","z","defineTool","path","process","fs","tool","z","defineTool","adapterOas","tool","Diagnostics","JsonSchemaAdapter","z","en","McpServer","StdioTransport"],"sources":["../package.json","../../../internals/shared/src/constants.ts","../../../internals/shared/src/init.ts","../../../internals/shared/src/loader.ts","../../../internals/utils/src/fs.ts","../../../internals/utils/src/promise.ts","../src/utils.ts","../src/tools/generate.ts","../src/tools/init.ts","../src/tools/validate.ts","../src/server.ts"],"sourcesContent":["","import type { PluginOption } from './types.ts'\n\nexport 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\nexport const availablePlugins: Array<PluginOption> = [\n {\n value: 'plugin-ts',\n label: 'TypeScript',\n hint: 'Recommended',\n packageName: '@kubb/plugin-ts',\n importName: 'pluginTs',\n category: 'types',\n },\n {\n value: 'plugin-axios',\n label: 'Axios Client',\n packageName: '@kubb/plugin-axios',\n importName: 'pluginAxios',\n category: 'client',\n },\n {\n value: 'plugin-fetch',\n label: 'Fetch Client',\n packageName: '@kubb/plugin-fetch',\n importName: 'pluginFetch',\n category: 'client',\n },\n {\n value: 'plugin-react-query',\n label: 'React Query / TanStack Query',\n packageName: '@kubb/plugin-react-query',\n importName: 'pluginReactQuery',\n category: 'framework',\n },\n {\n value: 'plugin-vue-query',\n label: 'Vue Query',\n packageName: '@kubb/plugin-vue-query',\n importName: 'pluginVueQuery',\n category: 'framework',\n },\n {\n value: 'plugin-zod',\n label: 'Zod Schemas',\n packageName: '@kubb/plugin-zod',\n importName: 'pluginZod',\n category: 'validation',\n },\n {\n value: 'plugin-faker',\n label: 'Faker.js Mocks',\n packageName: '@kubb/plugin-faker',\n importName: 'pluginFaker',\n category: 'mocks',\n },\n {\n value: 'plugin-msw',\n label: 'MSW Handlers',\n packageName: '@kubb/plugin-msw',\n importName: 'pluginMsw',\n category: 'mocks',\n },\n {\n value: 'plugin-cypress',\n label: 'Cypress Tests',\n packageName: '@kubb/plugin-cypress',\n importName: 'pluginCypress',\n category: 'testing',\n },\n {\n value: 'plugin-mcp',\n label: 'MCP Server (AI / Model Context Protocol)',\n packageName: '@kubb/plugin-mcp',\n importName: 'pluginMcp',\n category: 'ai',\n },\n {\n value: 'plugin-redoc',\n label: 'ReDoc Documentation',\n packageName: '@kubb/plugin-redoc',\n importName: 'pluginRedoc',\n category: 'documentation',\n },\n]\n","import { availablePlugins, KUBB_PACKAGE_NAME } from './constants.ts'\nimport type { PluginOption } from './types.ts'\n\n/**\n * Resolves a comma-separated plugin flag (e.g. `--plugins plugin-ts,plugin-zod`) into the\n * matching known plugin options. Unrecognized names are dropped, and a missing flag yields\n * an empty list.\n */\nexport function resolvePlugins(pluginsFlag: string | undefined): Array<PluginOption> {\n if (!pluginsFlag) {\n return []\n }\n const requested = pluginsFlag\n .split(',')\n .map((value) => value.trim())\n .filter(Boolean)\n return availablePlugins.filter((plugin) => requested.includes(plugin.value))\n}\n\nexport function generateConfigFile({\n selectedPlugins,\n inputPath,\n outputPath,\n}: {\n selectedPlugins: Array<PluginOption>\n inputPath: string\n outputPath: string\n}): string {\n const imports = selectedPlugins.map((plugin) => `import { ${plugin.importName} } from '${plugin.packageName}'`).join('\\n')\n\n const pluginConfigs = selectedPlugins.map((plugin) => ` ${plugin.importName}(),`).join('\\n')\n\n return `import { defineConfig } from 'kubb/config'\n${imports}\n\nexport default defineConfig({\n input: '${inputPath}',\n output: {\n path: '${outputPath}',\n clean: true,\n },\n plugins: [\n${pluginConfigs}\n ],\n})\n`\n}\n\n/**\n * Turns package names into install specifiers for the wizard.\n *\n * `kubb` is pinned to the exact version of the running CLI, since both ship from the same release\n * and resolving `kubb@beta` separately can land on a different version than the CLI doing the\n * scaffolding. Plugins release from their own repo on their own cadence, so they follow the\n * release channel of the CLI through its dist-tag.\n */\nexport function resolveInstallVersions({ packages, version }: { packages: Array<string>; version: string }): Array<string> {\n const prerelease = version.match(/-([a-z]+)/)?.[1]\n const tag = prerelease ?? 'latest'\n\n return packages.map((name) => (name === KUBB_PACKAGE_NAME ? `${name}@${version}` : `${name}@${tag}`))\n}\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 ModuleLoader.load}.\n */\ntype LoadModuleOptions = {\n /**\n * Return the module's default export instead of the full namespace.\n */\n default?: boolean\n}\n\n/**\n * Loads `.ts`/`.js` modules via jiti.\n */\ntype ModuleLoader = {\n load<T = unknown>(filePath: string, options?: LoadModuleOptions): Promise<T>\n}\n\n/**\n * Creates a jiti-based loader for Kubb's TypeScript and JavaScript config modules.\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 createModuleLoader().load('/abs/kubb.config.ts', { default: true })\n * ```\n */\nexport function createModuleLoader(): ModuleLoader {\n const jiti = createJiti(import.meta.url, JITI_OPTIONS)\n\n return {\n async load<T>(filePath: string, options?: LoadModuleOptions) {\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 }\n}\n","import { access, mkdir, readFile, rm, writeFile } from 'node:fs/promises'\nimport { dirname, isAbsolute, relative, resolve } from 'node:path'\nimport { runtime } from './runtime.ts'\n\n/**\n * Resolves to `true` when the file or directory at `path` exists.\n * Uses `Bun.file().exists()` when running under Bun, `fs.access` otherwise.\n *\n * @example\n * ```ts\n * if (await exists('./kubb.config.ts')) {\n * const content = await read('./kubb.config.ts')\n * }\n * ```\n */\nexport async function exists(path: string): Promise<boolean> {\n if (runtime.isBun) {\n return Bun.file(path).exists()\n }\n return access(path).then(\n () => true,\n () => false,\n )\n}\n\n/**\n * Reads the file at `path` as a UTF-8 string.\n * Uses `Bun.file().text()` when running under Bun, `fs.readFile` otherwise.\n *\n * @example\n * ```ts\n * const source = await read('./src/Pet.ts')\n * ```\n */\nexport async function read(path: string): Promise<string> {\n if (runtime.isBun) {\n return Bun.file(path).text()\n }\n return readFile(path, { encoding: 'utf8' })\n}\n\ntype WriteOptions = {\n /**\n * Previously read content, or `null` when the file does not exist.\n * Omitting this value reads the file before writing.\n */\n stored?: string | null\n /**\n * When `true`, re-reads the file immediately after writing and throws if the\n * content does not match — useful for catching write failures on unreliable file systems.\n */\n sanity?: boolean\n}\n\n/**\n * Whether `stored` already holds `source`, comparing on the trimmed text rather than the exact\n * bytes. Surrounding whitespace is what a formatter adds and what editors strip, and neither is a\n * reason to rewrite the file.\n *\n * Both sides are trimmed, so a storage that keeps bytes verbatim settles on the same answer as one\n * that normalizes what it stores. Trimming only `stored` would leave a source with leading\n * whitespace rewritten on every build, since the stored copy keeps the whitespace the comparison\n * has already dropped.\n */\nexport function matchesStored({ stored, source }: { stored: string; source: string }): boolean {\n return stored.trim() === source.trim()\n}\n\n/**\n * Writes `data` to `path`, trimming surrounding whitespace and ending the file with a single newline\n * the way prettier, biome, and oxfmt all do.\n * Skips the write when the trimmed content is empty, or when the file already holds that content.\n * Creates any missing parent directories automatically.\n * When `sanity` is `true`, re-reads the file after writing and throws if the content does not match.\n *\n * @example\n * ```ts\n * await write('./src/Pet.ts', source) // writes and returns the trimmed content plus a newline\n * await write('./src/Pet.ts', source) // null — file unchanged\n * await write('./src/Pet.ts', ' ') // null — empty content skipped\n * ```\n */\nexport async function write(path: string, data: string, options: WriteOptions = {}): Promise<string | null> {\n const trimmed = data.trim()\n if (trimmed === '') return null\n\n const content = `${trimmed}\\n`\n const resolved = resolve(path)\n let stored = options.stored\n\n if (stored === undefined) {\n if (runtime.isBun) {\n const file = Bun.file(resolved)\n stored = (await file.exists()) ? await file.text() : null\n } else {\n try {\n stored = await readFile(resolved, { encoding: 'utf-8' })\n } catch {\n /* file doesn't exist yet */\n stored = null\n }\n }\n }\n if (matchesStored({ stored: stored ?? '', source: trimmed })) return null\n\n if (runtime.isBun) {\n await Bun.write(resolved, content)\n return content\n }\n\n // Creating the directory up front costs a syscall per file, and every file after the first in a\n // directory pays it for nothing. Write first and only fall back when the directory is missing,\n // which also stays correct when something removed it mid-run.\n try {\n await writeFile(resolved, content, { encoding: 'utf-8' })\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error\n\n await mkdir(dirname(resolved), { recursive: true })\n await writeFile(resolved, content, { encoding: 'utf-8' })\n }\n\n if (options.sanity) {\n const savedData = await readFile(resolved, { encoding: 'utf-8' })\n if (savedData !== content) {\n throw new Error(`Sanity check failed for ${path}\\n\\nData[${data.length}]:\\n${data}\\n\\nSaved[${savedData.length}]:\\n${savedData}\\n`)\n }\n return savedData\n }\n\n return content\n}\n\n/**\n * Recursively removes `path`. Silently succeeds when `path` does not exist.\n *\n * @example\n * ```ts\n * await clean('./dist')\n * ```\n */\nexport async function clean(path: string): Promise<void> {\n return rm(path, { recursive: true, force: true })\n}\n\n/**\n * Converts a filesystem path to use POSIX (`/`) separators.\n *\n * Most of the codebase compares and composes paths as strings (prefix matching, joining for\n * import specifiers, splitting on `/`). On POSIX `path.resolve` already returns `/`-separated\n * paths, but on Windows it returns `\\`-separated paths, which breaks every such comparison.\n *\n * Routing every path that crosses a module boundary through `toPosixPath` keeps the rest of the\n * code platform-agnostic. The conversion runs unconditionally so Windows-specific behavior is\n * exercisable from POSIX CI.\n *\n * @example\n * toPosixPath('C:\\\\repo\\\\src\\\\pet.ts') // 'C:/repo/src/pet.ts'\n */\nexport function toPosixPath(filePath: string): string {\n return filePath.replaceAll('\\\\', '/')\n}\n\n/**\n * Strips the file extension from a path or file name.\n * Only removes the last `.ext` segment when the dot is not part of a directory name.\n *\n * @example\n * trimExtName('petStore.ts') // 'petStore'\n * trimExtName('/src/models/pet.ts') // '/src/models/pet'\n * trimExtName('/project.v2/gen/pet.ts') // '/project.v2/gen/pet'\n * trimExtName('noExtension') // 'noExtension'\n */\nexport function trimExtName(text: string): string {\n const dotIndex = text.lastIndexOf('.')\n if (dotIndex > 0 && !text.includes('/', dotIndex)) {\n return text.slice(0, dotIndex)\n }\n return text\n}\n\n/**\n * Resolves to `true` when `path` is `parent` itself or nested inside it. Both sides are resolved\n * to absolute paths first, so relative and `..`-containing inputs compare correctly.\n *\n * Guards a destructive or an out-of-tree operation: before wiping an output directory, check that\n * it does not contain the project root, and before loading a path a caller supplied, check that it\n * did not escape the directory it is allowed to read from.\n *\n * @example\n * isPathInside('./src/gen', '.') // true — nested inside the root\n * isPathInside('.', '.') // true — the same directory counts as inside\n * isPathInside('.', './src/gen') // false — the root is not inside its own output\n * isPathInside('../other', '.') // false — escapes the root\n */\nexport function isPathInside(path: string, parent: string): boolean {\n const resolvedPath = resolve(path)\n const resolvedParent = resolve(parent)\n if (resolvedPath === resolvedParent) {\n return true\n }\n\n const rel = relative(resolvedParent, resolvedPath)\n\n return rel !== '' && !rel.startsWith('..') && !isAbsolute(rel)\n}\n","/** A value that may already be resolved or still pending.\n *\n * @example\n * ```ts\n * function load(id: string): PossiblePromise<string> {\n * return cache.get(id) ?? fetchRemote(id)\n * }\n * ```\n */\nexport type PossiblePromise<T> = Promise<T> | T\n\n/** Returns `true` when `result` is a thenable `Promise`.\n *\n * @example\n * ```ts\n * isPromise(Promise.resolve(1)) // true\n * isPromise(42) // false\n * ```\n */\nexport function isPromise<T>(result: PossiblePromise<T>): result is Promise<T> {\n return result !== null && result !== undefined && typeof (result as Record<string, unknown>)['then'] === 'function'\n}\n\ntype Store<TKey, TValue> = {\n has(key: TKey): boolean\n get(key: TKey): TValue | undefined\n set(key: TKey, value: TValue): unknown\n}\n\n/**\n * Wraps `factory` with a keyed cache backed by the provided store.\n *\n * Pass a `WeakMap` for object keys (results are GC-eligible when the key is\n * collected) or a `Map` for primitive keys. For multi-argument functions,\n * nest two `memoize` calls — the outer keyed by the first argument, the\n * inner (created once per outer miss) keyed by the second.\n *\n * Because the cache is owned by the caller, it can be shared, inspected, or\n * cleared independently of the memoized function.\n *\n * @example Single WeakMap key\n * ```ts\n * const cache = new WeakMap<SchemaNode, Set<string>>()\n * const getRefs = memoize(cache, (node) => collectRefs(node))\n * ```\n *\n * @example Single Map key (primitive)\n * ```ts\n * const cache = new Map<string, Resolver>()\n * const getResolver = memoize(cache, (name) => buildResolver(name))\n * ```\n *\n * @example Two-level (object + primitive)\n * ```ts\n * const outer = new WeakMap<Params[], Map<string, Params[]>>()\n * const fn = memoize(outer, (params) => memoize(new Map(), (key) => transform(params, key)))\n * fn(params)('camelcase')\n * ```\n */\nexport function memoize<TKey, TValue>(store: Store<TKey, TValue>, factory: (key: TKey) => TValue): (key: TKey) => TValue {\n return (key: TKey): TValue => {\n if (store.has(key)) return store.get(key)!\n const value = factory(key)\n store.set(key, value)\n return value\n }\n}\n\ntype ParallelOptions<TItem> = {\n /**\n * Items to work through, handed out in order.\n */\n items: ReadonlyArray<TItem>\n /**\n * How many items may be in flight at once.\n */\n limit: number\n /**\n * Runs once per item, with the item's position so a caller can report progress.\n */\n run(item: TItem, index: number): Promise<void>\n}\n\n/**\n * Runs `run` over every item with at most `limit` in flight. Workers share one iterator, so each\n * takes the next item the moment it frees up instead of waiting for a batch to drain.\n *\n * @example\n * ```ts\n * await inParallel({ items: files, limit: 50, run: (file) => storage.writeItem(file.path, file.source) })\n * ```\n */\nexport async function inParallel<TItem>({ items, limit, run }: ParallelOptions<TItem>): Promise<void> {\n const queue = items.entries()\n\n const worker = async (): Promise<void> => {\n for (const [index, item] of queue) await run(item, index)\n }\n\n await Promise.all(Array.from({ length: Math.min(limit, items.length) }, () => worker()))\n}\n","import { existsSync } from 'node:fs'\nimport path from 'node:path'\nimport { CONFIG_EXTENSIONS, createModuleLoader } from '@internals/shared'\nimport { isPathInside, isPromise } from '@internals/utils'\nimport type { CLIOptions, Config, PossibleConfig, SerializedDiagnostic } from '@kubb/core'\n\nconst CONFIG_FILE_NAMES = CONFIG_EXTENSIONS.map((extension) => `kubb.config${extension}`)\n\n/**\n * Renders serialized diagnostics as a plain-text block for an AI assistant. Each entry\n * keeps the stable `code`, the source pointer, the suggested fix, and the docs link, so\n * the agent can act on the problem rather than parsing a bare message. No ANSI styling,\n * unlike the CLI renderer.\n */\nexport function formatDiagnostics(diagnostics: ReadonlyArray<SerializedDiagnostic>): string {\n return diagnostics.map((diagnostic) => formatDiagnostic(diagnostic)).join('\\n\\n')\n}\n\nfunction formatDiagnostic(diagnostic: SerializedDiagnostic): string {\n const { code, message, location, help, plugin, docsUrl } = diagnostic\n const lines = [plugin ? `[${code}] ${plugin}: ${message}` : `[${code}]: ${message}`]\n\n if (location && 'pointer' in location) {\n lines.push(` at: ${location.pointer}`)\n }\n if (help) {\n lines.push(` fix: ${help}`)\n }\n if (docsUrl) {\n lines.push(` see: ${docsUrl}`)\n }\n\n return lines.join('\\n')\n}\n\ntype NotifyFunction = (type: string, message: string, data?: Record<string, unknown>) => Promise<void>\n\nconst loader = createModuleLoader()\n\n// No cache: the MCP server is long-running, so every tool call re-reads the config to pick up edits.\nfunction loadModule(filePath: string): Promise<unknown> {\n return loader.load(filePath, { default: true })\n}\n\n/**\n * Loads the user's Kubb config and returns it with the directory it was found in.\n *\n * When `configPath` is given it must use an allowed extension and resolve inside\n * the current working directory, otherwise loading throws. When omitted, the\n * known `kubb.config.*` file names are tried in the current directory. Every\n * outcome is reported through `notify` before the function returns or throws.\n */\nexport async function loadUserConfig(configPath: string | undefined, { notify }: { notify: NotifyFunction }): Promise<{ userConfig: Config; cwd: string }> {\n if (configPath) {\n const ext = path.extname(configPath)\n if (!CONFIG_EXTENSIONS.some((extension) => extension === ext)) {\n const msg = `Invalid config file extension \"${ext}\". Allowed: ${CONFIG_EXTENSIONS.join(', ')}`\n await notify('CONFIG_ERROR', msg)\n throw new Error(msg)\n }\n const base = path.resolve(process.cwd())\n const resolvedConfigPath = path.resolve(base, configPath)\n if (!isPathInside(resolvedConfigPath, base)) {\n const msg = 'Invalid config file path: must be within the current working directory'\n await notify('CONFIG_ERROR', msg)\n throw new Error(msg)\n }\n const cwd = path.dirname(resolvedConfigPath)\n try {\n const userConfig = (await loadModule(resolvedConfigPath)) as Config\n await notify('CONFIG_LOADED', `Loaded config from ${resolvedConfigPath}`)\n return { userConfig, cwd }\n } catch (error) {\n const msg = `Failed to load config: ${error instanceof Error ? error.message : String(error)}`\n await notify('CONFIG_ERROR', msg)\n throw new Error(msg)\n }\n }\n\n const cwd = process.cwd()\n\n for (const configFileName of CONFIG_FILE_NAMES) {\n const configFilePath = path.resolve(process.cwd(), configFileName)\n if (!existsSync(configFilePath)) continue\n try {\n const userConfig = (await loadModule(configFilePath)) as Config\n await notify('CONFIG_LOADED', `Loaded ${configFileName} from current directory`)\n return { userConfig, cwd }\n } catch (err) {\n await notify('CONFIG_ERROR', `Failed to load ${configFileName}: ${err instanceof Error ? err.message : String(err)}`)\n }\n }\n\n await notify('CONFIG_ERROR', 'No config file found')\n throw new Error(`No config file found. Please provide a config path or create one of: ${CONFIG_FILE_NAMES.join(', ')}`)\n}\n\n/**\n * Inputs forwarded to a config when it is defined as a function.\n */\ntype ResolveUserConfigOptions = {\n /**\n * Path of the loaded config, passed through to the config function as `config`.\n */\n configPath?: string\n /**\n * Log level passed through to the config function.\n */\n logLevel?: CLIOptions['logLevel']\n}\n\n/**\n * Normalizes a possible config into a single resolved `Config`.\n *\n * Calls the config when it is a function, awaits it when it is a promise, and\n * picks the first entry when it resolves to an array.\n */\nexport async function resolveUserConfig(config: PossibleConfig<CLIOptions>, options: ResolveUserConfigOptions): Promise<Config> {\n const result = typeof config === 'function' ? config({ logLevel: options.logLevel, config: options.configPath }) : config\n const resolved = isPromise(result) ? await result : result\n\n return (Array.isArray(resolved) ? resolved[0] : resolved) as Config\n}\n","import path from 'node:path'\nimport { CONFIG_EXTENSIONS } from '@internals/shared'\nimport { type Config, createKubb, type Diagnostic, Diagnostics, type KubbHooks, Hookable } from '@kubb/core'\nimport { defineTool } from 'tmcp/tool'\nimport { tool } from 'tmcp/utils'\nimport * as z from 'zod/mini'\nimport { formatDiagnostics, loadUserConfig, resolveUserConfig } from '../utils.ts'\n\nconst generateSchema = z.object({\n config: z.optional(\n z\n .string()\n .check(\n z.minLength(1),\n z.describe(`Path to kubb.config file (supports ${CONFIG_EXTENSIONS.join(', ')}). If not provided, will look for kubb.config.* in current directory`),\n ),\n ),\n input: z.optional(z.string().check(z.minLength(1), z.describe('Path to OpenAPI/Swagger spec file (overrides config)'))),\n output: z.optional(z.string().check(z.minLength(1), z.describe('Output directory path (overrides config)'))),\n logLevel: z._default(z.enum(['silent', 'info', 'verbose']).check(z.describe('Log level for build output')), 'info'),\n})\n\nexport const generateTool = defineTool(\n {\n name: 'generate',\n description: 'Generate OpenAPI spec helpers using Kubb configuration',\n schema: generateSchema,\n },\n async function generate(schema: z.input<typeof generateSchema>) {\n const { config: configPath, input, output, logLevel } = schema\n\n try {\n const hooks = new Hookable<KubbHooks>()\n const messages: Array<string> = []\n\n const notify = async (type: string, message: string, data?: Record<string, unknown>) => {\n messages.push(data ? `${type}: ${message} ${JSON.stringify(data)}` : `${type}: ${message}`)\n }\n\n hooks.hook('kubb:info', async ({ message }: { message: string }) => {\n await notify('INFO', message)\n })\n\n hooks.hook('kubb:success', async ({ message }: { message: string }) => {\n await notify('SUCCESS', message)\n })\n\n hooks.hook('kubb:error', async ({ error }: { error: Error }) => {\n await notify('ERROR', error.message)\n })\n\n hooks.hook('kubb:warn', async ({ message }: { message: string }) => {\n await notify('WARN', message)\n })\n\n hooks.hook('kubb:diagnostic', async ({ diagnostic }: { diagnostic: Diagnostic }) => {\n await notify('DIAGNOSTIC', diagnostic.message, Diagnostics.serialize(diagnostic))\n })\n\n hooks.hook('kubb:plugin:start', async ({ plugin }) => {\n await notify('PLUGIN_START', `Plugin starting: ${plugin.name}`)\n })\n\n hooks.hook('kubb:plugin:end', async ({ plugin, duration }) => {\n await notify('PLUGIN_END', `Plugin finished: ${plugin.name}`, { duration })\n })\n\n hooks.hook('kubb:files:processing:start', async () => {\n await notify('FILES_START', 'Starting file processing')\n })\n\n hooks.hook('kubb:files:processing:update', async ({ files }: { files: Array<{ file: { name: string } }> }) => {\n await notify('FILES_UPDATE', `Processing ${files.length} files`)\n })\n\n hooks.hook('kubb:files:processing:end', async () => {\n await notify('FILES_END', 'File processing complete')\n })\n\n hooks.hook('kubb:generation:start', async () => {\n await notify('GENERATION_START', 'Generation started')\n })\n\n hooks.hook('kubb:setup:start', async () => {\n await notify('SETUP_START', 'Setting up Kubb')\n })\n\n hooks.hook('kubb:setup:end', async () => {\n await notify('SETUP_END', 'Kubb setup complete')\n await notify('BUILD_START', 'Starting build')\n })\n\n hooks.hook('kubb:generation:end', async () => {\n await notify('GENERATION_END', 'Generation ended')\n })\n\n let userConfig: Config\n let cwd: string\n\n try {\n const configResult = await loadUserConfig(configPath, { notify })\n userConfig = configResult.userConfig\n cwd = configResult.cwd\n\n if (Array.isArray(userConfig)) {\n throw new Error('Array type in kubb.config.ts is not supported in this tool. Please provide a single configuration object.')\n }\n\n userConfig = await resolveUserConfig(userConfig, {\n configPath,\n logLevel,\n })\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error)\n return tool.error(errorMessage)\n }\n\n const config: Config = {\n ...userConfig,\n root: path.resolve(cwd, userConfig.root ?? '.'),\n input: input ?? userConfig.input,\n output: output\n ? {\n ...userConfig.output,\n path: output,\n }\n : userConfig.output,\n }\n\n await notify('CONFIG_READY', 'Configuration ready')\n\n const kubb = createKubb(config, { hooks })\n const result = await kubb.generate()\n await notify('BUILD_END', `Build complete - Generated ${result.files.length} files`)\n\n const problems = result.diagnostics.filter(Diagnostics.isProblem)\n const errors = problems.filter((diagnostic) => diagnostic.severity === 'error')\n if (errors.length > 0) {\n await notify('BUILD_FAILED', `Build failed with ${errors.length} diagnostic(s)`)\n\n const serialized = problems.map((diagnostic) => Diagnostics.serialize(diagnostic))\n return tool.error(`Build failed:\\n${formatDiagnostics(serialized)}\\n\\n\\`\\`\\`json\\n${JSON.stringify(serialized, null, 2)}\\n\\`\\`\\``)\n }\n\n await notify('BUILD_SUCCESS', `Build completed successfully - Generated ${result.files.length} files`)\n\n return tool.text(`Build completed successfully!\\n\\nGenerated ${result.files.length} files\\n\\n${messages.join('\\n')}`)\n } catch (caughtError) {\n const serialized = Diagnostics.serialize(Diagnostics.from(caughtError))\n return tool.error(`Build error:\\n${formatDiagnostics([serialized])}\\n\\n\\`\\`\\`json\\n${JSON.stringify(serialized, null, 2)}\\n\\`\\`\\``)\n }\n },\n)\n","import fs from 'node:fs'\nimport path from 'node:path'\nimport process from 'node:process'\nimport { generateConfigFile, KUBB_CONFIG_FILENAME, resolvePlugins } from '@internals/shared'\nimport { defineTool } from 'tmcp/tool'\nimport { tool } from 'tmcp/utils'\nimport * as z from 'zod/mini'\n\nconst initSchema = z.object({\n input: z.optional(z.string().check(z.minLength(1), z.describe('Path to OpenAPI spec (default: ./openapi.yaml)'))),\n output: z.optional(z.string().check(z.minLength(1), z.describe('Output directory (default: ./src/gen)'))),\n plugins: z.optional(z.string().check(z.minLength(1), z.describe('Comma-separated list of plugins: plugin-ts,plugin-zod,...'))),\n})\n\nexport const initTool = defineTool(\n {\n name: 'init',\n description: 'Scaffold a kubb.config.ts in the current directory (non-interactive). Does not install packages.',\n schema: initSchema,\n },\n async ({ input = './openapi.yaml', output = './src/gen', plugins }) => {\n const selected = resolvePlugins(plugins)\n const content = generateConfigFile({ selectedPlugins: selected, inputPath: input, outputPath: output })\n const dest = path.join(process.cwd(), KUBB_CONFIG_FILENAME)\n if (fs.existsSync(dest)) {\n return tool.error(`${KUBB_CONFIG_FILENAME} already exists at ${dest}. Delete it first before running init again.`)\n }\n fs.writeFileSync(dest, content, 'utf-8')\n const packageList = ['kubb', ...selected.map((p) => p.packageName)].join(' ')\n return tool.text(`Created kubb.config.ts\\n\\nInstall packages:\\n npm install ${packageList}\\n\\nThen run:\\n npx kubb generate`)\n },\n)\n","import { adapterOas } from '@kubb/adapter-oas'\nimport { Diagnostics } from '@kubb/core'\nimport { defineTool } from 'tmcp/tool'\nimport { tool } from 'tmcp/utils'\nimport * as z from 'zod/mini'\nimport { formatDiagnostics } from '../utils.ts'\n\nconst validateSchema = z.object({\n input: z.string().check(z.minLength(1), z.describe('Path or URL to the OpenAPI/Swagger specification')),\n})\n\nexport const validateTool = defineTool(\n {\n name: 'validate',\n description: 'Validate an OpenAPI/Swagger specification file or URL',\n schema: validateSchema,\n },\n async ({ input }) => {\n try {\n await adapterOas().validate(input, { throwOnError: true })\n return tool.text(`Validation successful: ${input}`)\n } catch (err) {\n const serialized = Diagnostics.serialize(Diagnostics.from(err))\n return tool.error(`Validation failed:\\n${formatDiagnostics([serialized])}\\n\\n\\`\\`\\`json\\n${JSON.stringify(serialized, null, 2)}\\n\\`\\`\\``)\n }\n },\n)\n","import { StdioTransport } from '@tmcp/transport-stdio'\nimport { McpServer } from 'tmcp'\nimport { JsonSchemaAdapter } from 'tmcp/adapter'\nimport { en } from 'zod/locales'\nimport * as z from 'zod/mini'\nimport { version } from '../package.json'\nimport { generateTool } from './tools/generate.ts'\nimport { initTool } from './tools/init.ts'\nimport { validateTool } from './tools/validate.ts'\n\n/**\n * Describes each tool's input to MCP clients. `@tmcp/adapter-zod` imports the full `zod` build, so\n * this converts with Zod Mini instead. `io: 'input'` keeps fields with a default optional.\n */\nclass ZodMiniJsonSchemaAdapter extends JsonSchemaAdapter<z.ZodMiniType> {\n async toJsonSchema(schema: z.ZodMiniType) {\n // Zod's type also allows draft-4's boolean `exclusiveMaximum`, which the draft-7 target never emits.\n return z.toJSONSchema(schema, { target: 'draft-7', io: 'input' }) as Awaited<ReturnType<JsonSchemaAdapter<z.ZodMiniType>['toJsonSchema']>>\n }\n}\n\n/**\n * Builds the Kubb MCP server with the generate, validate, and init tools registered.\n *\n * @example\n * `const server = createMcpServer()`\n */\nexport function createMcpServer() {\n // Zod Mini ships without a locale, so validation errors would only say \"Invalid input\".\n z.config(en())\n const server = new McpServer({ name: 'Kubb', version }, { adapter: new ZodMiniJsonSchemaAdapter(), capabilities: { tools: {} } })\n server.tools([generateTool, validateTool, initTool])\n return server\n}\n\n/**\n * Starts the Kubb MCP server over stdio, the transport every local MCP client\n * (Claude, Copilot, editors) uses when it launches the server as a subprocess.\n */\nexport function startServer(): void {\n new StdioTransport(createMcpServer()).listen()\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACEA,MAAa,uBAAuB;;AAGpC,MAAa,oBAAoB;CAAC;CAAO;CAAQ;CAAQ;CAAO;CAAQ;AAAM;AAU9E,MAAa,mBAAwC;CACnD;EACE,OAAO;EACP,OAAO;EACP,MAAM;EACN,aAAa;EACb,YAAY;EACZ,UAAU;CACZ;CACA;EACE,OAAO;EACP,OAAO;EACP,aAAa;EACb,YAAY;EACZ,UAAU;CACZ;CACA;EACE,OAAO;EACP,OAAO;EACP,aAAa;EACb,YAAY;EACZ,UAAU;CACZ;CACA;EACE,OAAO;EACP,OAAO;EACP,aAAa;EACb,YAAY;EACZ,UAAU;CACZ;CACA;EACE,OAAO;EACP,OAAO;EACP,aAAa;EACb,YAAY;EACZ,UAAU;CACZ;CACA;EACE,OAAO;EACP,OAAO;EACP,aAAa;EACb,YAAY;EACZ,UAAU;CACZ;CACA;EACE,OAAO;EACP,OAAO;EACP,aAAa;EACb,YAAY;EACZ,UAAU;CACZ;CACA;EACE,OAAO;EACP,OAAO;EACP,aAAa;EACb,YAAY;EACZ,UAAU;CACZ;CACA;EACE,OAAO;EACP,OAAO;EACP,aAAa;EACb,YAAY;EACZ,UAAU;CACZ;CACA;EACE,OAAO;EACP,OAAO;EACP,aAAa;EACb,YAAY;EACZ,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;EAAc;EAAc;CAAQ,CAAC;CACnD,OAAO;AACT;;;;;AAMA,SAAgB,cAAoB;CAClC,IAAIC,sBAAAA,eAAe,gBAAgB,CAAC,CAAC,CAAC,OAAO;AAC/C"}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { t as __name } from "./rolldown-runtime-C0LytTxp.js";
|
|
2
2
|
import { McpServer } from "tmcp";
|
|
3
|
+
import * as z from "zod/mini";
|
|
3
4
|
//#region src/server.d.ts
|
|
4
5
|
/**
|
|
5
6
|
* Builds the Kubb MCP server with the generate, validate, and init tools registered.
|
|
@@ -7,7 +8,7 @@ import { McpServer } from "tmcp";
|
|
|
7
8
|
* @example
|
|
8
9
|
* `const server = createMcpServer()`
|
|
9
10
|
*/
|
|
10
|
-
export declare function createMcpServer(): McpServer<
|
|
11
|
+
export declare function createMcpServer(): McpServer<z.ZodMiniType<unknown, unknown, z.core.$ZodTypeInternals<unknown, unknown>>, undefined>;
|
|
11
12
|
/**
|
|
12
13
|
* Starts the Kubb MCP server over stdio, the transport every local MCP client
|
|
13
14
|
* (Claude, Copilot, editors) uses when it launches the server as a subprocess.
|
package/dist/index.js
CHANGED
|
@@ -1,18 +1,20 @@
|
|
|
1
1
|
import "./rolldown-runtime-C0LytTxp.js";
|
|
2
|
-
import { ValibotJsonSchemaAdapter } from "@tmcp/adapter-valibot";
|
|
3
2
|
import { StdioTransport } from "@tmcp/transport-stdio";
|
|
4
3
|
import { McpServer } from "tmcp";
|
|
4
|
+
import { JsonSchemaAdapter } from "tmcp/adapter";
|
|
5
|
+
import { en } from "zod/locales";
|
|
6
|
+
import * as z from "zod/mini";
|
|
5
7
|
import path, { isAbsolute, relative, resolve } from "node:path";
|
|
8
|
+
import { readFile } from "node:fs/promises";
|
|
6
9
|
import { createJiti } from "jiti";
|
|
7
10
|
import { Diagnostics, Hookable, createKubb } from "@kubb/core";
|
|
8
11
|
import { defineTool } from "tmcp/tool";
|
|
9
12
|
import { tool } from "tmcp/utils";
|
|
10
|
-
import * as v from "valibot";
|
|
11
13
|
import fs, { existsSync } from "node:fs";
|
|
12
14
|
import process$1 from "node:process";
|
|
13
15
|
import { adapterOas } from "@kubb/adapter-oas";
|
|
14
16
|
//#region package.json
|
|
15
|
-
var version = "5.6.
|
|
17
|
+
var version = "5.6.3";
|
|
16
18
|
//#endregion
|
|
17
19
|
//#region ../../internals/shared/src/constants.ts
|
|
18
20
|
const KUBB_CONFIG_FILENAME = "kubb.config.ts";
|
|
@@ -147,9 +149,15 @@ const JITI_OPTIONS = {
|
|
|
147
149
|
moduleCache: false
|
|
148
150
|
};
|
|
149
151
|
/**
|
|
152
|
+
* Plain JavaScript files. jiti hands these to Node's native `import()`, whose module cache never
|
|
153
|
+
* lets go of a file, so `moduleCache: false` alone would keep returning the first version of it.
|
|
154
|
+
*/
|
|
155
|
+
const JAVASCRIPT_EXTENSION = /\.[cm]?jsx?$/;
|
|
156
|
+
/**
|
|
150
157
|
* Creates a jiti-based loader for Kubb's TypeScript and JavaScript config modules.
|
|
151
158
|
*
|
|
152
|
-
* jiti transpiles TypeScript and the `@kubb/renderer-jsx` JSX runtime on the fly.
|
|
159
|
+
* jiti transpiles TypeScript and the `@kubb/renderer-jsx` JSX runtime on the fly. Every load
|
|
160
|
+
* re-evaluates the file, so a config edited on disk is picked up by the next load.
|
|
153
161
|
*
|
|
154
162
|
* @example
|
|
155
163
|
* ```ts
|
|
@@ -158,8 +166,14 @@ const JITI_OPTIONS = {
|
|
|
158
166
|
*/
|
|
159
167
|
function createModuleLoader() {
|
|
160
168
|
const jiti = createJiti(import.meta.url, JITI_OPTIONS);
|
|
161
|
-
return { load(filePath, options) {
|
|
162
|
-
return options?.default ? jiti.import(filePath, { default: true }) : jiti.import(filePath);
|
|
169
|
+
return { async load(filePath, options) {
|
|
170
|
+
if (!JAVASCRIPT_EXTENSION.test(filePath)) return options?.default ? jiti.import(filePath, { default: true }) : jiti.import(filePath);
|
|
171
|
+
const mod = await jiti.evalModule(await readFile(filePath, "utf8"), {
|
|
172
|
+
filename: filePath,
|
|
173
|
+
async: true,
|
|
174
|
+
forceTranspile: true
|
|
175
|
+
});
|
|
176
|
+
return options?.default ? mod?.default ?? mod : mod;
|
|
163
177
|
} };
|
|
164
178
|
}
|
|
165
179
|
//#endregion
|
|
@@ -293,15 +307,15 @@ async function resolveUserConfig(config, options) {
|
|
|
293
307
|
}
|
|
294
308
|
//#endregion
|
|
295
309
|
//#region src/tools/generate.ts
|
|
296
|
-
const generateSchema =
|
|
297
|
-
config:
|
|
298
|
-
input:
|
|
299
|
-
output:
|
|
300
|
-
logLevel:
|
|
310
|
+
const generateSchema = z.object({
|
|
311
|
+
config: z.optional(z.string().check(z.minLength(1), z.describe(`Path to kubb.config file (supports ${CONFIG_EXTENSIONS.join(", ")}). If not provided, will look for kubb.config.* in current directory`))),
|
|
312
|
+
input: z.optional(z.string().check(z.minLength(1), z.describe("Path to OpenAPI/Swagger spec file (overrides config)"))),
|
|
313
|
+
output: z.optional(z.string().check(z.minLength(1), z.describe("Output directory path (overrides config)"))),
|
|
314
|
+
logLevel: z._default(z.enum([
|
|
301
315
|
"silent",
|
|
302
316
|
"info",
|
|
303
317
|
"verbose"
|
|
304
|
-
])
|
|
318
|
+
]).check(z.describe("Log level for build output")), "info")
|
|
305
319
|
});
|
|
306
320
|
const generateTool = defineTool({
|
|
307
321
|
name: "generate",
|
|
@@ -401,10 +415,10 @@ const generateTool = defineTool({
|
|
|
401
415
|
});
|
|
402
416
|
//#endregion
|
|
403
417
|
//#region src/tools/init.ts
|
|
404
|
-
const initSchema =
|
|
405
|
-
input:
|
|
406
|
-
output:
|
|
407
|
-
plugins:
|
|
418
|
+
const initSchema = z.object({
|
|
419
|
+
input: z.optional(z.string().check(z.minLength(1), z.describe("Path to OpenAPI spec (default: ./openapi.yaml)"))),
|
|
420
|
+
output: z.optional(z.string().check(z.minLength(1), z.describe("Output directory (default: ./src/gen)"))),
|
|
421
|
+
plugins: z.optional(z.string().check(z.minLength(1), z.describe("Comma-separated list of plugins: plugin-ts,plugin-zod,...")))
|
|
408
422
|
});
|
|
409
423
|
const initTool = defineTool({
|
|
410
424
|
name: "init",
|
|
@@ -425,7 +439,7 @@ const initTool = defineTool({
|
|
|
425
439
|
});
|
|
426
440
|
//#endregion
|
|
427
441
|
//#region src/tools/validate.ts
|
|
428
|
-
const validateSchema =
|
|
442
|
+
const validateSchema = z.object({ input: z.string().check(z.minLength(1), z.describe("Path or URL to the OpenAPI/Swagger specification")) });
|
|
429
443
|
const validateTool = defineTool({
|
|
430
444
|
name: "validate",
|
|
431
445
|
description: "Validate an OpenAPI/Swagger specification file or URL",
|
|
@@ -442,17 +456,30 @@ const validateTool = defineTool({
|
|
|
442
456
|
//#endregion
|
|
443
457
|
//#region src/server.ts
|
|
444
458
|
/**
|
|
459
|
+
* Describes each tool's input to MCP clients. `@tmcp/adapter-zod` imports the full `zod` build, so
|
|
460
|
+
* this converts with Zod Mini instead. `io: 'input'` keeps fields with a default optional.
|
|
461
|
+
*/
|
|
462
|
+
var ZodMiniJsonSchemaAdapter = class extends JsonSchemaAdapter {
|
|
463
|
+
async toJsonSchema(schema) {
|
|
464
|
+
return z.toJSONSchema(schema, {
|
|
465
|
+
target: "draft-7",
|
|
466
|
+
io: "input"
|
|
467
|
+
});
|
|
468
|
+
}
|
|
469
|
+
};
|
|
470
|
+
/**
|
|
445
471
|
* Builds the Kubb MCP server with the generate, validate, and init tools registered.
|
|
446
472
|
*
|
|
447
473
|
* @example
|
|
448
474
|
* `const server = createMcpServer()`
|
|
449
475
|
*/
|
|
450
476
|
function createMcpServer() {
|
|
477
|
+
z.config(en());
|
|
451
478
|
const server = new McpServer({
|
|
452
479
|
name: "Kubb",
|
|
453
480
|
version
|
|
454
481
|
}, {
|
|
455
|
-
adapter: new
|
|
482
|
+
adapter: new ZodMiniJsonSchemaAdapter(),
|
|
456
483
|
capabilities: { tools: {} }
|
|
457
484
|
});
|
|
458
485
|
server.tools([
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["process"],"sources":["../package.json","../../../internals/shared/src/constants.ts","../../../internals/shared/src/init.ts","../../../internals/shared/src/loader.ts","../../../internals/utils/src/fs.ts","../../../internals/utils/src/promise.ts","../src/utils.ts","../src/tools/generate.ts","../src/tools/init.ts","../src/tools/validate.ts","../src/server.ts"],"sourcesContent":["","import type { PluginOption } from './types.ts'\n\nexport 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\nexport const availablePlugins: Array<PluginOption> = [\n {\n value: 'plugin-ts',\n label: 'TypeScript',\n hint: 'Recommended',\n packageName: '@kubb/plugin-ts',\n importName: 'pluginTs',\n category: 'types',\n },\n {\n value: 'plugin-axios',\n label: 'Axios Client',\n packageName: '@kubb/plugin-axios',\n importName: 'pluginAxios',\n category: 'client',\n },\n {\n value: 'plugin-fetch',\n label: 'Fetch Client',\n packageName: '@kubb/plugin-fetch',\n importName: 'pluginFetch',\n category: 'client',\n },\n {\n value: 'plugin-react-query',\n label: 'React Query / TanStack Query',\n packageName: '@kubb/plugin-react-query',\n importName: 'pluginReactQuery',\n category: 'framework',\n },\n {\n value: 'plugin-vue-query',\n label: 'Vue Query',\n packageName: '@kubb/plugin-vue-query',\n importName: 'pluginVueQuery',\n category: 'framework',\n },\n {\n value: 'plugin-zod',\n label: 'Zod Schemas',\n packageName: '@kubb/plugin-zod',\n importName: 'pluginZod',\n category: 'validation',\n },\n {\n value: 'plugin-faker',\n label: 'Faker.js Mocks',\n packageName: '@kubb/plugin-faker',\n importName: 'pluginFaker',\n category: 'mocks',\n },\n {\n value: 'plugin-msw',\n label: 'MSW Handlers',\n packageName: '@kubb/plugin-msw',\n importName: 'pluginMsw',\n category: 'mocks',\n },\n {\n value: 'plugin-cypress',\n label: 'Cypress Tests',\n packageName: '@kubb/plugin-cypress',\n importName: 'pluginCypress',\n category: 'testing',\n },\n {\n value: 'plugin-mcp',\n label: 'MCP Server (AI / Model Context Protocol)',\n packageName: '@kubb/plugin-mcp',\n importName: 'pluginMcp',\n category: 'ai',\n },\n {\n value: 'plugin-redoc',\n label: 'ReDoc Documentation',\n packageName: '@kubb/plugin-redoc',\n importName: 'pluginRedoc',\n category: 'documentation',\n },\n]\n","import { availablePlugins, KUBB_PACKAGE_NAME } from './constants.ts'\nimport type { PluginOption } from './types.ts'\n\n/**\n * Resolves a comma-separated plugin flag (e.g. `--plugins plugin-ts,plugin-zod`) into the\n * matching known plugin options. Unrecognized names are dropped, and a missing flag yields\n * an empty list.\n */\nexport function resolvePlugins(pluginsFlag: string | undefined): Array<PluginOption> {\n if (!pluginsFlag) {\n return []\n }\n const requested = pluginsFlag\n .split(',')\n .map((value) => value.trim())\n .filter(Boolean)\n return availablePlugins.filter((plugin) => requested.includes(plugin.value))\n}\n\nexport function generateConfigFile({\n selectedPlugins,\n inputPath,\n outputPath,\n}: {\n selectedPlugins: Array<PluginOption>\n inputPath: string\n outputPath: string\n}): string {\n const imports = selectedPlugins.map((plugin) => `import { ${plugin.importName} } from '${plugin.packageName}'`).join('\\n')\n\n const pluginConfigs = selectedPlugins.map((plugin) => ` ${plugin.importName}(),`).join('\\n')\n\n return `import { defineConfig } from 'kubb/config'\n${imports}\n\nexport default defineConfig({\n input: '${inputPath}',\n output: {\n path: '${outputPath}',\n clean: true,\n },\n plugins: [\n${pluginConfigs}\n ],\n})\n`\n}\n\n/**\n * Turns package names into install specifiers for the wizard.\n *\n * `kubb` is pinned to the exact version of the running CLI, since both ship from the same release\n * and resolving `kubb@beta` separately can land on a different version than the CLI doing the\n * scaffolding. Plugins release from their own repo on their own cadence, so they follow the\n * release channel of the CLI through its dist-tag.\n */\nexport function resolveInstallVersions({ packages, version }: { packages: Array<string>; version: string }): Array<string> {\n const prerelease = version.match(/-([a-z]+)/)?.[1]\n const tag = prerelease ?? 'latest'\n\n return packages.map((name) => (name === KUBB_PACKAGE_NAME ? `${name}@${version}` : `${name}@${tag}`))\n}\n","import { 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 * Per-call options for {@link ModuleLoader.load}.\n */\ntype LoadModuleOptions = {\n /**\n * Return the module's default export instead of the full namespace.\n */\n default?: boolean\n}\n\n/**\n * Loads `.ts`/`.js` modules via jiti.\n */\ntype ModuleLoader = {\n load<T = unknown>(filePath: string, options?: LoadModuleOptions): Promise<T>\n}\n\n/**\n * Creates a jiti-based loader for Kubb's TypeScript and JavaScript config modules.\n *\n * jiti transpiles TypeScript and the `@kubb/renderer-jsx` JSX runtime on the fly.\n *\n * @example\n * ```ts\n * const config = await createModuleLoader().load('/abs/kubb.config.ts', { default: true })\n * ```\n */\nexport function createModuleLoader(): ModuleLoader {\n const jiti = createJiti(import.meta.url, JITI_OPTIONS)\n\n return {\n load<T>(filePath: string, options?: LoadModuleOptions) {\n return (options?.default ? jiti.import(filePath, { default: true }) : jiti.import(filePath)) as Promise<T>\n },\n }\n}\n","import { access, mkdir, readFile, rm, writeFile } from 'node:fs/promises'\nimport { dirname, isAbsolute, relative, resolve } from 'node:path'\nimport { runtime } from './runtime.ts'\n\n/**\n * Resolves to `true` when the file or directory at `path` exists.\n * Uses `Bun.file().exists()` when running under Bun, `fs.access` otherwise.\n *\n * @example\n * ```ts\n * if (await exists('./kubb.config.ts')) {\n * const content = await read('./kubb.config.ts')\n * }\n * ```\n */\nexport async function exists(path: string): Promise<boolean> {\n if (runtime.isBun) {\n return Bun.file(path).exists()\n }\n return access(path).then(\n () => true,\n () => false,\n )\n}\n\n/**\n * Reads the file at `path` as a UTF-8 string.\n * Uses `Bun.file().text()` when running under Bun, `fs.readFile` otherwise.\n *\n * @example\n * ```ts\n * const source = await read('./src/Pet.ts')\n * ```\n */\nexport async function read(path: string): Promise<string> {\n if (runtime.isBun) {\n return Bun.file(path).text()\n }\n return readFile(path, { encoding: 'utf8' })\n}\n\ntype WriteOptions = {\n /**\n * Previously read content, or `null` when the file does not exist.\n * Omitting this value reads the file before writing.\n */\n stored?: string | null\n /**\n * When `true`, re-reads the file immediately after writing and throws if the\n * content does not match — useful for catching write failures on unreliable file systems.\n */\n sanity?: boolean\n}\n\n/**\n * Whether `stored` already holds `source`, comparing on the trimmed text rather than the exact\n * bytes. Surrounding whitespace is what a formatter adds and what editors strip, and neither is a\n * reason to rewrite the file.\n *\n * Both sides are trimmed, so a storage that keeps bytes verbatim settles on the same answer as one\n * that normalizes what it stores. Trimming only `stored` would leave a source with leading\n * whitespace rewritten on every build, since the stored copy keeps the whitespace the comparison\n * has already dropped.\n */\nexport function matchesStored({ stored, source }: { stored: string; source: string }): boolean {\n return stored.trim() === source.trim()\n}\n\n/**\n * Writes `data` to `path`, trimming surrounding whitespace and ending the file with a single newline\n * the way prettier, biome, and oxfmt all do.\n * Skips the write when the trimmed content is empty, or when the file already holds that content.\n * Creates any missing parent directories automatically.\n * When `sanity` is `true`, re-reads the file after writing and throws if the content does not match.\n *\n * @example\n * ```ts\n * await write('./src/Pet.ts', source) // writes and returns the trimmed content plus a newline\n * await write('./src/Pet.ts', source) // null — file unchanged\n * await write('./src/Pet.ts', ' ') // null — empty content skipped\n * ```\n */\nexport async function write(path: string, data: string, options: WriteOptions = {}): Promise<string | null> {\n const trimmed = data.trim()\n if (trimmed === '') return null\n\n const content = `${trimmed}\\n`\n const resolved = resolve(path)\n let stored = options.stored\n\n if (stored === undefined) {\n if (runtime.isBun) {\n const file = Bun.file(resolved)\n stored = (await file.exists()) ? await file.text() : null\n } else {\n try {\n stored = await readFile(resolved, { encoding: 'utf-8' })\n } catch {\n /* file doesn't exist yet */\n stored = null\n }\n }\n }\n if (matchesStored({ stored: stored ?? '', source: trimmed })) return null\n\n if (runtime.isBun) {\n await Bun.write(resolved, content)\n return content\n }\n\n // Creating the directory up front costs a syscall per file, and every file after the first in a\n // directory pays it for nothing. Write first and only fall back when the directory is missing,\n // which also stays correct when something removed it mid-run.\n try {\n await writeFile(resolved, content, { encoding: 'utf-8' })\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error\n\n await mkdir(dirname(resolved), { recursive: true })\n await writeFile(resolved, content, { encoding: 'utf-8' })\n }\n\n if (options.sanity) {\n const savedData = await readFile(resolved, { encoding: 'utf-8' })\n if (savedData !== content) {\n throw new Error(`Sanity check failed for ${path}\\n\\nData[${data.length}]:\\n${data}\\n\\nSaved[${savedData.length}]:\\n${savedData}\\n`)\n }\n return savedData\n }\n\n return content\n}\n\n/**\n * Recursively removes `path`. Silently succeeds when `path` does not exist.\n *\n * @example\n * ```ts\n * await clean('./dist')\n * ```\n */\nexport async function clean(path: string): Promise<void> {\n return rm(path, { recursive: true, force: true })\n}\n\n/**\n * Converts a filesystem path to use POSIX (`/`) separators.\n *\n * Most of the codebase compares and composes paths as strings (prefix matching, joining for\n * import specifiers, splitting on `/`). On POSIX `path.resolve` already returns `/`-separated\n * paths, but on Windows it returns `\\`-separated paths, which breaks every such comparison.\n *\n * Routing every path that crosses a module boundary through `toPosixPath` keeps the rest of the\n * code platform-agnostic. The conversion runs unconditionally so Windows-specific behavior is\n * exercisable from POSIX CI.\n *\n * @example\n * toPosixPath('C:\\\\repo\\\\src\\\\pet.ts') // 'C:/repo/src/pet.ts'\n */\nexport function toPosixPath(filePath: string): string {\n return filePath.replaceAll('\\\\', '/')\n}\n\n/**\n * Strips the file extension from a path or file name.\n * Only removes the last `.ext` segment when the dot is not part of a directory name.\n *\n * @example\n * trimExtName('petStore.ts') // 'petStore'\n * trimExtName('/src/models/pet.ts') // '/src/models/pet'\n * trimExtName('/project.v2/gen/pet.ts') // '/project.v2/gen/pet'\n * trimExtName('noExtension') // 'noExtension'\n */\nexport function trimExtName(text: string): string {\n const dotIndex = text.lastIndexOf('.')\n if (dotIndex > 0 && !text.includes('/', dotIndex)) {\n return text.slice(0, dotIndex)\n }\n return text\n}\n\n/**\n * Resolves to `true` when `path` is `parent` itself or nested inside it. Both sides are resolved\n * to absolute paths first, so relative and `..`-containing inputs compare correctly.\n *\n * Guards a destructive or an out-of-tree operation: before wiping an output directory, check that\n * it does not contain the project root, and before loading a path a caller supplied, check that it\n * did not escape the directory it is allowed to read from.\n *\n * @example\n * isPathInside('./src/gen', '.') // true — nested inside the root\n * isPathInside('.', '.') // true — the same directory counts as inside\n * isPathInside('.', './src/gen') // false — the root is not inside its own output\n * isPathInside('../other', '.') // false — escapes the root\n */\nexport function isPathInside(path: string, parent: string): boolean {\n const resolvedPath = resolve(path)\n const resolvedParent = resolve(parent)\n if (resolvedPath === resolvedParent) {\n return true\n }\n\n const rel = relative(resolvedParent, resolvedPath)\n\n return rel !== '' && !rel.startsWith('..') && !isAbsolute(rel)\n}\n","/** A value that may already be resolved or still pending.\n *\n * @example\n * ```ts\n * function load(id: string): PossiblePromise<string> {\n * return cache.get(id) ?? fetchRemote(id)\n * }\n * ```\n */\nexport type PossiblePromise<T> = Promise<T> | T\n\n/** Returns `true` when `result` is a thenable `Promise`.\n *\n * @example\n * ```ts\n * isPromise(Promise.resolve(1)) // true\n * isPromise(42) // false\n * ```\n */\nexport function isPromise<T>(result: PossiblePromise<T>): result is Promise<T> {\n return result !== null && result !== undefined && typeof (result as Record<string, unknown>)['then'] === 'function'\n}\n\ntype Store<TKey, TValue> = {\n has(key: TKey): boolean\n get(key: TKey): TValue | undefined\n set(key: TKey, value: TValue): unknown\n}\n\n/**\n * Wraps `factory` with a keyed cache backed by the provided store.\n *\n * Pass a `WeakMap` for object keys (results are GC-eligible when the key is\n * collected) or a `Map` for primitive keys. For multi-argument functions,\n * nest two `memoize` calls — the outer keyed by the first argument, the\n * inner (created once per outer miss) keyed by the second.\n *\n * Because the cache is owned by the caller, it can be shared, inspected, or\n * cleared independently of the memoized function.\n *\n * @example Single WeakMap key\n * ```ts\n * const cache = new WeakMap<SchemaNode, Set<string>>()\n * const getRefs = memoize(cache, (node) => collectRefs(node))\n * ```\n *\n * @example Single Map key (primitive)\n * ```ts\n * const cache = new Map<string, Resolver>()\n * const getResolver = memoize(cache, (name) => buildResolver(name))\n * ```\n *\n * @example Two-level (object + primitive)\n * ```ts\n * const outer = new WeakMap<Params[], Map<string, Params[]>>()\n * const fn = memoize(outer, (params) => memoize(new Map(), (key) => transform(params, key)))\n * fn(params)('camelcase')\n * ```\n */\nexport function memoize<TKey, TValue>(store: Store<TKey, TValue>, factory: (key: TKey) => TValue): (key: TKey) => TValue {\n return (key: TKey): TValue => {\n if (store.has(key)) return store.get(key)!\n const value = factory(key)\n store.set(key, value)\n return value\n }\n}\n\ntype ParallelOptions<TItem> = {\n /**\n * Items to work through, handed out in order.\n */\n items: ReadonlyArray<TItem>\n /**\n * How many items may be in flight at once.\n */\n limit: number\n /**\n * Runs once per item, with the item's position so a caller can report progress.\n */\n run(item: TItem, index: number): Promise<void>\n}\n\n/**\n * Runs `run` over every item with at most `limit` in flight. Workers share one iterator, so each\n * takes the next item the moment it frees up instead of waiting for a batch to drain.\n *\n * @example\n * ```ts\n * await inParallel({ items: files, limit: 50, run: (file) => storage.writeItem(file.path, file.source) })\n * ```\n */\nexport async function inParallel<TItem>({ items, limit, run }: ParallelOptions<TItem>): Promise<void> {\n const queue = items.entries()\n\n const worker = async (): Promise<void> => {\n for (const [index, item] of queue) await run(item, index)\n }\n\n await Promise.all(Array.from({ length: Math.min(limit, items.length) }, () => worker()))\n}\n","import { existsSync } from 'node:fs'\nimport path from 'node:path'\nimport { CONFIG_EXTENSIONS, createModuleLoader } from '@internals/shared'\nimport { isPathInside, isPromise } from '@internals/utils'\nimport type { CLIOptions, Config, PossibleConfig, SerializedDiagnostic } from '@kubb/core'\n\nconst CONFIG_FILE_NAMES = CONFIG_EXTENSIONS.map((extension) => `kubb.config${extension}`)\n\n/**\n * Renders serialized diagnostics as a plain-text block for an AI assistant. Each entry\n * keeps the stable `code`, the source pointer, the suggested fix, and the docs link, so\n * the agent can act on the problem rather than parsing a bare message. No ANSI styling,\n * unlike the CLI renderer.\n */\nexport function formatDiagnostics(diagnostics: ReadonlyArray<SerializedDiagnostic>): string {\n return diagnostics.map((diagnostic) => formatDiagnostic(diagnostic)).join('\\n\\n')\n}\n\nfunction formatDiagnostic(diagnostic: SerializedDiagnostic): string {\n const { code, message, location, help, plugin, docsUrl } = diagnostic\n const lines = [plugin ? `[${code}] ${plugin}: ${message}` : `[${code}]: ${message}`]\n\n if (location && 'pointer' in location) {\n lines.push(` at: ${location.pointer}`)\n }\n if (help) {\n lines.push(` fix: ${help}`)\n }\n if (docsUrl) {\n lines.push(` see: ${docsUrl}`)\n }\n\n return lines.join('\\n')\n}\n\ntype NotifyFunction = (type: string, message: string, data?: Record<string, unknown>) => Promise<void>\n\nconst loader = createModuleLoader()\n\n// No cache: the MCP server is long-running, so every tool call re-reads the config to pick up edits.\nfunction loadModule(filePath: string): Promise<unknown> {\n return loader.load(filePath, { default: true })\n}\n\n/**\n * Loads the user's Kubb config and returns it with the directory it was found in.\n *\n * When `configPath` is given it must use an allowed extension and resolve inside\n * the current working directory, otherwise loading throws. When omitted, the\n * known `kubb.config.*` file names are tried in the current directory. Every\n * outcome is reported through `notify` before the function returns or throws.\n */\nexport async function loadUserConfig(configPath: string | undefined, { notify }: { notify: NotifyFunction }): Promise<{ userConfig: Config; cwd: string }> {\n if (configPath) {\n const ext = path.extname(configPath)\n if (!CONFIG_EXTENSIONS.some((extension) => extension === ext)) {\n const msg = `Invalid config file extension \"${ext}\". Allowed: ${CONFIG_EXTENSIONS.join(', ')}`\n await notify('CONFIG_ERROR', msg)\n throw new Error(msg)\n }\n const base = path.resolve(process.cwd())\n const resolvedConfigPath = path.resolve(base, configPath)\n if (!isPathInside(resolvedConfigPath, base)) {\n const msg = 'Invalid config file path: must be within the current working directory'\n await notify('CONFIG_ERROR', msg)\n throw new Error(msg)\n }\n const cwd = path.dirname(resolvedConfigPath)\n try {\n const userConfig = (await loadModule(resolvedConfigPath)) as Config\n await notify('CONFIG_LOADED', `Loaded config from ${resolvedConfigPath}`)\n return { userConfig, cwd }\n } catch (error) {\n const msg = `Failed to load config: ${error instanceof Error ? error.message : String(error)}`\n await notify('CONFIG_ERROR', msg)\n throw new Error(msg)\n }\n }\n\n const cwd = process.cwd()\n\n for (const configFileName of CONFIG_FILE_NAMES) {\n const configFilePath = path.resolve(process.cwd(), configFileName)\n if (!existsSync(configFilePath)) continue\n try {\n const userConfig = (await loadModule(configFilePath)) as Config\n await notify('CONFIG_LOADED', `Loaded ${configFileName} from current directory`)\n return { userConfig, cwd }\n } catch (err) {\n await notify('CONFIG_ERROR', `Failed to load ${configFileName}: ${err instanceof Error ? err.message : String(err)}`)\n }\n }\n\n await notify('CONFIG_ERROR', 'No config file found')\n throw new Error(`No config file found. Please provide a config path or create one of: ${CONFIG_FILE_NAMES.join(', ')}`)\n}\n\n/**\n * Inputs forwarded to a config when it is defined as a function.\n */\ntype ResolveUserConfigOptions = {\n /**\n * Path of the loaded config, passed through to the config function as `config`.\n */\n configPath?: string\n /**\n * Log level passed through to the config function.\n */\n logLevel?: CLIOptions['logLevel']\n}\n\n/**\n * Normalizes a possible config into a single resolved `Config`.\n *\n * Calls the config when it is a function, awaits it when it is a promise, and\n * picks the first entry when it resolves to an array.\n */\nexport async function resolveUserConfig(config: PossibleConfig<CLIOptions>, options: ResolveUserConfigOptions): Promise<Config> {\n const result = typeof config === 'function' ? config({ logLevel: options.logLevel, config: options.configPath }) : config\n const resolved = isPromise(result) ? await result : result\n\n return (Array.isArray(resolved) ? resolved[0] : resolved) as Config\n}\n","import path from 'node:path'\nimport { CONFIG_EXTENSIONS } from '@internals/shared'\nimport { type Config, createKubb, type Diagnostic, Diagnostics, type KubbHooks, Hookable } from '@kubb/core'\nimport { defineTool } from 'tmcp/tool'\nimport { tool } from 'tmcp/utils'\nimport * as v from 'valibot'\nimport { formatDiagnostics, loadUserConfig, resolveUserConfig } from '../utils.ts'\n\nconst generateSchema = v.object({\n config: v.optional(\n v.pipe(\n v.string(),\n v.minLength(1),\n v.description(`Path to kubb.config file (supports ${CONFIG_EXTENSIONS.join(', ')}). If not provided, will look for kubb.config.* in current directory`),\n ),\n ),\n input: v.optional(v.pipe(v.string(), v.minLength(1), v.description('Path to OpenAPI/Swagger spec file (overrides config)'))),\n output: v.optional(v.pipe(v.string(), v.minLength(1), v.description('Output directory path (overrides config)'))),\n logLevel: v.optional(v.pipe(v.picklist(['silent', 'info', 'verbose']), v.description('Log level for build output')), 'info'),\n})\n\nexport const generateTool = defineTool(\n {\n name: 'generate',\n description: 'Generate OpenAPI spec helpers using Kubb configuration',\n schema: generateSchema,\n },\n async function generate(schema: v.InferInput<typeof generateSchema>) {\n const { config: configPath, input, output, logLevel } = schema\n\n try {\n const hooks = new Hookable<KubbHooks>()\n const messages: Array<string> = []\n\n const notify = async (type: string, message: string, data?: Record<string, unknown>) => {\n messages.push(data ? `${type}: ${message} ${JSON.stringify(data)}` : `${type}: ${message}`)\n }\n\n hooks.hook('kubb:info', async ({ message }: { message: string }) => {\n await notify('INFO', message)\n })\n\n hooks.hook('kubb:success', async ({ message }: { message: string }) => {\n await notify('SUCCESS', message)\n })\n\n hooks.hook('kubb:error', async ({ error }: { error: Error }) => {\n await notify('ERROR', error.message)\n })\n\n hooks.hook('kubb:warn', async ({ message }: { message: string }) => {\n await notify('WARN', message)\n })\n\n hooks.hook('kubb:diagnostic', async ({ diagnostic }: { diagnostic: Diagnostic }) => {\n await notify('DIAGNOSTIC', diagnostic.message, Diagnostics.serialize(diagnostic))\n })\n\n hooks.hook('kubb:plugin:start', async ({ plugin }) => {\n await notify('PLUGIN_START', `Plugin starting: ${plugin.name}`)\n })\n\n hooks.hook('kubb:plugin:end', async ({ plugin, duration }) => {\n await notify('PLUGIN_END', `Plugin finished: ${plugin.name}`, { duration })\n })\n\n hooks.hook('kubb:files:processing:start', async () => {\n await notify('FILES_START', 'Starting file processing')\n })\n\n hooks.hook('kubb:files:processing:update', async ({ files }: { files: Array<{ file: { name: string } }> }) => {\n await notify('FILES_UPDATE', `Processing ${files.length} files`)\n })\n\n hooks.hook('kubb:files:processing:end', async () => {\n await notify('FILES_END', 'File processing complete')\n })\n\n hooks.hook('kubb:generation:start', async () => {\n await notify('GENERATION_START', 'Generation started')\n })\n\n hooks.hook('kubb:setup:start', async () => {\n await notify('SETUP_START', 'Setting up Kubb')\n })\n\n hooks.hook('kubb:setup:end', async () => {\n await notify('SETUP_END', 'Kubb setup complete')\n await notify('BUILD_START', 'Starting build')\n })\n\n hooks.hook('kubb:generation:end', async () => {\n await notify('GENERATION_END', 'Generation ended')\n })\n\n let userConfig: Config\n let cwd: string\n\n try {\n const configResult = await loadUserConfig(configPath, { notify })\n userConfig = configResult.userConfig\n cwd = configResult.cwd\n\n if (Array.isArray(userConfig)) {\n throw new Error('Array type in kubb.config.ts is not supported in this tool. Please provide a single configuration object.')\n }\n\n userConfig = await resolveUserConfig(userConfig, {\n configPath,\n logLevel,\n })\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error)\n return tool.error(errorMessage)\n }\n\n const config: Config = {\n ...userConfig,\n root: path.resolve(cwd, userConfig.root ?? '.'),\n input: input ?? userConfig.input,\n output: output\n ? {\n ...userConfig.output,\n path: output,\n }\n : userConfig.output,\n }\n\n await notify('CONFIG_READY', 'Configuration ready')\n\n const kubb = createKubb(config, { hooks })\n const result = await kubb.generate()\n await notify('BUILD_END', `Build complete - Generated ${result.files.length} files`)\n\n const problems = result.diagnostics.filter(Diagnostics.isProblem)\n const errors = problems.filter((diagnostic) => diagnostic.severity === 'error')\n if (errors.length > 0) {\n await notify('BUILD_FAILED', `Build failed with ${errors.length} diagnostic(s)`)\n\n const serialized = problems.map((diagnostic) => Diagnostics.serialize(diagnostic))\n return tool.error(`Build failed:\\n${formatDiagnostics(serialized)}\\n\\n\\`\\`\\`json\\n${JSON.stringify(serialized, null, 2)}\\n\\`\\`\\``)\n }\n\n await notify('BUILD_SUCCESS', `Build completed successfully - Generated ${result.files.length} files`)\n\n return tool.text(`Build completed successfully!\\n\\nGenerated ${result.files.length} files\\n\\n${messages.join('\\n')}`)\n } catch (caughtError) {\n const serialized = Diagnostics.serialize(Diagnostics.from(caughtError))\n return tool.error(`Build error:\\n${formatDiagnostics([serialized])}\\n\\n\\`\\`\\`json\\n${JSON.stringify(serialized, null, 2)}\\n\\`\\`\\``)\n }\n },\n)\n","import fs from 'node:fs'\nimport path from 'node:path'\nimport process from 'node:process'\nimport { generateConfigFile, KUBB_CONFIG_FILENAME, resolvePlugins } from '@internals/shared'\nimport { defineTool } from 'tmcp/tool'\nimport { tool } from 'tmcp/utils'\nimport * as v from 'valibot'\n\nconst initSchema = v.object({\n input: v.optional(v.pipe(v.string(), v.minLength(1), v.description('Path to OpenAPI spec (default: ./openapi.yaml)'))),\n output: v.optional(v.pipe(v.string(), v.minLength(1), v.description('Output directory (default: ./src/gen)'))),\n plugins: v.optional(v.pipe(v.string(), v.minLength(1), v.description('Comma-separated list of plugins: plugin-ts,plugin-zod,...'))),\n})\n\nexport const initTool = defineTool(\n {\n name: 'init',\n description: 'Scaffold a kubb.config.ts in the current directory (non-interactive). Does not install packages.',\n schema: initSchema,\n },\n async ({ input = './openapi.yaml', output = './src/gen', plugins }) => {\n const selected = resolvePlugins(plugins)\n const content = generateConfigFile({ selectedPlugins: selected, inputPath: input, outputPath: output })\n const dest = path.join(process.cwd(), KUBB_CONFIG_FILENAME)\n if (fs.existsSync(dest)) {\n return tool.error(`${KUBB_CONFIG_FILENAME} already exists at ${dest}. Delete it first before running init again.`)\n }\n fs.writeFileSync(dest, content, 'utf-8')\n const packageList = ['kubb', ...selected.map((p) => p.packageName)].join(' ')\n return tool.text(`Created kubb.config.ts\\n\\nInstall packages:\\n npm install ${packageList}\\n\\nThen run:\\n npx kubb generate`)\n },\n)\n","import { adapterOas } from '@kubb/adapter-oas'\nimport { Diagnostics } from '@kubb/core'\nimport { defineTool } from 'tmcp/tool'\nimport { tool } from 'tmcp/utils'\nimport * as v from 'valibot'\nimport { formatDiagnostics } from '../utils.ts'\n\nconst validateSchema = v.object({\n input: v.pipe(v.string(), v.minLength(1), v.description('Path or URL to the OpenAPI/Swagger specification')),\n})\n\nexport const validateTool = defineTool(\n {\n name: 'validate',\n description: 'Validate an OpenAPI/Swagger specification file or URL',\n schema: validateSchema,\n },\n async ({ input }) => {\n try {\n await adapterOas().validate(input, { throwOnError: true })\n return tool.text(`Validation successful: ${input}`)\n } catch (err) {\n const serialized = Diagnostics.serialize(Diagnostics.from(err))\n return tool.error(`Validation failed:\\n${formatDiagnostics([serialized])}\\n\\n\\`\\`\\`json\\n${JSON.stringify(serialized, null, 2)}\\n\\`\\`\\``)\n }\n },\n)\n","import { ValibotJsonSchemaAdapter } from '@tmcp/adapter-valibot'\nimport { StdioTransport } from '@tmcp/transport-stdio'\nimport { McpServer } from 'tmcp'\nimport { version } from '../package.json'\nimport { generateTool } from './tools/generate.ts'\nimport { initTool } from './tools/init.ts'\nimport { validateTool } from './tools/validate.ts'\n\n/**\n * Builds the Kubb MCP server with the generate, validate, and init tools registered.\n *\n * @example\n * `const server = createMcpServer()`\n */\nexport function createMcpServer() {\n const server = new McpServer({ name: 'Kubb', version }, { adapter: new ValibotJsonSchemaAdapter(), capabilities: { tools: {} } })\n server.tools([generateTool, validateTool, initTool])\n return server\n}\n\n/**\n * Starts the Kubb MCP server over stdio, the transport every local MCP client\n * (Claude, Copilot, editors) uses when it launches the server as a subprocess.\n */\nexport function startServer(): void {\n new StdioTransport(createMcpServer()).listen()\n}\n"],"mappings":";;;;;;;;;;;;;;;;;ACEA,MAAa,uBAAuB;;AA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,qBAAqB,qBAAqB,KAAK,6CAA6C;CAEnH,GAAG,cAAc,MAAM,SAAS,OAAO;CACvC,MAAM,cAAc,CAAC,QAAQ,GAAG,SAAS,KAAK,MAAM,EAAE,WAAW,CAAC,CAAC,CAAC,KAAK,GAAG;CAC5E,OAAO,KAAK,KAAK,8DAA8D,YAAY,mCAAmC;AAChI,CACF;;;ACxBA,MAAM,iBAAiB,EAAE,OAAO,EAC9B,OAAO,EAAE,KAAK,EAAE,OAAO,GAAG,EAAE,UAAU,CAAC,GAAG,EAAE,YAAY,kDAAkD,CAAC,EAC7G,CAAC;AAED,MAAa,eAAe,WAC1B;CACE,MAAM;CACN,aAAa;CACb,QAAQ;AACV,GACA,OAAO,EAAE,YAAY;CACnB,IAAI;EACF,MAAM,WAAW,CAAC,CAAC,SAAS,OAAO,EAAE,cAAc,KAAK,CAAC;EACzD,OAAO,KAAK,KAAK,0BAA0B,OAAO;CACpD,SAAS,KAAK;EACZ,MAAM,aAAa,YAAY,UAAU,YAAY,KAAK,GAAG,CAAC;EAC9D,OAAO,KAAK,MAAM,uBAAuB,kBAAkB,CAAC,UAAU,CAAC,EAAE,kBAAkB,KAAK,UAAU,YAAY,MAAM,CAAC,EAAE,SAAS;CAC1I;AACF,CACF;;;;;;;;;ACZA,SAAgB,kBAAkB;CAChC,MAAM,SAAS,IAAI,UAAU;EAAE,MAAM;EAAQ;CAAQ,GAAG;EAAE,SAAS,IAAI,yBAAyB;EAAG,cAAc,EAAE,OAAO,CAAC,EAAE;CAAE,CAAC;CAChI,OAAO,MAAM;EAAC;EAAc;EAAc;CAAQ,CAAC;CACnD,OAAO;AACT;;;;;AAMA,SAAgB,cAAoB;CAClC,IAAI,eAAe,gBAAgB,CAAC,CAAC,CAAC,OAAO;AAC/C"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["process"],"sources":["../package.json","../../../internals/shared/src/constants.ts","../../../internals/shared/src/init.ts","../../../internals/shared/src/loader.ts","../../../internals/utils/src/fs.ts","../../../internals/utils/src/promise.ts","../src/utils.ts","../src/tools/generate.ts","../src/tools/init.ts","../src/tools/validate.ts","../src/server.ts"],"sourcesContent":["","import type { PluginOption } from './types.ts'\n\nexport 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\nexport const availablePlugins: Array<PluginOption> = [\n {\n value: 'plugin-ts',\n label: 'TypeScript',\n hint: 'Recommended',\n packageName: '@kubb/plugin-ts',\n importName: 'pluginTs',\n category: 'types',\n },\n {\n value: 'plugin-axios',\n label: 'Axios Client',\n packageName: '@kubb/plugin-axios',\n importName: 'pluginAxios',\n category: 'client',\n },\n {\n value: 'plugin-fetch',\n label: 'Fetch Client',\n packageName: '@kubb/plugin-fetch',\n importName: 'pluginFetch',\n category: 'client',\n },\n {\n value: 'plugin-react-query',\n label: 'React Query / TanStack Query',\n packageName: '@kubb/plugin-react-query',\n importName: 'pluginReactQuery',\n category: 'framework',\n },\n {\n value: 'plugin-vue-query',\n label: 'Vue Query',\n packageName: '@kubb/plugin-vue-query',\n importName: 'pluginVueQuery',\n category: 'framework',\n },\n {\n value: 'plugin-zod',\n label: 'Zod Schemas',\n packageName: '@kubb/plugin-zod',\n importName: 'pluginZod',\n category: 'validation',\n },\n {\n value: 'plugin-faker',\n label: 'Faker.js Mocks',\n packageName: '@kubb/plugin-faker',\n importName: 'pluginFaker',\n category: 'mocks',\n },\n {\n value: 'plugin-msw',\n label: 'MSW Handlers',\n packageName: '@kubb/plugin-msw',\n importName: 'pluginMsw',\n category: 'mocks',\n },\n {\n value: 'plugin-cypress',\n label: 'Cypress Tests',\n packageName: '@kubb/plugin-cypress',\n importName: 'pluginCypress',\n category: 'testing',\n },\n {\n value: 'plugin-mcp',\n label: 'MCP Server (AI / Model Context Protocol)',\n packageName: '@kubb/plugin-mcp',\n importName: 'pluginMcp',\n category: 'ai',\n },\n {\n value: 'plugin-redoc',\n label: 'ReDoc Documentation',\n packageName: '@kubb/plugin-redoc',\n importName: 'pluginRedoc',\n category: 'documentation',\n },\n]\n","import { availablePlugins, KUBB_PACKAGE_NAME } from './constants.ts'\nimport type { PluginOption } from './types.ts'\n\n/**\n * Resolves a comma-separated plugin flag (e.g. `--plugins plugin-ts,plugin-zod`) into the\n * matching known plugin options. Unrecognized names are dropped, and a missing flag yields\n * an empty list.\n */\nexport function resolvePlugins(pluginsFlag: string | undefined): Array<PluginOption> {\n if (!pluginsFlag) {\n return []\n }\n const requested = pluginsFlag\n .split(',')\n .map((value) => value.trim())\n .filter(Boolean)\n return availablePlugins.filter((plugin) => requested.includes(plugin.value))\n}\n\nexport function generateConfigFile({\n selectedPlugins,\n inputPath,\n outputPath,\n}: {\n selectedPlugins: Array<PluginOption>\n inputPath: string\n outputPath: string\n}): string {\n const imports = selectedPlugins.map((plugin) => `import { ${plugin.importName} } from '${plugin.packageName}'`).join('\\n')\n\n const pluginConfigs = selectedPlugins.map((plugin) => ` ${plugin.importName}(),`).join('\\n')\n\n return `import { defineConfig } from 'kubb/config'\n${imports}\n\nexport default defineConfig({\n input: '${inputPath}',\n output: {\n path: '${outputPath}',\n clean: true,\n },\n plugins: [\n${pluginConfigs}\n ],\n})\n`\n}\n\n/**\n * Turns package names into install specifiers for the wizard.\n *\n * `kubb` is pinned to the exact version of the running CLI, since both ship from the same release\n * and resolving `kubb@beta` separately can land on a different version than the CLI doing the\n * scaffolding. Plugins release from their own repo on their own cadence, so they follow the\n * release channel of the CLI through its dist-tag.\n */\nexport function resolveInstallVersions({ packages, version }: { packages: Array<string>; version: string }): Array<string> {\n const prerelease = version.match(/-([a-z]+)/)?.[1]\n const tag = prerelease ?? 'latest'\n\n return packages.map((name) => (name === KUBB_PACKAGE_NAME ? `${name}@${version}` : `${name}@${tag}`))\n}\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 ModuleLoader.load}.\n */\ntype LoadModuleOptions = {\n /**\n * Return the module's default export instead of the full namespace.\n */\n default?: boolean\n}\n\n/**\n * Loads `.ts`/`.js` modules via jiti.\n */\ntype ModuleLoader = {\n load<T = unknown>(filePath: string, options?: LoadModuleOptions): Promise<T>\n}\n\n/**\n * Creates a jiti-based loader for Kubb's TypeScript and JavaScript config modules.\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 createModuleLoader().load('/abs/kubb.config.ts', { default: true })\n * ```\n */\nexport function createModuleLoader(): ModuleLoader {\n const jiti = createJiti(import.meta.url, JITI_OPTIONS)\n\n return {\n async load<T>(filePath: string, options?: LoadModuleOptions) {\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 }\n}\n","import { access, mkdir, readFile, rm, writeFile } from 'node:fs/promises'\nimport { dirname, isAbsolute, relative, resolve } from 'node:path'\nimport { runtime } from './runtime.ts'\n\n/**\n * Resolves to `true` when the file or directory at `path` exists.\n * Uses `Bun.file().exists()` when running under Bun, `fs.access` otherwise.\n *\n * @example\n * ```ts\n * if (await exists('./kubb.config.ts')) {\n * const content = await read('./kubb.config.ts')\n * }\n * ```\n */\nexport async function exists(path: string): Promise<boolean> {\n if (runtime.isBun) {\n return Bun.file(path).exists()\n }\n return access(path).then(\n () => true,\n () => false,\n )\n}\n\n/**\n * Reads the file at `path` as a UTF-8 string.\n * Uses `Bun.file().text()` when running under Bun, `fs.readFile` otherwise.\n *\n * @example\n * ```ts\n * const source = await read('./src/Pet.ts')\n * ```\n */\nexport async function read(path: string): Promise<string> {\n if (runtime.isBun) {\n return Bun.file(path).text()\n }\n return readFile(path, { encoding: 'utf8' })\n}\n\ntype WriteOptions = {\n /**\n * Previously read content, or `null` when the file does not exist.\n * Omitting this value reads the file before writing.\n */\n stored?: string | null\n /**\n * When `true`, re-reads the file immediately after writing and throws if the\n * content does not match — useful for catching write failures on unreliable file systems.\n */\n sanity?: boolean\n}\n\n/**\n * Whether `stored` already holds `source`, comparing on the trimmed text rather than the exact\n * bytes. Surrounding whitespace is what a formatter adds and what editors strip, and neither is a\n * reason to rewrite the file.\n *\n * Both sides are trimmed, so a storage that keeps bytes verbatim settles on the same answer as one\n * that normalizes what it stores. Trimming only `stored` would leave a source with leading\n * whitespace rewritten on every build, since the stored copy keeps the whitespace the comparison\n * has already dropped.\n */\nexport function matchesStored({ stored, source }: { stored: string; source: string }): boolean {\n return stored.trim() === source.trim()\n}\n\n/**\n * Writes `data` to `path`, trimming surrounding whitespace and ending the file with a single newline\n * the way prettier, biome, and oxfmt all do.\n * Skips the write when the trimmed content is empty, or when the file already holds that content.\n * Creates any missing parent directories automatically.\n * When `sanity` is `true`, re-reads the file after writing and throws if the content does not match.\n *\n * @example\n * ```ts\n * await write('./src/Pet.ts', source) // writes and returns the trimmed content plus a newline\n * await write('./src/Pet.ts', source) // null — file unchanged\n * await write('./src/Pet.ts', ' ') // null — empty content skipped\n * ```\n */\nexport async function write(path: string, data: string, options: WriteOptions = {}): Promise<string | null> {\n const trimmed = data.trim()\n if (trimmed === '') return null\n\n const content = `${trimmed}\\n`\n const resolved = resolve(path)\n let stored = options.stored\n\n if (stored === undefined) {\n if (runtime.isBun) {\n const file = Bun.file(resolved)\n stored = (await file.exists()) ? await file.text() : null\n } else {\n try {\n stored = await readFile(resolved, { encoding: 'utf-8' })\n } catch {\n /* file doesn't exist yet */\n stored = null\n }\n }\n }\n if (matchesStored({ stored: stored ?? '', source: trimmed })) return null\n\n if (runtime.isBun) {\n await Bun.write(resolved, content)\n return content\n }\n\n // Creating the directory up front costs a syscall per file, and every file after the first in a\n // directory pays it for nothing. Write first and only fall back when the directory is missing,\n // which also stays correct when something removed it mid-run.\n try {\n await writeFile(resolved, content, { encoding: 'utf-8' })\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error\n\n await mkdir(dirname(resolved), { recursive: true })\n await writeFile(resolved, content, { encoding: 'utf-8' })\n }\n\n if (options.sanity) {\n const savedData = await readFile(resolved, { encoding: 'utf-8' })\n if (savedData !== content) {\n throw new Error(`Sanity check failed for ${path}\\n\\nData[${data.length}]:\\n${data}\\n\\nSaved[${savedData.length}]:\\n${savedData}\\n`)\n }\n return savedData\n }\n\n return content\n}\n\n/**\n * Recursively removes `path`. Silently succeeds when `path` does not exist.\n *\n * @example\n * ```ts\n * await clean('./dist')\n * ```\n */\nexport async function clean(path: string): Promise<void> {\n return rm(path, { recursive: true, force: true })\n}\n\n/**\n * Converts a filesystem path to use POSIX (`/`) separators.\n *\n * Most of the codebase compares and composes paths as strings (prefix matching, joining for\n * import specifiers, splitting on `/`). On POSIX `path.resolve` already returns `/`-separated\n * paths, but on Windows it returns `\\`-separated paths, which breaks every such comparison.\n *\n * Routing every path that crosses a module boundary through `toPosixPath` keeps the rest of the\n * code platform-agnostic. The conversion runs unconditionally so Windows-specific behavior is\n * exercisable from POSIX CI.\n *\n * @example\n * toPosixPath('C:\\\\repo\\\\src\\\\pet.ts') // 'C:/repo/src/pet.ts'\n */\nexport function toPosixPath(filePath: string): string {\n return filePath.replaceAll('\\\\', '/')\n}\n\n/**\n * Strips the file extension from a path or file name.\n * Only removes the last `.ext` segment when the dot is not part of a directory name.\n *\n * @example\n * trimExtName('petStore.ts') // 'petStore'\n * trimExtName('/src/models/pet.ts') // '/src/models/pet'\n * trimExtName('/project.v2/gen/pet.ts') // '/project.v2/gen/pet'\n * trimExtName('noExtension') // 'noExtension'\n */\nexport function trimExtName(text: string): string {\n const dotIndex = text.lastIndexOf('.')\n if (dotIndex > 0 && !text.includes('/', dotIndex)) {\n return text.slice(0, dotIndex)\n }\n return text\n}\n\n/**\n * Resolves to `true` when `path` is `parent` itself or nested inside it. Both sides are resolved\n * to absolute paths first, so relative and `..`-containing inputs compare correctly.\n *\n * Guards a destructive or an out-of-tree operation: before wiping an output directory, check that\n * it does not contain the project root, and before loading a path a caller supplied, check that it\n * did not escape the directory it is allowed to read from.\n *\n * @example\n * isPathInside('./src/gen', '.') // true — nested inside the root\n * isPathInside('.', '.') // true — the same directory counts as inside\n * isPathInside('.', './src/gen') // false — the root is not inside its own output\n * isPathInside('../other', '.') // false — escapes the root\n */\nexport function isPathInside(path: string, parent: string): boolean {\n const resolvedPath = resolve(path)\n const resolvedParent = resolve(parent)\n if (resolvedPath === resolvedParent) {\n return true\n }\n\n const rel = relative(resolvedParent, resolvedPath)\n\n return rel !== '' && !rel.startsWith('..') && !isAbsolute(rel)\n}\n","/** A value that may already be resolved or still pending.\n *\n * @example\n * ```ts\n * function load(id: string): PossiblePromise<string> {\n * return cache.get(id) ?? fetchRemote(id)\n * }\n * ```\n */\nexport type PossiblePromise<T> = Promise<T> | T\n\n/** Returns `true` when `result` is a thenable `Promise`.\n *\n * @example\n * ```ts\n * isPromise(Promise.resolve(1)) // true\n * isPromise(42) // false\n * ```\n */\nexport function isPromise<T>(result: PossiblePromise<T>): result is Promise<T> {\n return result !== null && result !== undefined && typeof (result as Record<string, unknown>)['then'] === 'function'\n}\n\ntype Store<TKey, TValue> = {\n has(key: TKey): boolean\n get(key: TKey): TValue | undefined\n set(key: TKey, value: TValue): unknown\n}\n\n/**\n * Wraps `factory` with a keyed cache backed by the provided store.\n *\n * Pass a `WeakMap` for object keys (results are GC-eligible when the key is\n * collected) or a `Map` for primitive keys. For multi-argument functions,\n * nest two `memoize` calls — the outer keyed by the first argument, the\n * inner (created once per outer miss) keyed by the second.\n *\n * Because the cache is owned by the caller, it can be shared, inspected, or\n * cleared independently of the memoized function.\n *\n * @example Single WeakMap key\n * ```ts\n * const cache = new WeakMap<SchemaNode, Set<string>>()\n * const getRefs = memoize(cache, (node) => collectRefs(node))\n * ```\n *\n * @example Single Map key (primitive)\n * ```ts\n * const cache = new Map<string, Resolver>()\n * const getResolver = memoize(cache, (name) => buildResolver(name))\n * ```\n *\n * @example Two-level (object + primitive)\n * ```ts\n * const outer = new WeakMap<Params[], Map<string, Params[]>>()\n * const fn = memoize(outer, (params) => memoize(new Map(), (key) => transform(params, key)))\n * fn(params)('camelcase')\n * ```\n */\nexport function memoize<TKey, TValue>(store: Store<TKey, TValue>, factory: (key: TKey) => TValue): (key: TKey) => TValue {\n return (key: TKey): TValue => {\n if (store.has(key)) return store.get(key)!\n const value = factory(key)\n store.set(key, value)\n return value\n }\n}\n\ntype ParallelOptions<TItem> = {\n /**\n * Items to work through, handed out in order.\n */\n items: ReadonlyArray<TItem>\n /**\n * How many items may be in flight at once.\n */\n limit: number\n /**\n * Runs once per item, with the item's position so a caller can report progress.\n */\n run(item: TItem, index: number): Promise<void>\n}\n\n/**\n * Runs `run` over every item with at most `limit` in flight. Workers share one iterator, so each\n * takes the next item the moment it frees up instead of waiting for a batch to drain.\n *\n * @example\n * ```ts\n * await inParallel({ items: files, limit: 50, run: (file) => storage.writeItem(file.path, file.source) })\n * ```\n */\nexport async function inParallel<TItem>({ items, limit, run }: ParallelOptions<TItem>): Promise<void> {\n const queue = items.entries()\n\n const worker = async (): Promise<void> => {\n for (const [index, item] of queue) await run(item, index)\n }\n\n await Promise.all(Array.from({ length: Math.min(limit, items.length) }, () => worker()))\n}\n","import { existsSync } from 'node:fs'\nimport path from 'node:path'\nimport { CONFIG_EXTENSIONS, createModuleLoader } from '@internals/shared'\nimport { isPathInside, isPromise } from '@internals/utils'\nimport type { CLIOptions, Config, PossibleConfig, SerializedDiagnostic } from '@kubb/core'\n\nconst CONFIG_FILE_NAMES = CONFIG_EXTENSIONS.map((extension) => `kubb.config${extension}`)\n\n/**\n * Renders serialized diagnostics as a plain-text block for an AI assistant. Each entry\n * keeps the stable `code`, the source pointer, the suggested fix, and the docs link, so\n * the agent can act on the problem rather than parsing a bare message. No ANSI styling,\n * unlike the CLI renderer.\n */\nexport function formatDiagnostics(diagnostics: ReadonlyArray<SerializedDiagnostic>): string {\n return diagnostics.map((diagnostic) => formatDiagnostic(diagnostic)).join('\\n\\n')\n}\n\nfunction formatDiagnostic(diagnostic: SerializedDiagnostic): string {\n const { code, message, location, help, plugin, docsUrl } = diagnostic\n const lines = [plugin ? `[${code}] ${plugin}: ${message}` : `[${code}]: ${message}`]\n\n if (location && 'pointer' in location) {\n lines.push(` at: ${location.pointer}`)\n }\n if (help) {\n lines.push(` fix: ${help}`)\n }\n if (docsUrl) {\n lines.push(` see: ${docsUrl}`)\n }\n\n return lines.join('\\n')\n}\n\ntype NotifyFunction = (type: string, message: string, data?: Record<string, unknown>) => Promise<void>\n\nconst loader = createModuleLoader()\n\n// No cache: the MCP server is long-running, so every tool call re-reads the config to pick up edits.\nfunction loadModule(filePath: string): Promise<unknown> {\n return loader.load(filePath, { default: true })\n}\n\n/**\n * Loads the user's Kubb config and returns it with the directory it was found in.\n *\n * When `configPath` is given it must use an allowed extension and resolve inside\n * the current working directory, otherwise loading throws. When omitted, the\n * known `kubb.config.*` file names are tried in the current directory. Every\n * outcome is reported through `notify` before the function returns or throws.\n */\nexport async function loadUserConfig(configPath: string | undefined, { notify }: { notify: NotifyFunction }): Promise<{ userConfig: Config; cwd: string }> {\n if (configPath) {\n const ext = path.extname(configPath)\n if (!CONFIG_EXTENSIONS.some((extension) => extension === ext)) {\n const msg = `Invalid config file extension \"${ext}\". Allowed: ${CONFIG_EXTENSIONS.join(', ')}`\n await notify('CONFIG_ERROR', msg)\n throw new Error(msg)\n }\n const base = path.resolve(process.cwd())\n const resolvedConfigPath = path.resolve(base, configPath)\n if (!isPathInside(resolvedConfigPath, base)) {\n const msg = 'Invalid config file path: must be within the current working directory'\n await notify('CONFIG_ERROR', msg)\n throw new Error(msg)\n }\n const cwd = path.dirname(resolvedConfigPath)\n try {\n const userConfig = (await loadModule(resolvedConfigPath)) as Config\n await notify('CONFIG_LOADED', `Loaded config from ${resolvedConfigPath}`)\n return { userConfig, cwd }\n } catch (error) {\n const msg = `Failed to load config: ${error instanceof Error ? error.message : String(error)}`\n await notify('CONFIG_ERROR', msg)\n throw new Error(msg)\n }\n }\n\n const cwd = process.cwd()\n\n for (const configFileName of CONFIG_FILE_NAMES) {\n const configFilePath = path.resolve(process.cwd(), configFileName)\n if (!existsSync(configFilePath)) continue\n try {\n const userConfig = (await loadModule(configFilePath)) as Config\n await notify('CONFIG_LOADED', `Loaded ${configFileName} from current directory`)\n return { userConfig, cwd }\n } catch (err) {\n await notify('CONFIG_ERROR', `Failed to load ${configFileName}: ${err instanceof Error ? err.message : String(err)}`)\n }\n }\n\n await notify('CONFIG_ERROR', 'No config file found')\n throw new Error(`No config file found. Please provide a config path or create one of: ${CONFIG_FILE_NAMES.join(', ')}`)\n}\n\n/**\n * Inputs forwarded to a config when it is defined as a function.\n */\ntype ResolveUserConfigOptions = {\n /**\n * Path of the loaded config, passed through to the config function as `config`.\n */\n configPath?: string\n /**\n * Log level passed through to the config function.\n */\n logLevel?: CLIOptions['logLevel']\n}\n\n/**\n * Normalizes a possible config into a single resolved `Config`.\n *\n * Calls the config when it is a function, awaits it when it is a promise, and\n * picks the first entry when it resolves to an array.\n */\nexport async function resolveUserConfig(config: PossibleConfig<CLIOptions>, options: ResolveUserConfigOptions): Promise<Config> {\n const result = typeof config === 'function' ? config({ logLevel: options.logLevel, config: options.configPath }) : config\n const resolved = isPromise(result) ? await result : result\n\n return (Array.isArray(resolved) ? resolved[0] : resolved) as Config\n}\n","import path from 'node:path'\nimport { CONFIG_EXTENSIONS } from '@internals/shared'\nimport { type Config, createKubb, type Diagnostic, Diagnostics, type KubbHooks, Hookable } from '@kubb/core'\nimport { defineTool } from 'tmcp/tool'\nimport { tool } from 'tmcp/utils'\nimport * as z from 'zod/mini'\nimport { formatDiagnostics, loadUserConfig, resolveUserConfig } from '../utils.ts'\n\nconst generateSchema = z.object({\n config: z.optional(\n z\n .string()\n .check(\n z.minLength(1),\n z.describe(`Path to kubb.config file (supports ${CONFIG_EXTENSIONS.join(', ')}). If not provided, will look for kubb.config.* in current directory`),\n ),\n ),\n input: z.optional(z.string().check(z.minLength(1), z.describe('Path to OpenAPI/Swagger spec file (overrides config)'))),\n output: z.optional(z.string().check(z.minLength(1), z.describe('Output directory path (overrides config)'))),\n logLevel: z._default(z.enum(['silent', 'info', 'verbose']).check(z.describe('Log level for build output')), 'info'),\n})\n\nexport const generateTool = defineTool(\n {\n name: 'generate',\n description: 'Generate OpenAPI spec helpers using Kubb configuration',\n schema: generateSchema,\n },\n async function generate(schema: z.input<typeof generateSchema>) {\n const { config: configPath, input, output, logLevel } = schema\n\n try {\n const hooks = new Hookable<KubbHooks>()\n const messages: Array<string> = []\n\n const notify = async (type: string, message: string, data?: Record<string, unknown>) => {\n messages.push(data ? `${type}: ${message} ${JSON.stringify(data)}` : `${type}: ${message}`)\n }\n\n hooks.hook('kubb:info', async ({ message }: { message: string }) => {\n await notify('INFO', message)\n })\n\n hooks.hook('kubb:success', async ({ message }: { message: string }) => {\n await notify('SUCCESS', message)\n })\n\n hooks.hook('kubb:error', async ({ error }: { error: Error }) => {\n await notify('ERROR', error.message)\n })\n\n hooks.hook('kubb:warn', async ({ message }: { message: string }) => {\n await notify('WARN', message)\n })\n\n hooks.hook('kubb:diagnostic', async ({ diagnostic }: { diagnostic: Diagnostic }) => {\n await notify('DIAGNOSTIC', diagnostic.message, Diagnostics.serialize(diagnostic))\n })\n\n hooks.hook('kubb:plugin:start', async ({ plugin }) => {\n await notify('PLUGIN_START', `Plugin starting: ${plugin.name}`)\n })\n\n hooks.hook('kubb:plugin:end', async ({ plugin, duration }) => {\n await notify('PLUGIN_END', `Plugin finished: ${plugin.name}`, { duration })\n })\n\n hooks.hook('kubb:files:processing:start', async () => {\n await notify('FILES_START', 'Starting file processing')\n })\n\n hooks.hook('kubb:files:processing:update', async ({ files }: { files: Array<{ file: { name: string } }> }) => {\n await notify('FILES_UPDATE', `Processing ${files.length} files`)\n })\n\n hooks.hook('kubb:files:processing:end', async () => {\n await notify('FILES_END', 'File processing complete')\n })\n\n hooks.hook('kubb:generation:start', async () => {\n await notify('GENERATION_START', 'Generation started')\n })\n\n hooks.hook('kubb:setup:start', async () => {\n await notify('SETUP_START', 'Setting up Kubb')\n })\n\n hooks.hook('kubb:setup:end', async () => {\n await notify('SETUP_END', 'Kubb setup complete')\n await notify('BUILD_START', 'Starting build')\n })\n\n hooks.hook('kubb:generation:end', async () => {\n await notify('GENERATION_END', 'Generation ended')\n })\n\n let userConfig: Config\n let cwd: string\n\n try {\n const configResult = await loadUserConfig(configPath, { notify })\n userConfig = configResult.userConfig\n cwd = configResult.cwd\n\n if (Array.isArray(userConfig)) {\n throw new Error('Array type in kubb.config.ts is not supported in this tool. Please provide a single configuration object.')\n }\n\n userConfig = await resolveUserConfig(userConfig, {\n configPath,\n logLevel,\n })\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error)\n return tool.error(errorMessage)\n }\n\n const config: Config = {\n ...userConfig,\n root: path.resolve(cwd, userConfig.root ?? '.'),\n input: input ?? userConfig.input,\n output: output\n ? {\n ...userConfig.output,\n path: output,\n }\n : userConfig.output,\n }\n\n await notify('CONFIG_READY', 'Configuration ready')\n\n const kubb = createKubb(config, { hooks })\n const result = await kubb.generate()\n await notify('BUILD_END', `Build complete - Generated ${result.files.length} files`)\n\n const problems = result.diagnostics.filter(Diagnostics.isProblem)\n const errors = problems.filter((diagnostic) => diagnostic.severity === 'error')\n if (errors.length > 0) {\n await notify('BUILD_FAILED', `Build failed with ${errors.length} diagnostic(s)`)\n\n const serialized = problems.map((diagnostic) => Diagnostics.serialize(diagnostic))\n return tool.error(`Build failed:\\n${formatDiagnostics(serialized)}\\n\\n\\`\\`\\`json\\n${JSON.stringify(serialized, null, 2)}\\n\\`\\`\\``)\n }\n\n await notify('BUILD_SUCCESS', `Build completed successfully - Generated ${result.files.length} files`)\n\n return tool.text(`Build completed successfully!\\n\\nGenerated ${result.files.length} files\\n\\n${messages.join('\\n')}`)\n } catch (caughtError) {\n const serialized = Diagnostics.serialize(Diagnostics.from(caughtError))\n return tool.error(`Build error:\\n${formatDiagnostics([serialized])}\\n\\n\\`\\`\\`json\\n${JSON.stringify(serialized, null, 2)}\\n\\`\\`\\``)\n }\n },\n)\n","import fs from 'node:fs'\nimport path from 'node:path'\nimport process from 'node:process'\nimport { generateConfigFile, KUBB_CONFIG_FILENAME, resolvePlugins } from '@internals/shared'\nimport { defineTool } from 'tmcp/tool'\nimport { tool } from 'tmcp/utils'\nimport * as z from 'zod/mini'\n\nconst initSchema = z.object({\n input: z.optional(z.string().check(z.minLength(1), z.describe('Path to OpenAPI spec (default: ./openapi.yaml)'))),\n output: z.optional(z.string().check(z.minLength(1), z.describe('Output directory (default: ./src/gen)'))),\n plugins: z.optional(z.string().check(z.minLength(1), z.describe('Comma-separated list of plugins: plugin-ts,plugin-zod,...'))),\n})\n\nexport const initTool = defineTool(\n {\n name: 'init',\n description: 'Scaffold a kubb.config.ts in the current directory (non-interactive). Does not install packages.',\n schema: initSchema,\n },\n async ({ input = './openapi.yaml', output = './src/gen', plugins }) => {\n const selected = resolvePlugins(plugins)\n const content = generateConfigFile({ selectedPlugins: selected, inputPath: input, outputPath: output })\n const dest = path.join(process.cwd(), KUBB_CONFIG_FILENAME)\n if (fs.existsSync(dest)) {\n return tool.error(`${KUBB_CONFIG_FILENAME} already exists at ${dest}. Delete it first before running init again.`)\n }\n fs.writeFileSync(dest, content, 'utf-8')\n const packageList = ['kubb', ...selected.map((p) => p.packageName)].join(' ')\n return tool.text(`Created kubb.config.ts\\n\\nInstall packages:\\n npm install ${packageList}\\n\\nThen run:\\n npx kubb generate`)\n },\n)\n","import { adapterOas } from '@kubb/adapter-oas'\nimport { Diagnostics } from '@kubb/core'\nimport { defineTool } from 'tmcp/tool'\nimport { tool } from 'tmcp/utils'\nimport * as z from 'zod/mini'\nimport { formatDiagnostics } from '../utils.ts'\n\nconst validateSchema = z.object({\n input: z.string().check(z.minLength(1), z.describe('Path or URL to the OpenAPI/Swagger specification')),\n})\n\nexport const validateTool = defineTool(\n {\n name: 'validate',\n description: 'Validate an OpenAPI/Swagger specification file or URL',\n schema: validateSchema,\n },\n async ({ input }) => {\n try {\n await adapterOas().validate(input, { throwOnError: true })\n return tool.text(`Validation successful: ${input}`)\n } catch (err) {\n const serialized = Diagnostics.serialize(Diagnostics.from(err))\n return tool.error(`Validation failed:\\n${formatDiagnostics([serialized])}\\n\\n\\`\\`\\`json\\n${JSON.stringify(serialized, null, 2)}\\n\\`\\`\\``)\n }\n },\n)\n","import { StdioTransport } from '@tmcp/transport-stdio'\nimport { McpServer } from 'tmcp'\nimport { JsonSchemaAdapter } from 'tmcp/adapter'\nimport { en } from 'zod/locales'\nimport * as z from 'zod/mini'\nimport { version } from '../package.json'\nimport { generateTool } from './tools/generate.ts'\nimport { initTool } from './tools/init.ts'\nimport { validateTool } from './tools/validate.ts'\n\n/**\n * Describes each tool's input to MCP clients. `@tmcp/adapter-zod` imports the full `zod` build, so\n * this converts with Zod Mini instead. `io: 'input'` keeps fields with a default optional.\n */\nclass ZodMiniJsonSchemaAdapter extends JsonSchemaAdapter<z.ZodMiniType> {\n async toJsonSchema(schema: z.ZodMiniType) {\n // Zod's type also allows draft-4's boolean `exclusiveMaximum`, which the draft-7 target never emits.\n return z.toJSONSchema(schema, { target: 'draft-7', io: 'input' }) as Awaited<ReturnType<JsonSchemaAdapter<z.ZodMiniType>['toJsonSchema']>>\n }\n}\n\n/**\n * Builds the Kubb MCP server with the generate, validate, and init tools registered.\n *\n * @example\n * `const server = createMcpServer()`\n */\nexport function createMcpServer() {\n // Zod Mini ships without a locale, so validation errors would only say \"Invalid input\".\n z.config(en())\n const server = new McpServer({ name: 'Kubb', version }, { adapter: new ZodMiniJsonSchemaAdapter(), capabilities: { tools: {} } })\n server.tools([generateTool, validateTool, initTool])\n return server\n}\n\n/**\n * Starts the Kubb MCP server over stdio, the transport every local MCP client\n * (Claude, Copilot, editors) uses when it launches the server as a subprocess.\n */\nexport function startServer(): void {\n new StdioTransport(createMcpServer()).listen()\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;ACEA,MAAa,uBAAuB;;AAGpC,MAAa,oBAAoB;CAAC;CAAO;CAAQ;CAAQ;CAAO;CAAQ;AAAM;AAU9E,MAAa,mBAAwC;CACnD;EACE,OAAO;EACP,OAAO;EACP,MAAM;EACN,aAAa;EACb,YAAY;EACZ,UAAU;CACZ;CACA;EACE,OAAO;EACP,OAAO;EACP,aAAa;EACb,YAAY;EACZ,UAAU;CACZ;CACA;EACE,OAAO;EACP,OAAO;EACP,aAAa;EACb,YAAY;EACZ,UAAU;CACZ;CACA;EACE,OAAO;EACP,OAAO;EACP,aAAa;EACb,YAAY;EACZ,UAAU;CACZ;CACA;EACE,OAAO;EACP,OAAO;EACP,aAAa;EACb,YAAY;EACZ,UAAU;CACZ;CACA;EACE,OAAO;EACP,OAAO;EACP,aAAa;EACb,YAAY;EACZ,UAAU;CACZ;CACA;EACE,OAAO;EACP,OAAO;EACP,aAAa;E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MAAM,EAAE,UAAU,CAAC,GAAG,EAAE,SAAS,kDAAkD,CAAC,EACxG,CAAC;AAED,MAAa,eAAe,WAC1B;CACE,MAAM;CACN,aAAa;CACb,QAAQ;AACV,GACA,OAAO,EAAE,YAAY;CACnB,IAAI;EACF,MAAM,WAAW,CAAC,CAAC,SAAS,OAAO,EAAE,cAAc,KAAK,CAAC;EACzD,OAAO,KAAK,KAAK,0BAA0B,OAAO;CACpD,SAAS,KAAK;EACZ,MAAM,aAAa,YAAY,UAAU,YAAY,KAAK,GAAG,CAAC;EAC9D,OAAO,KAAK,MAAM,uBAAuB,kBAAkB,CAAC,UAAU,CAAC,EAAE,kBAAkB,KAAK,UAAU,YAAY,MAAM,CAAC,EAAE,SAAS;CAC1I;AACF,CACF;;;;;;;ACZA,IAAM,2BAAN,cAAuC,kBAAiC;CACtE,MAAM,aAAa,QAAuB;EAExC,OAAO,EAAE,aAAa,QAAQ;GAAE,QAAQ;GAAW,IAAI;EAAQ,CAAC;CAClE;AACF;;;;;;;AAQA,SAAgB,kBAAkB;CAEhC,EAAE,OAAO,GAAG,CAAC;CACb,MAAM,SAAS,IAAI,UAAU;EAAE,MAAM;EAAQ;CAAQ,GAAG;EAAE,SAAS,IAAI,yBAAyB;EAAG,cAAc,EAAE,OAAO,CAAC,EAAE;CAAE,CAAC;CAChI,OAAO,MAAM;EAAC;EAAc;EAAc;CAAQ,CAAC;CACnD,OAAO;AACT;;;;;AAMA,SAAgB,cAAoB;CAClC,IAAI,eAAe,gBAAgB,CAAC,CAAC,CAAC,OAAO;AAC/C"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kubb/mcp",
|
|
3
|
-
"version": "5.6.
|
|
3
|
+
"version": "5.6.3",
|
|
4
4
|
"description": "MCP server for Kubb. Exposes code generation as a tool over the Model Context Protocol so AI assistants like Claude, Cursor, and other MCP-compatible clients can generate TypeScript types, clients, and more.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"ai",
|
|
@@ -62,21 +62,20 @@
|
|
|
62
62
|
"registry": "https://registry.npmjs.org/"
|
|
63
63
|
},
|
|
64
64
|
"dependencies": {
|
|
65
|
-
"@kubb/adapter-oas": "5.6.
|
|
66
|
-
"@kubb/core": "5.6.
|
|
67
|
-
"@tmcp/adapter-valibot": "^0.1.6",
|
|
65
|
+
"@kubb/adapter-oas": "5.6.3",
|
|
66
|
+
"@kubb/core": "5.6.3",
|
|
68
67
|
"@tmcp/transport-stdio": "^0.5.0",
|
|
69
68
|
"jiti": "^2.7.0",
|
|
70
69
|
"tmcp": "^1.20.0",
|
|
71
|
-
"
|
|
70
|
+
"zod": "^4.6.5"
|
|
72
71
|
},
|
|
73
72
|
"devDependencies": {
|
|
74
73
|
"@internals/shared": "0.0.1",
|
|
75
74
|
"@internals/utils": "0.0.1",
|
|
76
|
-
"@kubb/renderer-jsx": "5.6.
|
|
75
|
+
"@kubb/renderer-jsx": "5.6.3"
|
|
77
76
|
},
|
|
78
77
|
"peerDependencies": {
|
|
79
|
-
"@kubb/renderer-jsx": "5.6.
|
|
78
|
+
"@kubb/renderer-jsx": "5.6.3"
|
|
80
79
|
},
|
|
81
80
|
"engines": {
|
|
82
81
|
"node": ">=22"
|