padrone 1.5.0 → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (138) hide show
  1. package/CHANGELOG.md +36 -0
  2. package/README.md +15 -11
  3. package/dist/{args-D5PNDyNu.mjs → args-Cnq0nwSM.mjs} +91 -41
  4. package/dist/args-Cnq0nwSM.mjs.map +1 -0
  5. package/dist/codegen/index.mjs +4 -4
  6. package/dist/codegen/index.mjs.map +1 -1
  7. package/dist/commands-B_gufyR9.mjs +514 -0
  8. package/dist/commands-B_gufyR9.mjs.map +1 -0
  9. package/dist/{completion.mjs → completion-BEuflbDO.mjs} +12 -82
  10. package/dist/completion-BEuflbDO.mjs.map +1 -0
  11. package/dist/docs/index.d.mts +4 -4
  12. package/dist/docs/index.d.mts.map +1 -1
  13. package/dist/docs/index.mjs +10 -12
  14. package/dist/docs/index.mjs.map +1 -1
  15. package/dist/{errors-BiVrBgi6.mjs → errors-CL63UOzt.mjs} +26 -3
  16. package/dist/errors-CL63UOzt.mjs.map +1 -0
  17. package/dist/{formatter-DtHzbP22.d.mts → formatter-DrvhDMrq.d.mts} +3 -3
  18. package/dist/formatter-DrvhDMrq.d.mts.map +1 -0
  19. package/dist/{help-bbmu9-qd.mjs → help-B5Kk83of.mjs} +151 -37
  20. package/dist/help-B5Kk83of.mjs.map +1 -0
  21. package/dist/{types-Ch8Mk6Qb.d.mts → index-BaU3X6dY.d.mts} +621 -750
  22. package/dist/index-BaU3X6dY.d.mts.map +1 -0
  23. package/dist/index.d.mts +735 -37
  24. package/dist/index.d.mts.map +1 -1
  25. package/dist/index.mjs +3409 -1563
  26. package/dist/index.mjs.map +1 -1
  27. package/dist/{mcp-mLWIdUIu.mjs → mcp-BM-d0nZi.mjs} +13 -15
  28. package/dist/mcp-BM-d0nZi.mjs.map +1 -0
  29. package/dist/{serve-B0u43DK7.mjs → serve-Bk0JUlCj.mjs} +12 -14
  30. package/dist/serve-Bk0JUlCj.mjs.map +1 -0
  31. package/dist/{stream-BcC146Ud.mjs → stream-DC4H8YTx.mjs} +24 -3
  32. package/dist/stream-DC4H8YTx.mjs.map +1 -0
  33. package/dist/test.d.mts +5 -8
  34. package/dist/test.d.mts.map +1 -1
  35. package/dist/test.mjs +2 -13
  36. package/dist/test.mjs.map +1 -1
  37. package/dist/{update-check-CFX1FV3v.mjs → update-check-CZ2VqjnV.mjs} +16 -17
  38. package/dist/update-check-CZ2VqjnV.mjs.map +1 -0
  39. package/dist/zod.d.mts +2 -2
  40. package/dist/zod.d.mts.map +1 -1
  41. package/dist/zod.mjs +2 -2
  42. package/dist/zod.mjs.map +1 -1
  43. package/package.json +15 -12
  44. package/src/cli/completions.ts +14 -11
  45. package/src/cli/docs.ts +13 -10
  46. package/src/cli/doctor.ts +22 -18
  47. package/src/cli/index.ts +28 -82
  48. package/src/cli/init.ts +10 -7
  49. package/src/cli/link.ts +20 -16
  50. package/src/cli/wrap.ts +14 -11
  51. package/src/codegen/schema-to-code.ts +2 -2
  52. package/src/{args.ts → core/args.ts} +32 -225
  53. package/src/core/commands.ts +373 -0
  54. package/src/core/create.ts +268 -0
  55. package/src/core/default-runtime.ts +239 -0
  56. package/src/{errors.ts → core/errors.ts} +22 -0
  57. package/src/core/exec.ts +259 -0
  58. package/src/core/interceptors.ts +302 -0
  59. package/src/{parse.ts → core/parse.ts} +36 -89
  60. package/src/core/program-methods.ts +301 -0
  61. package/src/core/results.ts +229 -0
  62. package/src/core/runtime.ts +246 -0
  63. package/src/core/validate.ts +247 -0
  64. package/src/docs/index.ts +12 -13
  65. package/src/extension/auto-output.ts +95 -0
  66. package/src/extension/color.ts +38 -0
  67. package/src/extension/completion.ts +49 -0
  68. package/src/extension/config.ts +262 -0
  69. package/src/extension/env.ts +101 -0
  70. package/src/extension/help.ts +192 -0
  71. package/src/extension/index.ts +43 -0
  72. package/src/extension/ink.ts +93 -0
  73. package/src/extension/interactive.ts +106 -0
  74. package/src/extension/logger.ts +214 -0
  75. package/src/extension/man.ts +51 -0
  76. package/src/extension/mcp.ts +52 -0
  77. package/src/extension/progress-renderer.ts +338 -0
  78. package/src/extension/progress.ts +299 -0
  79. package/src/extension/repl.ts +94 -0
  80. package/src/extension/serve.ts +48 -0
  81. package/src/extension/signal.ts +87 -0
  82. package/src/extension/stdin.ts +62 -0
  83. package/src/extension/suggestions.ts +114 -0
  84. package/src/extension/timing.ts +81 -0
  85. package/src/extension/tracing.ts +175 -0
  86. package/src/extension/update-check.ts +77 -0
  87. package/src/extension/utils.ts +51 -0
  88. package/src/extension/version.ts +63 -0
  89. package/src/{completion.ts → feature/completion.ts} +12 -12
  90. package/src/{interactive.ts → feature/interactive.ts} +4 -4
  91. package/src/{mcp.ts → feature/mcp.ts} +12 -15
  92. package/src/{repl-loop.ts → feature/repl-loop.ts} +10 -13
  93. package/src/{serve.ts → feature/serve.ts} +11 -15
  94. package/src/feature/test.ts +262 -0
  95. package/src/{update-check.ts → feature/update-check.ts} +16 -16
  96. package/src/{wrap.ts → feature/wrap.ts} +10 -8
  97. package/src/index.ts +111 -30
  98. package/src/{formatter.ts → output/formatter.ts} +131 -31
  99. package/src/{help.ts → output/help.ts} +22 -8
  100. package/src/{zod.d.ts → schema/zod.d.ts} +1 -1
  101. package/src/schema/zod.ts +50 -0
  102. package/src/test.ts +2 -276
  103. package/src/types/args-meta.ts +151 -0
  104. package/src/types/builder.ts +697 -0
  105. package/src/types/command.ts +157 -0
  106. package/src/types/index.ts +59 -0
  107. package/src/types/interceptor.ts +296 -0
  108. package/src/types/preferences.ts +83 -0
  109. package/src/types/result.ts +71 -0
  110. package/src/types/schema.ts +19 -0
  111. package/src/util/dotenv.ts +244 -0
  112. package/src/{shell-utils.ts → util/shell-utils.ts} +26 -9
  113. package/src/{stream.ts → util/stream.ts} +27 -1
  114. package/src/{type-helpers.ts → util/type-helpers.ts} +23 -16
  115. package/src/{type-utils.ts → util/type-utils.ts} +71 -33
  116. package/src/util/utils.ts +51 -0
  117. package/src/zod.ts +1 -50
  118. package/dist/args-D5PNDyNu.mjs.map +0 -1
  119. package/dist/chunk-CjcI7cDX.mjs +0 -15
  120. package/dist/command-utils-B1D-HqCd.mjs +0 -1117
  121. package/dist/command-utils-B1D-HqCd.mjs.map +0 -1
  122. package/dist/completion.d.mts +0 -64
  123. package/dist/completion.d.mts.map +0 -1
  124. package/dist/completion.mjs.map +0 -1
  125. package/dist/errors-BiVrBgi6.mjs.map +0 -1
  126. package/dist/formatter-DtHzbP22.d.mts.map +0 -1
  127. package/dist/help-bbmu9-qd.mjs.map +0 -1
  128. package/dist/mcp-mLWIdUIu.mjs.map +0 -1
  129. package/dist/serve-B0u43DK7.mjs.map +0 -1
  130. package/dist/stream-BcC146Ud.mjs.map +0 -1
  131. package/dist/types-Ch8Mk6Qb.d.mts.map +0 -1
  132. package/dist/update-check-CFX1FV3v.mjs.map +0 -1
  133. package/src/command-utils.ts +0 -882
  134. package/src/create.ts +0 -1829
  135. package/src/runtime.ts +0 -497
  136. package/src/types.ts +0 -1291
  137. package/src/utils.ts +0 -140
  138. /package/src/{colorizer.ts → output/colorizer.ts} +0 -0
@@ -1 +0,0 @@
1
- {"version":3,"file":"command-utils-B1D-HqCd.mjs","names":[],"sources":["../src/utils.ts","../src/runtime.ts","../src/command-utils.ts"],"sourcesContent":["import type { AnyPadroneCommand } from './types.ts';\n\nexport function getRootCommand(cmd: AnyPadroneCommand): AnyPadroneCommand {\n let current = cmd;\n while (current.parent) current = current.parent;\n return current;\n}\n\n/**\n * Attempts to get the version from various sources:\n * 1. Explicit version set on the command\n * 2. npm_package_version environment variable (set by npm/yarn/pnpm when running scripts)\n * 3. package.json in current or parent directories\n * @param explicitVersion - Version explicitly set via .version()\n * @returns The version string or '0.0.0' if not found\n */\nexport function getVersion(explicitVersion?: string): string {\n // 1. Use explicit version if provided\n if (explicitVersion) return explicitVersion;\n\n // 2. Check npm_package_version env var (set by npm/yarn/pnpm during script execution)\n if (typeof process !== 'undefined' && process.env?.npm_package_version) {\n return process.env.npm_package_version;\n }\n\n // 3. Try to read from package.json\n if (typeof process !== 'undefined') {\n try {\n const fs = require('node:fs');\n const path = require('node:path');\n let dir = process.cwd();\n\n // Walk up the directory tree looking for package.json\n for (let i = 0; i < 10; i++) {\n const pkgPath = path.join(dir, 'package.json');\n if (fs.existsSync(pkgPath)) {\n const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8'));\n if (pkg.version) return pkg.version;\n }\n const parentDir = path.dirname(dir);\n if (parentDir === dir) break; // Reached root\n dir = parentDir;\n }\n } catch {\n // Ignore errors (e.g., fs not available in browser)\n }\n }\n\n return '0.0.0';\n}\n\n/**\n * Loads and parses a config file from the given path.\n * Supports JSON, JSONC (JSON with comments), and attempts to parse other formats.\n * @param configPath - Path to the config file\n * @returns Parsed config data or undefined if loading fails\n */\nexport function loadConfigFile(configPath: string): Record<string, unknown> | undefined {\n if (typeof process === 'undefined') return undefined;\n\n try {\n const fs = require('node:fs');\n const path = require('node:path');\n\n // Resolve to absolute path\n const absolutePath = path.isAbsolute(configPath) ? configPath : path.resolve(process.cwd(), configPath);\n\n if (!fs.existsSync(absolutePath)) {\n console.error(`Config file not found: ${absolutePath}`);\n return undefined;\n }\n\n const getContent = () => fs.readFileSync(absolutePath, 'utf-8');\n const ext = path.extname(absolutePath).toLowerCase();\n\n if (ext === '.yaml' || ext === '.yml') {\n return Bun.YAML.parse(getContent()) as any;\n }\n\n if (ext === '.toml') {\n return Bun.TOML.parse(getContent()) as any;\n }\n\n if (ext === '.json') {\n if (Bun.JSONC) return Bun.JSONC.parse(getContent()) as any;\n try {\n return JSON.parse(getContent());\n } catch {\n return Bun.JSONC.parse(getContent()) as any;\n }\n }\n\n if (ext === '.jsonc') {\n return Bun.JSONC.parse(getContent()) as any;\n }\n\n if (ext === '.js' || ext === '.cjs' || ext === '.mjs' || ext === '.ts' || ext === '.cts' || ext === '.mts') {\n // For JS files, require them\n return require(absolutePath);\n }\n\n // For unknown extensions, try to parse as JSON\n try {\n return JSON.parse(getContent());\n } catch {\n console.error(`Unable to parse config file: ${absolutePath}`);\n return undefined;\n }\n } catch (error) {\n console.error(`Error loading config file: ${error}`);\n return undefined;\n }\n}\n\n/**\n * Searches for a config file from a list of possible file names.\n * Searches in the current working directory.\n * @param configFiles - Array of possible config file names to search for\n * @returns The path to the first found config file, or undefined if none found\n */\nexport function findConfigFile(configFiles: string[]): string | undefined {\n if (typeof process === 'undefined' || !configFiles?.length) return undefined;\n\n try {\n const fs = require('node:fs');\n const path = require('node:path');\n const cwd = process.cwd();\n\n for (const configFile of configFiles) {\n const configPath = path.isAbsolute(configFile) ? configFile : path.resolve(cwd, configFile);\n if (fs.existsSync(configPath)) {\n return configPath;\n }\n }\n } catch {\n // Ignore errors (e.g., fs not available in browser)\n }\n\n return undefined;\n}\n","import type { ColorConfig, ColorTheme } from './colorizer.ts';\nimport type { HelpFormat } from './formatter.ts';\nimport { findConfigFile, loadConfigFile } from './utils.ts';\n\n/**\n * A progress indicator instance (spinner, progress bar, etc).\n * Created by the runtime's `progress` factory and used to show loading state during command execution.\n */\nexport type PadroneProgressIndicator = {\n /** Update the displayed message. */\n update: (message: string) => void;\n /** Mark as succeeded and stop. Pass `null` to stop without rendering a final message. */\n succeed: (message?: string | null, options?: { indicator?: string }) => void;\n /** Mark as failed and stop. Pass `null` to stop without rendering a final message. */\n fail: (message?: string | null, options?: { indicator?: string }) => void;\n /** Stop without success/fail status. */\n stop: () => void;\n /** Temporarily hide the indicator so other output can be written cleanly. */\n pause: () => void;\n /** Redraw the indicator after a `pause()`. */\n resume: () => void;\n};\n\n/** Built-in spinner presets. */\nexport type PadroneSpinnerPreset = 'dots' | 'line' | 'arc' | 'bounce';\n\n/**\n * Spinner configuration for progress indicators.\n * - A preset name (e.g., `'dots'`) to use built-in frames.\n * - An object with custom `frames` and/or `interval`.\n * - `false` to disable the spinner animation (static text only).\n */\nexport type PadroneSpinnerConfig = PadroneSpinnerPreset | { frames?: string[]; interval?: number } | false;\n\n/**\n * Options passed to the runtime's `progress` factory.\n */\nexport type PadroneProgressOptions = {\n spinner?: PadroneSpinnerConfig;\n /** Character/string shown before the success message. Defaults to `'✔'`. */\n successIndicator?: string;\n /** Character/string shown before the error message. Defaults to `'✖'`. */\n errorIndicator?: string;\n};\n\n/**\n * Controls interactive prompting capability and default behavior at the runtime level.\n * - `'supported'` — capable; caller decides.\n * - `'unsupported'` — hard veto; nothing can override.\n * - `'forced'` — capable and forces prompts by default.\n * - `'disabled'` — capable but suppresses prompts by default.\n */\nexport type InteractiveMode = 'supported' | 'unsupported' | 'forced' | 'disabled';\n\n/**\n * Configuration passed to the runtime's `prompt` function for interactive field prompting.\n * The prompt type and choices are auto-detected from the field's JSON schema.\n */\nexport type InteractivePromptConfig = {\n /** The field name being prompted. */\n name: string;\n /** Human-readable message/label for the prompt, derived from the field's description or name. */\n message: string;\n /** The prompt type, auto-detected from the JSON schema. */\n type: 'input' | 'confirm' | 'select' | 'multiselect' | 'password';\n /** Available choices for select/multiselect prompts. */\n choices?: { label: string; value: unknown }[];\n /** Default value from the schema. */\n default?: unknown;\n};\n\n/**\n * Defines the execution context for a Padrone program.\n * Abstracts all environment-dependent I/O so the CLI framework\n * can run outside of a terminal (e.g., web UIs, chat interfaces, testing).\n *\n * All fields are optional — unspecified fields fall back to the Node.js/Bun defaults.\n */\nexport type PadroneRuntime = {\n /** Write normal output (replaces console.log). Receives the raw value — runtime handles formatting. */\n output?: (...args: unknown[]) => void;\n /** Write error output (replaces console.error). */\n error?: (text: string) => void;\n /** Return the raw CLI arguments (replaces process.argv.slice(2)). */\n argv?: () => string[];\n /** Return environment variables (replaces process.env). */\n env?: () => Record<string, string | undefined>;\n /** Default help output format. */\n format?: HelpFormat | 'auto';\n /** Color theme for ANSI/console help output. A theme name or partial color config. */\n theme?: ColorTheme | ColorConfig;\n /** Load and parse a config file by path. Return undefined if not found or unparsable. */\n loadConfigFile?: (path: string) => Record<string, unknown> | undefined;\n /** Find the first existing file from a list of candidate names. */\n findFile?: (names: string[]) => string | undefined;\n /**\n * Standard input abstraction. Provides methods to read piped data from stdin.\n * When not provided, defaults to reading from `process.stdin`.\n *\n * Used by commands that declare a `stdin` field in their arguments meta.\n * The framework reads stdin automatically during the validate phase and\n * injects the data into the specified argument field.\n */\n stdin?: {\n /** Whether stdin is a TTY (interactive terminal) vs a pipe/file. */\n isTTY?: boolean;\n /** Read all of stdin as a string. */\n text: () => Promise<string>;\n /** Async iterable of lines for streaming. */\n lines: () => AsyncIterable<string>;\n };\n /**\n * Controls interactive prompting capability and default behavior.\n * - `'supported'` — runtime can handle prompts; caller (flag/pref) decides whether to prompt. This is the default when `prompt` is provided.\n * - `'unsupported'` — runtime cannot handle prompts; hard veto that nothing can override.\n * - `'forced'` — runtime supports prompts and forces them by default (prompts even for provided values).\n * - `'disabled'` — runtime supports prompts but suppresses them by default.\n *\n * `'unsupported'` is the only immutable state. For the others, the `--interactive`/`-i` flag\n * and `cli()` preferences can override the default behavior.\n */\n interactive?: InteractiveMode;\n /**\n * Prompt the user for input. Called during `cli()` for fields marked as interactive.\n * When `interactive` is `true` and this is not provided, defaults to an Enquirer-based terminal prompt.\n */\n prompt?: (config: InteractivePromptConfig) => Promise<unknown>;\n /**\n * Create a progress indicator (spinner, progress bar, etc).\n * Used by commands that set `progress` in their config, or manually via `ctx.progress()` in actions.\n * When not provided, auto-progress is silently skipped and `ctx.progress()` returns a no-op indicator.\n */\n progress?: (message: string, options?: PadroneProgressOptions) => PadroneProgressIndicator;\n /**\n * Read a line of input from the user. Used by `repl()` for custom runtimes\n * (web UIs, chat interfaces, testing).\n * Returns the input string, `null` on EOF (e.g. Ctrl+D, closed connection),\n * or `REPL_SIGINT` when the user presses Ctrl+C.\n *\n * When not provided, `repl()` uses a built-in Node.js readline session\n * with command history (up/down arrows) and tab completion.\n */\n readLine?: (prompt: string) => Promise<string | typeof REPL_SIGINT | null>;\n};\n\n/**\n * Internal resolved runtime where all fields are guaranteed to be present.\n * The `prompt`, `interactive`, and `readLine` fields remain optional since not all runtimes provide them.\n */\nexport type ResolvedPadroneRuntime = Required<\n Omit<PadroneRuntime, 'prompt' | 'interactive' | 'readLine' | 'stdin' | 'progress' | 'theme'>\n> &\n Pick<PadroneRuntime, 'prompt' | 'interactive' | 'readLine' | 'stdin' | 'progress' | 'theme'>;\n\n/**\n * Default terminal prompt implementation powered by Enquirer.\n * Lazily imported to avoid loading Enquirer when not needed.\n */\nasync function defaultTerminalPrompt(config: InteractivePromptConfig): Promise<unknown> {\n const Enquirer = (await import('enquirer')).default;\n\n const question: Record<string, unknown> = {\n type: config.type,\n name: config.name,\n message: config.message,\n };\n\n if (config.default !== undefined) {\n question.initial = config.default;\n }\n\n if (config.choices) {\n question.choices = config.choices.map((c) => ({\n name: String(c.value),\n message: c.label,\n }));\n }\n\n const response = (await Enquirer.prompt(question as any)) as Record<string, unknown>;\n return response[config.name];\n}\n\n/**\n * Internal session config for the REPL's persistent readline interface.\n */\nexport type ReplSessionConfig = {\n completer?: (line: string) => [string[], string];\n history?: string[];\n};\n\n/**\n * Creates a persistent Node.js readline session for the REPL.\n * Enables up/down arrow history navigation and tab completion.\n * Used internally by `repl()` when no custom `readLine` is provided.\n */\n/**\n * Sentinel value returned by the terminal REPL session when Ctrl+C is pressed.\n * Distinguished from empty string (user pressed enter) and null (EOF/Ctrl+D).\n */\nexport const REPL_SIGINT = Symbol('REPL_SIGINT');\n\nexport function createTerminalReplSession(config: ReplSessionConfig) {\n // History accumulates across per-call interfaces, giving us\n // up/down arrow navigation without a persistent stdin listener\n // that would conflict with Enquirer or other stdin consumers.\n let history: string[] = config.history ? [...config.history] : [];\n let currentCompleter = config.completer;\n\n return {\n /** Update the tab completer (e.g. when REPL scope changes). Takes effect on the next question. */\n set completer(fn: ((line: string) => [string[], string]) | undefined) {\n currentCompleter = fn;\n },\n async question(prompt: string): Promise<string | typeof REPL_SIGINT | null> {\n const { createInterface } = await import('node:readline');\n const opts: Record<string, unknown> = {\n input: process.stdin,\n output: process.stdout,\n terminal: true,\n history: [...history],\n historySize: Math.max(history.length, 1000),\n };\n if (currentCompleter) {\n opts.completer = currentCompleter;\n }\n const rl = createInterface(opts as any);\n\n return new Promise((resolve) => {\n let resolved = false;\n const settle = (value: string | typeof REPL_SIGINT | null) => {\n if (resolved) return;\n resolved = true;\n rl.close();\n resolve(value);\n };\n\n rl.question(prompt, (answer) => {\n // Grab updated history (includes the new entry) before closing.\n if (Array.isArray((rl as any).history)) history = [...(rl as any).history];\n settle(answer);\n });\n // Ctrl+C: cancel current line, print newline, resolve SIGINT sentinel.\n rl.once('SIGINT', () => {\n process.stdout.write('\\n');\n settle(REPL_SIGINT);\n });\n // EOF (Ctrl+D) fires close without the question callback.\n rl.once('close', () => {\n // Write newline so zsh doesn't show '%' (partial-line indicator).\n process.stdout.write('\\n');\n settle(null);\n });\n });\n },\n close() {\n // No persistent interface to clean up.\n },\n };\n}\n\n/**\n * Auto-detect interactive mode when not explicitly set.\n * Returns 'disabled' in CI environments or non-TTY contexts, 'supported' otherwise.\n */\nfunction detectInteractiveMode(): InteractiveMode {\n if (typeof process === 'undefined') return 'disabled';\n if (process.env.CI || process.env.CONTINUOUS_INTEGRATION) return 'disabled';\n if (!process.stdout?.isTTY) return 'disabled';\n return 'supported';\n}\n\n/**\n * Creates the default Node.js/Bun runtime.\n */\n/**\n * Creates a default stdin reader from `process.stdin`.\n * Only created when a command actually declares a `stdin` meta field.\n */\nfunction createDefaultStdin(): NonNullable<PadroneRuntime['stdin']> {\n return {\n get isTTY() {\n // process.stdin.isTTY is `true` when interactive terminal, `undefined` when piped/redirected.\n // Node.js never sets it to `false` — it's either `true` or absent.\n if (typeof process === 'undefined') return true;\n return process.stdin?.isTTY === true;\n },\n async text() {\n if (typeof process === 'undefined') return '';\n const chunks: Buffer[] = [];\n for await (const chunk of process.stdin) {\n chunks.push(typeof chunk === 'string' ? Buffer.from(chunk) : chunk);\n }\n return Buffer.concat(chunks).toString('utf-8');\n },\n async *lines() {\n if (typeof process === 'undefined') return;\n const { createInterface } = await import('node:readline');\n const rl = createInterface({ input: process.stdin });\n try {\n for await (const line of rl) {\n yield line;\n }\n } finally {\n rl.close();\n }\n },\n };\n}\n\nconst spinnerPresets: Record<PadroneSpinnerPreset, string[]> = {\n dots: ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'],\n line: ['-', '\\\\', '|', '/'],\n arc: ['◜', '◠', '◝', '◞', '◡', '◟'],\n bounce: ['⠁', '⠂', '⠄', '⡀', '⢀', '⠠', '⠐', '⠈'],\n};\n\nfunction resolveSpinnerConfig(config?: PadroneSpinnerConfig): { frames: string[]; interval: number; disabled: boolean } {\n if (config === false) return { frames: [], interval: 80, disabled: true };\n if (typeof config === 'string') return { frames: spinnerPresets[config], interval: 80, disabled: false };\n if (typeof config === 'object') {\n return {\n frames: config.frames ?? spinnerPresets.dots,\n interval: config.interval ?? 80,\n disabled: false,\n };\n }\n return { frames: spinnerPresets.dots, interval: 80, disabled: false };\n}\n\n/**\n * Creates a built-in terminal spinner. Returns a no-op indicator in non-TTY/CI environments.\n */\nfunction createTerminalSpinner(message: string, options?: PadroneProgressOptions): PadroneProgressIndicator {\n const { frames, interval, disabled: spinnerDisabled } = resolveSpinnerConfig(options?.spinner);\n const successIcon = options?.successIndicator ?? '✔';\n const errorIcon = options?.errorIndicator ?? '✖';\n\n const formatFinal = (icon: string, msg: string) => (icon ? `${icon} ${msg}\\n` : `${msg}\\n`);\n\n if (typeof process === 'undefined' || !process.stderr?.isTTY) {\n // Non-TTY: just log start/end, no animation\n return {\n update() {},\n succeed(msg, opts) {\n if (msg === null) return;\n const icon = opts?.indicator ?? successIcon;\n if (msg || message) process?.stderr?.write?.(formatFinal(icon, msg || message));\n },\n fail(msg, opts) {\n if (msg === null) return;\n const icon = opts?.indicator ?? errorIcon;\n if (msg || message) process?.stderr?.write?.(formatFinal(icon, msg || message));\n },\n stop() {},\n pause() {},\n resume() {},\n };\n }\n\n // If spinner is disabled and there's no message, nothing to render\n if (spinnerDisabled && !message) {\n return { update() {}, succeed() {}, fail() {}, stop() {}, pause() {}, resume() {} };\n }\n\n let frame = 0;\n let text = message;\n let stopped = false;\n let paused = false;\n\n const writeStderr = process.stderr.write.bind(process.stderr);\n const writeStdout = process.stdout.write.bind(process.stdout);\n const clearLine = () => writeStderr('\\x1b[2K\\r');\n\n const render = () => {\n if (paused || stopped) return;\n if (spinnerDisabled) {\n // Static text only, no spinner frames\n if (text) writeStderr(`\\x1b[2K\\r${text}`);\n } else {\n const prefix = frames[frame] ?? '';\n writeStderr(`\\x1b[2K\\r${text ? `${prefix} ${text}` : prefix}`);\n }\n };\n\n const timer = spinnerDisabled\n ? undefined\n : setInterval(() => {\n frame = (frame + 1) % frames.length;\n render();\n }, interval);\n\n render();\n\n const clear = () => {\n if (stopped) return;\n stopped = true;\n paused = false;\n if (timer) clearInterval(timer);\n clearLine();\n };\n\n return {\n update(msg) {\n if (stopped) return;\n text = msg;\n render();\n },\n succeed(msg, opts) {\n clear();\n if (msg === null) return;\n const finalMsg = msg ?? text;\n const icon = opts?.indicator ?? successIcon;\n if (finalMsg) writeStderr(formatFinal(icon, finalMsg));\n },\n fail(msg, opts) {\n clear();\n if (msg === null) return;\n const finalMsg = msg ?? text;\n const icon = opts?.indicator ?? errorIcon;\n if (finalMsg) writeStderr(formatFinal(icon, finalMsg));\n },\n stop() {\n clear();\n },\n pause() {\n if (stopped || paused) return;\n paused = true;\n clearLine();\n writeStdout('\\x1b[2K\\r');\n },\n resume() {\n if (stopped || !paused) return;\n paused = false;\n render();\n },\n };\n}\n\nexport function createDefaultRuntime(): ResolvedPadroneRuntime {\n return {\n output: (...args) => console.log(...args),\n error: (text) => console.error(text),\n argv: () => (typeof process !== 'undefined' ? process.argv.slice(2) : []),\n env: () => (typeof process !== 'undefined' ? (process.env as Record<string, string | undefined>) : {}),\n format: 'auto',\n loadConfigFile,\n findFile: findConfigFile,\n prompt: defaultTerminalPrompt,\n interactive: detectInteractiveMode(),\n progress: createTerminalSpinner,\n };\n}\n\n/**\n * Merges a partial runtime with the default runtime.\n */\n/**\n * Returns the stdin abstraction: custom runtime stdin > default process.stdin.\n * Returns `undefined` when no custom stdin is provided and process.stdin is not piped.\n */\nexport function resolveStdin(partial?: PadroneRuntime): NonNullable<PadroneRuntime['stdin']> | undefined {\n if (partial?.stdin) return partial.stdin;\n const defaultStdin = createDefaultStdin();\n // Only use default stdin if it's actually piped (isTTY === false).\n // This avoids accidentally blocking on stdin in tests/CI.\n if (defaultStdin.isTTY) return undefined;\n return defaultStdin;\n}\n\n/**\n * Like `resolveStdin`, but always returns a stdin source even when it's a TTY.\n * Used for async streams which support interactive (non-piped) input.\n */\nexport function resolveStdinAlways(partial?: PadroneRuntime): NonNullable<PadroneRuntime['stdin']> {\n if (partial?.stdin) return partial.stdin;\n return createDefaultStdin();\n}\n\nexport function resolveRuntime(partial?: PadroneRuntime): ResolvedPadroneRuntime {\n const defaults = createDefaultRuntime();\n if (!partial) return defaults;\n return {\n output: partial.output ?? defaults.output,\n error: partial.error ?? defaults.error,\n argv: partial.argv ?? defaults.argv,\n env: partial.env ?? defaults.env,\n format: partial.format ?? defaults.format,\n loadConfigFile: partial.loadConfigFile ?? defaults.loadConfigFile,\n findFile: partial.findFile ?? defaults.findFile,\n interactive: partial.interactive ?? defaults.interactive,\n prompt: partial.prompt ?? defaults.prompt,\n readLine: partial.readLine ?? defaults.readLine,\n progress: partial.progress ?? defaults.progress,\n stdin: partial.stdin,\n theme: partial.theme,\n };\n}\n","import { extractSchemaMetadata, JSON_SCHEMA_OPTS } from './args.ts';\nimport { type PadroneProgressIndicator, type ResolvedPadroneRuntime, resolveRuntime } from './runtime.ts';\nimport type { Thenable } from './type-utils.ts';\nimport type {\n AnyPadroneCommand,\n PadronePlugin,\n PadroneSchema,\n PluginErrorContext,\n PluginErrorResult,\n PluginShutdownContext,\n PluginStartContext,\n} from './types.ts';\n\n// ---------------------------------------------------------------------------\n// Lazy command resolution\n// ---------------------------------------------------------------------------\n\nexport const lazyResolver = Symbol('lazyResolver');\n\n/** Resolves a lazy command in place by calling its stored resolver. No-op if already resolved. */\nexport function resolveCommand(cmd: AnyPadroneCommand): AnyPadroneCommand {\n const resolver = (cmd as any)[lazyResolver];\n if (resolver) {\n delete (cmd as any)[lazyResolver];\n resolver(cmd);\n }\n return cmd;\n}\n\n/** Recursively resolves a command and all its descendants. */\nexport function resolveAllCommands(cmd: AnyPadroneCommand): void {\n resolveCommand(cmd);\n if (cmd.commands) {\n for (const sub of cmd.commands) resolveAllCommands(sub);\n }\n}\n\n/** Checks whether a value is a Padrone program/builder. */\nexport function isPadroneProgram(value: unknown): value is object {\n return !!value && typeof value === 'object' && commandSymbol in value;\n}\n\n/** Extracts the underlying command from a program/builder and resolves the full command tree. */\nexport function getCommand(program: object): AnyPadroneCommand {\n const cmd = commandSymbol in program ? ((program as any)[commandSymbol] as AnyPadroneCommand) : (program as AnyPadroneCommand);\n resolveAllCommands(cmd);\n return cmd;\n}\n\n/**\n * Brands a schema as async, signaling that its `validate()` may return a Promise.\n * When an async-branded schema is passed to `.arguments()`, `.configFile()`, or `.env()`,\n * the command's `parse()` and `cli()` will return Promises.\n *\n * @example\n * ```ts\n * const schema = asyncSchema(z.object({\n * name: z.string(),\n * }).check(async (data) => {\n * // async validation logic\n * }));\n *\n * const program = createPadrone('app')\n * .command('greet', (c) => c.arguments(schema).action((args) => args.name));\n *\n * // parse() now returns Promise<PadroneParseResult>\n * const result = await program.parse('greet --name world');\n * ```\n */\nexport function asyncSchema<T extends PadroneSchema>(schema: T): T & { '~async': true } {\n return Object.assign(schema, { '~async': true as const });\n}\n\nexport const commandSymbol = Symbol('padrone_command');\n\nexport const noop = <TRes>() => undefined as TRes;\n\n/** Config keys that are merged when overriding a command. */\nexport const configKeys = [\n 'title',\n 'description',\n 'version',\n 'deprecated',\n 'hidden',\n 'mutation',\n 'needsApproval',\n 'autoOutput',\n 'updateCheck',\n] as const;\n\n/**\n * Merges an existing command with an override.\n * - Config fields are shallow-merged (new overrides old).\n * - Action, arguments, meta, config schema, env schema are taken from the override if set.\n * - Subcommands are recursively merged by name.\n */\nexport function mergeCommands(existing: AnyPadroneCommand, override: AnyPadroneCommand): AnyPadroneCommand {\n resolveCommand(existing);\n resolveCommand(override);\n const merged: AnyPadroneCommand = { ...existing };\n\n // Merge config fields\n for (const key of configKeys) {\n if (override[key] !== undefined) (merged as any)[key] = override[key];\n }\n\n // Override fields: take from override if explicitly set (not inherited from existing via spread)\n if (override.action !== existing.action) merged.action = override.action;\n if (override.argsSchema !== existing.argsSchema) merged.argsSchema = override.argsSchema;\n if (override.meta !== existing.meta) merged.meta = override.meta;\n if (override.configSchema !== existing.configSchema) merged.configSchema = override.configSchema;\n if (override.envSchema !== existing.envSchema) merged.envSchema = override.envSchema;\n if (override.configFiles !== existing.configFiles) merged.configFiles = override.configFiles;\n if (override.isAsync !== existing.isAsync) merged.isAsync = override.isAsync || existing.isAsync;\n if (override.runtime !== existing.runtime) merged.runtime = override.runtime;\n if (override.plugins !== existing.plugins) merged.plugins = override.plugins;\n if (override.aliases !== existing.aliases) merged.aliases = override.aliases;\n if (override.progress !== existing.progress) merged.progress = override.progress;\n\n // Recursively merge subcommands by name\n if (override.commands) {\n const baseCommands = [...(existing.commands || [])];\n for (const overrideChild of override.commands) {\n const existingIndex = baseCommands.findIndex((c) => c.name === overrideChild.name);\n if (existingIndex >= 0) {\n baseCommands[existingIndex] = mergeCommands(baseCommands[existingIndex]!, overrideChild);\n } else {\n baseCommands.push(overrideChild);\n }\n }\n merged.commands = baseCommands;\n }\n\n return merged;\n}\n\n/**\n * Maps over a value that may or may not be a Promise.\n * If the value is a Promise, chains with `.then()`. Otherwise, calls the function synchronously.\n * This preserves sync behavior for sync schemas and async behavior for async schemas.\n */\nexport function thenMaybe<T, U>(value: T | Promise<T>, fn: (v: T) => U | Promise<U>): U | Promise<U> {\n if (value instanceof Promise) return value.then(fn);\n return fn(value);\n}\n\n/**\n * Makes a sync result object thenable by adding `.then()`, `.catch()`, and `.finally()` methods.\n * If the value is already a Promise, returns it as-is.\n * This allows users to write `await program.cli()` or `program.cli().then(...)` regardless of sync/async.\n *\n * The `.then()` resolves with a plain copy (without thenable methods) to avoid infinite\n * recursive unwrapping by the Promise resolution algorithm.\n */\nexport function makeThenable<T>(value: T | Promise<T>): Thenable<T> {\n if (value instanceof Promise) return value as any;\n if (value !== null && typeof value === 'object' && !('then' in value)) {\n const toPlain = () => {\n const plain = { ...value } as any;\n delete plain.then;\n delete plain.catch;\n delete plain.finally;\n return plain as T;\n };\n // biome-ignore lint/suspicious/noThenProperty: intentional thenable shim for sync results\n (value as any).then = (onfulfilled?: (v: T) => any, onrejected?: (reason: any) => any) => {\n try {\n const result = onfulfilled ? onfulfilled(toPlain()) : toPlain();\n return Promise.resolve(result);\n } catch (err) {\n if (onrejected) return Promise.resolve(onrejected(err));\n return Promise.reject(err);\n }\n };\n (value as any).catch = (onrejected?: (reason: any) => any) => (value as any).then(undefined, onrejected);\n (value as any).finally = (onfinally?: () => void) =>\n (value as any).then(\n (v: any) => {\n onfinally?.();\n return v;\n },\n (err: any) => {\n onfinally?.();\n throw err;\n },\n );\n }\n return value as any;\n}\n\n/**\n * Wraps a Promise to include a `drain()` method at the top level.\n * This allows `await promise.drain()` without first awaiting the promise.\n * Since cli/eval never reject, this just delegates to the resolved result's `drain()`.\n */\nexport function withPromiseDrain<T extends Promise<any>>(promise: T): T & { drain: () => Promise<any> } {\n (promise as any).drain = async () => {\n const resolved = await promise;\n return resolved.drain();\n };\n return promise as any;\n}\n\nexport function isIterator(value: unknown): value is Iterator<unknown> {\n return typeof value === 'object' && value !== null && Symbol.iterator in value && typeof (value as any)[Symbol.iterator] === 'function';\n}\n\nexport function isAsyncIterator(value: unknown): value is AsyncIterator<unknown> {\n return (\n typeof value === 'object' &&\n value !== null &&\n Symbol.asyncIterator in value &&\n typeof (value as any)[Symbol.asyncIterator] === 'function'\n );\n}\n\n/**\n * Writes a command's return value to output, handling promises, iterators, and async iterators.\n * Values are passed directly to the output function without stringification —\n * runtimes like Node/Bun already format objects via console.log.\n * Returns void or a Promise depending on whether async consumption is needed.\n */\nexport function outputValue(value: unknown, output: (...args: unknown[]) => void): void | Promise<void> {\n if (value == null) return;\n\n // Async iterator — consume and output each yielded value\n if (isAsyncIterator(value)) {\n return (async () => {\n const iter = (value as any)[Symbol.asyncIterator]();\n while (true) {\n const { done, value: item } = await iter.next();\n if (done) break;\n if (item != null) output(item);\n }\n })();\n }\n\n // Sync iterator (but not a plain string/array which also have Symbol.iterator)\n if (typeof value !== 'string' && !Array.isArray(value) && isIterator(value)) {\n const iter = (value as any)[Symbol.iterator]();\n while (true) {\n const { done, value: item } = iter.next();\n if (done) break;\n if (item != null) output(item);\n }\n return;\n }\n\n // Promise — await then output\n if (value instanceof Promise) {\n return value.then((resolved) => outputValue(resolved, output));\n }\n\n // Pass value directly — runtime handles formatting\n output(value);\n}\n\n/**\n * Resolves a result value by unwrapping Promises and collecting iterables into arrays.\n * This is the runtime counterpart of the `Drained<T>` type.\n */\nexport async function drainValue(value: unknown): Promise<unknown> {\n // Unwrap promises first\n if (value instanceof Promise) {\n return drainValue(await value);\n }\n\n // Async iterator — collect into array\n if (isAsyncIterator(value)) {\n const items: unknown[] = [];\n const iter = (value as any)[Symbol.asyncIterator]();\n while (true) {\n const { done, value: item } = await iter.next();\n if (done) break;\n items.push(item);\n }\n return items;\n }\n\n // Sync iterator (but not string/array)\n if (typeof value !== 'string' && !Array.isArray(value) && isIterator(value)) {\n const items: unknown[] = [];\n const iter = (value as any)[Symbol.iterator]();\n while (true) {\n const { done, value: item } = iter.next();\n if (done) break;\n items.push(item);\n }\n return items;\n }\n\n return value;\n}\n\n/**\n * Attaches a `drain()` method to a command result object.\n * If the result has an `error` field, `drain()` returns `{ error }`.\n * Otherwise, resolves the result (unwrapping Promises, collecting iterables), catches errors,\n * and returns a discriminated union `{ value } | { error }` that never throws.\n */\nexport function withDrain<T extends Record<string, unknown>>(obj: T): T & { drain: () => Promise<any> } {\n (obj as any).drain = async () => {\n if ('error' in obj && obj.error !== undefined) {\n return { error: obj.error };\n }\n try {\n const value = await drainValue(obj.result);\n return { value };\n } catch (err) {\n return { error: err };\n }\n };\n return obj as any;\n}\n\n/**\n * Creates an error command result with a `drain()` that returns the error.\n */\nexport function errorResult(error: unknown, partial?: { command?: unknown; args?: unknown; argsResult?: unknown }) {\n return withDrain({\n error,\n result: undefined,\n command: partial?.command,\n args: partial?.args,\n argsResult: partial?.argsResult,\n });\n}\n\n/**\n * Deduplicates plugins by `id`. When multiple plugins share the same `id`,\n * only the last one in the array is kept. Plugins without an `id` are always kept.\n */\nfunction deduplicatePlugins(plugins: PadronePlugin<any, any>[]): PadronePlugin<any, any>[] {\n // Fast path: no ids at all\n if (!plugins.some((p) => p.id)) return plugins;\n\n // Find the last index for each id\n const lastIndex = new Map<string, number>();\n for (let i = 0; i < plugins.length; i++) {\n const id = plugins[i]!.id;\n if (id) lastIndex.set(id, i);\n }\n\n return plugins.filter((p, i) => !p.id || lastIndex.get(p.id) === i);\n}\n\n/**\n * Runs a plugin chain for a given phase using the onion/middleware pattern.\n * Plugins are sorted by `order` (ascending, stable), then composed so that\n * the first plugin in sorted order is the outermost wrapper.\n * If no plugins handle this phase, `core` is called directly.\n */\nexport function runPluginChain<TCtx, TResult>(\n phase: 'start' | 'parse' | 'validate' | 'execute' | 'error' | 'shutdown',\n plugins: PadronePlugin<any, any>[],\n ctx: TCtx,\n core: () => TResult | Promise<TResult>,\n): TResult | Promise<TResult> {\n // Deduplicate by id (last wins), then filter to plugins that have a handler for this phase\n const deduped = deduplicatePlugins(plugins);\n const phasePlugins = deduped.filter((p) => p[phase]);\n if (phasePlugins.length === 0) return core();\n\n // Stable sort by order (lower = outermost). Equal order preserves registration order.\n phasePlugins.sort((a, b) => (a.order ?? 0) - (b.order ?? 0));\n\n // Build chain from inside out: last plugin wraps core, first plugin is outermost\n let next = core;\n for (let i = phasePlugins.length - 1; i >= 0; i--) {\n const handler = phasePlugins[i]![phase]! as unknown as (\n ctx: TCtx,\n next: () => TResult | Promise<TResult>,\n ) => TResult | Promise<TResult>;\n const prevNext = next;\n next = () => handler(ctx, prevNext);\n }\n\n return next();\n}\n\n/**\n * Wraps a pipeline with start → error → shutdown lifecycle hooks.\n * - `start` plugins wrap the pipeline (onion pattern, root plugins only).\n * - On error: `error` plugins run (can transform/suppress the error).\n * - Always: `shutdown` plugins run (success or failure).\n */\nexport function wrapWithLifecycle<T>(\n plugins: PadronePlugin<any, any>[],\n command: AnyPadroneCommand,\n state: Record<string, unknown>,\n input: string | undefined,\n pipeline: () => T | Promise<T>,\n wrapErrorResult?: (result: unknown) => T,\n): T | Promise<T> {\n const hasStart = plugins.some((p) => p.start);\n const hasError = plugins.some((p) => p.error);\n const hasShutdown = plugins.some((p) => p.shutdown);\n\n const cleanupProgress = (error?: unknown, result?: unknown) => {\n const indicator = state._progress as PadroneProgressIndicator | undefined;\n if (indicator) {\n // If there's no progress config (lazy/manual indicator), just stop it silently\n const hasProgressConfig = '_progressMsg' in state;\n if (!hasProgressConfig) {\n indicator.stop();\n } else if (error !== undefined) {\n const fallback = error instanceof Error ? error.message : String(error);\n const { message: errorMsg, indicator: errorIcon } = resolveProgressMessage(state._progressError, error, fallback);\n indicator.fail(errorMsg, errorIcon !== undefined ? { indicator: errorIcon } : undefined);\n } else {\n const { message: successMsg, indicator: successIcon } = resolveProgressMessage(state._progressSuccess, result);\n indicator.succeed(successMsg, successIcon !== undefined ? { indicator: successIcon } : undefined);\n }\n (state._restoreOutput as (() => void) | undefined)?.();\n state._progress = undefined;\n state._restoreOutput = undefined;\n }\n };\n\n // Fast path: no lifecycle plugins — still need progress cleanup\n if (!hasStart && !hasError && !hasShutdown) {\n let result: T | Promise<T>;\n try {\n result = pipeline();\n } catch (e) {\n cleanupProgress(e);\n throw e;\n }\n if (result instanceof Promise) {\n return result.then(\n (r) => {\n cleanupProgress();\n return r;\n },\n (e) => {\n cleanupProgress(e);\n throw e;\n },\n );\n }\n cleanupProgress();\n return result;\n }\n\n const runShutdown = (error?: unknown, result?: unknown) => {\n cleanupProgress(error);\n if (!hasShutdown) return;\n const ctx: PluginShutdownContext = { command, state, error, result };\n return runPluginChain('shutdown', plugins, ctx, () => {});\n };\n\n const runError = (error: unknown): T | Promise<T> => {\n if (!hasError) {\n const s = runShutdown(error);\n if (s instanceof Promise)\n return s.then(() => {\n throw error;\n });\n throw error;\n }\n const ctx: PluginErrorContext = { command, state, error };\n const errorResult = runPluginChain('error', plugins, ctx, (): PluginErrorResult => ({ error }));\n return thenMaybe(errorResult, (er) => {\n if (er.error !== undefined) {\n const s = runShutdown(er.error);\n return thenMaybe(s as void | Promise<void>, () => {\n throw er.error;\n });\n }\n const wrapped = wrapErrorResult ? wrapErrorResult(er.result) : (er.result as T);\n const s = runShutdown(undefined, wrapped);\n return thenMaybe(s as void | Promise<void>, () => wrapped);\n });\n };\n\n const handleSuccess = (result: T): T | Promise<T> => {\n const s = runShutdown(undefined, result);\n if (s instanceof Promise) return s.then(() => result);\n return result;\n };\n\n // Run start phase wrapping the pipeline\n const startCtx: PluginStartContext = { command, state, input };\n let result: T | Promise<T>;\n try {\n result = (hasStart ? runPluginChain('start', plugins, startCtx, pipeline) : pipeline()) as T | Promise<T>;\n } catch (e) {\n return runError(e);\n }\n\n if (result instanceof Promise) {\n return result.then(handleSuccess, runError);\n }\n\n return handleSuccess(result);\n}\n\n/**\n * Resolves the runtime for a command by walking up the parent chain.\n * Returns a fully resolved runtime with all defaults filled in.\n */\nexport function getCommandRuntime(cmd: AnyPadroneCommand): ResolvedPadroneRuntime {\n let current: AnyPadroneCommand | undefined = cmd;\n while (current) {\n if (current.runtime) return resolveRuntime(current.runtime);\n current = current.parent;\n }\n return resolveRuntime();\n}\n\n/** No-op progress indicator returned when the runtime doesn't provide a `progress` factory. */\nconst noopIndicator: PadroneProgressIndicator = {\n update() {},\n succeed() {},\n fail() {},\n stop() {},\n pause() {},\n resume() {},\n};\n\n/** Creates a progress indicator from the runtime, or returns a no-op if unavailable. */\nexport function createProgress(\n runtime: ResolvedPadroneRuntime,\n message: string,\n options?: import('./runtime.ts').PadroneProgressOptions,\n): PadroneProgressIndicator {\n return runtime.progress?.(message, options) ?? noopIndicator;\n}\n\n/**\n * Creates a lazy progress indicator that defers real indicator creation until first use.\n * This allows `ctx.progress` to work even without `.progress()` config, as long as the\n * runtime provides a progress factory.\n */\nexport function createLazyIndicator(runtime: ResolvedPadroneRuntime, state: Record<string, unknown>): PadroneProgressIndicator {\n if (!runtime.progress) return noopIndicator;\n\n let real: PadroneProgressIndicator | undefined;\n const ensure = (message?: string) => {\n if (!real) {\n real = runtime.progress!(message ?? '', undefined);\n state._progress = real;\n }\n return real;\n };\n\n return {\n update(msg) {\n ensure(msg).update(msg);\n },\n succeed(msg) {\n if (real) real.succeed(msg);\n },\n fail(msg) {\n if (real) real.fail(msg);\n },\n stop() {\n if (real) real.stop();\n },\n pause() {\n if (real) real.pause();\n },\n resume() {\n if (real) real.resume();\n },\n };\n}\n\n/**\n * Resolves a progress message field (static or callback) into the arguments for succeed/fail.\n * Handles string, null, `{ message, indicator }` objects, and callback functions.\n */\nexport function resolveProgressMessage(\n field: unknown,\n value: unknown,\n fallback?: string,\n): { message: string | null | undefined; indicator?: string } {\n const raw = typeof field === 'function' ? (field as (v: unknown) => unknown)(value) : field;\n if (raw === undefined) return { message: fallback };\n if (raw === null || typeof raw === 'string') return { message: raw };\n if (typeof raw === 'object' && raw !== null) {\n const obj = raw as { message?: string | null; indicator?: string };\n return { message: obj.message, indicator: obj.indicator };\n }\n return { message: fallback };\n}\n\nexport { noopIndicator };\n\nexport function isAsyncBranded(schema: unknown): boolean {\n return !!schema && typeof schema === 'object' && '~async' in schema && (schema as any)['~async'] === true;\n}\n\nexport function hasInteractiveConfig(meta: unknown): boolean {\n if (!meta || typeof meta !== 'object') return false;\n const m = meta as Record<string, unknown>;\n return m.interactive === true || Array.isArray(m.interactive) || m.optionalInteractive === true || Array.isArray(m.optionalInteractive);\n}\n\nexport function warnIfUnexpectedAsync<T>(value: T, command: AnyPadroneCommand): T {\n if (typeof process !== 'undefined' && process.env?.NODE_ENV === 'production') return value;\n if (value instanceof Promise && !command.isAsync) {\n const runtime = getCommandRuntime(command);\n runtime.error(\n `[padrone] Command \"${command.path || command.name}\" returned a Promise from validation, ` +\n `but was not marked as async. Use \\`.async()\\` on the builder or \\`asyncSchema()\\` to brand your schema. ` +\n `Without this, TypeScript will infer a sync return type and the result will be a Promise at runtime.`,\n );\n }\n return value;\n}\n\n/**\n * Recursively re-paths a command tree under a new parent path, updating parent references.\n */\nexport function repathCommandTree(\n cmd: AnyPadroneCommand,\n newName: string,\n parentPath: string,\n parent: AnyPadroneCommand,\n): AnyPadroneCommand {\n resolveCommand(cmd);\n const newPath = parentPath ? `${parentPath} ${newName}` : newName;\n const remounted: AnyPadroneCommand = {\n ...cmd,\n name: newName,\n path: newPath,\n parent,\n version: undefined,\n };\n\n if (cmd.commands?.length) {\n remounted.commands = cmd.commands.map((child) => repathCommandTree(child, child.name, newPath, remounted));\n }\n\n return remounted;\n}\n\n/**\n * Builds a completer function for the REPL from the command tree.\n * Completes command names, subcommand names, option names (--foo), and aliases (-f).\n * Also includes dot-prefixed built-in REPL commands (.exit, .clear, .scope, .help, .history).\n */\nexport function buildReplCompleter(\n rootCommand: AnyPadroneCommand,\n builtins: {\n inScope?: boolean;\n },\n): (line: string) => [string[], string] {\n resolveAllCommands(rootCommand);\n return (line: string): [string[], string] => {\n const trimmed = line.trimStart();\n const parts = trimmed.split(/\\s+/);\n const lastPart = parts[parts.length - 1] ?? '';\n\n // If we're completing a dot-command\n if (lastPart.startsWith('.')) {\n const dotCmds = ['.exit', '.clear', '.help', '.history'];\n if (rootCommand.commands?.some((c) => c.commands?.length) || builtins.inScope) dotCmds.push('.scope');\n const hits = dotCmds.filter((c) => c.startsWith(lastPart));\n return [hits.length ? hits : dotCmds, lastPart];\n }\n\n // If we're completing an option (starts with -)\n if (lastPart.startsWith('-')) {\n // Find which command we're in\n const commandParts = parts.slice(0, -1).filter((p) => !p.startsWith('-'));\n let targetCommand = rootCommand;\n for (const part of commandParts) {\n resolveCommand(targetCommand);\n const sub = targetCommand.commands?.find((c) => c.name === part || c.aliases?.includes(part));\n if (sub) {\n resolveCommand(sub);\n targetCommand = sub;\n } else break;\n }\n\n // Get options for this command\n const options: string[] = [];\n if (targetCommand.argsSchema) {\n try {\n const argsMeta = targetCommand.meta?.fields;\n const { flags, aliases } = extractSchemaMetadata(targetCommand.argsSchema, argsMeta, targetCommand.meta?.autoAlias);\n const jsonSchema = targetCommand.argsSchema['~standard'].jsonSchema.input(JSON_SCHEMA_OPTS) as Record<string, any>;\n if (jsonSchema.type === 'object' && jsonSchema.properties) {\n for (const key of Object.keys(jsonSchema.properties)) {\n options.push(`--${key}`);\n }\n for (const flag of Object.keys(flags)) {\n options.push(`-${flag}`);\n }\n for (const alias of Object.keys(aliases)) {\n options.push(`--${alias}`);\n }\n }\n } catch {\n // Ignore schema parsing errors\n }\n }\n // Add global flags\n options.push('--help', '-h');\n\n const hits = options.filter((o) => o.startsWith(lastPart));\n return [hits.length ? hits : options, lastPart];\n }\n\n // Completing command names\n const commandParts = parts.filter((p) => !p.startsWith('-'));\n // Walk into subcommands for all but the last token\n let targetCommand = rootCommand;\n for (let i = 0; i < commandParts.length - 1; i++) {\n resolveCommand(targetCommand);\n const sub = targetCommand.commands?.find((c) => c.name === commandParts[i] || c.aliases?.includes(commandParts[i]!));\n if (sub) {\n resolveCommand(sub);\n targetCommand = sub;\n } else break;\n }\n\n const candidates: string[] = [];\n\n // Add subcommand names and aliases\n if (targetCommand.commands) {\n for (const cmd of targetCommand.commands) {\n if (!cmd.hidden) {\n candidates.push(cmd.name);\n if (cmd.aliases) candidates.push(...cmd.aliases);\n }\n }\n }\n\n // Add dot-commands and `..` shorthand at the root level (relative to current scope)\n if (targetCommand === rootCommand) {\n candidates.push('.help', '.exit', '.clear', '.history');\n if (rootCommand.commands?.some((c) => c.commands?.length) || builtins.inScope) candidates.push('.scope');\n if (builtins.inScope) candidates.push('..');\n }\n\n const hits = candidates.filter((c) => c.startsWith(lastPart));\n return [hits.length ? hits : candidates, lastPart];\n };\n}\n\n/**\n * Computes the Levenshtein edit distance between two strings.\n */\nfunction levenshtein(a: string, b: string): number {\n const m = a.length;\n const n = b.length;\n const dp: number[] = Array.from({ length: n + 1 }, (_, i) => i);\n\n for (let i = 1; i <= m; i++) {\n let prev = dp[0]!;\n dp[0] = i;\n for (let j = 1; j <= n; j++) {\n const temp = dp[j]!;\n dp[j] = a[i - 1] === b[j - 1] ? prev : 1 + Math.min(prev, dp[j]!, dp[j - 1]!);\n prev = temp;\n }\n }\n\n return dp[n]!;\n}\n\n/**\n * Finds the closest match from a list of candidates using Levenshtein distance.\n * Returns the suggestion string (e.g. 'Did you mean \"deploy\"?') or empty string if no good match.\n * Threshold: distance must be at most 40% of the longer string's length (min 1, max 3).\n */\nexport function suggestSimilar(input: string, candidates: string[]): string {\n if (candidates.length === 0) return '';\n\n const lower = input.toLowerCase();\n let bestDist = Infinity;\n let bestMatch = '';\n\n for (const candidate of candidates) {\n const dist = levenshtein(lower, candidate.toLowerCase());\n if (dist < bestDist) {\n bestDist = dist;\n bestMatch = candidate;\n }\n }\n\n const maxLen = Math.max(input.length, bestMatch.length);\n const threshold = Math.min(3, Math.max(1, Math.ceil(maxLen * 0.4)));\n\n if (bestDist > 0 && bestDist <= threshold) {\n return `Did you mean \"${bestMatch}\"?`;\n }\n\n return '';\n}\n\nexport function findCommandByName(name: string, commands?: AnyPadroneCommand[]): AnyPadroneCommand | undefined {\n if (!commands) return undefined;\n\n const foundByName = commands.find((cmd) => cmd.name === name);\n if (foundByName) return resolveCommand(foundByName);\n\n // Check for aliases\n const foundByAlias = commands.find((cmd) => cmd.aliases?.includes(name));\n if (foundByAlias) return resolveCommand(foundByAlias);\n\n for (const cmd of commands) {\n if (name.startsWith(`${cmd.name} `)) {\n resolveCommand(cmd);\n if (cmd.commands) {\n const subCommandName = name.slice(cmd.name.length + 1);\n const subCommand = findCommandByName(subCommandName, cmd.commands);\n if (subCommand) return subCommand;\n }\n }\n // Check aliases for nested commands\n if (cmd.aliases) {\n for (const alias of cmd.aliases) {\n if (name.startsWith(`${alias} `)) {\n resolveCommand(cmd);\n if (cmd.commands) {\n const subCommandName = name.slice(alias.length + 1);\n const subCommand = findCommandByName(subCommandName, cmd.commands);\n if (subCommand) return subCommand;\n }\n }\n }\n }\n }\n return undefined;\n}\n\n// ---------------------------------------------------------------------------\n// Shared utilities for MCP and serve\n// ---------------------------------------------------------------------------\n\nexport type CollectedEndpoint = { name: string; command: AnyPadroneCommand };\n\n/** Collect all actionable commands recursively. Hidden commands are excluded. */\nexport function collectEndpoints(commands: AnyPadroneCommand[] | undefined, prefix: string): CollectedEndpoint[] {\n if (!commands) return [];\n const endpoints: CollectedEndpoint[] = [];\n for (const cmd of commands) {\n resolveCommand(cmd);\n if (cmd.hidden) continue;\n const path = cmd.name ? (prefix ? `${prefix}.${cmd.name}` : cmd.name) : prefix;\n if (cmd.action || cmd.argsSchema) {\n endpoints.push({ name: path, command: cmd });\n }\n if (cmd.commands?.length) {\n endpoints.push(...collectEndpoints(cmd.commands, path));\n }\n }\n return endpoints;\n}\n\n/** Build the JSON Schema for a command's arguments. */\nexport function buildInputSchema(cmd: AnyPadroneCommand): Record<string, unknown> {\n if (!cmd.argsSchema) {\n return { type: 'object', additionalProperties: false };\n }\n try {\n return cmd.argsSchema['~standard'].jsonSchema.input(JSON_SCHEMA_OPTS) as Record<string, unknown>;\n } catch {\n return { type: 'object', additionalProperties: false };\n }\n}\n\n/** Serialize a record of args into CLI flag strings. */\nexport function serializeArgsToFlags(args: Record<string, unknown>): string[] {\n const parts: string[] = [];\n for (const [key, value] of Object.entries(args)) {\n if (value === undefined) continue;\n if (typeof value === 'boolean') {\n parts.push(value ? `--${key}` : `--no-${key}`);\n } else if (Array.isArray(value)) {\n for (const v of value) parts.push(`--${key}=${String(v)}`);\n } else {\n const strVal =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AqB,MAAyC;CAC5E,MAAM,QAAkB,EAAE;AAC1B,MAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,KAAK,EAAE;AAC/C,MAAI,UAAU,KAAA,EAAW;AACzB,MAAI,OAAO,UAAU,UACnB,OAAM,KAAK,QAAQ,KAAK,QAAQ,QAAQ,MAAM;WACrC,MAAM,QAAQ,MAAM,CAC7B,MAAK,MAAM,KAAK,MAAO,OAAM,KAAK,KAAK,IAAI,GAAG,OAAO,EAAE,GAAG;OACrD;GACL,MAAM,SAAS,OAAO,MAAM;AAC5B,SAAM,KAAK,OAAO,SAAS,IAAI,GAAG,KAAK,IAAI,IAAI,OAAO,KAAK,KAAK,IAAI,GAAG,SAAS;;;AAGpF,QAAO"}
@@ -1,64 +0,0 @@
1
- import { n as AnyPadroneCommand } from "./types-Ch8Mk6Qb.mjs";
2
-
3
- //#region src/shell-utils.d.ts
4
- type ShellType = 'bash' | 'zsh' | 'fish' | 'powershell';
5
- /**
6
- * Detects the current shell from environment variables and process info.
7
- * @returns The detected shell type, or undefined if unknown
8
- */
9
- declare function detectShell(): ShellType | undefined;
10
- declare function getRcFile(shell: ShellType, home?: string): string | null;
11
- declare function escapeRegExp(str: string): string;
12
- /**
13
- * Writes a snippet to a shell config file using begin/end markers for idempotency.
14
- * If a block with the same begin marker exists, it is replaced. Otherwise the snippet is appended.
15
- */
16
- declare function writeToRcFile(rcFile: string, snippet: string, beginMarker: string, endMarker: string): {
17
- file: string;
18
- updated: boolean;
19
- };
20
- //#endregion
21
- //#region src/completion.d.ts
22
- /**
23
- * Generates a Bash completion script for the program.
24
- */
25
- declare function generateBashCompletion(program: AnyPadroneCommand): string;
26
- /**
27
- * Generates a Zsh completion script for the program.
28
- */
29
- declare function generateZshCompletion(program: AnyPadroneCommand): string;
30
- /**
31
- * Generates a Fish completion script for the program.
32
- */
33
- declare function generateFishCompletion(program: AnyPadroneCommand): string;
34
- /**
35
- * Generates a PowerShell completion script for the program.
36
- */
37
- declare function generatePowerShellCompletion(program: AnyPadroneCommand): string;
38
- /**
39
- * Generates a completion script for the specified shell.
40
- */
41
- declare function generateCompletion(program: AnyPadroneCommand, shell: ShellType): string;
42
- /**
43
- * Gets the installation instructions for a shell completion script.
44
- */
45
- declare function getCompletionInstallInstructions(programName: string, shell: ShellType): string;
46
- /**
47
- * Generates the completion output with automatic shell detection.
48
- * If shell is not specified, detects the current shell and provides instructions.
49
- */
50
- declare function generateCompletionOutput(program: AnyPadroneCommand, shell?: ShellType): string;
51
- interface SetupCompletionsResult {
52
- /** The file that was written to. */
53
- file: string;
54
- /** Whether an existing completion block was replaced (true) or a new one was appended (false). */
55
- updated: boolean;
56
- }
57
- /**
58
- * Sets up shell completions by writing an eval snippet to the appropriate shell config file.
59
- * Uses marker comments for idempotency — re-running replaces the existing block.
60
- */
61
- declare function setupCompletions(programName: string, shell: ShellType): SetupCompletionsResult;
62
- //#endregion
63
- export { SetupCompletionsResult, type ShellType, detectShell, escapeRegExp, generateBashCompletion, generateCompletion, generateCompletionOutput, generateFishCompletion, generatePowerShellCompletion, generateZshCompletion, getCompletionInstallInstructions, getRcFile, setupCompletions, writeToRcFile };
64
- //# sourceMappingURL=completion.d.mts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"completion.d.mts","names":[],"sources":["../src/shell-utils.ts","../src/completion.ts"],"mappings":";;;KAAY,SAAA;;;AAAZ;;iBAMgB,WAAA,CAAA,GAAe,SAAA;AAAA,iBAmCf,SAAA,CAAU,KAAA,EAAO,SAAA,EAAW,IAAA;AAAA,iBAkB5B,YAAA,CAAa,GAAA;AArD7B;;;;AAAA,iBA6DgB,aAAA,CAAc,MAAA,UAAgB,OAAA,UAAiB,WAAA,UAAqB,SAAA;EAAsB,IAAA;EAAc,OAAA;AAAA;;;AAnExH;;;AAAA,iBC4FgB,sBAAA,CAAuB,OAAA,EAAS,iBAAA;;ADtFhD;;iBC+LgB,qBAAA,CAAsB,OAAA,EAAS,iBAAA;;;AD5J/C;iBCsOgB,sBAAA,CAAuB,OAAA,EAAS,iBAAA;;;;iBAoDhC,4BAAA,CAA6B,OAAA,EAAS,iBAAA;;;;iBAkEtC,kBAAA,CAAmB,OAAA,EAAS,iBAAA,EAAmB,KAAA,EAAO,SAAA;;;;iBAkBtD,gCAAA,CAAiC,WAAA,UAAqB,KAAA,EAAO,SAAA;ADpV7E;;;;AAAA,iBCsXgB,wBAAA,CAAyB,OAAA,EAAS,iBAAA,EAAmB,KAAA,GAAQ,SAAA;AAAA,UA0C5D,sBAAA;EDha8C;ECka7D,IAAA;EDlawG;ECoaxG,OAAA;AAAA;;;;;iBAOc,gBAAA,CAAiB,WAAA,UAAqB,KAAA,EAAO,SAAA,GAAY,sBAAA"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"completion.mjs","names":[],"sources":["../src/shell-utils.ts","../src/completion.ts"],"sourcesContent":["export type ShellType = 'bash' | 'zsh' | 'fish' | 'powershell';\n\n/**\n * Detects the current shell from environment variables and process info.\n * @returns The detected shell type, or undefined if unknown\n */\nexport function detectShell(): ShellType | undefined {\n if (typeof process === 'undefined') return undefined;\n\n // Method 1: Check SHELL environment variable (most common)\n const shellEnv = process.env.SHELL || '';\n if (shellEnv.includes('zsh')) return 'zsh';\n if (shellEnv.includes('bash')) return 'bash';\n if (shellEnv.includes('fish')) return 'fish';\n\n // Method 2: Check Windows-specific shells\n if (process.env.PSModulePath || process.env.POWERSHELL_DISTRIBUTION_CHANNEL) {\n return 'powershell';\n }\n\n // Method 3: Check parent process on Unix-like systems\n try {\n const ppid = process.ppid;\n if (ppid) {\n const { execSync } = require('node:child_process') as typeof import('node:child_process');\n const processName = execSync(`ps -p ${ppid} -o comm=`, {\n encoding: 'utf-8',\n stdio: ['pipe', 'pipe', 'ignore'],\n }).trim();\n\n if (processName.includes('zsh')) return 'zsh';\n if (processName.includes('bash')) return 'bash';\n if (processName.includes('fish')) return 'fish';\n }\n } catch {\n // Ignore errors (e.g., ps not available)\n }\n\n return undefined;\n}\n\nexport function getRcFile(shell: ShellType, home?: string): string | null {\n const { homedir } = require('node:os') as typeof import('node:os');\n const { join } = require('node:path') as typeof import('node:path');\n const h = home ?? homedir();\n switch (shell) {\n case 'bash':\n return join(h, '.bashrc');\n case 'zsh':\n return join(h, '.zshrc');\n case 'fish':\n return join(h, '.config', 'fish', 'config.fish');\n case 'powershell':\n return process.env.PROFILE || join(h, 'Documents', 'PowerShell', 'Microsoft.PowerShell_profile.ps1');\n default:\n return null;\n }\n}\n\nexport function escapeRegExp(str: string): string {\n return str.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n}\n\n/**\n * Writes a snippet to a shell config file using begin/end markers for idempotency.\n * If a block with the same begin marker exists, it is replaced. Otherwise the snippet is appended.\n */\nexport function writeToRcFile(rcFile: string, snippet: string, beginMarker: string, endMarker: string): { file: string; updated: boolean } {\n const { existsSync, mkdirSync, readFileSync, writeFileSync } = require('node:fs') as typeof import('node:fs');\n const { dirname } = require('node:path') as typeof import('node:path');\n const existing = existsSync(rcFile) ? readFileSync(rcFile, 'utf-8') : '';\n\n if (existing.includes(beginMarker)) {\n const pattern = new RegExp(`${escapeRegExp(beginMarker)}[\\\\s\\\\S]*?${escapeRegExp(endMarker)}`);\n writeFileSync(rcFile, existing.replace(pattern, snippet));\n return { file: rcFile, updated: true };\n }\n\n mkdirSync(dirname(rcFile), { recursive: true });\n const separator = existing.length > 0 && !existing.endsWith('\\n') ? '\\n' : '';\n writeFileSync(rcFile, `${existing}${separator}\\n${snippet}\\n`);\n return { file: rcFile, updated: false };\n}\n","import { extractSchemaMetadata, JSON_SCHEMA_OPTS } from './args.ts';\nimport { detectShell, getRcFile, type ShellType, writeToRcFile } from './shell-utils.ts';\nimport type { AnyPadroneCommand } from './types.ts';\n\nexport { detectShell, escapeRegExp, getRcFile, type ShellType, writeToRcFile } from './shell-utils.ts';\n\n/**\n * Collects all commands from a program recursively.\n */\nfunction collectAllCommands(cmd: AnyPadroneCommand): AnyPadroneCommand[] {\n const result: AnyPadroneCommand[] = [];\n\n if (cmd.commands) {\n for (const subcmd of cmd.commands) {\n if (!subcmd.hidden) {\n result.push(subcmd);\n result.push(...collectAllCommands(subcmd));\n }\n }\n }\n\n return result;\n}\n\ninterface ExtractedArg {\n name: string;\n alias?: string;\n isBoolean: boolean;\n enum?: string[];\n description?: string;\n}\n\n/**\n * Extracts all argument names from a command's schema.\n */\nfunction extractArguments(cmd: AnyPadroneCommand): ExtractedArg[] {\n const argList: ExtractedArg[] = [];\n\n if (!cmd.argsSchema) return argList;\n\n try {\n const argsMeta = cmd.meta?.fields;\n const { aliases } = extractSchemaMetadata(cmd.argsSchema, argsMeta, cmd.meta?.autoAlias);\n\n // Build reverse map: argName → aliasName\n const argToAlias: Record<string, string> = {};\n for (const [aliasName, argName] of Object.entries(aliases)) {\n if (!argToAlias[argName]) argToAlias[argName] = aliasName;\n }\n\n const jsonSchema = cmd.argsSchema['~standard'].jsonSchema.input(JSON_SCHEMA_OPTS) as Record<string, any>;\n\n if (jsonSchema.type === 'object' && jsonSchema.properties) {\n for (const [key, prop] of Object.entries(jsonSchema.properties as Record<string, any>)) {\n const enumValues = (prop.enum ?? prop.items?.enum) as string[] | undefined;\n const optMeta = argsMeta?.[key];\n argList.push({\n name: key,\n alias: argToAlias[key],\n isBoolean: prop?.type === 'boolean',\n enum: enumValues,\n description: optMeta?.description ?? prop.description,\n });\n }\n }\n } catch {\n // Ignore schema parsing errors\n }\n\n return argList;\n}\n\n/**\n * Collects unique args across all commands, preserving first-seen enum values.\n */\nfunction collectUniqueArgs(program: AnyPadroneCommand, commands: AnyPadroneCommand[]): Map<string, ExtractedArg> {\n const seen = new Map<string, ExtractedArg>();\n\n for (const cmd of [program, ...commands]) {\n for (const arg of extractArguments(cmd)) {\n if (!seen.has(arg.name)) {\n seen.set(arg.name, arg);\n }\n }\n }\n\n return seen;\n}\n\n/**\n * Generates a Bash completion script for the program.\n */\nexport function generateBashCompletion(program: AnyPadroneCommand): string {\n const programName = program.name;\n const commands = collectAllCommands(program);\n const commandNames = commands.map((c) => c.name).join(' ');\n const uniqueArgs = collectUniqueArgs(program, commands);\n\n // Collect all option names\n const allArguments = new Set<string>();\n allArguments.add('--help');\n allArguments.add('--version');\n\n for (const arg of uniqueArgs.values()) {\n allArguments.add(`--${arg.name}`);\n if (arg.alias) allArguments.add(`--${arg.alias}`);\n }\n\n const argsList = Array.from(allArguments).join(' ');\n\n // Build case branches for options with enum values\n const enumCases: string[] = [];\n for (const arg of uniqueArgs.values()) {\n if (!arg.enum || arg.enum.length === 0) continue;\n const values = arg.enum.join(' ');\n const patterns = [`--${arg.name}`];\n if (arg.alias) patterns.push(`--${arg.alias}`);\n enumCases.push(` ${patterns.join('|')}) COMPREPLY=($(compgen -W \"${values}\" -- \"$cur\")); return 0 ;;`);\n }\n\n const enumBlock =\n enumCases.length > 0\n ? `\n # Complete option values\n case \"$prev\" in\n${enumCases.join('\\n')}\n esac\n\n`\n : '\\n';\n\n return `###-begin-${programName}-completion-###\n#\n# ${programName} command completion script\n#\n# Installation: ${programName} completion >> ~/.bashrc (or ~/.zshrc)\n# Or, maybe: ${programName} completion > /usr/local/etc/bash_completion.d/${programName}\n#\n\nif type complete &>/dev/null; then\n _${programName}_completion() {\n local cur prev words cword\n if type _get_comp_words_by_ref &>/dev/null; then\n _get_comp_words_by_ref -n = -n @ -n : -w words -i cword\n else\n cword=\"$COMP_CWORD\"\n words=(\"\\${COMP_WORDS[@]}\")\n fi\n\n cur=\"\\${words[cword]}\"\n prev=\"\\${words[cword-1]}\"\n\n local commands=\"${commandNames}\"\n local args=\"${argsList}\"\n${enumBlock} # Complete args when current word starts with -\n if [[ \"$cur\" == -* ]]; then\n COMPREPLY=($(compgen -W \"$args\" -- \"$cur\"))\n return 0\n fi\n\n # Complete commands\n COMPREPLY=($(compgen -W \"$commands\" -- \"$cur\"))\n }\n complete -o bashdefault -o default -o nospace -F _${programName}_completion ${programName}\nelif type compdef &>/dev/null; then\n _${programName}_completion() {\n local si=$IFS\n local commands=\"${commandNames}\"\n local args=\"${argsList}\"\n\n if [[ \"\\${words[CURRENT]}\" == -* ]]; then\n compadd -- \\${=args}\n else\n compadd -- \\${=commands}\n fi\n IFS=$si\n }\n compdef _${programName}_completion ${programName}\nelif type compctl &>/dev/null; then\n _${programName}_completion() {\n local commands=\"${commandNames}\"\n local args=\"${argsList}\"\n\n if [[ \"\\${words[CURRENT]}\" == -* ]]; then\n reply=(\\${=args})\n else\n reply=(\\${=commands})\n fi\n }\n compctl -K _${programName}_completion ${programName}\nfi\n###-end-${programName}-completion-###`;\n}\n\n/**\n * Generates a Zsh completion script for the program.\n */\nexport function generateZshCompletion(program: AnyPadroneCommand): string {\n const programName = program.name;\n const commands = collectAllCommands(program);\n\n // Generate command completions with descriptions\n const commandCompletions = commands\n .map((cmd) => {\n const desc = cmd.description || cmd.title || '';\n const escapedDesc = desc.replace(/'/g, \"'\\\\''\").replace(/:/g, '\\\\:');\n return ` '${cmd.name}:${escapedDesc}'`;\n })\n .join('\\n');\n\n // Collect all args with descriptions and enum values\n const argumentCompletions: string[] = [];\n argumentCompletions.push(\" '--help[Show help information]'\");\n argumentCompletions.push(\" '--version[Show version number]'\");\n\n const uniqueArgs = collectUniqueArgs(program, commands);\n\n for (const arg of uniqueArgs.values()) {\n const desc = arg.description || '';\n const escapedDesc = desc.replace(/'/g, \"'\\\\''\").replace(/\\[/g, '\\\\[').replace(/\\]/g, '\\\\]');\n\n // Zsh action spec for enum values: :label:(val1 val2 val3)\n const valueAction = arg.enum?.length ? `: :(${arg.enum.join(' ')})` : '';\n\n if (arg.alias) {\n argumentCompletions.push(` {--${arg.alias},--${arg.name}}'[${escapedDesc}]${valueAction}'`);\n } else {\n argumentCompletions.push(` '--${arg.name}[${escapedDesc}]${valueAction}'`);\n }\n }\n\n return `#compdef ${programName}\n###-begin-${programName}-completion-###\n#\n# ${programName} command completion script for Zsh\n#\n# Installation: ${programName} completion >> ~/.zshrc\n# Or: ${programName} completion > ~/.zsh/completions/_${programName}\n#\n\n_${programName}() {\n local -a commands\n local -a args\n\n commands=(\n${commandCompletions}\n )\n\n args=(\n${argumentCompletions.join('\\n')}\n )\n\n _arguments -s \\\\\n $args \\\\\n '1: :->command' \\\\\n '*::arg:->args'\n\n case \"$state\" in\n command)\n _describe 'command' commands\n ;;\n esac\n}\n\n_${programName}\n###-end-${programName}-completion-###`;\n}\n\n/**\n * Generates a Fish completion script for the program.\n */\nexport function generateFishCompletion(program: AnyPadroneCommand): string {\n const programName = program.name;\n const commands = collectAllCommands(program);\n\n const lines: string[] = [\n `###-begin-${programName}-completion-###`,\n '#',\n `# ${programName} command completion script for Fish`,\n '#',\n `# Installation: ${programName} completion > ~/.config/fish/completions/${programName}.fish`,\n '#',\n '',\n `# Clear existing completions`,\n `complete -c ${programName} -e`,\n '',\n '# Commands',\n ];\n\n for (const cmd of commands) {\n const desc = cmd.description || cmd.title || '';\n const escapedDesc = desc.replace(/'/g, \"\\\\'\");\n lines.push(`complete -c ${programName} -n \"__fish_use_subcommand\" -a \"${cmd.name}\" -d '${escapedDesc}'`);\n }\n\n lines.push('');\n lines.push('# Global arguments');\n lines.push(`complete -c ${programName} -l help -d 'Show help information'`);\n lines.push(`complete -c ${programName} -l version -d 'Show version number'`);\n\n const uniqueArgs = collectUniqueArgs(program, commands);\n\n for (const arg of uniqueArgs.values()) {\n const desc = arg.description || '';\n const escapedDesc = desc.replace(/'/g, \"\\\\'\");\n // Fish: -xa 'val1 val2' provides exclusive value completions\n const valueFlag = arg.enum?.length ? ` -xa '${arg.enum.join(' ')}'` : '';\n\n if (arg.alias) {\n lines.push(`complete -c ${programName} -l ${arg.name} -s ${arg.alias} -d '${escapedDesc}'${valueFlag}`);\n } else {\n lines.push(`complete -c ${programName} -l ${arg.name} -d '${escapedDesc}'${valueFlag}`);\n }\n }\n\n lines.push(`###-end-${programName}-completion-###`);\n\n return lines.join('\\n');\n}\n\n/**\n * Generates a PowerShell completion script for the program.\n */\nexport function generatePowerShellCompletion(program: AnyPadroneCommand): string {\n const programName = program.name;\n const commands = collectAllCommands(program);\n const uniqueArgs = collectUniqueArgs(program, commands);\n\n const commandNames = commands.map((c) => `'${c.name}'`).join(', ');\n\n // Collect all option names\n const argNames: string[] = [\"'--help'\", \"'--version'\"];\n for (const arg of uniqueArgs.values()) {\n argNames.push(`'--${arg.name}'`);\n if (arg.alias) argNames.push(`'--${arg.alias}'`);\n }\n\n // Build switch cases for option value completion\n const enumCases: string[] = [];\n for (const arg of uniqueArgs.values()) {\n if (!arg.enum || arg.enum.length === 0) continue;\n const values = arg.enum.map((v) => `'${v}'`).join(', ');\n const patterns = [`'--${arg.name}'`];\n if (arg.alias) patterns.push(`'--${arg.alias}'`);\n enumCases.push(` ${patterns.join(', ')} { @(${values}) | Where-Object { $_ -like \"$wordToComplete*\" } | ForEach-Object {\n [System.Management.Automation.CompletionResult]::new($_, $_, 'ParameterValue', $_)\n }; return }`);\n }\n\n const enumBlock =\n enumCases.length > 0\n ? `\n # Complete option values\n $prevWord = $commandAst.CommandElements | Select-Object -Last 2 | Select-Object -First 1\n switch ($prevWord) {\n${enumCases.join('\\n')}\n }\n\n`\n : '\\n';\n\n return `###-begin-${programName}-completion-###\n#\n# ${programName} command completion script for PowerShell\n#\n# Installation: ${programName} completion >> $PROFILE\n#\n\nRegister-ArgumentCompleter -Native -CommandName ${programName} -ScriptBlock {\n param($wordToComplete, $commandAst, $cursorPosition)\n\n $commands = @(${commandNames})\n $args = @(${argNames.join(', ')})\n${enumBlock} if ($wordToComplete -like '-*') {\n $args | Where-Object { $_ -like \"$wordToComplete*\" } | ForEach-Object {\n [System.Management.Automation.CompletionResult]::new($_, $_, 'ParameterValue', $_)\n }\n } else {\n $commands | Where-Object { $_ -like \"$wordToComplete*\" } | ForEach-Object {\n [System.Management.Automation.CompletionResult]::new($_, $_, 'ParameterValue', $_)\n }\n }\n}\n###-end-${programName}-completion-###`;\n}\n\n/**\n * Generates a completion script for the specified shell.\n */\nexport function generateCompletion(program: AnyPadroneCommand, shell: ShellType): string {\n switch (shell) {\n case 'bash':\n return generateBashCompletion(program);\n case 'zsh':\n return generateZshCompletion(program);\n case 'fish':\n return generateFishCompletion(program);\n case 'powershell':\n return generatePowerShellCompletion(program);\n default:\n throw new Error(`Unsupported shell: ${shell}`);\n }\n}\n\n/**\n * Gets the installation instructions for a shell completion script.\n */\nexport function getCompletionInstallInstructions(programName: string, shell: ShellType): string {\n switch (shell) {\n case 'bash':\n return `# Add to ~/.bashrc:\n${programName} completion bash >> ~/.bashrc\n\n# Or install system-wide:\n${programName} completion bash > /usr/local/etc/bash_completion.d/${programName}`;\n\n case 'zsh':\n return `# Add to ~/.zshrc:\n${programName} completion zsh >> ~/.zshrc\n\n# Or add to completions directory:\n${programName} completion zsh > ~/.zsh/completions/_${programName}`;\n\n case 'fish':\n return `# Install to Fish completions:\n${programName} completion fish > ~/.config/fish/completions/${programName}.fish`;\n\n case 'powershell':\n return `# Add to PowerShell profile:\n${programName} completion powershell >> $PROFILE`;\n\n default:\n return `# Run: ${programName} completion <shell>\n# Supported shells: bash, zsh, fish, powershell`;\n }\n}\n\n/**\n * Generates the completion output with automatic shell detection.\n * If shell is not specified, detects the current shell and provides instructions.\n */\nexport function generateCompletionOutput(program: AnyPadroneCommand, shell?: ShellType): string {\n const programName = program.name;\n\n if (shell) {\n return generateCompletion(program, shell);\n }\n\n // Auto-detect shell and provide instructions\n const detectedShell = detectShell();\n\n if (detectedShell) {\n const instructions = getCompletionInstallInstructions(programName, detectedShell);\n const script = generateCompletion(program, detectedShell);\n\n return `# Detected shell: ${detectedShell}\n#\n${instructions}\n#\n# Or evaluate directly (temporary, for current session only):\n# eval \"$(${programName} completion ${detectedShell})\"\n\n${script}`;\n }\n\n // Could not detect shell - provide usage info\n return `# Shell auto-detection failed.\n#\n# Usage: ${programName} completion <shell>\n#\n# Supported shells:\n# bash - Bash completion script\n# zsh - Zsh completion script\n# fish - Fish completion script\n# powershell - PowerShell completion script\n#\n# Example:\n# ${programName} completion bash >> ~/.bashrc\n# ${programName} completion zsh >> ~/.zshrc\n# ${programName} completion fish > ~/.config/fish/completions/${programName}.fish\n# ${programName} completion powershell >> $PROFILE`;\n}\n\nexport interface SetupCompletionsResult {\n /** The file that was written to. */\n file: string;\n /** Whether an existing completion block was replaced (true) or a new one was appended (false). */\n updated: boolean;\n}\n\n/**\n * Sets up shell completions by writing an eval snippet to the appropriate shell config file.\n * Uses marker comments for idempotency — re-running replaces the existing block.\n */\nexport function setupCompletions(programName: string, shell: ShellType): SetupCompletionsResult {\n const { existsSync, mkdirSync, writeFileSync } = require('node:fs') as typeof import('node:fs');\n const { join } = require('node:path') as typeof import('node:path');\n const { homedir } = require('node:os') as typeof import('node:os');\n\n const beginMarker = `###-begin-${programName}-completion-###`;\n const endMarker = `###-end-${programName}-completion-###`;\n const snippet = buildSetupSnippet(programName, shell, beginMarker, endMarker);\n\n if (shell === 'fish') {\n const completionsDir = join(homedir(), '.config', 'fish', 'completions');\n const filePath = join(completionsDir, `${programName}.fish`);\n mkdirSync(completionsDir, { recursive: true });\n const existed = existsSync(filePath);\n writeFileSync(filePath, `${snippet}\\n`);\n return { file: filePath, updated: existed };\n }\n\n const rcFile = getRcFile(shell);\n if (!rcFile) {\n throw new Error(`Could not determine config file for ${shell}.`);\n }\n\n return writeToRcFile(rcFile, snippet, beginMarker, endMarker);\n}\n\nfunction buildSetupSnippet(programName: string, shell: ShellType, beginMarker: string, endMarker: string): string {\n const evalCmd = `${programName} completion ${shell}`;\n\n switch (shell) {\n case 'bash':\n case 'zsh':\n return `${beginMarker}\\neval \"$(${evalCmd})\"\\n${endMarker}`;\n case 'fish':\n return `${beginMarker}\\n${evalCmd} | source\\n${endMarker}`;\n case 'powershell':\n return `${beginMarker}\\n${evalCmd} | Invoke-Expression\\n${endMarker}`;\n }\n}\n"],"mappings":";;;;;;;AAMA,SAAgB,cAAqC;AACnD,KAAI,OAAO,YAAY,YAAa,QAAO,KAAA;CAG3C,MAAM,WAAW,QAAQ,IAAI,SAAS;AACtC,KAAI,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ACH,OAAM,IAAI,MAAM,uCAAuC,MAAM,GAAG;AAGlE,QAAO,cAAc,QAAQ,SAAS,aAAa,UAAU;;AAG/D,SAAS,kBAAkB,aAAqB,OAAkB,aAAqB,WAA2B;CAChH,MAAM,UAAU,GAAG,YAAY,cAAc;AAE7C,SAAQ,OAAR;EACE,KAAK;EACL,KAAK,MACH,QAAO,GAAG,YAAY,YAAY,QAAQ,MAAM;EAClD,KAAK,OACH,QAAO,GAAG,YAAY,IAAI,QAAQ,aAAa;EACjD,KAAK,aACH,QAAO,GAAG,YAAY,IAAI,QAAQ,wBAAwB"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"errors-BiVrBgi6.mjs","names":[],"sources":["../src/errors.ts"],"sourcesContent":["/**\n * Structured error hierarchy for Padrone CLI framework.\n *\n * All Padrone errors extend `PadroneError`, which carries an exit code,\n * optional suggestions, and context about which command/phase produced the error.\n * This allows callers to distinguish user errors (bad input) from bugs (unexpected throws)\n * and to present formatted, actionable error messages.\n */\n\nexport type PadroneErrorOptions = {\n /** Process exit code. Defaults to 1. */\n exitCode?: number;\n /** Actionable suggestions shown to the user (e.g. \"Use --env production\"). */\n suggestions?: string[];\n /** The command path that produced the error (e.g. \"deploy staging\"). */\n command?: string;\n /** The phase where the error occurred. */\n phase?: 'parse' | 'validate' | 'execute' | 'config';\n /** Original cause for error chaining. */\n cause?: unknown;\n};\n\n/**\n * Base error class for all Padrone errors.\n * Carries structured metadata for user-friendly formatting and programmatic handling.\n *\n * @example\n * ```ts\n * throw new PadroneError('Something went wrong', {\n * exitCode: 1,\n * suggestions: ['Try --help for usage information'],\n * });\n * ```\n */\nexport class PadroneError extends Error {\n readonly exitCode: number;\n readonly suggestions: string[];\n readonly command?: string;\n readonly phase?: 'parse' | 'validate' | 'execute' | 'config';\n\n constructor(message: string, options?: PadroneErrorOptions) {\n super(message, options?.cause ? { cause: options.cause } : undefined);\n this.name = 'PadroneError';\n this.exitCode = options?.exitCode ?? 1;\n this.suggestions = options?.suggestions ?? [];\n this.command = options?.command;\n this.phase = options?.phase;\n }\n\n /**\n * Returns a serializable representation of the error,\n * suitable for non-terminal runtimes (web UIs, APIs, etc.).\n */\n toJSON(): {\n name: string;\n message: string;\n exitCode: number;\n suggestions: string[];\n command?: string;\n phase?: string;\n } {\n return {\n name: this.name,\n message: this.message,\n exitCode: this.exitCode,\n suggestions: this.suggestions,\n command: this.command,\n phase: this.phase,\n };\n }\n}\n\n/**\n * Thrown when command routing fails — unknown command, unexpected arguments, etc.\n */\nexport class RoutingError extends PadroneError {\n constructor(message: string, options?: PadroneErrorOptions) {\n super(message, { phase: 'parse', ...options });\n this.name = 'RoutingError';\n }\n}\n\n/**\n * Thrown when argument or schema validation fails.\n * Carries the structured issues from the schema validator.\n */\nexport class ValidationError extends PadroneError {\n readonly issues: readonly { path?: PropertyKey[]; message: string }[];\n\n constructor(message: string, issues: readonly { path?: PropertyKey[]; message: string }[], options?: PadroneErrorOptions) {\n super(message, { phase: 'validate', ...options });\n this.name = 'ValidationError';\n this.issues = issues;\n }\n\n override toJSON() {\n return {\n ...super.toJSON(),\n issues: this.issues.map((i) => ({ path: i.path?.map(String), message: i.message })),\n };\n }\n}\n\n/**\n * Thrown when config file loading or validation fails.\n */\nexport class ConfigError extends PadroneError {\n constructor(message: string, options?: PadroneErrorOptions) {\n super(message, { phase: 'config', ...options });\n this.name = 'ConfigError';\n }\n}\n\n/**\n * Thrown from user action handlers to surface structured errors with exit codes and suggestions.\n * This is the primary error class users should throw from their command actions.\n *\n * @example\n * ```ts\n * throw new ActionError('Missing environment', {\n * exitCode: 1,\n * suggestions: ['Use --env production or --env staging'],\n * });\n * ```\n */\nexport class ActionError extends PadroneError {\n constructor(message: string, options?: PadroneErrorOptions) {\n super(message, { phase: 'execute', ...options });\n this.name = 'ActionError';\n }\n}\n"],"mappings":";;;;;;;;;;;;;AAkCA,IAAa,eAAb,cAAkC,MAAM;CACtC;CACA;CACA;CACA;CAEA,YAAY,SAAiB,SAA+B;AAC1D,Q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ApEZ;EAsEA,QAAA,GAAW,eAAA,IAlEX;EAoEA,QAAA,aAhEA;EAkEA,cAAA,GAAiB,QAAA;AAAA"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"help-bbmu9-qd.mjs","names":[],"sources":["../src/colorizer.ts","../src/formatter.ts","../src/help.ts"],"sourcesContent":["// ANSI color/style codes\nconst ansiCodes: Record<AnsiStyle, string> = {\n reset: '\\x1b[0m',\n bold: '\\x1b[1m',\n dim: '\\x1b[2m',\n italic: '\\x1b[3m',\n underline: '\\x1b[4m',\n strikethrough: '\\x1b[9m',\n red: '\\x1b[31m',\n green: '\\x1b[32m',\n yellow: '\\x1b[33m',\n blue: '\\x1b[34m',\n magenta: '\\x1b[35m',\n cyan: '\\x1b[36m',\n white: '\\x1b[37m',\n gray: '\\x1b[90m',\n};\n\n/**\n * Available ANSI styles that can be combined for each color role.\n */\nexport type AnsiStyle =\n | 'reset'\n | 'bold'\n | 'dim'\n | 'italic'\n | 'underline'\n | 'strikethrough'\n | 'red'\n | 'green'\n | 'yellow'\n | 'blue'\n | 'magenta'\n | 'cyan'\n | 'white'\n | 'gray';\n\n/**\n * Maps each semantic color role to an array of ANSI styles.\n * Partial configs are merged with the default theme.\n */\nexport type ColorConfig = {\n command?: AnsiStyle[];\n arg?: AnsiStyle[];\n type?: AnsiStyle[];\n description?: AnsiStyle[];\n label?: AnsiStyle[];\n meta?: AnsiStyle[];\n example?: AnsiStyle[];\n exampleValue?: AnsiStyle[];\n deprecated?: AnsiStyle[];\n};\n\nexport type Colorizer = {\n command: (text: string) => string;\n arg: (text: string) => string;\n type: (text: string) => string;\n description: (text: string) => string;\n label: (text: string) => string;\n meta: (text: string) => string;\n example: (text: string) => string;\n exampleValue: (text: string) => string;\n deprecated: (text: string) => string;\n};\n\n// ============================================================================\n// Predefined Themes\n// ============================================================================\n\nconst defaultTheme: Required<ColorConfig> = {\n command: ['cyan', 'bold'],\n arg: ['green'],\n type: ['yellow'],\n description: ['dim'],\n label: ['bold'],\n meta: ['gray'],\n example: ['underline'],\n exampleValue: ['italic'],\n deprecated: ['strikethrough', 'gray'],\n};\n\nconst oceanTheme: Required<ColorConfig> = {\n command: ['blue', 'bold'],\n arg: ['cyan'],\n type: ['green'],\n description: ['dim'],\n label: ['bold'],\n meta: ['gray'],\n example: ['underline', 'cyan'],\n exampleValue: ['italic'],\n deprecated: ['strikethrough', 'gray'],\n};\n\nconst warmTheme: Required<ColorConfig> = {\n command: ['yellow', 'bold'],\n arg: ['red'],\n type: ['magenta'],\n description: ['dim'],\n label: ['bold'],\n meta: ['gray'],\n example: ['underline', 'yellow'],\n exampleValue: ['italic'],\n deprecated: ['strikethrough', 'gray'],\n};\n\nconst monochromeTheme: Required<ColorConfig> = {\n command: ['bold'],\n arg: ['underline'],\n type: ['dim'],\n description: ['dim'],\n label: ['bold'],\n meta: ['dim'],\n example: ['underline'],\n exampleValue: ['italic'],\n deprecated: ['strikethrough', 'dim'],\n};\n\n/**\n * Available predefined color themes.\n */\nexport type ColorTheme = 'default' | 'ocean' | 'warm' | 'monochrome';\n\nexport const colorThemes: Record<ColorTheme, Required<ColorConfig>> = {\n default: defaultTheme,\n ocean: oceanTheme,\n warm: warmTheme,\n monochrome: monochromeTheme,\n};\n\nfunction makeStyleFn(styles: AnsiStyle[]): (text: string) => string {\n const prefix = styles.map((s) => ansiCodes[s]).join('');\n return (text: string) => `${prefix}${text}${ansiCodes.reset}`;\n}\n\nfunction resolveConfig(config?: ColorTheme | ColorConfig): Required<ColorConfig> {\n if (!config) return defaultTheme;\n if (typeof config === 'string') return colorThemes[config] ?? defaultTheme;\n return { ...defaultTheme, ...config };\n}\n\nexport function createColorizer(config?: ColorTheme | ColorConfig): Colorizer {\n const resolved = resolveConfig(config);\n return {\n command: makeStyleFn(resolved.command),\n arg: makeStyleFn(resolved.arg),\n type: makeStyleFn(resolved.type),\n description: makeStyleFn(resolved.description),\n label: makeStyleFn(resolved.label),\n meta: makeStyleFn(resolved.meta),\n example: makeStyleFn(resolved.example),\n exampleValue: makeStyleFn(resolved.exampleValue),\n deprecated: makeStyleFn(resolved.deprecated),\n };\n}\n","import { camelToKebab } from './args.ts';\nimport { type ColorConfig, type ColorTheme, createColorizer } from './colorizer.ts';\n\nexport type HelpFormat = 'text' | 'ansi' | 'console' | 'markdown' | 'html' | 'json';\nexport type HelpDetail = 'minimal' | 'standard' | 'full';\n\n// ============================================================================\n// Help Info Types (shared with help.ts)\n// ============================================================================\n\n/**\n * Information about a single positional argument.\n */\nexport type HelpPositionalInfo = {\n name: string;\n description?: string;\n optional: boolean;\n default?: unknown;\n type?: string;\n enum?: string[];\n};\n\n/**\n * Information about a single argument/flag.\n */\nexport type HelpArgumentInfo = {\n name: string;\n description?: string;\n optional: boolean;\n default?: unknown;\n type?: string;\n enum?: string[];\n /** Single-character short flags (shown as `-v`) */\n flags?: string[];\n /** Multi-character alternative long names (shown as `--dry-run`) */\n aliases?: string[];\n deprecated?: boolean | string;\n hidden?: boolean;\n examples?: unknown[];\n /** Environment variable(s) this arg can be set from */\n env?: string | string[];\n /** Whether this arg is an array type (shown as <type...>) */\n variadic?: boolean;\n /** Whether this arg is a boolean (shown as --[no-]arg) */\n negatable?: boolean;\n /** Config file key that maps to this arg */\n configKey?: string;\n /** Group name for organizing this option under a labeled section in help output */\n group?: string;\n};\n\n/**\n * Information about a subcommand (minimal info for listing).\n */\nexport type HelpSubcommandInfo = {\n name: string;\n title?: string;\n description?: string;\n aliases?: string[];\n deprecated?: boolean | string;\n hidden?: boolean;\n hasSubcommands?: boolean;\n /** Group name for organizing this command under a labeled section in help output */\n group?: string;\n};\n\n/**\n * Information about a built-in command/flag entry.\n */\nexport type HelpBuiltinInfo = {\n name: string;\n description?: string;\n sub?: { name: string; description?: string }[];\n};\n\n/**\n * Comprehensive JSON structure for help information.\n * This is the single source of truth that all formatters use.\n */\nexport type HelpInfo = {\n /** The full command name (e.g., \"cli serve\" or \"<root>\") */\n name: string;\n /** Short title for the command */\n title?: string;\n /** Command description */\n description?: string;\n /** Alternative names/aliases for this command */\n aliases?: string[];\n /** Whether the command is deprecated */\n deprecated?: boolean | string;\n /** Whether the command is hidden */\n hidden?: boolean;\n /** Usage string parts for flexible formatting */\n usage: {\n command: string;\n hasSubcommands: boolean;\n hasPositionals: boolean;\n hasArguments: boolean;\n /** The name of the field that reads from stdin, if any. Shown as `[stdin > field]` in usage. */\n stdinField?: string;\n };\n /** List of subcommands */\n subcommands?: HelpSubcommandInfo[];\n /** Positional arguments */\n positionals?: HelpPositionalInfo[];\n /** Arguments/flags (only visible ones, hidden filtered out) */\n arguments?: HelpArgumentInfo[];\n /** Built-in commands and flags (shown only for root command) */\n builtins?: HelpBuiltinInfo[];\n /** Command-level usage examples (shown in help output) */\n examples?: string[];\n /** Full help info for nested commands (used in 'full' detail mode) */\n nestedCommands?: HelpInfo[];\n};\n\n// ============================================================================\n// Formatter Interface\n// ============================================================================\n\n/**\n * A formatter that takes the entire HelpInfo structure and produces formatted output.\n */\nexport type Formatter = {\n /** Format the entire help info structure into a string */\n format: (info: HelpInfo) => string;\n};\n\n// ============================================================================\n// Internal Styling Types\n// ============================================================================\n\n/**\n * Internal styling functions used by formatters.\n * These handle the visual styling of individual text elements.\n */\ntype Styler = {\n command: (text: string) => string;\n arg: (text: string) => string;\n type: (text: string) => string;\n description: (text: string) => string;\n label: (text: string) => string;\n section: (text: string) => string;\n meta: (text: string) => string;\n example: (text: string) => string;\n exampleValue: (text: string) => string;\n deprecated: (text: string) => string;\n};\n\n/**\n * Layout configuration for formatters.\n */\ntype LayoutConfig = {\n newline: string;\n indent: (level: number) => string;\n join: (parts: string[]) => string;\n wrapDocument?: (content: string) => string;\n};\n\n// ============================================================================\n// Styler Factories\n// ============================================================================\n\nfunction createTextStyler(): Styler {\n return {\n command: (text) => text,\n arg: (text) => text,\n type: (text) => text,\n description: (text) => text,\n label: (text) => text,\n section: (text) => text,\n meta: (text) => text,\n example: (text) => text,\n exampleValue: (text) => text,\n deprecated: (text) => text,\n };\n}\n\nfunction createAnsiStyler(theme?: ColorTheme | ColorConfig): Styler {\n const colorizer = createColorizer(theme);\n return {\n command: colorizer.command,\n arg: colorizer.arg,\n type: colorizer.type,\n description: colorizer.description,\n label: colorizer.label,\n section: colorizer.label,\n meta: colorizer.meta,\n example: colorizer.example,\n exampleValue: colorizer.exampleValue,\n deprecated: colorizer.deprecated,\n };\n}\n\nfunction createConsoleStyler(theme?: ColorTheme | ColorConfig): Styler {\n return createAnsiStyler(theme);\n}\n\nfunction createMarkdownStyler(): Styler {\n return {\n command: (text) => `**${text}**`,\n arg: (text) => `\\`${text}\\``,\n type: (text) => `\\`${text}\\``,\n description: (text) => text,\n label: (text) => `**${text}**`,\n section: (text) => `### ${text}`,\n meta: (text) => `*${text}*`,\n example: (text) => `**${text}**`,\n exampleValue: (text) => `\\`${text}\\``,\n deprecated: (text) => `~~${text}~~`,\n };\n}\n\nfunction escapeHtml(text: string): string {\n return text.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\"/g, '&quot;').replace(/'/g, '&#039;');\n}\n\nfunction createHtmlStyler(): Styler {\n return {\n command: (text) => `<strong style=\"color: #00bcd4;\">${escapeHtml(text)}</strong>`,\n arg: (text) => `<code style=\"color: #4caf50;\">${escapeHtml(text)}</code>`,\n type: (text) => `<code style=\"color: #ff9800;\">${escapeHtml(text)}</code>`,\n description: (text) => `<span style=\"color: #666;\">${escapeHtml(text)}</span>`,\n label: (text) => `<strong>${escapeHtml(text)}</strong>`,\n section: (text) => `<h3>${escapeHtml(text)}</h3>`,\n meta: (text) => `<span style=\"color: #999;\">${escapeHtml(text)}</span>`,\n example: (text) => `<strong style=\"text-decoration: underline;\">${escapeHtml(text)}</strong>`,\n exampleValue: (text) => `<em>${escapeHtml(text)}</em>`,\n deprecated: (text) => `<del style=\"color: #999;\">${escapeHtml(text)}</del>`,\n };\n}\n\n// ============================================================================\n// Layout Configurations\n// ============================================================================\n\nfunction createTextLayout(): LayoutConfig {\n return {\n newline: '\\n',\n indent: (level) => ' '.repeat(level),\n join: (parts) => parts.filter(Boolean).join(' '),\n };\n}\n\nfunction createMarkdownLayout(): LayoutConfig {\n return {\n newline: '\\n\\n',\n indent: (level) => {\n if (level === 0) return '';\n if (level === 1) return ' ';\n return ' ';\n },\n join: (parts) => parts.filter(Boolean).join(' '),\n };\n}\n\nfunction createHtmlLayout(): LayoutConfig {\n return {\n newline: '<br>',\n indent: (level) => '&nbsp;&nbsp;'.repeat(level),\n join: (parts) => parts.filter(Boolean).join(' '),\n wrapDocument: (content) => `<div style=\"font-family: monospace; line-height: 1.6;\">${content}</div>`,\n };\n}\n\n// ============================================================================\n// Generic Formatter Implementation\n// ============================================================================\n\n/**\n * Creates a formatter that uses the given styler and layout configuration.\n */\nfunction createGenericFormatter(styler: Styler, layout: LayoutConfig, showAllBuiltins?: boolean): Formatter {\n const { newline, indent, join, wrapDocument } = layout;\n\n function formatUsageSection(info: HelpInfo): string[] {\n const usageParts: string[] = [styler.command(info.usage.command), info.usage.hasSubcommands ? styler.meta('[command]') : ''];\n // Show actual positional argument names in usage line\n if (info.positionals && info.positionals.length > 0) {\n for (const arg of info.positionals) {\n const name = arg.name.startsWith('...') ? `${arg.name}` : arg.name;\n usageParts.push(styler.meta(arg.optional ? `[${name}]` : `<${name}>`));\n }\n }\n if (info.usage.hasArguments) usageParts.push(styler.meta('[options]'));\n return [`${styler.label('Usage:')} ${join(usageParts)}`];\n }\n\n function formatSubcommandsSection(info: HelpInfo): string[] {\n const lines: string[] = [];\n const subcommands = info.subcommands!;\n\n const subcommandSuffix = (c: HelpSubcommandInfo) => (c.hasSubcommands ? ' <subcommand>' : '');\n const formatAliasParts = (c: HelpSubcommandInfo) => {\n if (!c.aliases?.length) return { plain: '', styled: '' };\n const realAliases = c.aliases.filter((a) => a !== '[default]');\n const hasDefault = c.aliases.some((a) => a === '[default]');\n const parts: string[] = [];\n const styledParts: string[] = [];\n if (realAliases.length) {\n parts.push(`(${realAliases.join(', ')})`);\n styledParts.push(`(${realAliases.join(', ')})`);\n }\n if (hasDefault) {\n parts.push('[default]');\n styledParts.push(styler.meta('[default]'));\n }\n return { plain: parts.length ? ` ${parts.join(' ')}` : '', styled: styledParts.length ? ` ${styledParts.join(' ')}` : '' };\n };\n // Column width is computed across all subcommands for consistent alignment\n const maxNameLength = Math.max(\n ...subcommands.map((c) => {\n return (c.name + subcommandSuffix(c) + formatAliasParts(c).plain).length;\n }),\n );\n\n const grouped = Object.groupBy(subcommands, (c) => c.group ?? '');\n\n const renderSubcommands = (cmds: HelpSubcommandInfo[]) => {\n for (const subCmd of cmds) {\n const aliasParts = formatAliasParts(subCmd);\n const suffix = subcommandSuffix(subCmd);\n const commandDisplay = subCmd.name + suffix + aliasParts.plain;\n const padding = ' '.repeat(Math.max(0, maxNameLength - commandDisplay.length + 2));\n const isDeprecated = !!subCmd.deprecated;\n const isDefaultEntry = subCmd.name === '[default]';\n const commandName = isDeprecated\n ? styler.deprecated(commandDisplay)\n : (isDefaultEntry ? styler.meta(subCmd.name) : styler.command(subCmd.name)) +\n (suffix ? styler.meta(suffix) : '') +\n aliasParts.styled;\n const lineParts: string[] = [commandName, padding];\n\n // Use title if available, otherwise use description\n const displayText = subCmd.title ?? subCmd.description;\n if (displayText) {\n lineParts.push(isDeprecated ? styler.deprecated(displayText) : styler.description(displayText));\n }\n if (isDeprecated) {\n const deprecatedMeta =\n typeof subCmd.deprecated === 'string' ? styler.meta(` (deprecated: ${subCmd.deprecated})`) : styler.meta(' (deprecated)');\n lineParts.push(deprecatedMeta);\n }\n lines.push(indent(1) + lineParts.join(''));\n }\n };\n\n for (const [key, items] of Object.entries(grouped)) {\n if (lines.length > 0) lines.push('');\n lines.push(styler.section(key ? `${key}:` : 'Commands:'));\n renderSubcommands(items!);\n }\n\n // Skip hint when builtins are present — the builtins section shows a combined hint\n if (!info.builtins?.length) {\n lines.push('');\n lines.push(styler.meta(`Run \"${info.name} [command] --help\" for more information on a command.`));\n }\n\n return lines;\n }\n\n function formatPositionalsSection(info: HelpInfo): string[] {\n const lines: string[] = [];\n const args = info.positionals!;\n\n lines.push(styler.section('Arguments:'));\n\n const maxNameLength = Math.min(32, Math.max(...args.map((a) => a.name.length)));\n\n for (const arg of args) {\n const padding = ' '.repeat(Math.max(2, maxNameLength - arg.name.length + 2));\n const descParts: string[] = [];\n if (arg.description) descParts.push(styler.description(arg.description));\n if (info.usage.stdinField === arg.name) descParts.push(styler.meta('(stdin)'));\n if (arg.enum) descParts.push(styler.meta(`(choices: ${arg.enum.join(', ')})`));\n if (arg.default !== undefined) descParts.push(styler.meta(`(default: ${String(arg.default)})`));\n lines.push(indent(1) + styler.arg(arg.name) + padding + join(descParts));\n }\n\n return lines;\n }\n\n function formatArgumentsSection(info: HelpInfo): string[] {\n const lines: string[] = [];\n const argList = info.arguments || [];\n\n // Helper to check if a default value is meaningful (not empty string/array)\n const hasDefault = (value: unknown): boolean => {\n if (value === undefined) return false;\n if (value === '') return false;\n if (Array.isArray(value) && value.length === 0) return false;\n return true;\n };\n\n // Build columns: flags | names | type | description\n const argColumns = argList.map((arg) => {\n // Promote kebab-case alias to primary display name if it exists\n const kebab = camelToKebab(arg.name);\n const primaryName = kebab && arg.aliases?.includes(kebab) ? kebab : arg.name;\n const remainingAliases = arg.aliases?.filter((a) => a !== primaryName);\n\n const flagsPlain = arg.flags?.length ? arg.flags.map((f) => `-${f}`).join(', ') : '';\n const namesPlain = [`--${primaryName}`, ...(remainingAliases?.map((a) => `--${a}`) || [])].join(', ');\n const typePlain = arg.type && arg.type !== 'boolean' ? (arg.optional ? `[${arg.type}]` : `<${arg.type}>`) : '';\n\n const isDeprecated = !!arg.deprecated;\n\n return { flagsPlain, namesPlain, typePlain, isDeprecated, arg };\n });\n\n // Column widths are computed across all args (regardless of group) for consistent alignment\n const maxFlagsWidth = Math.min(12, Math.max(0, ...argColumns.map((c) => c.flagsPlain.length)));\n const maxNamesWidth = Math.min(32, Math.max(0, ...argColumns.map((c) => c.namesPlain.length)));\n const maxTypeWidth = Math.min(16, Math.max(0, ...argColumns.map((c) => c.typePlain.length)));\n const hasAnyFlags = maxFlagsWidth > 0;\n\n // Split into ordered groups: ungrouped first as \"Options:\", then each group in first-seen order\n const grouped = Object.groupBy(argColumns, (c) => c.arg.group ?? '');\n\n const renderArgColumns = (columns: typeof argColumns) => {\n for (const { flagsPlain, namesPlain, typePlain, isDeprecated, arg } of columns) {\n const parts: string[] = [];\n\n // Flags column\n if (hasAnyFlags) {\n const styledFlags = isDeprecated ? (flagsPlain ? styler.deprecated(flagsPlain) : '') : flagsPlain ? styler.arg(flagsPlain) : '';\n const flagsPadding = ' '.repeat(Math.max(0, maxFlagsWidth - flagsPlain.length));\n const separator = flagsPlain ? ', ' : ' ';\n parts.push(styledFlags + flagsPadding + separator);\n }\n\n // Names column\n const styledNames = isDeprecated ? styler.deprecated(namesPlain) : styler.arg(namesPlain);\n const namesPadding = ' '.repeat(Math.max(2, maxNamesWidth - namesPlain.length + 2));\n parts.push(styledNames + namesPadding);\n\n // Type column\n if (maxTypeWidth > 0) {\n const styledType = typePlain ? styler.type(typePlain) : '';\n const typePadding = ' '.repeat(Math.max(2, maxTypeWidth - typePlain.length + 2));\n parts.push(styledType + typePadding);\n }\n\n // Line 1: description\n const descParts: string[] = [];\n if (arg.description) descParts.push(isDeprecated ? styler.deprecated(arg.description) : styler.description(arg.description));\n lines.push(indent(1) + parts.join('') + join(descParts));\n\n // Line 2: deprecated (no reason), default, choices\n const line2Parts: string[] = [];\n if (isDeprecated && typeof arg.deprecated !== 'string') line2Parts.push(styler.meta('(deprecated)'));\n if (hasDefault(arg.default)) line2Parts.push(styler.meta(`(default: ${String(arg.default)})`));\n if (arg.enum) line2Parts.push(styler.meta(`(choices: ${arg.enum.join(', ')})`));\n if (line2Parts.length > 0) lines.push(indent(3) + join(line2Parts));\n\n // Line 3: deprecated (with reason), examples\n const line3Parts: string[] = [];\n if (isDeprecated && typeof arg.deprecated === 'string') line3Parts.push(styler.meta(`(deprecated: ${arg.deprecated})`));\n if (arg.examples && arg.examples.length > 0) {\n const exampleValues = arg.examples.map((example) => (typeof example === 'string' ? example : JSON.stringify(example))).join(', ');\n line3Parts.push(styler.example('Example:'), styler.exampleValue(exampleValues));\n }\n if (line3Parts.length > 0) lines.push(indent(3) + join(line3Parts));\n\n // Line 4: stdin, env, config\n const line4Parts: string[] = [];\n if (info.usage.stdinField === arg.name) line4Parts.push(styler.meta('(stdin)'));\n if (arg.env) {\n const envVars = typeof arg.env === 'string' ? [arg.env] : arg.env;\n line4Parts.push(styler.example('Env:'), styler.exampleValue(envVars.join(', ')));\n }\n if (arg.configKey) {\n line4Parts.push(styler.example('Config:'), styler.exampleValue(arg.configKey));\n }\n if (line4Parts.length > 0) lines.push(indent(3) + join(line4Parts));\n }\n };\n\n for (const [key, items] of Object.entries(grouped)) {\n if (lines.length > 0) lines.push('');\n lines.push(styler.section(key ? `${key}:` : 'Options:'));\n renderArgColumns(items!);\n }\n\n return lines;\n }\n\n function formatBuiltinsSection(info: HelpInfo): string[] {\n const lines: string[] = [];\n const builtins = info.builtins!;\n\n if (!showAllBuiltins) {\n // Collapsed summary: show selected builtins on a single line with a combined hint\n const highlights = ['help [command]', 'version', '[command] --repl'];\n lines.push(`${styler.label('Global:')} ${styler.meta(highlights.join(', '))}`);\n const hint = info.usage.hasSubcommands\n ? `Run \"${info.name} [command] --help\" for more information. Use \"--all\" for all global commands.`\n : `Use \"${info.name} help --all\" for more information on global commands.`;\n lines.push(styler.meta(hint));\n return lines;\n }\n\n lines.push(styler.section('Global:'));\n\n // Compute max effective name length for alignment across main and sub entries\n const allLengths: number[] = [];\n for (const entry of builtins) {\n allLengths.push(entry.name.length);\n if (entry.sub) {\n for (const sub of entry.sub) {\n // Sub entries get extra indent(2) - indent(1) = 2 chars\n allLengths.push(sub.name.length + 2);\n }\n }\n }\n const maxLen = Math.max(...allLengths);\n\n for (const entry of builtins) {\n const padding = ' '.repeat(Math.max(2, maxLen - entry.name.length + 2));\n const parts: string[] = [styler.command(entry.name)];\n if (entry.description) parts.push(padding + styler.description(entry.description));\n lines.push(indent(1) + parts.join(''));\n\n if (entry.sub) {\n for (const sub of entry.sub) {\n const subPadding = ' '.repeat(Math.max(2, maxLen - sub.name.length));\n const subParts: string[] = [styler.arg(sub.name)];\n if (sub.description) subParts.push(subPadding + styler.description(sub.description));\n lines.push(indent(2) + subParts.join(''));\n }\n }\n }\n\n return lines;\n }\n\n return {\n format(info: HelpInfo): string {\n const lines: string[] = [];\n\n // Show deprecation warning at the top if command is deprecated\n if (info.deprecated) {\n const deprecationMessage =\n typeof info.deprecated === 'string' ? `⚠️ This command is deprecated: ${info.deprecated}` : '⚠️ This command is deprecated';\n lines.push(styler.deprecated(deprecationMessage));\n lines.push('');\n }\n\n // Usage section\n lines.push(...formatUsageSection(info));\n lines.push('');\n\n // Title section (if present, shows a short summary line)\n if (info.title) {\n lines.push(styler.label(info.title));\n lines.push('');\n }\n\n // Aliases section (if present)\n if (info.aliases && info.aliases.length > 0) {\n lines.push(styler.meta(`Aliases: ${info.aliases.join(', ')}`));\n lines.push('');\n }\n\n // Description section (if present)\n if (info.description) {\n lines.push(styler.description(info.description));\n lines.push('');\n }\n\n // Examples section (if present)\n if (info.examples && info.examples.length > 0) {\n lines.push(styler.section('Examples:'));\n for (const ex of info.examples) {\n lines.push(indent(1) + styler.meta('$ ') + styler.exampleValue(ex));\n }\n lines.push('');\n }\n\n // Subcommands section\n if (info.subcommands && info.subcommands.length > 0) {\n lines.push(...formatSubcommandsSection(info));\n lines.push('');\n }\n\n if (info.positionals && info.positionals.length > 0) {\n lines.push(...formatPositionalsSection(info));\n lines.push('');\n }\n\n if (info.arguments && info.arguments.length > 0) {\n lines.push(...formatArgumentsSection(info));\n lines.push('');\n }\n\n if (info.builtins && info.builtins.length > 0) {\n lines.push(...formatBuiltinsSection(info));\n lines.push('');\n }\n\n // Show --no- hint when there are negatable boolean options defaulting to true\n if (info.arguments?.some((arg) => arg.negatable && arg.default === true)) {\n lines.push(styler.meta('Boolean options can be negated with --no-<option>.'));\n lines.push('');\n }\n\n // Nested commands section (full detail mode)\n if (info.nestedCommands?.length) {\n lines.push(styler.section('Subcommand Details:'));\n lines.push('');\n for (const nestedCmd of info.nestedCommands) {\n lines.push(styler.meta('─'.repeat(60)));\n lines.push(this.format(nestedCmd));\n }\n }\n\n const result = lines.join(newline);\n return wrapDocument ? wrapDocument(result) : result;\n },\n };\n}\n\n// ============================================================================\n// JSON Formatter\n// ============================================================================\n\nfunction createJsonFormatter(): Formatter {\n return {\n format(info: HelpInfo): string {\n return JSON.stringify(info, null, 2);\n },\n };\n}\n\n// ============================================================================\n// Formatter Factory\n// ============================================================================\n\nfunction shouldUseAnsi(): boolean {\n if (typeof process === 'undefined') return false;\n if (process.env.NO_COLOR) return false;\n if (process.env.CI) return false;\n if (process.stdout && typeof process.stdout.isTTY === 'boolean') return process.stdout.isTTY;\n return false;\n}\n\n// ============================================================================\n// Minimal Formatter\n// ============================================================================\n\n/**\n * Creates a minimal formatter that outputs just a single-line usage string.\n */\nfunction createMinimalFormatter(): Formatter {\n return {\n format(info: HelpInfo): string {\n const parts: string[] = [info.usage.command];\n if (info.usage.hasSubcommands) parts.push('[command]');\n if (info.positionals && info.positionals.length > 0) {\n for (const arg of info.positionals) {\n const name = arg.name.startsWith('...') ? `${arg.name}` : arg.name;\n parts.push(arg.optional ? `[${name}]` : `<${name}>`);\n }\n }\n if (info.usage.hasArguments) parts.push('[options]');\n return parts.join(' ');\n },\n };\n}\n\nexport function createFormatter(\n format: HelpFormat | 'auto',\n detail: HelpDetail = 'standard',\n theme?: ColorTheme | ColorConfig,\n all?: boolean,\n): Formatter {\n if (detail === 'minimal') return createMinimalFormatter();\n if (format === 'json') return createJsonFormatter();\n if (format === 'ansi' || (format === 'auto' && shouldUseAnsi()))\n return createGenericFormatter(createAnsiStyler(theme), createTextLayout(), all);\n if (format === 'console') return createGenericFormatter(createConsoleStyler(theme), createTextLayout(), all);\n if (format === 'markdown') return createGenericFormatter(createMarkdownStyler(), createMarkdownLayout(), all);\n if (format === 'html') return createGenericFormatter(createHtmlStyler(), createHtmlLayout(), all);\n return createGenericFormatter(createTextStyler(), createTextLayout(), all);\n}\n","import type { StandardJSONSchemaV1 } from '@standard-schema/spec';\nimport { extractSchemaMetadata, JSON_SCHEMA_OPTS, type PadroneArgsSchemaMeta, parsePositionalConfig, parseStdinConfig } from './args.ts';\nimport type { ColorConfig, ColorTheme } from './colorizer.ts';\nimport { findCommandByName } from './command-utils.ts';\nimport {\n createFormatter,\n type HelpArgumentInfo,\n type HelpDetail,\n type HelpFormat,\n type HelpInfo,\n type HelpPositionalInfo,\n type HelpSubcommandInfo,\n} from './formatter.ts';\nimport type { AnyPadroneCommand } from './types.ts';\nimport { getRootCommand } from './utils.ts';\n\nexport type HelpPreferences = {\n format?: HelpFormat | 'auto';\n detail?: HelpDetail;\n theme?: ColorTheme | ColorConfig;\n /** Show all global commands and flags in full detail */\n all?: boolean;\n};\n\n/**\n * Extract positional arguments info from schema based on meta.positional config.\n */\nfunction extractPositionalArgsInfo(\n schema: StandardJSONSchemaV1,\n meta?: PadroneArgsSchemaMeta,\n): { args: HelpPositionalInfo[]; positionalNames: Set<string> } {\n const args: HelpPositionalInfo[] = [];\n const positionalNames = new Set<string>();\n\n if (!schema || !meta?.positional || meta.positional.length === 0) {\n return { args, positionalNames };\n }\n\n const positionalConfig = parsePositionalConfig(meta.positional);\n\n try {\n const jsonSchema = schema['~standard'].jsonSchema.input(JSON_SCHEMA_OPTS) as Record<string, any>;\n\n if (jsonSchema.type === 'object' && jsonSchema.properties) {\n const properties = jsonSchema.properties as Record<string, any>;\n const required = (jsonSchema.required as string[]) || [];\n\n for (const { name, variadic } of positionalConfig) {\n const prop = properties[name];\n if (!prop) continue;\n\n positionalNames.add(name);\n const optMeta = meta.fields?.[name];\n\n args.push({\n name: variadic ? `...${name}` : name,\n description: optMeta?.description ?? prop.description,\n optional: !required.includes(name),\n default: prop.default,\n type: variadic ? `array<${prop.items?.type || 'string'}>` : prop.type,\n enum: (prop.enum ?? prop.items?.enum) as string[] | undefined,\n });\n }\n }\n } catch {\n // Fallback to empty result if toJSONSchema fails\n }\n\n return { args, positionalNames };\n}\n\nfunction extractArgsInfo(schema: StandardJSONSchemaV1, meta?: PadroneArgsSchemaMeta, positionalNames?: Set<string>) {\n const result: HelpArgumentInfo[] = [];\n if (!schema) return result;\n\n const vendor = schema['~standard'].vendor;\n if (!vendor.includes('zod')) return result;\n\n const argsMeta = meta?.fields;\n\n try {\n const jsonSchema = schema['~standard'].jsonSchema.input(JSON_SCHEMA_OPTS) as Record<string, any>;\n\n // Handle object: z.object({ key: z.string(), ... })\n if (jsonSchema.type === 'object' && jsonSchema.properties) {\n const properties = jsonSchema.properties as Record<string, any>;\n const required = (jsonSchema.required as string[]) || [];\n const propertyNames = new Set(Object.keys(properties));\n\n // Helper to check if a negated version of an arg exists\n const hasExplicitNegation = (key: string): boolean => {\n // Check for noVerbose style (camelCase)\n const camelNegated = `no${key.charAt(0).toUpperCase()}${key.slice(1)}`;\n if (propertyNames.has(camelNegated)) return true;\n // Check for no-verbose style (kebab-case, though rare in JS)\n const kebabNegated = `no-${key}`;\n if (propertyNames.has(kebabNegated)) return true;\n return false;\n };\n\n // Helper to check if this arg is itself a negation of another arg\n const isNegationOf = (key: string): boolean => {\n // Check for noVerbose -> verbose (camelCase)\n if (key.startsWith('no') && key.length > 2 && key[2] === key[2]?.toUpperCase()) {\n const positiveKey = key.charAt(2).toLowerCase() + key.slice(3);\n if (propertyNames.has(positiveKey)) return true;\n }\n // Check for no-verbose -> verbose (kebab-case)\n if (key.startsWith('no-')) {\n const positiveKey = key.slice(3);\n if (propertyNames.has(positiveKey)) return true;\n }\n return false;\n };\n\n for (const [key, prop] of Object.entries(properties)) {\n // Skip positional arguments - they are shown in arguments section\n if (positionalNames?.has(key)) continue;\n\n const isOptional = !required.includes(key);\n const enumValues = (prop.enum ?? prop.items?.enum) as string[] | undefined;\n const optMeta = argsMeta?.[key];\n const propType = prop.type as string;\n\n // Booleans are negatable unless there's an explicit noArg property\n // or this arg is itself a negation of another arg\n const isNegatable = propType === 'boolean' && !hasExplicitNegation(key) && !isNegationOf(key);\n\n result.push({\n name: key,\n description: optMeta?.description ?? prop.description,\n optional: isOptional,\n default: prop.default,\n type: propType === 'array' ? `${prop.items?.type || 'string'}[]` : propType,\n enum: enumValues,\n deprecated: optMeta?.deprecated ?? prop?.deprecated,\n hidden: optMeta?.hidden ?? prop?.hidden,\n examples: optMeta?.examples ?? prop?.examples,\n variadic: propType === 'array',\n negatable: isNegatable,\n group: optMeta?.group,\n });\n }\n }\n } catch {\n // Fallback to empty result if toJSONSchema fails\n }\n\n return result;\n}\n\n// ============================================================================\n// Core Help Info Builder\n// ============================================================================\n\n/**\n * Builds a comprehensive HelpInfo structure from a command.\n * This is the single source of truth that all formatters use.\n * @param cmd - The command to build help info for\n * @param detail - The level of detail ('minimal', 'standard', or 'full')\n */\nexport function getHelpInfo(cmd: AnyPadroneCommand, detail: HelpPreferences['detail'] = 'standard', all?: boolean): HelpInfo {\n const rootCmd = getRootCommand(cmd);\n // A command is a \"default\" command if its name is '' or it has '' as an alias\n const isDefaultCommand = cmd.parent && (!cmd.name || cmd.aliases?.includes(''));\n // For commands with empty name, use the first non-empty alias as display name\n const nonEmptyAliases = cmd.aliases?.filter(Boolean);\n const commandName = cmd.path || cmd.name || nonEmptyAliases?.[0] || (cmd.parent ? '[default]' : 'program');\n // Build display aliases: real aliases (excluding the one promoted to display name) + [default] marker\n const remainingAliases = !cmd.name && nonEmptyAliases?.length ? nonEmptyAliases.slice(1) : (nonEmptyAliases ?? []);\n const displayAliases = isDefaultCommand ? [...remainingAliases, '[default]'] : nonEmptyAliases;\n\n // Extract positional args from schema based on meta.positional\n const { args: positionalArgs, positionalNames } = cmd.argsSchema\n ? extractPositionalArgsInfo(cmd.argsSchema, cmd.meta)\n : { args: [], positionalNames: new Set<string>() };\n\n const hasPositionals = positionalArgs.length > 0;\n\n const helpInfo: HelpInfo = {\n name: commandName,\n title: cmd.title,\n description: cmd.description,\n examples: cmd.examples,\n aliases: displayAliases,\n deprecated: cmd.deprecated,\n hidden: cmd.hidden,\n usage: {\n command: rootCmd === cmd ? commandName : `${rootCmd.name} ${commandName}`,\n hasSubcommands: !!(cmd.commands && cmd.commands.length > 0),\n hasPositionals,\n hasArguments: false, // updated below after extracting arguments\n stdinField: cmd.meta?.stdin ? parseStdinConfig(cmd.meta.stdin) : undefined,\n },\n };\n\n // Build subcommands info (filter out hidden commands unless showing full detail)\n if (cmd.commands && cmd.commands.length > 0) {\n const visibleCommands = detail === 'full' ? cmd.commands : cmd.commands.filter((c) => !c.hidden);\n // If the command has both a handler and subcommands, show the handler as a \"[default]\" entry\n const selfEntry: typeof helpInfo.subcommands = cmd.action\n ? [{ name: '[default]', title: cmd.title, description: cmd.description }]\n : [];\n\n helpInfo.subcommands = [\n ...selfEntry,\n ...visibleCommands.flatMap((c): HelpSubcommandInfo[] => {\n const isDefault = !c.name || c.aliases?.includes('');\n const nonEmptyAliases = c.aliases?.filter(Boolean);\n const displayName = c.name || nonEmptyAliases?.[0] || '[default]';\n const remainingAliases = !c.name && nonEmptyAliases?.length ? nonEmptyAliases.slice(1) : (nonEmptyAliases ?? []);\n // Only add [default] alias marker if it's not already the display name\n const displayAliases =\n isDefault && displayName !== '[default]' ? [...remainingAliases, '[default]'] : isDefault ? remainingAliases : nonEmptyAliases;\n const hasSubcommands = !!(c.commands && c.commands.length > 0);\n\n // If a command has subcommands AND a default handler (direct or '' subcommand),\n // show two entries: one for the default action, one for the subcommand router\n const hasDefaultHandler = c.action || c.commands?.some((sub) => !sub.name || sub.aliases?.includes(''));\n if (hasSubcommands && hasDefaultHandler) {\n const defaultSub = !c.action ? c.commands?.find((sub) => !sub.name || sub.aliases?.includes('')) : undefined;\n const hasDefaultSubInfo = defaultSub && (defaultSub.title || defaultSub.description);\n return [\n {\n name: displayName,\n title: hasDefaultSubInfo ? defaultSub.title : c.title,\n description: hasDefaultSubInfo ? defaultSub.description : c.description,\n aliases: displayAliases?.length ? displayAliases : undefined,\n deprecated: c.deprecated,\n hidden: c.hidden,\n group: c.group,\n },\n {\n name: displayName,\n title: c.title,\n description: c.description,\n deprecated: c.deprecated,\n hidden: c.hidden,\n hasSubcommands: true,\n group: c.group,\n },\n ];\n }\n\n return [\n {\n name: displayName,\n title: c.title,\n description: c.description,\n aliases: displayAliases?.length ? displayAliases : undefined,\n deprecated: c.deprecated,\n hidden: c.hidden,\n hasSubcommands,\n group: c.group,\n },\n ];\n }),\n ];\n\n // In 'full' detail mode, recursively build help for all nested commands\n if (detail === 'full') {\n helpInfo.nestedCommands = visibleCommands.map((c) => getHelpInfo(c, 'full'));\n }\n }\n\n // Build arguments info from positionals\n if (hasPositionals) {\n helpInfo.positionals = positionalArgs;\n }\n\n // Build arguments info with aliases (excluding positional args)\n if (cmd.argsSchema) {\n const argsInfo = extractArgsInfo(cmd.argsSchema, cmd.meta, positionalNames);\n const argMap: Record<string, HelpArgumentInfo> = Object.fromEntries(argsInfo.map((arg) => [arg.name, arg]));\n\n // Merge flags and aliases into arguments\n const { flags, aliases } = extractSchemaMetadata(cmd.argsSchema, cmd.meta?.fields, cmd.meta?.autoAlias);\n for (const [flag, name] of Object.entries(flags)) {\n const arg = argMap[name];\n if (!arg) continue;\n arg.flags = [...(arg.flags || []), flag];\n }\n for (const [alias, name] of Object.entries(aliases)) {\n const arg = argMap[name];\n if (!arg) continue;\n arg.aliases = [...(arg.aliases || []), alias];\n }\n\n // Filter out hidden arguments\n const visibleArgs = argsInfo.filter((arg) => !arg.hidden);\n if (visibleArgs.length > 0) {\n helpInfo.arguments = visibleArgs;\n helpInfo.usage.hasArguments = true;\n }\n }\n\n // Add global commands/flags (root command by default, all commands when --all is passed)\n if (!cmd.parent || all) {\n const builtins: HelpInfo['builtins'] = [];\n\n if (!findCommandByName('help', rootCmd.commands)) {\n builtins.push({\n name: 'help [command], -h, --help',\n description: 'Show help for a command',\n sub: [\n { name: '--all', description: 'Show all global commands and flags' },\n { name: '--detail <level>', description: 'Detail level (minimal, standard, full)' },\n { name: '--format <format>', description: 'Output format (text, ansi, json, markdown, html)' },\n ],\n });\n }\n\n if (!findCommandByName('version', rootCmd.commands)) {\n builtins.push({\n name: 'version, -v, --version',\n description: 'Show version information',\n });\n }\n\n if (!findCommandByName('completion', rootCmd.commands)) {\n builtins.push({\n name: 'completion [shell]',\n description: 'Generate shell completions (bash, zsh, fish, powershell)',\n });\n }\n\n if (!findCommandByName('man', rootCmd.commands)) {\n builtins.push({\n name: 'man',\n description: 'Show or install man pages (--setup to install, --remove to uninstall) (experimental)',\n });\n }\n\n builtins.push({\n name: '[command] --repl',\n description: 'Start interactive REPL scoped to a command',\n });\n\n if (!findCommandByName('mcp', rootCmd.commands)) {\n builtins.push({\n name: 'mcp [http|stdio]',\n description: 'Start a Model Context Protocol server to expose commands as AI tools (experimental)',\n sub: [\n { name: '--port <port>', description: 'HTTP port (default: 3000)' },\n { name: '--host <host>', description: 'HTTP host (default: 127.0.0.1)' },\n ],\n });\n }\n\n builtins.push({\n name: '--color [theme], --no-color',\n description: 'Set color theme (default, ocean, warm, monochrome) or disable colors',\n });\n\n if (builtins.length > 0) {\n helpInfo.builtins = builtins;\n }\n }\n\n return helpInfo;\n}\n\n// ============================================================================\n// Main Entry Point\n// ============================================================================\n\nexport function generateHelp(rootCommand: AnyPadroneCommand, commandObj: AnyPadroneCommand = rootCommand, prefs?: HelpPreferences): string {\n const helpInfo = getHelpInfo(commandObj, prefs?.detail, prefs?.all);\n const formatter = createFormatter(prefs?.format ?? 'auto', prefs?.detail, prefs?.theme, prefs?.all);\n return formatter.format(helpInfo);\n}\n"],"mappings":";;;AACA,MAAM,YAAuC;CAC3C,OAAO;CACP,MAAM;CACN,KAAK;CACL,QAAQ;CACR,WAAW;CACX,eAAe;CACf,KAAK;CACL,OAAO;CACP,QAAQ;CACR,MAAM;CACN,SAAS;CACT,MAAM;CACN,OAAO;CACP,MAAM;CACP;AAqD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B,QAAO;;AAOT,SAAgB,aAAa,aAAgC,aAAgC,aAAa,OAAiC;CACzI,MAAM,WAAW,YAAY,YAAY,OAAO,QAAQ,OAAO,IAAI;AAEnE,QADkB,gBAAgB,OAAO,UAAU,QAAQ,OAAO,QAAQ,OAAO,OAAO,OAAO,IAAI,CAClF,OAAO,SAAS"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"mcp-mLWIdUIu.mjs","names":[],"sources":["../src/mcp.ts"],"sourcesContent":["import { buildInputSchema, collectEndpoints, serializeArgsToFlags } from './command-utils.ts';\nimport { generateHelp } from './help.ts';\nimport type { AnyPadroneCommand, AnyPadroneProgram } from './types.ts';\n\nexport type PadroneMcpPreferences = {\n /** Server name. Defaults to the program name. */\n name?: string;\n /** Server version. Defaults to the program version. */\n version?: string;\n /**\n * Transport mode.\n * - `'http'` — Start a Streamable HTTP server (default). Responds with `application/json` or `text/event-stream` based on the client's `Accept` header. Use `port` and `host` to configure.\n * - `'stdio'` — Communicate over stdin/stdout with newline-delimited JSON.\n */\n transport?: 'http' | 'stdio';\n /** HTTP port. Defaults to `3000`. Only used with `transport: 'http'`. */\n port?: number;\n /** HTTP host. Defaults to `'127.0.0.1'`. Only used with `transport: 'http'`. */\n host?: string;\n /** Base path for the MCP endpoint. Defaults to `'/mcp'`. Only used with `transport: 'http'`. */\n basePath?: string;\n /** CORS allowed origin. Defaults to `'*'`. Set to a specific origin or `false` to disable CORS headers. Only used with HTTP transports. */\n cors?: string | false;\n};\n\nconst PROTOCOL_VERSION = '2025-11-25';\n\ntype JsonRpcRequest = {\n jsonrpc: '2.0';\n id?: string | number;\n method: string;\n params?: Record<string, unknown>;\n};\n\ntype JsonRpcResponse = {\n jsonrpc: '2.0';\n id: string | number | null;\n result?: unknown;\n error?: { code: number; message: string; data?: unknown };\n};\n\n/** Convert an endpoint dot-path to a valid MCP tool name. Spec allows: [A-Za-z0-9_\\-\\.] */\nfunction toToolName(path: string): string {\n return path.replace(/\\s+/g, '.');\n}\n\n/** Convert a tool name back to a command path (dot → space). */\nfunction toCommandPath(toolName: string): string {\n return toolName.replace(/\\./g, ' ');\n}\n\n/** Build MCP tool annotations from a command's metadata. */\nfunction buildAnnotations(cmd: AnyPadroneCommand) {\n if (cmd.mutation == null) return undefined;\n return {\n destructiveHint: cmd.mutation || undefined,\n readOnlyHint: cmd.mutation === false || undefined,\n };\n}\n\n/** Build an MCP tool definition from a command. */\nfunction buildToolDefinition(name: string, cmd: AnyPadroneCommand) {\n return {\n name: toToolName(name),\n title: cmd.title ?? undefined,\n description: cmd.description || cmd.title || `Run the \"${name}\" command`,\n inputSchema: buildInputSchema(cmd),\n annotations: buildAnnotations(cmd),\n };\n}\n\n/** Create the MCP request handler. Returns an async function that processes a JSON-RPC request and returns a response (or undefined for notifications). */\nexport function createMcpHandler(\n existingCommand: AnyPadroneCommand,\n evalCommand: AnyPadroneProgram['eval'],\n prefs?: PadroneMcpPreferences,\n) {\n const serverName = prefs?.name ?? existingCommand.name;\n const serverVersion = prefs?.version ?? existingCommand.version ?? '0.0.0';\n\n const rootTools = collectEndpoints(existingCommand.commands, '');\n if (existingCommand.action || existingCommand.argsSchema) {\n rootTools.unshift({ name: '', command: existingCommand });\n }\n\n const toolMap = new Map(rootTools.map((t) => [toToolName(t.name), t]));\n\n const helpToolName = 'help';\n const helpToolDef = {\n name: helpToolName,\n title: 'Help',\n description: `Show help for the \"${serverName}\" program or a specific command`,\n inputSchema: {\n type: 'object' as const,\n properties: { command: { type: 'string', description: 'Command name to get help for (omit for program help)' } },\n additionalProperties: false,\n },\n };\n\n return async function handleRequest(req: JsonRpcRequest): Promise<JsonRpcResponse | undefined> {\n const { id, method, params } = req;\n\n switch (method) {\n case 'initialize':\n return {\n jsonrpc: '2.0',\n id: id ?? null,\n result: {\n protocolVersion: PROTOCOL_VERSION,\n capabilities: { tools: {} },\n serverInfo: { name: serverName, version: serverVersion },\n },\n };\n\n case 'notifications/initialized':\n case 'notifications/cancelled':\n return undefined;\n\n case 'ping':\n return { jsonrpc: '2.0', id: id ?? null, result: {} };\n\n case 'tools/list': {\n const tools = [...rootTools.map((t) => buildToolDefinition(t.name, t.command)), helpToolDef];\n return { jsonrpc: '2.0', id: id ?? null, result: { tools } };\n }\n\n case 'tools/call': {\n const toolName = params?.name as string;\n const args = (params?.arguments ?? {}) as Record<string, unknown>;\n\n // Built-in help tool\n if (toolName === helpToolName) {\n const cmdName = args.command as string | undefined;\n const targetCmd = cmdName ? rootTools.find((t) => t.name === cmdName || toToolName(t.name) === cmdName)?.command : undefined;\n const helpText = generateHelp(existingCommand, targetCmd ?? existingCommand, { format: 'text', detail: 'full' });\n return {\n jsonrpc: '2.0',\n id: id ?? null,\n result: { content: [{ type: 'text', text: helpText }], isError: false },\n };\n }\n\n const tool = toolMap.get(toolName);\n if (!tool) {\n return {\n jsonrpc: '2.0',\n id: id ?? null,\n error: { code: -32602, message: `Unknown tool: ${toolName}` },\n };\n }\n\n // Build command string: convert tool name back to command path + serialize args as flags\n const commandPath = toCommandPath(tool.name);\n const argParts = serializeArgsToFlags(args);\n const input = [commandPath, ...argParts].filter(Boolean).join(' ') || undefined;\n\n try {\n const output: string[] = [];\n const errors: string[] = [];\n const result = await evalCommand(input as any, {\n autoOutput: false,\n runtime: {\n output: (...outArgs: unknown[]) => output.push(outArgs.map(String).join(' ')),\n error: (text: string) => errors.push(text),\n interactive: 'unsupported',\n format: 'text',\n },\n });\n\n const content: { type: string; text: string }[] = [];\n\n if (result.error) {\n const errorMsg = result.error instanceof Error ? result.error.message : String(result.error);\n if (errors.length) content.push({ type: 'text', text: errors.join('\\n') });\n content.push({ type: 'text', text: errorMsg });\n return { jsonrpc: '2.0', id: id ?? null, result: { content, isError: true } };\n }\n\n if (result.argsResult?.issues) {\n const issueMessages = result.argsResult.issues.map((i: any) => `${i.path?.join('.') || 'root'}: ${i.message}`).join('\\n');\n content.push({ type: 'text', text: `Validation error:\\n${issueMessages}` });\n return { jsonrpc: '2.0', id: id ?? null, result: { content, isError: true } };\n }\n\n if (output.length) content.push({ type: 'text', text: output.join('\\n') });\n if (result.result !== undefined && result.result !== null) {\n const resultText = typeof result.result === 'string' ? result.result : JSON.stringify(result.result, null, 2);\n content.push({ type: 'text', text: resultText });\n }\n if (content.length === 0) content.push({ type: 'text', text: 'Done.' });\n return { jsonrpc: '2.0', id: id ?? null, result: { content, isError: false } };\n } catch (err) {\n const errorMsg = err instanceof Error ? err.message : String(err);\n return {\n jsonrpc: '2.0',\n id: id ?? null,\n result: { content: [{ type: 'text', text: errorMsg }], isError: true },\n };\n }\n }\n\n default: {\n if (id !== undefined) {\n return { jsonrpc: '2.0', id, error: { code: -32601, message: `Method not found: ${method}` } };\n }\n return undefined;\n }\n }\n };\n}\n\n/** stdio transport: newline-delimited JSON per 2025-11-25 spec. */\nasync function startStdioTransport(handleRequest: (req: JsonRpcRequest) => Promise<JsonRpcResponse | undefined>): Promise<void> {\n const { stdin, stdout } = await import('node:process');\n const { createInterface } = await import('node:readline');\n\n function send(msg: JsonRpcResponse) {\n stdout.write(`${JSON.stringify(msg)}\\n`);\n }\n\n const rl = createInterface({ input: stdin, crlfDelay: Infinity });\n\n for await (const line of rl) {\n if (!line.trim()) continue;\n try {\n const req = JSON.parse(line) as JsonRpcRequest;\n const res = await handleRequest(req);\n if (res) send(res);\n } catch {\n // Ignore malformed JSON\n }\n }\n}\n\n/** Streamable HTTP transport per 2025-11-25 spec. Responds with JSON or SSE based on client's Accept header. */\nasync function startHttpTransport(\n handleRequest: (req: JsonRpcRequest) => Promise<JsonRpcResponse | undefined>,\n prefs: PadroneMcpPreferences,\n log: (msg: string) => void,\n): Promise<void> {\n const http = await import('node:http');\n const crypto = await import('node:crypto');\n\n const port = prefs.port ?? 3000;\n const host = prefs.host ?? '127.0.0.1';\n const endpoint = prefs.basePath ?? '/mcp';\n\n // Session management\n let sessionId: string | undefined;\n let negotiatedVersion: string | undefined;\n\n const corsOrigin = prefs.cors !== false ? (prefs.cors ?? '*') : undefined;\n\n const server = http.createServer(async (req, res) => {\n // CORS headers\n if (corsOrigin) {\n res.setHeader('Access-Control-Allow-Origin', corsOrigin);\n res.setHeader('Access-Control-Allow-Methods', 'POST, GET, DELETE, OPTIONS');\n res.setHeader('Access-Control-Allow-Headers', 'Content-Type, MCP-Session-Id, MCP-Protocol-Version');\n res.setHeader('Access-Control-Expose-Headers', 'MCP-Session-Id');\n }\n\n if (req.method === 'OPTIONS') {\n res.writeHead(corsOrigin ? 204 : 405);\n res.end();\n return;\n }\n\n if (req.url !== endpoint) {\n res.writeHead(404, { 'Content-Type': 'application/json' });\n res.end(JSON.stringify({ error: 'Not found' }));\n return;\n }\n\n // DELETE: terminate session\n if (req.method === 'DELETE') {\n const reqSessionId = req.headers['mcp-session-id'] as string | undefined;\n if (sessionId && reqSessionId === sessionId) {\n sessionId = undefined;\n negotiatedVersion = undefined;\n res.writeHead(200);\n res.end();\n } else {\n res.writeHead(404);\n res.end();\n }\n return;\n }\n\n // GET: SSE stream (not implemented — return 405)\n if (req.method === 'GET') {\n res.writeHead(405, { 'Content-Type': 'application/json' });\n res.end(JSON.stringify({ jsonrpc: '2.0', id: null, error: { code: -32601, message: 'SSE stream not supported' } }));\n return;\n }\n\n if (req.method !== 'POST') {\n res.writeHead(405);\n res.end();\n return;\n }\n\n // Validate session ID on non-initialize requests\n const reqSessionId = req.headers['mcp-session-id'] as string | undefined;\n if (sessionId && reqSessionId && reqSessionId !== sessionId) {\n res.writeHead(404, { 'Content-Type': 'application/json' });\n res.end(JSON.stringify({ jsonrpc: '2.0', id: null, error: { code: -32600, message: 'Invalid session' } }));\n return;\n }\n\n // Validate MCP-Protocol-Version header on post-init requests\n const reqProtocolVersion = req.headers['mcp-protocol-version'] as string | undefined;\n if (negotiatedVersion && reqProtocolVersion && reqProtocolVersion !== negotiatedVersion) {\n res.writeHead(400, { 'Content-Type': 'application/json' });\n res.end(JSON.stringify({ jsonrpc: '2.0', id: null, error: { code: -32600, message: 'Protocol version mismatch' } }));\n return;\n }\n\n // Read request body\n const chunks: Buffer[] = [];\n for await (const chunk of req) {\n chunks.push(chunk);\n }\n const body = Buffer.concat(chunks).toString('utf-8');\n\n let rpcRequest: JsonRpcRequest;\n try {\n rpcRequest = JSON.parse(body);\n } catch {\n res.writeHead(400, { 'Content-Type': 'application/json' });\n res.end(JSON.stringify({ jsonrpc: '2.0', id: null, error: { code: -32700, message: 'Parse error' } }));\n return;\n }\n\n const response = await handleRequest(rpcRequest);\n\n // On initialize response: create session and set header\n if (rpcRequest.method === 'initialize' && response?.result) {\n sessionId = crypto.randomUUID();\n negotiatedVersion = PROTOCOL_VERSION;\n res.setHeader('MCP-Session-Id', sessionId);\n }\n\n if (response) {\n const accept = req.headers.accept ?? '';\n if (accept.includes('text/event-stream')) {\n res.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', Connection: 'keep-alive' });\n res.write(`event: message\\ndata: ${JSON.stringify(response)}\\n\\n`);\n res.end();\n } else {\n res.writeHead(200, { 'Content-Type': 'application/json' });\n res.end(JSON.stringify(response));\n }\n } else {\n // Notification or response from client — no body\n res.writeHead(202);\n res.end();\n }\n });\n\n return new Promise<void>((resolve, reject) => {\n server.listen(port, host, () => {\n log(`MCP server listening on http://${host}:${port}${endpoint}`);\n });\n server.on('error', reject);\n const onSignal = () => {\n server.close(() => resolve());\n };\n process.on('SIGINT', onSignal);\n process.on('SIGTERM', onSignal);\n });\n}\n\nexport async function startMcpServer(\n _program: AnyPadroneProgram,\n existingCommand: AnyPadroneCommand,\n evalCommand: AnyPadroneProgram['eval'],\n prefs?: PadroneMcpPreferences,\n): Promise<void> {\n const handleRequest = createMcpHandler(existingCommand, evalCommand, prefs);\n const transport = prefs?.transport ?? 'http';\n\n if (transport === 'stdio') {\n return startStdioTransport(handleRequest);\n }\n\n const { getCommandRuntime } = await import('./command-utils.ts');\n const runtime = getCommandRuntime(existingCommand);\n return startHttpTransport(handleRequest, prefs ?? {}, (msg) => runtime.error(msg));\n}\n"],"mappings":";;;AAyBA,MAAM,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