webmcp-codegen 0.3.1 → 0.3.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/cli.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/cli.ts","../src/wire.ts"],"sourcesContent":["#!/usr/bin/env node\n\n/**\n * The webmcp-codegen CLI.\n *\n * The path we optimize for is the zero-everything first run:\n *\n * npx webmcp-codegen generate\n *\n * No install, no config file, no flags. The CLI finds your API spec, finds\n * the package that is your web app, writes working tools into it, wires the\n * registration into your app's entry file, and tells you how to see it all\n * working. Choices we had to ask for are remembered in .webmcp-codegen.json\n * so we never ask twice.\n *\n * When you outgrow the defaults:\n *\n * --spec/--out quick overrides without a config file\n * init writes codegen.config.mjs for full control (needs the\n * package installed, since the config imports from it)\n *\n * Plus the flags you'd expect on a codegen tool: --dry-run to preview,\n * --watch to re-run on change, --skip-audit to bypass the safety report,\n * --force to write through audit errors, --config to point at a config\n * file somewhere else.\n */\n\nimport { existsSync, watch } from \"node:fs\";\nimport { writeFile } from \"node:fs/promises\";\nimport { basename, join, relative } from \"node:path\";\nimport { createInterface } from \"node:readline/promises\";\nimport { parseArgs } from \"node:util\";\nimport { CONFIG_FILE_NAMES, loadConfig } from \"./config.js\";\nimport { loadDataFile, saveDataFile } from \"./data-file.js\";\nimport { findSpecs } from \"./detect.js\";\nimport { js } from \"./generators/js.js\";\nimport { type GenerateResult, runGenerate } from \"./pipeline.js\";\nimport { type GenerateFlags, resolveSetup, type Setup } from \"./setup.js\";\nimport { openapi } from \"./sources/openapi.js\";\nimport type { CodegenConfig, ReviewedTool } from \"./types.js\";\nimport { applyWiring, planWiring, type WirePlan } from \"./wire.js\";\n\nconst HELP = `webmcp-codegen: generate WebMCP tools from the API contracts you already have\n\nFastest start (no install, no config):\n npx webmcp-codegen generate --dry-run Detect your spec, preview the tools\n npx webmcp-codegen generate Write the tool files, wire them up\n\nCommands:\n init Write a codegen.config.mjs for full control\n generate Generate (or update) your WebMCP tools\n generate --watch Re-generate when files change\n dev Open the tools dashboard (list, edit, try tools)\n\nFlags for generate:\n --spec PATH Which OpenAPI spec to use (auto-detected when omitted)\n --out DIR Where the tool files go (default: your web app's src/webmcp)\n --dry-run Preview what would be written, write nothing\n --skip-audit Skip the safety report\n --force Write files even when the audit reports errors\n --config PATH Use a config file at PATH\n\nFlags for dev:\n --port N Dashboard port (default: 4700)\n`;\n\nconst CONFIG_FILE = \"codegen.config.mjs\";\n\n/** How many tools to list before folding the rest into a count. */\nconst MAX_LISTED_TOOLS = 15;\n\nasync function main(): Promise<number> {\n const { positionals, values } = parseArgs({\n allowPositionals: true,\n options: {\n \"dry-run\": { type: \"boolean\", default: false },\n \"skip-audit\": { type: \"boolean\", default: false },\n force: { type: \"boolean\", default: false },\n watch: { type: \"boolean\", default: false },\n config: { type: \"string\" },\n spec: { type: \"string\" },\n out: { type: \"string\" },\n port: { type: \"string\" },\n help: { type: \"boolean\", default: false },\n },\n });\n\n const command = positionals[0];\n if (values.help || !command) {\n console.log(HELP);\n return 0;\n }\n\n switch (command) {\n case \"init\":\n return init();\n case \"dev\":\n return dev(Number.parseInt(values.port ?? \"4700\", 10));\n case \"generate\":\n return generate({\n dryRun: values[\"dry-run\"],\n skipAudit: values[\"skip-audit\"],\n force: values.force,\n watch: values.watch,\n configPath: values.config,\n spec: values.spec,\n out: values.out,\n });\n default:\n console.error(`Unknown command \"${command}\".\\n`);\n console.log(HELP);\n return 1;\n }\n}\n\n/** Detect the project's API spec and write a starter config. */\nasync function init(): Promise<number> {\n const cwd = process.cwd();\n const configPath = join(cwd, CONFIG_FILE);\n\n if (existsSync(configPath)) {\n console.error(`${CONFIG_FILE} already exists. Nothing to do.`);\n return 1;\n }\n\n const specs = await findSpecs(cwd);\n const specPath = specs.length > 0 ? `./${specs[0]}` : \"./openapi.yaml\";\n\n await writeFile(\n configPath,\n `import { defineConfig } from \"webmcp-codegen\";\nimport { openapi } from \"webmcp-codegen/sources\";\nimport { js } from \"webmcp-codegen/generators\";\n\nexport default defineConfig({\n sources: [openapi({ spec: \"${specPath}\" })],\n generate: [js({ outDir: \"./src/webmcp\" })],\n safety: {\n // Extra field names to treat as PII, on top of the built-in list:\n // piiFields: [\"internalId\"],\n // Tools to skip entirely (matched against name and route):\n // exclude: [\"internal\"],\n },\n});\n`,\n );\n\n // The config imports from the package, so keeping it means installing it.\n console.log(\"Installed the package? A config file needs it:\");\n console.log(\" npm install -D webmcp-codegen\\n\");\n if (specs.length > 0) {\n console.log(`Found ${specs[0]}. Wrote ${CONFIG_FILE}.`);\n console.log(\"\\nNext: npx webmcp-codegen generate --dry-run\");\n } else {\n console.log(`No OpenAPI spec found, so ${CONFIG_FILE} points at ./openapi.yaml.`);\n console.log(\"Edit the `spec` path to point at your spec, then run:\");\n console.log(\"\\n npx webmcp-codegen generate --dry-run\");\n }\n return 0;\n}\n\nasync function generate(flags: GenerateFlags): Promise<number> {\n const cwd = process.cwd();\n\n if (flags.watch) {\n // Watch mode never exits; it re-runs generate on every relevant change.\n // Wiring is idempotent, so it is part of every pass and quietly no-ops\n // after the first.\n await watchLoop(cwd, flags);\n return 0;\n }\n\n const result = await runOnce(cwd, flags);\n return result.blocked ? 1 : 0;\n}\n\n/** One generate pass: resolve setup, run the pipeline, wire, report. */\nasync function runOnce(cwd: string, flags: GenerateFlags): Promise<GenerateResult> {\n const setup = await resolveSetup(cwd, flags);\n const data = await loadDataFile(cwd);\n const result = await runGenerate(setup.config, {\n cwd,\n dryRun: flags.dryRun,\n skipAudit: flags.skipAudit,\n force: flags.force,\n overrides: data.overrides,\n });\n\n // Registration wiring: additive, idempotent, and only for real runs.\n let wiring: WirePlan | null = null;\n if (!result.blocked && setup.app) {\n const outDir = findOutDir(setup.config);\n if (outDir) {\n wiring = await planWiring(cwd, setup.app, outDir);\n if (wiring && wiring.edits.length > 0 && !flags.dryRun && result.wrote) {\n await applyWiring(wiring);\n }\n }\n }\n\n // Remember the choices detection made, so the next run never re-asks.\n if (!setup.fromConfigFile && !flags.dryRun && result.wrote) {\n await saveDataFile(cwd, setup.remember);\n }\n\n printReport(result, flags, setup, wiring, cwd);\n return result;\n}\n\n/** Pull the outDir back out of the resolved config (there is one generator). */\nfunction findOutDir(config: CodegenConfig): string | undefined {\n return config.generate[0]?.outDir;\n}\n\n/**\n * The report is the product's voice: plain language, no jargon, one line per\n * file, findings grouped by severity, and a summary that says what happens\n * next — including the one command's worth of \"try it\" at the end.\n */\nfunction printReport(\n result: GenerateResult,\n flags: GenerateFlags,\n setup: Setup,\n wiring: WirePlan | null,\n cwd: string,\n): void {\n const { tools, skipped, findings, files, notes, blocked } = result;\n\n console.log(`\\nwebmcp-codegen (${setup.label}): ${tools.length} tool(s)`);\n\n for (const note of notes) {\n console.log(`\\n note: ${note}`);\n }\n\n if (skipped.length > 0) {\n console.log(`\\n ${skipped.length} endpoint(s) skipped:`);\n for (const entry of skipped) {\n console.log(` ${entry.ref}: ${entry.reason}`);\n }\n }\n\n console.log(\"\");\n const listed = tools.slice(0, MAX_LISTED_TOOLS);\n for (const tool of listed) {\n const state = tool.enabledByDefault ? \"\" : \" starts disabled\";\n console.log(` ${tool.name} [${tool.sideEffect}]${state} ← ${tool.source.ref}`);\n }\n if (tools.length > listed.length) {\n console.log(` …and ${tools.length - listed.length} more`);\n }\n\n if (findings.length > 0) {\n console.log(\"\");\n for (const finding of findings) {\n const icon = finding.level === \"error\" ? \"✖\" : \"⚠\";\n const where = finding.tool ? ` (${finding.tool})` : \"\";\n console.log(` ${icon} ${finding.message}${where}`);\n }\n }\n\n if (files.length > 0) {\n console.log(\"\");\n for (const file of files) {\n if (file.action === \"unchanged\" && !file.conflict) continue;\n const shown = file.conflict\n ? `conflict → wrote ${relative(cwd, file.conflict)}`\n : file.action;\n console.log(` ${shown}: ${relative(cwd, file.path)}`);\n }\n }\n\n if (wiring) {\n if (wiring.alreadyWired) {\n console.log(\"\\n registration: already wired into your app\");\n } else if (wiring.edits.length > 0) {\n console.log(flags.dryRun ? \"\\n registration (would do):\" : \"\\n registration:\");\n for (const edit of wiring.edits) {\n console.log(` ${edit.summary}`);\n }\n if (!flags.dryRun) {\n console.log(\" undo: delete the added lines (nothing else was touched)\");\n }\n }\n } else if (!blocked && setup.app) {\n console.log(\"\\n registration: could not find your app's entry file, so add this by hand:\");\n console.log(' import { registerAllTools } from \"<path-to>/src/webmcp\";');\n console.log(\" void registerAllTools();\");\n }\n\n if (blocked) {\n console.log(\n \"\\nGeneration blocked by audit errors. Fix them, or re-run with --force to write anyway.\",\n );\n return;\n }\n if (flags.dryRun) {\n console.log(\"\\nDry run: nothing written. Re-run without --dry-run to write these files.\");\n return;\n }\n\n printNextSteps(result);\n}\n\n/**\n * The parting message. The read tools already work; the mutations are one\n * uncomment away; and we end with the single most convincing thing a new\n * user can do: watch an agent call their app.\n */\nfunction printNextSteps(result: GenerateResult): void {\n const enabled = result.tools.filter((tool) => tool.enabledByDefault);\n const disabled = result.tools.filter((tool) => !tool.enabledByDefault);\n\n const parts: string[] = [];\n if (enabled.length > 0) parts.push(`${enabled.length} read tool(s) work out of the box`);\n if (disabled.length > 0) {\n parts.push(`${disabled.length} tool(s) start disabled (open the file and uncomment to enable)`);\n }\n console.log(`\\nDone. ${parts.join(\"; \")}.`);\n\n const suggestion = pickSuggestedTool(result.tools);\n console.log(\"\\nTry it:\");\n console.log(\" 1. Start your app and open it in Chrome.\");\n console.log(\" 2. Turn on chrome://flags/#enable-webmcp-testing and reload the page.\");\n if (suggestion) {\n console.log(` 3. Ask the agent: \"${suggestion}\"`);\n } else {\n console.log(\" 3. Ask the agent to use one of your tools.\");\n }\n}\n\n/**\n * The example request in the \"try it\" line. Pick an enabled read tool —\n * preferably one whose name sounds like listing or looking something up —\n * and phrase it the way a user would say it, from the spec's own description.\n */\nfunction pickSuggestedTool(tools: ReviewedTool[]): string | undefined {\n const reads = tools.filter((tool) => tool.enabledByDefault && tool.endpointRole === \"endpoint\");\n if (reads.length === 0) return undefined;\n const tool =\n reads.find((candidate) => /^(list|get|search|find|fetch|recent)-/.test(candidate.name)) ??\n reads[0];\n if (!tool) return undefined;\n\n const description = tool.description.trim().replace(/\\.$/, \"\");\n // A template description (\"GET /v1/trips\") would read as jargon; fall back\n // to the tool name in words (\"list trips\").\n const looksTemplated = /^(GET|POST|PUT|PATCH|DELETE)\\s/.test(description);\n const phrase = looksTemplated\n ? tool.name.replace(/-/g, \" \")\n : description.charAt(0).toLowerCase() + description.slice(1);\n return phrase;\n}\n\n/**\n * The tools dashboard: a local control panel for what was generated.\n * Runs until Ctrl+C; nothing is written to the app, ever.\n */\nasync function dev(port: number): Promise<number> {\n const { startDevServer } = await import(\"./dev/server.js\");\n const server = await startDevServer({ cwd: process.cwd(), port });\n console.log(`\\nwebmcp-codegen dashboard: http://localhost:${port}`);\n console.log(\"List, describe, enable, and try your tools. Ctrl+C to stop.\\n\");\n\n await new Promise<void>((resolveExit) => {\n process.on(\"SIGINT\", () => {\n server.close();\n resolveExit();\n });\n });\n return 0;\n}\n\n/**\n * Re-run generate when anything relevant changes. Node's recursive watcher\n * covers Linux/macOS/Windows on Node 20+, which is our engine floor anyway.\n */\nasync function watchLoop(cwd: string, flags: GenerateFlags): Promise<void> {\n await runOnce(cwd, { ...flags, dryRun: false });\n console.log(\"\\nWatching for changes… (Ctrl+C to stop)\");\n\n let timer: NodeJS.Timeout | undefined;\n watch(cwd, { recursive: true }, (_event, filename) => {\n if (!filename) return;\n // Only source-ish changes are worth regenerating for. Never react to our\n // own outputs (generated files, the data file) or watch mode loops.\n if (/node_modules|\\.git|\\/dist|\\/src\\/webmcp|\\.webmcp-codegen\\.json/.test(filename)) return;\n if (!/\\.(ya?ml|json|ts|tsx|mts|mjs)$/.test(filename)) return;\n clearTimeout(timer);\n timer = setTimeout(() => {\n runOnce(cwd, { ...flags, dryRun: false }).catch((error: unknown) => {\n console.error(error instanceof Error ? error.message : error);\n });\n }, 300);\n });\n}\n\nmain()\n .then((code) => process.exit(code))\n .catch((error: unknown) => {\n console.error(error instanceof Error ? error.message : error);\n process.exit(1);\n });\n","/**\n * Registration wiring: making the app actually register its tools.\n *\n * Generated files do nothing until something calls registerAllTools() once at\n * startup. Rather than telling the developer to go do that, we do it for\n * them — under strict rules, because this is the one place we edit *their*\n * files instead of ours:\n *\n * 1. Edits are additive only. We insert lines; we never change or remove\n * existing ones.\n * 2. Idempotent. If the wiring is already there, we do nothing.\n * 3. Honest. Every edit is reported with exact paths and how to undo it.\n * 4. When we cannot find the entry point with confidence, we do not guess:\n * we print the two lines and where they go, and leave it to the human.\n */\n\nimport { readFile, writeFile } from \"node:fs/promises\";\nimport { dirname, join, relative } from \"node:path\";\nimport type { WebApp } from \"./detect-app.js\";\n\nexport interface WireEdit {\n /** Absolute path of the file to create or modify. */\n path: string;\n action: \"create\" | \"modify\";\n /** The full new contents (for modify: the existing contents plus our lines). */\n contents: string;\n /** One human sentence per edit, for the report. */\n summary: string;\n}\n\nexport interface WirePlan {\n edits: WireEdit[];\n /** Set when we already found the wiring in place. */\n alreadyWired?: boolean;\n}\n\n/**\n * Compute the wiring edits for the detected app, or null when we cannot\n * locate the entry point with confidence (the CLI then prints manual\n * instructions instead).\n */\nexport async function planWiring(\n cwd: string,\n app: WebApp,\n outDir: string,\n): Promise<WirePlan | null> {\n switch (app.framework) {\n case \"next\":\n return planNextWiring(cwd, app, outDir);\n case \"vite-react\":\n return planViteWiring(cwd, app, outDir);\n default:\n // Nuxt/SvelteKit/unknown: we know where the tools go but not where the\n // app boots. Print instructions rather than guess-edit an entry file.\n return null;\n }\n}\n\n/** Apply a plan. Kept trivial on purpose: the plan already did the thinking. */\nexport async function applyWiring(plan: WirePlan): Promise<void> {\n for (const edit of plan.edits) {\n await writeFile(edit.path, edit.contents, \"utf8\");\n }\n}\n\n/* ── Next.js (app router) ──────────────────────────────────────────────── */\n\n/**\n * Next needs the registration to run on the client, so we generate a tiny\n * \"use client\" component next to the tools and mount it in the root layout:\n *\n * import { WebMCPRegister } from \"../webmcp/register\"; ← added\n * ...\n * <body>\n * <WebMCPRegister /> ← added\n * {children}\n */\nasync function planNextWiring(cwd: string, app: WebApp, outDir: string): Promise<WirePlan | null> {\n const layoutCandidates = [\n join(cwd, app.dir, \"src/app/layout.tsx\"),\n join(cwd, app.dir, \"src/app/layout.jsx\"),\n join(cwd, app.dir, \"app/layout.tsx\"),\n join(cwd, app.dir, \"app/layout.jsx\"),\n ];\n const layoutPath = await firstExisting(layoutCandidates);\n if (!layoutPath) return null;\n\n const registerPath = join(cwd, outDir, \"register.tsx\");\n const layout = await readFile(layoutPath, \"utf8\");\n if (layout.includes(\"WebMCPRegister\")) return { edits: [], alreadyWired: true };\n\n // Import path from the layout's directory to the register component.\n const importPath = withoutExtension(relative(dirname(layoutPath), registerPath));\n\n const edits: WireEdit[] = [\n {\n path: registerPath,\n action: \"create\",\n contents: nextRegisterComponent(),\n summary: `created ${relative(cwd, registerPath)} (a client component that registers your tools on page load)`,\n },\n ];\n\n const withImport = insertAfterLastImport(\n layout,\n `import { WebMCPRegister } from \"${importPath}\";`,\n );\n if (!withImport) return null;\n // Mount right after <body ...>, each element on its own line.\n const withComponent = withImport.replace(\n /<body([^>]*)>\\s*/,\n \"<body$1>\\n <WebMCPRegister />\\n \",\n );\n if (withComponent === withImport) return null; // No <body> tag found; do not guess.\n\n edits.push({\n path: layoutPath,\n action: \"modify\",\n contents: withComponent,\n summary: `added 2 lines to ${relative(cwd, layoutPath)} (an import and <WebMCPRegister /> inside <body>)`,\n });\n return { edits };\n}\n\nfunction nextRegisterComponent(): string {\n return `\"use client\";\n\nimport { useEffect } from \"react\";\nimport { registerAllTools } from \"./index\";\n\n/**\n * Registers the generated WebMCP tools once, on page load.\n * Generated by webmcp-codegen. Safe to move; keep it mounted near the root.\n */\nexport function WebMCPRegister() {\n useEffect(() => {\n void registerAllTools();\n }, []);\n return null;\n}\n`;\n}\n\n/* ── Vite + React (SPAs) ───────────────────────────────────────────────── */\n\n/**\n * A Vite app boots in main.tsx, so wiring is two added lines there:\n *\n * import { registerAllTools } from \"./webmcp\"; ← added\n * void registerAllTools(); ← added\n */\nasync function planViteWiring(cwd: string, app: WebApp, outDir: string): Promise<WirePlan | null> {\n const entryCandidates = [\n join(cwd, app.dir, \"src/main.tsx\"),\n join(cwd, app.dir, \"src/main.jsx\"),\n join(cwd, app.dir, \"src/index.tsx\"),\n join(cwd, app.dir, \"src/index.jsx\"),\n ];\n const entryPath = await firstExisting(entryCandidates);\n if (!entryPath) return null;\n\n const entry = await readFile(entryPath, \"utf8\");\n if (entry.includes(\"registerAllTools\")) return { edits: [], alreadyWired: true };\n\n const importPath = withoutExtension(relative(dirname(entryPath), join(cwd, outDir, \"index\")));\n const withWiring = insertAfterLastImport(\n entry,\n `import { registerAllTools } from \"${importPath}\";\\n\\nvoid registerAllTools();`,\n );\n if (!withWiring) return null;\n\n return {\n edits: [\n {\n path: entryPath,\n action: \"modify\",\n contents: withWiring,\n summary: `added 2 lines to ${relative(cwd, entryPath)} (an import and a registerAllTools() call)`,\n },\n ],\n };\n}\n\n/* ── Shared helpers ────────────────────────────────────────────────────── */\n\n/** Insert a line after the file's last top-level import statement. */\nfunction insertAfterLastImport(source: string, line: string): string | null {\n const lines = source.split(\"\\n\");\n let lastImport = -1;\n for (let index = 0; index < lines.length; index += 1) {\n if (/^import\\s/.test(lines[index] as string)) lastImport = index;\n }\n if (lastImport === -1) return null;\n lines.splice(lastImport + 1, 0, line);\n return lines.join(\"\\n\");\n}\n\n/**\n * Turn a filesystem path into a JS import specifier: no extension, and an\n * explicit \"./\" when the target is in the same directory or deeper —\n * `relative()` alone yields \"webmcp/index\", which JS would read as a\n * package name, not a file.\n */\nfunction withoutExtension(path: string): string {\n const bare = path.replace(/\\.(tsx?|jsx?)$/, \"\").replace(/\\/index$/, \"\");\n return bare.startsWith(\".\") ? bare : `./${bare}`;\n}\n\nasync function firstExisting(paths: string[]): Promise<string | undefined> {\n for (const path of paths) {\n try {\n await readFile(path, \"utf8\");\n return path;\n } catch {\n // Try the next candid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T;AAMA,eAAe,UAAU,KAAa,OAAqC;AACzE,QAAM,QAAQ,KAAK,EAAE,GAAG,OAAO,QAAQ,MAAM,CAAC;AAC9C,UAAQ,IAAI,+CAA0C;AAEtD,MAAI;AACJ,QAAM,KAAK,EAAE,WAAW,KAAK,GAAG,CAAC,QAAQ,aAAa;AACpD,QAAI,CAAC,SAAU;AAGf,QAAI,iEAAiE,KAAK,QAAQ,EAAG;AACrF,QAAI,CAAC,iCAAiC,KAAK,QAAQ,EAAG;AACtD,iBAAa,KAAK;AAClB,YAAQ,WAAW,MAAM;AACvB,cAAQ,KAAK,EAAE,GAAG,OAAO,QAAQ,MAAM,CAAC,EAAE,MAAM,CAAC,UAAmB;AAClE,gBAAQ,MAAM,iBAAiB,QAAQ,MAAM,UAAU,KAAK;AAAA,MAC9D,CAAC;AAAA,IACH,GAAG,GAAG;AAAA,EACR,CAAC;AACH;AAEA,KAAK,EACF,KAAK,CAAC,SAAS,QAAQ,KAAK,IAAI,CAAC,EACjC,MAAM,CAAC,UAAmB;AACzB,UAAQ,MAAM,iBAAiB,QAAQ,MAAM,UAAU,KAAK;AAC5D,UAAQ,KAAK,CAAC;AAChB,CAAC;","names":["writeFile","join","relative","join","writeFile","relative","tool"]}
1
+ {"version":3,"sources":["../src/cli.ts","../src/cli-output.ts","../src/wire.ts"],"sourcesContent":["#!/usr/bin/env node\n/**\n * webmcp-codegen's command line.\n *\n * Design goals, in order:\n * 1. The default output is the summary you need, not a log dump.\n * 2. Every line earns its place; if it doesn't help you decide, it's gone.\n * 3. The next step is always visible, never assumed.\n * 4. Beautiful enough that developers screenshot it.\n *\n * Commands:\n * webmcp-codegen the interactive dashboard (same as `dev`)\n * webmcp-codegen generate write tool files from your spec\n * webmcp-codegen init write a codegen.config.mjs for full control\n * webmcp-codegen --help detailed help with examples\n *\n * Zero dependencies: argument parsing is Node's util.parseArgs, output is\n * ANSI escapes we control character by character.\n */\n\nimport { existsSync } from \"node:fs\";\nimport { writeFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { parseArgs } from \"node:util\";\nimport { dim, renderSummary, renderVerbose } from \"./cli-output.js\";\nimport { CONFIG_FILE_NAMES } from \"./config.js\";\nimport { saveDataFile } from \"./data-file.js\";\nimport { findSpecs } from \"./detect.js\";\nimport { startDevServer } from \"./dev/server.js\";\nimport { runGenerate } from \"./pipeline.js\";\nimport { resolveSetup } from \"./setup.js\";\nimport { applyWiring, planWiring, type WirePlan } from \"./wire.js\";\n\nconst HELP = `\nwebmcp-codegen — generate WebMCP tools from your OpenAPI spec\n\nUsage\n npx webmcp-codegen [command] [flags]\n\nCommands\n generate Generate tool files from your spec (default when no command given)\n dev Open the tools dashboard (list, describe, toggle, test)\n init Write a codegen.config.mjs for full control\n\nFlags\n --spec PATH Which OpenAPI spec to use (auto-detected when omitted)\n --out DIR Where tool files go (default: your web app's src/webmcp)\n --dry-run Preview what would be written, write nothing\n --verbose Show every tool, not just the summary\n --force Write files even when the audit reports errors\n --skip-audit Skip the safety report\n --config PATH Use a config file at PATH\n --port N Dashboard port (default: 4700)\n --help Show this help\n\nExamples\n npx webmcp-codegen generate # detect spec, generate tools\n npx webmcp-codegen generate --dry-run # preview without writing\n npx webmcp-codegen dev # open the dashboard\n npx webmcp-codegen generate --verbose # see all 72 tools listed\n\nDocs\n https://webmcp-codegen.vercel.app/docs\n`;\n\nexport interface CliFlags {\n dryRun: boolean;\n skipAudit: boolean;\n force: boolean;\n verbose: boolean;\n watch: boolean;\n config?: string;\n spec?: string;\n out?: string;\n port?: number;\n help: boolean;\n}\n\nasync function main(): Promise<number> {\n const { values, positionals } = parseArgs({\n args: process.argv.slice(2),\n allowPositionals: true,\n options: {\n \"dry-run\": { type: \"boolean\", default: false },\n \"skip-audit\": { type: \"boolean\", default: false },\n force: { type: \"boolean\", default: false },\n verbose: { type: \"boolean\", default: false },\n watch: { type: \"boolean\", default: false },\n config: { type: \"string\" },\n spec: { type: \"string\" },\n out: { type: \"string\" },\n port: { type: \"string\" },\n help: { type: \"boolean\", default: false },\n },\n });\n\n const flags: CliFlags = {\n dryRun: values[\"dry-run\"] ?? false,\n skipAudit: values[\"skip-audit\"] ?? false,\n force: values.force ?? false,\n verbose: values.verbose ?? false,\n watch: values.watch ?? false,\n config: values.config,\n spec: values.spec,\n out: values.out,\n port: values.port ? Number.parseInt(values.port, 10) : undefined,\n help: values.help,\n };\n\n if (flags.help) {\n console.log(HELP);\n return 0;\n }\n\n const command = positionals[0] ?? \"generate\";\n\n switch (command) {\n case \"init\":\n return init();\n case \"dev\":\n return dev(flags.port ?? 4700);\n case \"generate\":\n return generate(flags);\n default:\n console.error(`Unknown command: ${command}\\n`);\n console.log(HELP);\n return 1;\n }\n}\n\nasync function init(): Promise<number> {\n const cwd = process.cwd();\n const configFile = CONFIG_FILE_NAMES[0] ?? \"codegen.config.mjs\";\n const configPath = join(cwd, configFile);\n\n if (existsSync(configPath)) {\n console.error(`\\n✖ ${configFile} already exists. Nothing to do.\\n`);\n return 1;\n }\n\n const specs = await findSpecs(cwd);\n const specPath = specs.length > 0 ? `./${specs[0]}` : \"./openapi.yaml\";\n\n await writeFile(\n configPath,\n `import { defineConfig } from \"webmcp-codegen\";\nimport { openapi } from \"webmcp-codegen/sources\";\nimport { js } from \"webmcp-codegen/generators\";\n\nexport default defineConfig({\n sources: [openapi({ spec: \"${specPath}\" })],\n generate: [js({ outDir: \"./src/webmcp\" })],\n safety: {\n // Extra field names to treat as PII, on top of the built-in list:\n // piiFields: [\"internalId\"],\n // Tools to skip entirely (matched against name and route):\n // exclude: [\"internal\"],\n },\n});\n`,\n );\n\n console.log(`\\n✔ Wrote ${configFile}\\n`);\n console.log(\"Edit it to add sources, change the output directory, or set safety options.\");\n console.log(\"Docs: https://webmcp-codegen.vercel.app/docs/configuration\\n\");\n return 0;\n}\n\nasync function dev(port: number): Promise<number> {\n const cwd = process.cwd();\n const server = await startDevServer({ cwd, port, open: true });\n console.log(`\\n✔ Dashboard: http://localhost:${port}\\n`);\n console.log(\"List, describe, enable, and test your tools. Ctrl+C to stop.\\n\");\n\n await new Promise<void>((resolveExit) => {\n process.on(\"SIGINT\", () => {\n server.close();\n resolveExit();\n });\n });\n return 0;\n}\n\nasync function generate(flags: CliFlags): Promise<number> {\n const cwd = process.cwd();\n const setup = await resolveSetup(cwd, {\n dryRun: flags.dryRun,\n skipAudit: flags.skipAudit,\n force: flags.force,\n watch: flags.watch,\n spec: flags.spec,\n out: flags.out,\n configPath: flags.config,\n });\n\n const result = await runGenerate(setup.config, {\n cwd,\n dryRun: flags.dryRun,\n force: flags.force,\n skipAudit: flags.skipAudit,\n });\n\n // Registration wiring: additive, idempotent, and only for real runs.\n let wiring: WirePlan | null = null;\n if (!result.blocked && setup.app) {\n const outDir = setup.config.generate[0]?.outDir;\n if (outDir) {\n wiring = await planWiring(cwd, setup.app, outDir);\n if (wiring && wiring.edits.length > 0 && !flags.dryRun && result.wrote) {\n await applyWiring(wiring);\n }\n }\n }\n\n // Remember the choices detection made, so the next run never re-asks.\n if (!setup.fromConfigFile && !flags.dryRun && result.wrote) {\n await saveDataFile(cwd, setup.remember);\n }\n\n if (flags.verbose) {\n renderVerbose(result, setup, cwd);\n } else {\n renderSummary(result, setup, cwd, wiring);\n }\n\n if (flags.watch && !flags.dryRun) {\n // TODO: implement watch mode\n console.log(dim(\"\\n --watch is not implemented yet. Run generate again after changes.\\n\"));\n }\n\n return result.blocked ? 1 : 0;\n}\n\nmain().then(\n (code) => process.exit(code),\n (error) => {\n console.error(\"\\n✖ Unexpected error:\", error instanceof Error ? error.message : error);\n console.error(\"\\nPlease report this: https://github.com/SouravInsights/groundstate/issues\\n\");\n process.exit(1);\n },\n);\n","/**\n * CLI output rendering. The design goal: a summary you can scan in three\n * seconds, with the next step always visible. Every line must earn its place\n * and be understandable by someone who has never seen the tool before.\n */\n\nimport type { GenerateResult } from \"./pipeline.js\";\nimport type { Setup } from \"./setup.js\";\nimport type { WirePlan } from \"./wire.js\";\n\n// ANSI escapes\nconst ESC = \"\\x1b[\";\nconst RESET = `${ESC}0m`;\nconst BOLD = `${ESC}1m`;\nconst DIM = `${ESC}2m`;\n\nconst FG = {\n red: `${ESC}31m`,\n green: `${ESC}32m`,\n yellow: `${ESC}33m`,\n blue: `${ESC}34m`,\n cyan: `${ESC}36m`,\n gray: `${ESC}90m`,\n};\n\nfunction c(color: keyof typeof FG, text: string): string {\n return `${FG[color]}${text}${RESET}`;\n}\n\nfunction bold(text: string): string {\n return `${BOLD}${text}${RESET}`;\n}\n\nexport function dim(text: string): string {\n return `${DIM}${text}${RESET}`;\n}\n\n/** Group findings by what the user needs to know. */\nfunction summarizeFindings(findings: GenerateResult[\"findings\"]): {\n auth: number;\n admin: number;\n pii: number;\n postAsRead: number;\n other: number;\n} {\n const counts = { auth: 0, admin: 0, pii: 0, postAsRead: 0, other: 0 };\n for (const f of findings) {\n const msg = f.message.toLowerCase();\n if (msg.includes(\"sign-in\") || msg.includes(\"auth\") || msg.includes(\"session\")) {\n counts.auth++;\n } else if (msg.includes(\"admin\")) {\n counts.admin++;\n } else if (msg.includes(\"pii\") || msg.includes(\"email\")) {\n counts.pii++;\n } else if (msg.includes(\"post\") && msg.includes(\"read\")) {\n counts.postAsRead++;\n } else {\n counts.other++;\n }\n }\n return counts;\n}\n\n/** The default summary output — written for humans, not machines. */\nexport function renderSummary(\n result: GenerateResult,\n setup: Setup,\n _cwd: string,\n wiring?: WirePlan | null,\n): void {\n const { tools, findings, skipped } = result;\n const reads = tools.filter((t) => t.sideEffect === \"read\").length;\n const writes = tools.filter((t) => t.sideEffect === \"write\").length;\n const destructives = tools.filter((t) => t.sideEffect === \"destructive\").length;\n const enabled = tools.filter((t) => t.enabledByDefault).length;\n\n const findingCounts = summarizeFindings(findings);\n const totalFindings = findings.length;\n\n // Header\n console.log(\"\");\n console.log(` ${bold(\"webmcp-codegen\")}`);\n console.log(dim(` ${setup.label}`));\n console.log(\"\");\n\n // What happened\n console.log(` ${c(\"green\", \"✓\")} ${bold(`${tools.length} tools generated`)}`);\n console.log(dim(` ${enabled} ready to use, ${tools.length - enabled} start disabled`));\n if (skipped.length > 0) {\n console.log(dim(` ${skipped.length} skipped (webhooks and excluded endpoints)`));\n }\n console.log(\"\");\n\n // Safety notes — human-readable\n if (totalFindings > 0) {\n console.log(` ${c(\"yellow\", \"!\")} ${bold(`${totalFindings} safety note${totalFindings === 1 ? \"\" : \"s\"}`)}`);\n if (findingCounts.auth > 0) {\n console.log(dim(` ${findingCounts.auth} auth endpoint${findingCounts.auth === 1 ? \"\" : \"s\"} disabled (agents shouldn't sign in)`));\n }\n if (findingCounts.admin > 0) {\n console.log(dim(` ${findingCounts.admin} admin endpoint${findingCounts.admin === 1 ? \"\" : \"s\"} disabled (review each before enabling)`));\n }\n if (findingCounts.pii > 0) {\n console.log(dim(` ${findingCounts.pii} endpoint${findingCounts.pii === 1 ? \"\" : \"s\"} may return personal data`));\n }\n if (findingCounts.postAsRead > 0) {\n console.log(dim(` ${findingCounts.postAsRead} POST endpoint${findingCounts.postAsRead === 1 ? \"\" : \"s\"} treated as read-only (verify this is correct)`));\n }\n console.log(dim(` Run with --verbose to see all details`));\n console.log(\"\");\n }\n\n // Where things went\n const outDir = setup.config.generate[0]?.outDir ?? \"src/webmcp\";\n console.log(` ${c(\"cyan\", \"→\")} ${bold(\"Files\")} ${outDir}`);\n if (wiring && !wiring.alreadyWired) {\n console.log(` ${c(\"cyan\", \"→\")} ${bold(\"Registration\")} wired into your app`);\n }\n console.log(\"\");\n\n // Next step\n console.log(` ${bold(\"Next:\")} ${c(\"cyan\", \"npx webmcp-codegen dev\")}`);\n console.log(dim(\" Review your tools, edit descriptions, test them live\"));\n console.log(\"\");\n console.log(dim(` Docs: https://webmcp-codegen.vercel.app/docs`));\n console.log(\"\");\n}\n\n/** Verbose output — every tool, for when you want the full list. */\nexport function renderVerbose(result: GenerateResult, setup: Setup, _cwd: string): void {\n const { tools, findings, skipped } = result;\n\n console.log(\"\");\n console.log(bold(`webmcp-codegen`));\n console.log(dim(`${tools.length} tools from ${setup.label}`));\n console.log(\"\");\n\n // Skipped first\n if (skipped.length > 0) {\n console.log(c(\"gray\", \"Skipped:\"));\n for (const s of skipped) {\n console.log(` ${dim(s.ref)}`);\n console.log(` ${dim(s.reason)}`);\n }\n console.log(\"\");\n }\n\n // Tools grouped by risk\n const byRisk = {\n read: tools.filter((t) => t.sideEffect === \"read\"),\n write: tools.filter((t) => t.sideEffect === \"write\"),\n destructive: tools.filter((t) => t.sideEffect === \"destructive\"),\n };\n\n const riskLabels: Record<string, string> = {\n read: c(\"green\", \"Read-only\"),\n write: c(\"yellow\", \"Write\"),\n destructive: c(\"red\", \"Destructive\"),\n };\n\n for (const [risk, group] of Object.entries(byRisk)) {\n if (group.length === 0) continue;\n console.log(riskLabels[risk] ?? risk);\n for (const tool of group) {\n const status = tool.enabledByDefault ? \"\" : dim(\" (disabled)\");\n console.log(` ${tool.name}${status}`);\n if (tool.description) console.log(` ${dim(tool.description)}`);\n }\n console.log(\"\");\n }\n\n // Findings\n if (findings.length > 0) {\n console.log(bold(\"Safety notes:\"));\n for (const f of findings) {\n const icon = f.level === \"error\" ? c(\"red\", \"✖\") : c(\"yellow\", \"⚠\");\n const where = f.tool ? dim(` (${f.tool})`) : \"\";\n console.log(` ${icon} ${f.message}${where}`);\n }\n console.log(\"\");\n }\n\n console.log(dim(`Files: ${setup.config.generate[0]?.outDir ?? \"src/webmcp\"}`));\n console.log(dim(`Docs: https://webmcp-codegen.vercel.app/docs`));\n console.log(\"\");\n}\n","/**\n * Registration wiring: making the app actually register its tools.\n *\n * Generated files do nothing until something calls registerAllTools() once at\n * startup. Rather than telling the developer to go do that, we do it for\n * them — under strict rules, because this is the one place we edit *their*\n * files instead of ours:\n *\n * 1. Edits are additive only. We insert lines; we never change or remove\n * existing ones.\n * 2. Idempotent. If the wiring is already there, we do nothing.\n * 3. Honest. Every edit is reported with exact paths and how to undo it.\n * 4. When we cannot find the entry point with confidence, we do not guess:\n * we print the two lines and where they go, and leave it to the human.\n */\n\nimport { readFile, writeFile } from \"node:fs/promises\";\nimport { dirname, join, relative } from \"node:path\";\nimport type { WebApp } from \"./detect-app.js\";\n\nexport interface WireEdit {\n /** Absolute path of the file to create or modify. */\n path: string;\n action: \"create\" | \"modify\";\n /** The full new contents (for modify: the existing contents plus our lines). */\n contents: string;\n /** One human sentence per edit, for the report. */\n summary: string;\n}\n\nexport interface WirePlan {\n edits: WireEdit[];\n /** Set when we already found the wiring in place. */\n alreadyWired?: boolean;\n}\n\n/**\n * Compute the wiring edits for the detected app, or null when we cannot\n * locate the entry point with confidence (the CLI then prints manual\n * instructions instead).\n */\nexport async function planWiring(\n cwd: string,\n app: WebApp,\n outDir: string,\n): Promise<WirePlan | null> {\n switch (app.framework) {\n case \"next\":\n return planNextWiring(cwd, app, outDir);\n case \"vite-react\":\n return planViteWiring(cwd, app, outDir);\n default:\n // Nuxt/SvelteKit/unknown: we know where the tools go but not where the\n // app boots. Print instructions rather than guess-edit an entry file.\n return null;\n }\n}\n\n/** Apply a plan. Kept trivial on purpose: the plan already did the thinking. */\nexport async function applyWiring(plan: WirePlan): Promise<void> {\n for (const edit of plan.edits) {\n await writeFile(edit.path, edit.contents, \"utf8\");\n }\n}\n\n/* ── Next.js (app router) ──────────────────────────────────────────────── */\n\n/**\n * Next needs the registration to run on the client, so we generate a tiny\n * \"use client\" component next to the tools and mount it in the root layout:\n *\n * import { WebMCPRegister } from \"../webmcp/register\"; ← added\n * ...\n * <body>\n * <WebMCPRegister /> ← added\n * {children}\n */\nasync function planNextWiring(cwd: string, app: WebApp, outDir: string): Promise<WirePlan | null> {\n const layoutCandidates = [\n join(cwd, app.dir, \"src/app/layout.tsx\"),\n join(cwd, app.dir, \"src/app/layout.jsx\"),\n join(cwd, app.dir, \"app/layout.tsx\"),\n join(cwd, app.dir, \"app/layout.jsx\"),\n ];\n const layoutPath = await firstExisting(layoutCandidates);\n if (!layoutPath) return null;\n\n const registerPath = join(cwd, outDir, \"register.tsx\");\n const layout = await readFile(layoutPath, \"utf8\");\n if (layout.includes(\"WebMCPRegister\")) return { edits: [], alreadyWired: true };\n\n // Import path from the layout's directory to the register component.\n const importPath = withoutExtension(relative(dirname(layoutPath), registerPath));\n\n const edits: WireEdit[] = [\n {\n path: registerPath,\n action: \"create\",\n contents: nextRegisterComponent(),\n summary: `created ${relative(cwd, registerPath)} (a client component that registers your tools on page load)`,\n },\n ];\n\n const withImport = insertAfterLastImport(\n layout,\n `import { WebMCPRegister } from \"${importPath}\";`,\n );\n if (!withImport) return null;\n // Mount right after <body ...>, each element on its own line.\n const withComponent = withImport.replace(\n /<body([^>]*)>\\s*/,\n \"<body$1>\\n <WebMCPRegister />\\n \",\n );\n if (withComponent === withImport) return null; // No <body> tag found; do not guess.\n\n edits.push({\n path: layoutPath,\n action: \"modify\",\n contents: withComponent,\n summary: `added 2 lines to ${relative(cwd, layoutPath)} (an import and <WebMCPRegister /> inside <body>)`,\n });\n return { edits };\n}\n\nfunction nextRegisterComponent(): string {\n return `\"use client\";\n\nimport { useEffect } from \"react\";\nimport { registerAllTools } from \"./index\";\n\n/**\n * Registers the generated WebMCP tools once, on page load.\n * Generated by webmcp-codegen. Safe to move; keep it mounted near the root.\n */\nexport function WebMCPRegister() {\n useEffect(() => {\n void registerAllTools();\n }, []);\n return null;\n}\n`;\n}\n\n/* ── Vite + React (SPAs) ───────────────────────────────────────────────── */\n\n/**\n * A Vite app boots in main.tsx, so wiring is two added lines there:\n *\n * import { registerAllTools } from \"./webmcp\"; ← added\n * void registerAllTools(); ← added\n */\nasync function planViteWiring(cwd: string, app: WebApp, outDir: string): Promise<WirePlan | null> {\n const entryCandidates = [\n join(cwd, app.dir, \"src/main.tsx\"),\n join(cwd, app.dir, \"src/main.jsx\"),\n join(cwd, app.dir, \"src/index.tsx\"),\n join(cwd, app.dir, \"src/index.jsx\"),\n ];\n const entryPath = await firstExisting(entryCandidates);\n if (!entryPath) return null;\n\n const entry = await readFile(entryPath, \"utf8\");\n if (entry.includes(\"registerAllTools\")) return { edits: [], alreadyWired: true };\n\n const importPath = withoutExtension(relative(dirname(entryPath), join(cwd, outDir, \"index\")));\n const withWiring = insertAfterLastImport(\n entry,\n `import { registerAllTools } from \"${importPath}\";\\n\\nvoid registerAllTools();`,\n );\n if (!withWiring) return null;\n\n return {\n edits: [\n {\n path: entryPath,\n action: \"modify\",\n contents: withWiring,\n summary: `added 2 lines to ${relative(cwd, entryPath)} (an import and a registerAllTools() call)`,\n },\n ],\n };\n}\n\n/* ── Shared helpers ────────────────────────────────────────────────────── */\n\n/** Insert a line after the file's last top-level import statement. */\nfunction insertAfterLastImport(source: string, line: string): string | null {\n const lines = source.split(\"\\n\");\n let lastImport = -1;\n for (let index = 0; index < lines.length; index += 1) {\n if (/^import\\s/.test(lines[index] as string)) lastImport = index;\n }\n if (lastImport === -1) return null;\n lines.splice(lastImport + 1, 0, line);\n return lines.join(\"\\n\");\n}\n\n/**\n * Turn a filesystem path into a JS import specifier: no extension, and an\n * explicit \"./\" when the target is in the same directory or deeper —\n * `relative()` alone yields \"webmcp/index\", which JS would read as a\n * package name, not a file.\n */\nfunction withoutExtension(path: string): string {\n const bare = path.replace(/\\.(tsx?|jsx?)$/, \"\").replace(/\\/index$/, \"\");\n return bare.startsWith(\".\") ? bare : `./${bare}`;\n}\n\nasync function firstExisting(paths: string[]): Promise<string | undefined> {\n for (const path of paths) {\n try {\n await readFile(path, \"utf8\");\n return path;\n } catch {\n // Try the next candidate.\n }\n }\n return undefined;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAoBA,SAAS,kBAAkB;AAC3B,SAAS,aAAAA,kBAAiB;AAC1B,SAAS,QAAAC,aAAY;AACrB,SAAS,iBAAiB;;;ACZ1B,IAAM,MAAM;AACZ,IAAM,QAAQ,GAAG,GAAG;AACpB,IAAM,OAAO,GAAG,GAAG;AACnB,IAAM,MAAM,GAAG,GAAG;AAElB,IAAM,KAAK;AAAA,EACT,KAAK,GAAG,GAAG;AAAA,EACX,OAAO,GAAG,GAAG;AAA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AAY,MAAM;AAAA,MAC1B;AAAA,IACF;AAAA,EACF;AAGA,MAAI,CAAC,MAAM,kBAAkB,CAAC,MAAM,UAAU,OAAO,OAAO;AAC1D,UAAM,aAAa,KAAK,MAAM,QAAQ;AAAA,EACxC;AAEA,MAAI,MAAM,SAAS;AACjB,kBAAc,QAAQ,OAAO,GAAG;AAAA,EAClC,OAAO;AACL,kBAAc,QAAQ,OAAO,KAAK,MAAM;AAAA,EAC1C;AAEA,MAAI,MAAM,SAAS,CAAC,MAAM,QAAQ;AAEhC,YAAQ,IAAI,IAAI,yEAAyE,CAAC;AAAA,EAC5F;AAEA,SAAO,OAAO,UAAU,IAAI;AAC9B;AAEA,KAAK,EAAE;AAAA,EACL,CAAC,SAAS,QAAQ,KAAK,IAAI;AAAA,EAC3B,CAAC,UAAU;AACT,YAAQ,MAAM,8BAAyB,iBAAiB,QAAQ,MAAM,UAAU,KAAK;AACrF,YAAQ,MAAM,8EAA8E;AAC5F,YAAQ,KAAK,CAAC;AAAA,EAChB;AACF;","names":["writeFile","join","join","writeFile"]}
@@ -0,0 +1,25 @@
1
+ import { Server } from 'node:http';
2
+
3
+ /**
4
+ * The dev dashboard server: `npx webmcp-codegen dev`.
5
+ *
6
+ * A small HTTP server on localhost that serves the tools UI and answers its
7
+ * three kinds of requests: list the tools, save an override (description /
8
+ * enabled) to .webmcp-codegen.json, and run a tool's endpoint for a direct
9
+ * test. It reuses the exact pipeline the CLI runs, so what the dashboard
10
+ * shows is what a generate run would write.
11
+ *
12
+ * It exists only while the command is running, listens on localhost only,
13
+ * and nothing about it ever touches the user's app bundle — by design, so
14
+ * this dev tool can never leak into production.
15
+ */
16
+
17
+ interface DevServerOptions {
18
+ cwd: string;
19
+ port: number;
20
+ /** Open the browser automatically. False in tests and CI. */
21
+ open?: boolean;
22
+ }
23
+ declare function startDevServer(options: DevServerOptions): Promise<Server>;
24
+
25
+ export { type DevServerOptions, startDevServer };
@@ -0,0 +1,12 @@
1
+ import {
2
+ startDevServer
3
+ } from "../chunk-MUTXYBL6.js";
4
+ import "../chunk-MJQ5B6HB.js";
5
+ import "../chunk-EAKYM4YS.js";
6
+ import "../chunk-3LTHWIAP.js";
7
+ import "../chunk-FWSATV7C.js";
8
+ import "../chunk-KSQMJERY.js";
9
+ export {
10
+ startDevServer
11
+ };
12
+ //# sourceMappingURL=server.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
@@ -1,4 +1,4 @@
1
- import { T as ToolGenerator } from '../types-DWUum51l.js';
1
+ import { T as ToolGenerator } from '../types-DfK3AA5H.js';
2
2
 
3
3
  /**
4
4
  * The `js` generator, named after what lands in your repo: plain JavaScript/
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  js
3
- } from "../chunk-I4ZL527H.js";
3
+ } from "../chunk-EAKYM4YS.js";
4
4
  import "../chunk-KSQMJERY.js";
5
5
  export {
6
6
  js
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { C as CodegenConfig, a as ToolOverrides, R as ReviewedTool, b as SkippedEndpoint, A as AuditFinding, G as GeneratedFile } from './types-DWUum51l.js';
2
- export { c as CandidateTool, J as JsonSchema, d as RiskTier, e as SafetyOptions, f as SideEffect, S as Source, g as SourceKind, T as ToolGenerator, h as ToolHints } from './types-DWUum51l.js';
1
+ import { C as CodegenConfig, a as ToolOverrides, R as ReviewedTool, S as SkippedEndpoint, A as AuditFinding, G as GeneratedFile } from './types-DfK3AA5H.js';
2
+ export { b as CandidateTool, J as JsonSchema, c as RiskTier, d as SafetyOptions, e as SideEffect, f as Source, g as SourceKind, T as ToolGenerator, h as ToolHints } from './types-DfK3AA5H.js';
3
3
 
4
4
  /**
5
5
  * Config: `defineConfig` for authoring, `loadConfig` for the CLI.
@@ -1,4 +1,4 @@
1
- import { S as Source } from '../types-DWUum51l.js';
1
+ import { f as Source } from '../types-DfK3AA5H.js';
2
2
 
3
3
  /**
4
4
  * The OpenAPI source.
@@ -186,4 +186,4 @@ interface CodegenConfig {
186
186
  safety?: SafetyOptions;
187
187
  }
188
188
 
189
- export type { AuditFinding as A, CodegenConfig as C, GeneratedFile as G, JsonSchema as J, ReviewedTool as R, Source as S, ToolGenerator as T, ToolOverrides as a, SkippedEndpoint as b, CandidateTool as c, RiskTier as d, SafetyOptions as e, SideEffect as f, SourceKind as g, ToolHints as h };
189
+ export type { AuditFinding as A, CodegenConfig as C, GeneratedFile as G, JsonSchema as J, ReviewedTool as R, SkippedEndpoint as S, ToolGenerator as T, ToolOverrides as a, CandidateTool as b, RiskTier as c, SafetyOptions as d, SideEffect as e, Source as f, SourceKind as g, ToolHints as h };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "webmcp-codegen",
3
- "version": "0.3.1",
3
+ "version": "0.3.3",
4
4
  "description": "Generate safe, typed, human-reviewed WebMCP tools from the API contracts you already have (OpenAPI, tRPC, Zod).",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -28,8 +28,8 @@
28
28
  "dist"
29
29
  ],
30
30
  "scripts": {
31
- "build": "tsup src/index.ts src/cli.ts src/sources/index.ts src/generators/index.ts --format esm --dts --sourcemap --clean",
32
- "dev": "tsup src/index.ts src/cli.ts src/sources/index.ts src/generators/index.ts --format esm --dts --sourcemap --watch",
31
+ "build": "tsup src/index.ts src/cli.ts src/sources/index.ts src/generators/index.ts src/dev/server.ts --format esm --dts --sourcemap --clean",
32
+ "dev": "tsup src/index.ts src/cli.ts src/sources/index.ts src/generators/index.ts src/dev/server.ts --format esm --dts --sourcemap --watch",
33
33
  "test": "vitest run",
34
34
  "typecheck": "tsc --noEmit"
35
35
  },
@@ -1,235 +0,0 @@
1
- import {
2
- CONFIG_FILE_NAMES,
3
- loadConfig
4
- } from "./chunk-MJQ5B6HB.js";
5
- import {
6
- openapi
7
- } from "./chunk-3LTHWIAP.js";
8
- import {
9
- js
10
- } from "./chunk-I4ZL527H.js";
11
-
12
- // src/data-file.ts
13
- import { readFile, writeFile } from "fs/promises";
14
- import { join } from "path";
15
- var DATA_FILE_NAME = ".webmcp-codegen.json";
16
- async function loadDataFile(cwd) {
17
- try {
18
- const parsed = JSON.parse(await readFile(join(cwd, DATA_FILE_NAME), "utf8"));
19
- return parsed && typeof parsed === "object" ? parsed : {};
20
- } catch {
21
- return {};
22
- }
23
- }
24
- async function saveDataFile(cwd, patch) {
25
- const current = await loadDataFile(cwd);
26
- const next = { ...current, ...patch };
27
- if (JSON.stringify(next) === JSON.stringify(current)) return;
28
- await writeFile(join(cwd, DATA_FILE_NAME), `${JSON.stringify(next, null, 2)}
29
- `, "utf8");
30
- }
31
-
32
- // src/detect.ts
33
- import { readdir } from "fs/promises";
34
- import { join as join2, relative } from "path";
35
- var SPEC_FILE_PATTERN = /^(openapi|swagger|api)\.(ya?ml|json)$/i;
36
- var IGNORED_DIRS = /* @__PURE__ */ new Set([
37
- "node_modules",
38
- ".git",
39
- ".turbo",
40
- ".next",
41
- "dist",
42
- "build",
43
- "coverage"
44
- ]);
45
- var MAX_DEPTH = 5;
46
- async function findSpecs(cwd) {
47
- const found = [];
48
- async function walk(dir, depth) {
49
- if (depth > MAX_DEPTH) return;
50
- let entries;
51
- try {
52
- entries = await readdir(dir, { withFileTypes: true });
53
- } catch {
54
- return;
55
- }
56
- for (const entry of entries) {
57
- if (entry.isDirectory()) {
58
- if (!IGNORED_DIRS.has(entry.name)) await walk(join2(dir, entry.name), depth + 1);
59
- } else if (SPEC_FILE_PATTERN.test(entry.name)) {
60
- found.push({ path: join2(dir, entry.name), depth });
61
- }
62
- }
63
- }
64
- await walk(cwd, 0);
65
- return found.sort((a, b) => a.depth - b.depth).map((entry) => relative(cwd, entry.path));
66
- }
67
-
68
- // src/setup.ts
69
- import { existsSync } from "fs";
70
- import { basename, join as join4 } from "path";
71
- import { createInterface } from "readline/promises";
72
-
73
- // src/detect-app.ts
74
- import { readdir as readdir2, readFile as readFile2 } from "fs/promises";
75
- import { join as join3 } from "path";
76
- var FRAMEWORKS = [
77
- { dep: "next", framework: "next" },
78
- { dep: "nuxt", framework: "nuxt" },
79
- { dep: "@sveltejs/kit", framework: "sveltekit" }
80
- ];
81
- async function findWebApps(cwd) {
82
- const packageDirs = await findPackageDirs(cwd);
83
- const apps = [];
84
- for (const dir of packageDirs) {
85
- const pkg = await readPackageJson(join3(cwd, dir));
86
- if (!pkg) continue;
87
- const deps = {
88
- ...pkg.dependencies,
89
- ...pkg.devDependencies
90
- };
91
- const known = FRAMEWORKS.find(({ dep }) => deps[dep]);
92
- const framework = known?.framework ?? (deps.react && deps.vite ? "vite-react" : void 0);
93
- if (framework) apps.push({ dir, framework });
94
- }
95
- return apps.sort((a, b) => score(b) - score(a));
96
- function score(app) {
97
- return (app.framework === "unknown" ? 0 : 10) + (/(^|\/)(web|app|frontend|client)$/.test(app.dir) ? 2 : 0);
98
- }
99
- }
100
- async function findPackageDirs(cwd) {
101
- const dirs = [];
102
- const root = await readPackageJson(join3(cwd, ""));
103
- if (root) {
104
- dirs.push(".");
105
- for (const pattern of await workspaceGlobs(cwd, root)) {
106
- dirs.push(...await expandShallowGlob(cwd, pattern));
107
- }
108
- }
109
- return [...new Set(dirs)];
110
- }
111
- async function workspaceGlobs(cwd, rootPkg) {
112
- const workspaces = rootPkg.workspaces;
113
- if (Array.isArray(workspaces)) return workspaces;
114
- if (workspaces && typeof workspaces === "object" && Array.isArray(workspaces.packages)) {
115
- return workspaces.packages;
116
- }
117
- return readPnpmWorkspaceGlobs(cwd);
118
- }
119
- async function readPnpmWorkspaceGlobs(cwd) {
120
- try {
121
- const text = await readFile2(join3(cwd, "pnpm-workspace.yaml"), "utf8");
122
- const packagesBlock = /^packages:\s*\n((?:\s+-\s+.+\n?)+)/m.exec(text);
123
- if (!packagesBlock) return [];
124
- return [...packagesBlock[1].matchAll(/^\s+-\s+['"]?([^'"\n]+?)['"]?\s*$/gm)].map(
125
- (match) => match[1]
126
- );
127
- } catch {
128
- return [];
129
- }
130
- }
131
- async function expandShallowGlob(cwd, pattern) {
132
- const starAt = pattern.indexOf("*");
133
- const base = starAt === -1 ? pattern : pattern.slice(0, starAt).replace(/\/$/, "");
134
- if (starAt === -1) return [base];
135
- try {
136
- const entries = await readdir2(join3(cwd, base), { withFileTypes: true });
137
- return entries.filter((entry) => entry.isDirectory()).map((entry) => `${base}/${entry.name}`);
138
- } catch {
139
- return [];
140
- }
141
- }
142
- async function readPackageJson(dir) {
143
- try {
144
- return JSON.parse(await readFile2(join3(dir, "package.json"), "utf8"));
145
- } catch {
146
- return void 0;
147
- }
148
- }
149
-
150
- // src/setup.ts
151
- async function resolveSetup(cwd, flags) {
152
- const hasConfigFile = flags.configPath ? existsSync(join4(cwd, flags.configPath)) : CONFIG_FILE_NAMES.some((name) => existsSync(join4(cwd, name)));
153
- if (hasConfigFile) {
154
- const { config, path } = await loadConfig(cwd, flags.configPath);
155
- if (flags.spec || flags.out) {
156
- console.warn(`Note: --spec/--out are ignored; ${basename(path)} is in charge here.`);
157
- }
158
- const data2 = await loadDataFile(cwd);
159
- const apps = await findWebApps(cwd);
160
- const app2 = apps.find((candidate) => candidate.dir === data2.app) ?? apps[0];
161
- return { config, label: basename(path), app: app2, fromConfigFile: true, remember: {} };
162
- }
163
- if (flags.configPath) {
164
- throw new Error(`No config file at "${flags.configPath}".`);
165
- }
166
- const data = await loadDataFile(cwd);
167
- const spec = flags.spec ?? data.spec ?? await detectSpec(cwd);
168
- let app;
169
- if (!flags.out) {
170
- const apps = await findWebApps(cwd);
171
- const remembered = apps.find((candidate) => candidate.dir === data.app);
172
- if (remembered) {
173
- app = remembered;
174
- } else if (apps.length === 1) {
175
- app = apps[0];
176
- console.log(`Found your web app: ${app?.dir} (${app?.framework})`);
177
- } else if (apps.length > 1) {
178
- app = await askWhichApp(apps);
179
- }
180
- }
181
- const outDir = flags.out ?? (app && app.dir !== "." ? `${app.dir}/src/webmcp` : "./src/webmcp");
182
- return {
183
- config: { sources: [openapi({ spec })], generate: [js({ outDir })] },
184
- label: flags.spec ? `--spec ${spec}` : `detected ${spec}`,
185
- app,
186
- fromConfigFile: false,
187
- remember: { spec, app: app?.dir }
188
- };
189
- }
190
- async function askWhichApp(apps) {
191
- if (!process.stdin.isTTY) {
192
- const first = apps[0];
193
- console.log(`Several packages look like web apps; using ${first.dir}. Override with --out.`);
194
- return first;
195
- }
196
- console.log("Several packages look like the web app. Which one should the tools live in?");
197
- apps.forEach((app, index) => {
198
- console.log(` ${index + 1}. ${app.dir} (${app.framework})${index === 0 ? " [default]" : ""}`);
199
- });
200
- const rl = createInterface({ input: process.stdin, output: process.stdout });
201
- try {
202
- const answer = await rl.question("Choice [1]: ");
203
- const picked = Number.parseInt(answer.trim() || "1", 10);
204
- return apps[picked - 1] ?? apps[0];
205
- } finally {
206
- rl.close();
207
- }
208
- }
209
- async function detectSpec(cwd) {
210
- const specs = await findSpecs(cwd);
211
- if (specs.length === 0) {
212
- throw new Error(
213
- "No OpenAPI spec found in this project.\nPoint at one: npx webmcp-codegen generate --spec path/to/openapi.json"
214
- );
215
- }
216
- if (specs.length > 1) {
217
- const list = specs.map((spec) => ` - ${spec}`).join("\n");
218
- throw new Error(
219
- `Found ${specs.length} API specs:
220
- ${list}
221
-
222
- Pick one: npx webmcp-codegen generate --spec ${specs[0]}`
223
- );
224
- }
225
- console.log(`Detected ${specs[0]} (override with --spec)`);
226
- return specs[0];
227
- }
228
-
229
- export {
230
- loadDataFile,
231
- saveDataFile,
232
- findSpecs,
233
- resolveSetup
234
- };
235
- //# sourceMappingURL=chunk-CCVNYNJ5.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/data-file.ts","../src/detect.ts","../src/setup.ts","../src/detect-app.ts"],"sourcesContent":["/**\n * The remembered-choices file: `.webmcp-codegen.json` at the project root.\n *\n * It is plain data — never code — so it works in the pure-npx flow (no\n * install needed) and can be read and written safely by the CLI and the dev\n * dashboard alike. It holds two kinds of things:\n *\n * - choices we asked for once and should never ask again\n * (\"which of these packages is your web app?\")\n * - overrides per-tool edits made in the dashboard (description,\n * enabled). They are applied after the safety review, so\n * they survive regeneration.\n *\n * The config file (codegen.config.mjs) stays the source of truth for\n * *structure* (sources, generators, safety). This file is for *choices and\n * tweaks*. Editing it by hand is fine; it is meant to be committed.\n */\n\nimport { readFile, writeFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport type { ToolOverrides } from \"./types.js\";\n\nexport const DATA_FILE_NAME = \".webmcp-codegen.json\";\n\nexport interface DataFile {\n /** The spec we used (or were told to use), relative to the project root. */\n spec?: string;\n /** The web app package directory, relative to the project root. */\n app?: string;\n /** Per-tool tweaks, keyed by tool name. */\n overrides?: ToolOverrides;\n}\n\nexport async function loadDataFile(cwd: string): Promise<DataFile> {\n try {\n const parsed = JSON.parse(await readFile(join(cwd, DATA_FILE_NAME), \"utf8\")) as DataFile;\n return parsed && typeof parsed === \"object\" ? parsed : {};\n } catch {\n return {};\n }\n}\n\n/**\n * Merge and write. Only the keys given are touched; everything already in\n * the file (especially overrides) survives. Writes nothing when the merged\n * result equals what's already there, so watch mode never loops on us.\n */\nexport async function saveDataFile(cwd: string, patch: Partial<DataFile>): Promise<void> {\n const current = await loadDataFile(cwd);\n const next: DataFile = { ...current, ...patch };\n if (JSON.stringify(next) === JSON.stringify(current)) return;\n await writeFile(join(cwd, DATA_FILE_NAME), `${JSON.stringify(next, null, 2)}\\n`, \"utf8\");\n}\n","/**\n * Spec auto-detection: the reason `npx webmcp-codegen generate` works with\n * zero arguments, zero config, and zero install.\n *\n * The rule is deliberately boring: walk the project (skipping the obvious\n * noise), recognize the usual spec filenames, and return what we find\n * shallowest-first. When exactly one spec exists we just use it; the CLI\n * layer decides what to do about zero or several.\n */\n\nimport type { Dirent } from \"node:fs\";\nimport { readdir } from \"node:fs/promises\";\nimport { join, relative } from \"node:path\";\n\n/** Filenames we recognize as API specs. */\nexport const SPEC_FILE_PATTERN = /^(openapi|swagger|api)\\.(ya?ml|json)$/i;\n\n/** Directories never worth descending into. */\nconst IGNORED_DIRS = new Set([\n \"node_modules\",\n \".git\",\n \".turbo\",\n \".next\",\n \"dist\",\n \"build\",\n \"coverage\",\n]);\n\n/**\n * How deep we look. Enough for monorepo layouts like\n * apps/server/openapi/openapi.json (depth 3) without wandering forever.\n */\nconst MAX_DEPTH = 5;\n\n/**\n * Find API spec files under `cwd`, returned as paths relative to `cwd`,\n * shallowest first. A root-level spec is a likelier intent than one\n * buried six folders deep.\n */\nexport async function findSpecs(cwd: string): Promise<string[]> {\n const found: { path: string; depth: number }[] = [];\n\n async function walk(dir: string, depth: number): Promise<void> {\n if (depth > MAX_DEPTH) return;\n let entries: Dirent[];\n try {\n entries = await readdir(dir, { withFileTypes: true });\n } catch {\n return; // Unreadable directory. Skip it, never die on detection.\n }\n for (const entry of entries) {\n if (entry.isDirectory()) {\n if (!IGNORED_DIRS.has(entry.name)) await walk(join(dir, entry.name), depth + 1);\n } else if (SPEC_FILE_PATTERN.test(entry.name)) {\n found.push({ path: join(dir, entry.name), depth });\n }\n }\n }\n\n await walk(cwd, 0);\n return found.sort((a, b) => a.depth - b.depth).map((entry) => relative(cwd, entry.path));\n}\n","/**\n * Setup resolution: where the tools come from and where they go.\n *\n * Shared by the CLI (`generate`) and the dev dashboard (`dev`), so both see\n * the same project the same way:\n *\n * 1. a config file (codegen.config.mjs or --config) for full control\n * 2. --spec/--out flags as quick overrides, no config needed\n * 3. remembered choices from .webmcp-codegen.json\n * 4. auto-detection: the spec by filename, the web app by its package.json\n *\n * Branches 2-4 build the config right here, which is what makes\n * `npx webmcp-codegen generate` work without installing the package: the\n * user's project never has to resolve a webmcp-codegen import.\n */\n\nimport { existsSync } from \"node:fs\";\nimport { basename, join } from \"node:path\";\nimport { createInterface } from \"node:readline/promises\";\nimport { CONFIG_FILE_NAMES, loadConfig } from \"./config.js\";\nimport { loadDataFile } from \"./data-file.js\";\nimport { findSpecs } from \"./detect.js\";\nimport { findWebApps, type WebApp } from \"./detect-app.js\";\nimport { js } from \"./generators/js.js\";\nimport { openapi } from \"./sources/openapi.js\";\nimport type { CodegenConfig } from \"./types.js\";\n\nexport interface GenerateFlags {\n dryRun: boolean;\n skipAudit: boolean;\n force: boolean;\n watch: boolean;\n configPath?: string;\n spec?: string;\n out?: string;\n}\n\nexport interface Setup {\n config: CodegenConfig;\n label: string;\n /** The web app we detected (when detection ran). Drives placement + wiring. */\n app?: WebApp;\n /** True when the config came from a config file rather than detection. */\n fromConfigFile: boolean;\n /** Choices to remember in .webmcp-codegen.json after a successful run. */\n remember: { spec?: string; app?: string };\n}\n\n/**\n * Where the tools come from and where they go, in priority order:\n *\n * 1. a config file (codegen.config.mjs or --config) for full control\n * 2. --spec/--out flags as quick overrides, no config needed\n * 3. remembered choices from .webmcp-codegen.json\n * 4. auto-detection: the spec by filename, the web app by its package.json\n *\n * Branches 2-4 build the config right here inside the CLI, which is what\n * makes `npx webmcp-codegen generate` work without installing the package:\n * the user's project never has to resolve a webmcp-codegen import.\n */\nexport async function resolveSetup(cwd: string, flags: GenerateFlags): Promise<Setup> {\n const hasConfigFile = flags.configPath\n ? existsSync(join(cwd, flags.configPath))\n : CONFIG_FILE_NAMES.some((name) => existsSync(join(cwd, name)));\n\n if (hasConfigFile) {\n const { config, path } = await loadConfig(cwd, flags.configPath);\n if (flags.spec || flags.out) {\n console.warn(`Note: --spec/--out are ignored; ${basename(path)} is in charge here.`);\n }\n // Wiring still works with a config file if we can find the app.\n const data = await loadDataFile(cwd);\n const apps = await findWebApps(cwd);\n const app = apps.find((candidate) => candidate.dir === data.app) ?? apps[0];\n return { config, label: basename(path), app, fromConfigFile: true, remember: {} };\n }\n if (flags.configPath) {\n throw new Error(`No config file at \"${flags.configPath}\".`);\n }\n\n const data = await loadDataFile(cwd);\n\n // The spec: flag wins, then the remembered choice, then detection.\n const spec = flags.spec ?? data.spec ?? (await detectSpec(cwd));\n\n // The web app: detection decides placement. Only asked once; the answer\n // is remembered in .webmcp-codegen.json.\n let app: WebApp | undefined;\n if (!flags.out) {\n const apps = await findWebApps(cwd);\n const remembered = apps.find((candidate) => candidate.dir === data.app);\n if (remembered) {\n app = remembered;\n } else if (apps.length === 1) {\n app = apps[0];\n console.log(`Found your web app: ${app?.dir} (${app?.framework})`);\n } else if (apps.length > 1) {\n app = await askWhichApp(apps);\n }\n }\n\n const outDir = flags.out ?? (app && app.dir !== \".\" ? `${app.dir}/src/webmcp` : \"./src/webmcp\");\n return {\n config: { sources: [openapi({ spec })], generate: [js({ outDir })] },\n label: flags.spec ? `--spec ${spec}` : `detected ${spec}`,\n app,\n fromConfigFile: false,\n remember: { spec, app: app?.dir },\n };\n}\n\n/**\n * The one question this CLI asks. Several packages look like the web app;\n * a human picks, and .webmcp-codegen.json remembers it. Non-interactive\n * shells (CI) get the best guess with a note, never a hang.\n */\nasync function askWhichApp(apps: WebApp[]): Promise<WebApp> {\n if (!process.stdin.isTTY) {\n const first = apps[0] as WebApp;\n console.log(`Several packages look like web apps; using ${first.dir}. Override with --out.`);\n return first;\n }\n console.log(\"Several packages look like the web app. Which one should the tools live in?\");\n apps.forEach((app, index) => {\n console.log(` ${index + 1}. ${app.dir} (${app.framework})${index === 0 ? \" [default]\" : \"\"}`);\n });\n const rl = createInterface({ input: process.stdin, output: process.stdout });\n try {\n const answer = await rl.question(\"Choice [1]: \");\n const picked = Number.parseInt(answer.trim() || \"1\", 10);\n return apps[picked - 1] ?? (apps[0] as WebApp);\n } finally {\n rl.close();\n }\n}\n\n/**\n * Find the project's API spec. One candidate: use it and say so. Several:\n * list them and make the human pick. None: say exactly what to do next.\n */\nasync function detectSpec(cwd: string): Promise<string> {\n const specs = await findSpecs(cwd);\n\n if (specs.length === 0) {\n throw new Error(\n \"No OpenAPI spec found in this project.\\n\" +\n \"Point at one: npx webmcp-codegen generate --spec path/to/openapi.json\",\n );\n }\n if (specs.length > 1) {\n const list = specs.map((spec) => ` - ${spec}`).join(\"\\n\");\n throw new Error(\n `Found ${specs.length} API specs:\\n${list}\\n\\n` +\n `Pick one: npx webmcp-codegen generate --spec ${specs[0]}`,\n );\n }\n\n console.log(`Detected ${specs[0]} (override with --spec)`);\n return specs[0] as string;\n}\n\n","/**\n * Web-app detection: where the generated tools should live.\n *\n * The tools are browser code, so they belong in whichever package *is* the\n * web app — not next to the spec, and not wherever the command happened to\n * run. In a monorepo like:\n *\n * apps/\n * ├── server/ (has the openapi.json)\n * └── web/ (has next in its package.json) ← tools go here\n *\n * detection means reading package.json files and looking for a browser\n * framework. One candidate: we use it and say so. Several: the CLI asks\n * once and remembers the answer in .webmcp-codegen.json.\n */\n\nimport { readdir, readFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\n\nexport interface WebApp {\n /** Package directory relative to the project root, e.g. \"apps/web\". */\n dir: string;\n framework: \"next\" | \"vite-react\" | \"nuxt\" | \"sveltekit\" | \"unknown\";\n}\n\n/** The frameworks we recognize, best-supported first. */\nconst FRAMEWORKS: { dep: string; framework: WebApp[\"framework\"] }[] = [\n { dep: \"next\", framework: \"next\" },\n { dep: \"nuxt\", framework: \"nuxt\" },\n { dep: \"@sveltejs/kit\", framework: \"sveltekit\" },\n];\n\n/**\n * Find web apps in the project. Returns candidates with the likeliest first\n * (a known framework beats \"has react\", an app named \"web\" beats \"admin\").\n */\nexport async function findWebApps(cwd: string): Promise<WebApp[]> {\n const packageDirs = await findPackageDirs(cwd);\n const apps: WebApp[] = [];\n\n for (const dir of packageDirs) {\n const pkg = await readPackageJson(join(cwd, dir));\n if (!pkg) continue;\n const deps = {\n ...(pkg.dependencies as Record<string, string> | undefined),\n ...(pkg.devDependencies as Record<string, string> | undefined),\n };\n const known = FRAMEWORKS.find(({ dep }) => deps[dep]);\n // A bare react+vite pair is a Vite SPA; react alone is too weak a signal.\n const framework =\n known?.framework ?? (deps.react && deps.vite ? (\"vite-react\" as const) : undefined);\n if (framework) apps.push({ dir, framework });\n }\n\n // Prefer known frameworks, then the package literally named like the app.\n return apps.sort((a, b) => score(b) - score(a));\n\n function score(app: WebApp): number {\n return (\n (app.framework === \"unknown\" ? 0 : 10) +\n (/(^|\\/)(web|app|frontend|client)$/.test(app.dir) ? 2 : 0)\n );\n }\n}\n\n/** Every directory holding a package.json, root first. */\nasync function findPackageDirs(cwd: string): Promise<string[]> {\n const dirs: string[] = [];\n const root = await readPackageJson(join(cwd, \"\"));\n if (root) {\n dirs.push(\".\");\n for (const pattern of await workspaceGlobs(cwd, root)) {\n dirs.push(...(await expandShallowGlob(cwd, pattern)));\n }\n }\n return [...new Set(dirs)];\n}\n\n/** Workspace globs from package.json workspaces or pnpm-workspace.yaml. */\nasync function workspaceGlobs(cwd: string, rootPkg: Record<string, unknown>): Promise<string[]> {\n const workspaces = rootPkg.workspaces;\n if (Array.isArray(workspaces)) return workspaces as string[];\n if (\n workspaces &&\n typeof workspaces === \"object\" &&\n Array.isArray((workspaces as { packages?: unknown }).packages)\n ) {\n return (workspaces as { packages: string[] }).packages;\n }\n // pnpm monorepos: parse the \"packages:\" list out of pnpm-workspace.yaml.\n // Kept deliberately shallow: we only support single-star globs anyway.\n return readPnpmWorkspaceGlobs(cwd);\n}\n\nasync function readPnpmWorkspaceGlobs(cwd: string): Promise<string[]> {\n try {\n const text = await readFile(join(cwd, \"pnpm-workspace.yaml\"), \"utf8\");\n const packagesBlock = /^packages:\\s*\\n((?:\\s+-\\s+.+\\n?)+)/m.exec(text);\n if (!packagesBlock) return [];\n return [...(packagesBlock[1] as string).matchAll(/^\\s+-\\s+['\"]?([^'\"\\n]+?)['\"]?\\s*$/gm)].map(\n (match) => match[1] as string,\n );\n } catch {\n return [];\n }\n}\n\n/**\n * Expand a workspace glob, but only one star deep (\"apps/*\"). Deep globs\n * (\"packages/**\") are truncated at the first star; a monorepo app is never\n * buried deeper than that in practice.\n */\nasync function expandShallowGlob(cwd: string, pattern: string): Promise<string[]> {\n const starAt = pattern.indexOf(\"*\");\n const base = starAt === -1 ? pattern : pattern.slice(0, starAt).replace(/\\/$/, \"\");\n if (starAt === -1) return [base];\n try {\n const entries = await readdir(join(cwd, base), { withFileTypes: true });\n return entries.filter((entry) => entry.isDirectory()).map((entry) => `${base}/${entry.name}`);\n } catch {\n return [];\n }\n}\n\nasync function readPackageJson(dir: string): Promise<Record<string, unknown> | undefined> {\n try {\n return JSON.parse(await readFile(join(dir, \"package.json\"), \"utf8\")) as Record<string, unknown>;\n } catch {\n return undefined;\n }\n}\n"],"mappings":";;;;;;;;;;;;AAkBA,SAAS,UAAU,iBAAiB;AACpC,SAAS,YAAY;AAGd,IAAM,iBAAiB;AAW9B,eAAsB,aAAa,KAAgC;AACjE,MAAI;AACF,UAAM,SAAS,KAAK,MAAM,MAAM,SAAS,KAAK,KAAK,cAAc,GAAG,MAAM,CAAC;AAC3E,WAAO,UAAU,OAAO,WAAW,WAAW,SAAS,CAAC;AAAA,EAC1D,QAAQ;AACN,WAAO,CAAC;AAAA,EACV;AACF;AAOA,eAAsB,aAAa,KAAa,OAAyC;AACvF,QAAM,UAAU,MAAM,aAAa,GAAG;AACtC,QAAM,OAAiB,EAAE,GAAG,SAAS,GAAG,MAAM;AAC9C,MAAI,KAAK,UAAU,IAAI,MAAM,KAAK,UAAU,OAAO,EAAG;AACtD,QAAM,UAAU,KAAK,KAAK,cAAc,GAAG,GAAG,KAAK,UAAU,MAAM,MAAM,CAAC,CAAC;AAAA,GAAM,MAAM;AACzF;;;ACzCA,SAAS,eAAe;AACxB,SAAS,QAAAA,OAAM,gBAAgB;AAGxB,IAAM,oBAAoB;AAGjC,IAAM,eAAe,oBAAI,IAAI;AAAA,EAC3B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAMD,IAAM,YAAY;AAOlB,eAAsB,UAAU,KAAgC;AAC9D,QAAM,QAA2C,CAAC;AAElD,iBAAe,KAAK,KAAa,OAA8B;AAC7D,QAAI,QAAQ,UAAW;AACvB,QAAI;AACJ,QAAI;AACF,gBAAU,MAAM,QAAQ,KAAK,EAAE,eAAe,KAAK,CAAC;AAAA,IACtD,QAAQ;AACN;AAAA,IACF;AACA,eAAW,SA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ACD,QAAM,KAAK,gBAAgB,EAAE,OAAO,QAAQ,OAAO,QAAQ,QAAQ,OAAO,CAAC;AAC3E,MAAI;AACF,UAAM,SAAS,MAAM,GAAG,SAAS,cAAc;AAC/C,UAAM,SAAS,OAAO,SAAS,OAAO,KAAK,KAAK,KAAK,EAAE;AACvD,WAAO,KAAK,SAAS,CAAC,KAAM,KAAK,CAAC;AAAA,EACpC,UAAE;AACA,OAAG,MAAM;AAAA,EACX;AACF;AAMA,eAAe,WAAW,KAA8B;AACtD,QAAM,QAAQ,MAAM,UAAU,GAAG;AAEjC,MAAI,MAAM,WAAW,GAAG;AACtB,UAAM,IAAI;AAAA,MACR;AAAA,IAEF;AAAA,EACF;AACA,MAAI,MAAM,SAAS,GAAG;AACpB,UAAM,OAAO,MAAM,IAAI,CAAC,SAAS,OAAO,IAAI,EAAE,EAAE,KAAK,IAAI;AACzD,UAAM,IAAI;AAAA,MACR,SAAS,MAAM,MAAM;AAAA,EAAgB,IAAI;AAAA;AAAA,gDACU,MAAM,CAAC,CAAC;AAAA,IAC7D;AAAA,EACF;AAEA,UAAQ,IAAI,YAAY,MAAM,CAAC,CAAC,yBAAyB;AACzD,SAAO,MAAM,CAAC;AAChB;","names":["join","join","readdir","readFile","join","join","data","app"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/generators/js.ts","../src/generators/js-templates.ts"],"sourcesContent":["/**\n * The `js` generator, named after what lands in your repo: plain JavaScript/\n * TypeScript files that call the spec's imperative API\n * (`document.modelContext.registerTool`).\n *\n * Output layout for `js({ outDir: \"./src/webmcp\" })`:\n *\n * src/webmcp/\n * ├── runtime.webmcp.ts ← fully generated, never edit\n * ├── index.ts ← fully generated, registers everything\n * ├── get-order-status.webmcp.ts ← generated contract + YOUR execute()\n * └── ...\n *\n * Each per-tool file has two regions, divided by marker comments:\n *\n * generated region schema, input type, tool definition, register()\n * ── end generated ── everything below survives regeneration\n * your region execute(), scaffolded once, then owned by you\n *\n * This file contains only the *file mechanics*: which files exist, and how to\n * update them without destroying hand-written code. The text of the generated\n * code itself lives in js-templates.ts, keeping \"what the output looks like\"\n * separate from \"how files get written\" is what keeps both readable.\n */\n\nimport { readFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport type { GeneratedFile, ReviewedTool, ToolGenerator } from \"../types.js\";\nimport {\n barrelSource,\n generatedRegion,\n ownedRegionScaffold,\n runtimeSource,\n} from \"./js-templates.js\";\n\nexport interface JsGeneratorOptions {\n /** Where the tool files go, relative to the project root. */\n outDir: string;\n}\n\n/**\n * The marker lines that split a per-tool file in two. They are the merge\n * contract: we may rewrite everything up to and including GENERATED_END,\n * and we must never touch anything after it. js-templates.ts imports these\n * so the marker text is defined in exactly one place.\n */\nexport const GENERATED_START = \"// ─── webmcp-codegen: generated. Do not edit this region. ───\";\nexport const GENERATED_END =\n \"// ─── webmcp-codegen: end generated. Your code below survives regeneration. ───\";\n\n/** Create the `js` generator for the config's `generate` array. */\nexport function js(options: JsGeneratorOptions): ToolGenerator {\n return {\n kind: \"js\",\n outDir: options.outDir,\n async generate(tools, cwd) {\n const outDir = join(cwd, options.outDir);\n const files: GeneratedFile[] = [];\n\n // The runtime and the barrel are regenerated wholesale every run;\n // their headers say \"do not edit\", and we mean it.\n files.push(await plainFile(join(outDir, \"runtime.webmcp.ts\"), runtimeSource()));\n files.push(await plainFile(join(outDir, \"index.ts\"), barrelSource(tools)));\n\n for (const tool of tools) {\n files.push(await toolFile(tool, outDir));\n }\n return files;\n },\n };\n}\n\n/** A fully-generated file: create if missing, overwrite if changed, skip if same. */\nasync function plainFile(path: string, contents: string): Promise<GeneratedFile> {\n try {\n const existing = await readFile(path, \"utf8\");\n return { path, contents, action: existing === contents ? \"unchanged\" : \"update\" };\n } catch {\n return { path, contents, action: \"create\" };\n }\n}\n\n/**\n * Build (or merge) one per-tool file. The only I/O here is reading the\n * existing file to check for a hand-written region worth keeping.\n */\nasync function toolFile(tool: ReviewedTool, outDir: string): Promise<GeneratedFile> {\n const path = join(outDir, `${tool.name}.webmcp.ts`);\n const head = generatedRegion(tool);\n\n let existing: string | undefined;\n try {\n existing = await readFile(path, \"utf8\");\n } catch {\n // No file yet: brand new tool, so we also lay down the execute() scaffold.\n return { path, contents: `${head}\\n${ownedRegionScaffold(tool)}`, action: \"create\" };\n }\n\n const markerIndex = existing.indexOf(GENERATED_END);\n if (markerIndex === -1) {\n // Someone removed the markers or hand-wrote this path from scratch.\n // Never clobber their work: report a conflict and let the pipeline put\n // our version in a `.new` sibling for a human to merge.\n return { path, contents: existing, action: \"unchanged\", conflict: `${path}.new` };\n }\n\n // Keep everything the developer wrote below the marker, word for word.\n const preservedTail = existing.slice(markerIndex + GENERATED_END.length);\n const contents = head + preservedTail;\n return { path, contents, action: contents === existing ? \"unchanged\" : \"update\" };\n}\n","/**\n * The text of the code the `js` generator writes.\n *\n * Heads up before reading on: every function here returns *TypeScript source\n * code as a string*. When you see `export const ...` inside quotes, that's\n * the output a user's repo will contain, not this module's own logic.\n * Building output from arrays of lines (rather than nested template strings)\n * keeps the quoting readable; the only escaping left is for code samples\n * inside the generated comments.\n *\n * Three kinds of output are built here:\n * - generatedRegion() the per-tool contract (regenerated freely)\n * - ownedRegionScaffold() the execute() body (written once, then owned)\n * - runtimeSource() / barrelSource() fully-generated support files\n *\n * The contract the output fulfills: read tools work out of the box (a real\n * request to the endpoint), mutation tools start disabled with the working\n * code generated but commented out, and the user-confirmation step for\n * mutations lives in the generated region so it cannot be edited away.\n */\n\nimport { jsonSchemaToTs, pascalCase } from \"../schema.js\";\nimport type { ReviewedTool } from \"../types.js\";\nimport { GENERATED_END, GENERATED_START } from \"./js.js\";\n\n/**\n * Everything above the end-marker of a per-tool file: the parts that must\n * track the API contract exactly: name, description, schema, input type,\n * hints, and the register() wrapper.\n */\nexport function generatedRegion(tool: ReviewedTool): string {\n const pascal = pascalCase(tool.name);\n const camel = lowercaseFirst(pascal);\n const schemaJson = JSON.stringify(tool.inputSchema, null, 2);\n const inputType = jsonSchemaToTs(tool.inputSchema, undefined);\n const mutates = tool.riskTier !== \"safe-read\";\n\n // The imports cover what this file's regions use: the generated register()\n // and the owned execute() scaffold. A developer who replaces the scaffold\n // with their own API client can trim the imports they stop using.\n const runtimeImports = [\n \"getModelContext\",\n ...(mutates ? [\"requestUserConfirmation\"] : []),\n \"callApi\",\n \"toolResult\",\n ...(tool.enabledByDefault ? [] : [\"toolDisabled\"]),\n ].join(\", \");\n\n const registerBody = mutates\n ? [\n ` await modelContext.registerTool(`,\n ` {`,\n ` ...${camel}Tool,`,\n ` execute: async (input) => {`,\n ` // This tool changes things, so the user is always asked first. The`,\n ` // confirmation lives in the generated region: it cannot be edited away.`,\n ` const confirmed = await requestUserConfirmation(`,\n ` ${JSON.stringify(`Allow the agent to: ${tool.description}`)},`,\n ` );`,\n ` if (!confirmed) {`,\n ` return {`,\n ` content: [{ type: \"text\", text: \"The user declined this action.\" }],`,\n ` isError: true,`,\n ` };`,\n ` }`,\n ` // The browser has already validated the agent's input against the schema.`,\n ` return execute${pascal}(input as ${tool.inputTypeName});`,\n ` },`,\n ` },`,\n ` { signal },`,\n ` );`,\n ]\n : [\n ` await modelContext.registerTool(`,\n ` {`,\n ` ...${camel}Tool,`,\n ` // The browser has already validated the agent's input against the schema.`,\n ` execute: (input) => execute${pascal}(input as ${tool.inputTypeName}),`,\n ` },`,\n ` { signal },`,\n ` );`,\n ];\n\n return [\n `import { ${runtimeImports} } from \"./runtime.webmcp\";`,\n ``,\n GENERATED_START,\n `/**`,\n ` * ${tool.description}`,\n ` *`,\n ` * Source: ${tool.source.ref} (${tool.source.kind}). Risk: ${tool.riskTier}.`,\n ` * Starts ${tool.enabledByDefault ? \"enabled\" : \"disabled\"} (see execute${pascal} below).`,\n ` * Regenerate with: npx webmcp-codegen generate`,\n ` */`,\n ``,\n `/** The exact contract advertised to the agent. Derived from the API spec. Do not hand-edit. */`,\n `export const ${camel}InputSchema = ${schemaJson};`,\n ``,\n `/** What \\`execute\\` receives. The browser validates agent input against the schema above. */`,\n `export type ${tool.inputTypeName} = ${inputType};`,\n ``,\n `/** Safety hints computed by webmcp-codegen. Informational metadata for hosts and UIs. */`,\n `export const ${camel}Hints = ${JSON.stringify(tool.hints)} as const;`,\n ``,\n `/** The tool definition, minus \\`execute\\` (which is yours, below the marker). */`,\n `export const ${camel}Tool = {`,\n ` name: ${JSON.stringify(tool.name)},`,\n ` description: ${JSON.stringify(tool.description)},`,\n ` inputSchema: ${camel}InputSchema,`,\n `};`,\n ``,\n `/**`,\n ` * Register this tool with WebMCP. Call it once on page load, or use`,\n ` * registerAllTools() from the generated index.ts.`,\n ` *`,\n ` * Pass an AbortSignal to unregister later: controller.abort().`,\n ` */`,\n `export async function register${pascal}(signal?: AbortSignal): Promise<void> {`,\n ` const modelContext = getModelContext();`,\n ...registerBody,\n `}`,\n ``,\n GENERATED_END,\n ].join(\"\\n\");\n}\n\n/**\n * The scaffold below the marker, written exactly once (when the file is\n * first created). After that the developer owns it and regeneration never\n * touches it. That promise is the whole reason the marker split exists.\n *\n * The scaffold is real code, not a TODO: the spec knows the method, the\n * path, and which fields go where, so the default implementation actually\n * calls the endpoint from the page, with the signed-in user's session.\n * Reads are born working; mutations are born disabled (the working code is\n * right there, commented out, one deliberate edit away from live).\n */\nexport function ownedRegionScaffold(tool: ReviewedTool): string {\n const pascal = pascalCase(tool.name);\n const call = requestCall(tool);\n const lines: string[] = [\n ``,\n `/**`,\n ` * What actually happens when the agent calls \"${tool.name}\".`,\n ` *`,\n ` * Default implementation: calls ${tool.source.ref} from this page, with the`,\n ` * signed-in user's session. Replace it with your app's own API client`,\n ` * whenever you like; the contract above never changes.`,\n ];\n\n if (tool.serverUrl) {\n lines.push(\n ` *`,\n ` * Calls the API at ${tool.serverUrl} (from your spec's servers list).`,\n );\n }\n\n if (tool.riskTier !== \"safe-read\") {\n lines.push(\n ` *`,\n ` * This tool is ${tool.riskTier}: it ${\n tool.riskTier === \"destructive-confirm\" ? \"cannot easily be undone\" : \"changes things\"\n }.`,\n ` * The user is asked to confirm every call (built into the generated region).`,\n );\n }\n lines.push(` */`);\n\n if (tool.piiInOutput.length > 0) {\n lines.push(\n `//`,\n `// ⚠ webmcp-codegen flagged these response fields as likely PII: ${tool.piiInOutput.join(\", \")}.`,\n `// Everything you return reaches the agent. Leave those fields out of what you`,\n `// return unless the agent genuinely needs them, and say so in a comment if you keep them.`,\n );\n }\n\n if (tool.enabledByDefault) {\n lines.push(\n `export async function execute${pascal}(input: ${tool.inputTypeName}) {`,\n ` ${call}`,\n ` return toolResult(data);`,\n `}`,\n );\n } else {\n lines.push(\n `export async function execute${pascal}(input: ${tool.inputTypeName}) {`,\n ` // This tool starts disabled: it ${\n tool.endpointRole === \"endpoint\"\n ? \"changes things\"\n : `wraps an ${tool.endpointRole} endpoint`\n }. Agents can see it, and calling it tells`,\n ` // them it is disabled. To enable it, delete the line below and uncomment the code.`,\n ` return toolDisabled(\"${tool.name}.webmcp.ts\");`,\n ``,\n ` // ${call}`,\n ` // return toolResult(data);`,\n `}`,\n );\n }\n\n return lines.join(\"\\n\");\n}\n\n/**\n * The one working request line inside a scaffold, built from what the spec\n * knows: the path template becomes a template literal, query params become\n * the search string, body fields become the JSON body.\n *\n * \"/pets/{id}\" + DELETE → const data = await callApi(`/pets/${input.id}`, { method: \"DELETE\" });\n *\n * When the source carries no route information, we fall back to an honest\n * TODO instead of inventing a URL.\n */\nfunction requestCall(tool: ReviewedTool): string {\n if (!tool.httpMethod || !tool.pathTemplate || !tool.paramLocations) {\n return `const data = null; // TODO: call your app's existing code here.`;\n }\n\n const { path: pathParams, query: queryParams, body: bodyParams } = tool.paramLocations;\n\n // \"/pets/{id}\" → `/pets/${input.id}`. Params the schema knows by name.\n let pathExpr = `\\`${tool.pathTemplate.replace(/\\{([^}]+)\\}/g, (_m, param: string) => `\\${${inputRef(param)}}`)}\\``;\n if (pathParams.length === 0) pathExpr = JSON.stringify(tool.pathTemplate);\n\n // When the spec declares an absolute server URL, use it so the call goes\n // to the API even when the app and API are on different origins.\n if (tool.serverUrl) {\n const base = tool.serverUrl.endsWith(\"/\") ? tool.serverUrl.slice(0, -1) : tool.serverUrl;\n pathExpr = `\\`${base}\\${${pathExpr}}\\``;\n }\n\n const options: string[] = [`method: ${JSON.stringify(tool.httpMethod)}`];\n if (queryParams.length > 0) {\n const entries = queryParams.map((name) => `${safeKey(name)}: ${inputRef(name)}`).join(\", \");\n options.push(`query: { ${entries} }`);\n }\n if (bodyParams.length > 0) {\n if (bodyParams.length === 1 && bodyParams[0] === \"body\") {\n // A non-object request body arrives as a single \"body\" field.\n options.push(`body: input.body`);\n } else {\n const entries = bodyParams.map((name) => `${safeKey(name)}: ${inputRef(name)}`).join(\", \");\n options.push(`body: { ${entries} }`);\n }\n }\n\n return `const data = await callApi(${pathExpr}, { ${options.join(\", \")} });`;\n}\n\n/**\n * How generated code reads a field off `input`. Dot access for identifier\n * names (\"input.limit\"), bracket access for the rest (\"input[\"pet-id\"]\").\n */\nfunction inputRef(name: string): string {\n return /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(name)\n ? `input.${name}`\n : `input[${JSON.stringify(name)}]`;\n}\n\n/** Quote an object key only when it needs it. */\nfunction safeKey(name: string): string {\n return /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(name) ? name : JSON.stringify(name);\n}\n\n/**\n * The shared runtime: the minimal WebMCP browser types plus the helpers the\n * generated files use. Kept tiny on purpose: this is the only browser\n * coupling in the output.\n */\nexport function runtimeSource(): string {\n return `/**\n * Generated by webmcp-codegen. This file is fully regenerated on every run.\n * Do not edit by hand; your changes will be lost.\n */\n\n/** The result shape tools return (same as MCP tool results). */\nexport interface WebMcpToolResult {\n content: { type: \"text\"; text: string }[];\n isError?: boolean;\n [key: string]: unknown;\n}\n\n/** A tool as the browser runtime understands it. */\nexport interface WebMcpToolDefinition {\n name: string;\n description: string;\n inputSchema?: Record<string, unknown>;\n execute: (input: Record<string, unknown>) => unknown | Promise<unknown>;\n}\n\n/** The slice of the WebMCP draft spec the generated code uses. */\nexport interface ModelContext {\n registerTool(\n tool: WebMcpToolDefinition,\n options?: { signal?: AbortSignal },\n ): Promise<void>;\n}\n\n/**\n * Access the page's WebMCP model context, with a helpful error when the\n * browser doesn't have one (rather than an undefined-callsite mystery).\n */\nexport function getModelContext(): ModelContext {\n const modelContext = (document as unknown as { modelContext?: ModelContext }).modelContext;\n if (!modelContext) {\n throw new Error(\n \"WebMCP is not available in this browser. \" +\n \"Enable chrome://flags/#enable-webmcp-testing (Chrome 146+), \" +\n \"or add the WebMCP polyfill to your app.\",\n );\n }\n return modelContext;\n}\n\n/**\n * Call your API from the page. Same origin by default (pass a full URL when\n * the API lives on another host), always with the signed-in user's session\n * cookies. Throws on HTTP errors; returns the parsed JSON body, or raw text\n * when the response is not JSON.\n */\nexport async function callApi(\n path: string,\n options: { method?: string; query?: Record<string, unknown>; body?: unknown } = {},\n): Promise<unknown> {\n const url = new URL(path, window.location.origin);\n for (const [key, value] of Object.entries(options.query ?? {})) {\n if (value !== undefined && value !== null) url.searchParams.set(key, String(value));\n }\n const response = await fetch(url, {\n method: options.method ?? \"GET\",\n credentials: \"include\",\n headers: options.body !== undefined ? { \"content-type\": \"application/json\" } : undefined,\n body: options.body !== undefined ? JSON.stringify(options.body) : undefined,\n });\n if (!response.ok) {\n throw new Error(\"Request failed: \" + response.status + \" \" + response.statusText);\n }\n if (response.status === 204) return null;\n const text = await response.text();\n try {\n return JSON.parse(text);\n } catch {\n return text;\n }\n}\n\n/** Wrap a result in the MCP shape, so tool bodies stay one line. */\nexport function toolResult(data: unknown): WebMcpToolResult {\n return {\n content: [\n { type: \"text\", text: typeof data === \"string\" ? data : JSON.stringify(data, null, 2) },\n ],\n };\n}\n\n/**\n * What a disabled tool tells the agent. The tool stays visible (so the agent\n * knows it exists and can ask the human to enable it) but does nothing.\n */\nexport function toolDisabled(fileName: string): WebMcpToolResult {\n return {\n content: [\n {\n type: \"text\",\n text:\n \"This tool is currently disabled by the app developer. Ask them to enable it \" +\n \"(uncomment the implementation in \" + fileName + \").\",\n },\n ],\n isError: true,\n };\n}\n\n/**\n * Default \"agent proposes, human confirms\" gate for write/destructive tools.\n * Deliberately minimal (window.confirm). Replace it with your app's own\n * dialog when you outgrow it. The point is that the user always gets a say.\n */\nexport function requestUserConfirmation(message: string): Promise<boolean> {\n return Promise.resolve(window.confirm(message));\n}\n`;\n}\n\n/** The barrel: one import that registers every generated tool. */\nexport function barrelSource(tools: ReviewedTool[]): string {\n const imports = tools\n .map((tool) => `import { register${pascalCase(tool.name)} } from \"./${tool.name}.webmcp\";`)\n .join(\"\\n\");\n const names = tools.map((tool) => `register${pascalCase(tool.name)}`).join(\",\\n \");\n\n return `/**\n * Generated by webmcp-codegen. This file is fully regenerated on every run.\n * Import registerAllTools() once at app startup:\n *\n * import { registerAllTools } from \"./webmcp\";\n * await registerAllTools();\n */\n\n${imports}\n\nconst registrations = [\n ${names}\n];\n\n/**\n * Register every generated tool with WebMCP. One tool failing (for example\n * because the page's Permissions-Policy disables tools) never takes the\n * others down with it. The failure is logged and registration continues.\n */\nexport async function registerAllTools(signal?: AbortSignal): Promise<void> {\n for (const register of registrations) {\n try {\n await register(signal);\n } catch (error) {\n console.warn(\"[webmcp-codegen] a tool failed to register:\", error);\n }\n }\n}\n`;\n}\n\n/** \"GetOrderStatus\" → \"getOrderStatus\" (for the generated const names). */\nfunction lowercaseFirst(pascal: string): string {\n return pascal.charAt(0).toLowerCase() + pascal.slice(1);\n}\n"],"mappings":";;;;;;AAyBA,SAAS,gBAAgB;AACzB,SAAS,YAAY;;;ACId,SAAS,gBAAgB,MAA4B;AAC1D,QAAM,SAAS,WAAW,KAAK,IAAI;AACnC,QAAM,QAAQ,eAAe,MAAM;AACnC,QAAM,aAAa,KAAK,UAAU,KAAK,aAAa,MAAM,CAAC;AAC3D,QAAM,YAAY,eAAe,KAAK,aAAa,MAAS;AAC5D,QAAM,UAAU,KAAK,aAAa;AAKlC,QAAM,iBAAiB;AAAA,IACrB;AAAA,IACA,GAA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