@unliftedq/kman 0.0.2 → 0.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/main.js.map DELETED
@@ -1,61 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../../../node_modules/.bun/commander@14.0.3/node_modules/commander/lib/error.js", "../../../node_modules/.bun/commander@14.0.3/node_modules/commander/lib/argument.js", "../../../node_modules/.bun/commander@14.0.3/node_modules/commander/lib/help.js", "../../../node_modules/.bun/commander@14.0.3/node_modules/commander/lib/option.js", "../../../node_modules/.bun/commander@14.0.3/node_modules/commander/lib/suggestSimilar.js", "../../../node_modules/.bun/commander@14.0.3/node_modules/commander/lib/command.js", "../../../node_modules/.bun/commander@14.0.3/node_modules/commander/index.js", "../../../node_modules/.bun/@iarna+toml@2.2.5/node_modules/@iarna/toml/lib/parser.js", "../../../node_modules/.bun/@iarna+toml@2.2.5/node_modules/@iarna/toml/lib/create-datetime.js", "../../../node_modules/.bun/@iarna+toml@2.2.5/node_modules/@iarna/toml/lib/format-num.js", "../../../node_modules/.bun/@iarna+toml@2.2.5/node_modules/@iarna/toml/lib/create-datetime-float.js", "../../../node_modules/.bun/@iarna+toml@2.2.5/node_modules/@iarna/toml/lib/create-date.js", "../../../node_modules/.bun/@iarna+toml@2.2.5/node_modules/@iarna/toml/lib/create-time.js", "../../../node_modules/.bun/@iarna+toml@2.2.5/node_modules/@iarna/toml/lib/toml-parser.js", "../../../node_modules/.bun/@iarna+toml@2.2.5/node_modules/@iarna/toml/parse-pretty-error.js", "../../../node_modules/.bun/@iarna+toml@2.2.5/node_modules/@iarna/toml/parse-string.js", "../../../node_modules/.bun/@iarna+toml@2.2.5/node_modules/@iarna/toml/parse-async.js", "../../../node_modules/.bun/@iarna+toml@2.2.5/node_modules/@iarna/toml/parse-stream.js", "../../../node_modules/.bun/@iarna+toml@2.2.5/node_modules/@iarna/toml/parse.js", "../../../node_modules/.bun/@iarna+toml@2.2.5/node_modules/@iarna/toml/stringify.js", "../../../node_modules/.bun/@iarna+toml@2.2.5/node_modules/@iarna/toml/toml.js", "../../../node_modules/.bun/commander@14.0.3/node_modules/commander/esm.mjs", "../../../packages/types/src/profile.ts", "../../../packages/types/src/errors.ts", "../src/commands/agent.ts", "../../../packages/core/src/paths.ts", "../../../packages/core/src/profile/schema.ts", "../../../packages/core/src/profile/read.ts", "../../../packages/core/src/profile/validate.ts", "../../../packages/core/src/profile/write.ts", "../../../packages/core/src/context/build.ts", "../../../packages/core/src/launcher/launcher.ts", "../src/common/stdin.ts", "../../../packages/skills/src/source-parser.ts", "../../../packages/skills/src/discover.ts", "../../../packages/skills/src/vendor.ts", "../../../packages/skills/src/manifest.ts", "../../../packages/skills/src/update.ts", "../../../packages/skills/src/fetch.ts", "../../../packages/skills/src/remove.ts", "../../../packages/skills/src/list.ts", "../src/common/agent-option.ts", "../src/commands/skills.ts", "../../../packages/backend-base/src/spawn-helpers.ts", "../../../packages/backend-claude-code/src/backend.ts", "../../../packages/backend-copilot-cli/src/backend.ts", "../src/common/backend-registry.ts", "../src/common/run-args.ts", "../src/commands/run.ts", "../src/commands/chat.ts", "../src/commands/version.ts", "../src/main.ts"],
4
- "sourcesContent": [
5
- "/**\n * CommanderError class\n */\nclass CommanderError extends Error {\n /**\n * Constructs the CommanderError class\n * @param {number} exitCode suggested exit code which could be used with process.exit\n * @param {string} code an id string representing the error\n * @param {string} message human-readable description of the error\n */\n constructor(exitCode, code, message) {\n super(message);\n // properly capture stack trace in Node.js\n Error.captureStackTrace(this, this.constructor);\n this.name = this.constructor.name;\n this.code = code;\n this.exitCode = exitCode;\n this.nestedError = undefined;\n }\n}\n\n/**\n * InvalidArgumentError class\n */\nclass InvalidArgumentError extends CommanderError {\n /**\n * Constructs the InvalidArgumentError class\n * @param {string} [message] explanation of why argument is invalid\n */\n constructor(message) {\n super(1, 'commander.invalidArgument', message);\n // properly capture stack trace in Node.js\n Error.captureStackTrace(this, this.constructor);\n this.name = this.constructor.name;\n }\n}\n\nexports.CommanderError = CommanderError;\nexports.InvalidArgumentError = InvalidArgumentError;\n",
6
- "const { InvalidArgumentError } = require('./error.js');\n\nclass Argument {\n /**\n * Initialize a new command argument with the given name and description.\n * The default is that the argument is required, and you can explicitly\n * indicate this with <> around the name. Put [] around the name for an optional argument.\n *\n * @param {string} name\n * @param {string} [description]\n */\n\n constructor(name, description) {\n this.description = description || '';\n this.variadic = false;\n this.parseArg = undefined;\n this.defaultValue = undefined;\n this.defaultValueDescription = undefined;\n this.argChoices = undefined;\n\n switch (name[0]) {\n case '<': // e.g. <required>\n this.required = true;\n this._name = name.slice(1, -1);\n break;\n case '[': // e.g. [optional]\n this.required = false;\n this._name = name.slice(1, -1);\n break;\n default:\n this.required = true;\n this._name = name;\n break;\n }\n\n if (this._name.endsWith('...')) {\n this.variadic = true;\n this._name = this._name.slice(0, -3);\n }\n }\n\n /**\n * Return argument name.\n *\n * @return {string}\n */\n\n name() {\n return this._name;\n }\n\n /**\n * @package\n */\n\n _collectValue(value, previous) {\n if (previous === this.defaultValue || !Array.isArray(previous)) {\n return [value];\n }\n\n previous.push(value);\n return previous;\n }\n\n /**\n * Set the default value, and optionally supply the description to be displayed in the help.\n *\n * @param {*} value\n * @param {string} [description]\n * @return {Argument}\n */\n\n default(value, description) {\n this.defaultValue = value;\n this.defaultValueDescription = description;\n return this;\n }\n\n /**\n * Set the custom handler for processing CLI command arguments into argument values.\n *\n * @param {Function} [fn]\n * @return {Argument}\n */\n\n argParser(fn) {\n this.parseArg = fn;\n return this;\n }\n\n /**\n * Only allow argument value to be one of choices.\n *\n * @param {string[]} values\n * @return {Argument}\n */\n\n choices(values) {\n this.argChoices = values.slice();\n this.parseArg = (arg, previous) => {\n if (!this.argChoices.includes(arg)) {\n throw new InvalidArgumentError(\n `Allowed choices are ${this.argChoices.join(', ')}.`,\n );\n }\n if (this.variadic) {\n return this._collectValue(arg, previous);\n }\n return arg;\n };\n return this;\n }\n\n /**\n * Make argument required.\n *\n * @returns {Argument}\n */\n argRequired() {\n this.required = true;\n return this;\n }\n\n /**\n * Make argument optional.\n *\n * @returns {Argument}\n */\n argOptional() {\n this.required = false;\n return this;\n }\n}\n\n/**\n * Takes an argument and returns its human readable equivalent for help usage.\n *\n * @param {Argument} arg\n * @return {string}\n * @private\n */\n\nfunction humanReadableArgName(arg) {\n const nameOutput = arg.name() + (arg.variadic === true ? '...' : '');\n\n return arg.required ? '<' + nameOutput + '>' : '[' + nameOutput + ']';\n}\n\nexports.Argument = Argument;\nexports.humanReadableArgName = humanReadableArgName;\n",
7
- "const { humanReadableArgName } = require('./argument.js');\n\n/**\n * TypeScript import types for JSDoc, used by Visual Studio Code IntelliSense and `npm run typescript-checkJS`\n * https://www.typescriptlang.org/docs/handbook/jsdoc-supported-types.html#import-types\n * @typedef { import(\"./argument.js\").Argument } Argument\n * @typedef { import(\"./command.js\").Command } Command\n * @typedef { import(\"./option.js\").Option } Option\n */\n\n// Although this is a class, methods are static in style to allow override using subclass or just functions.\nclass Help {\n constructor() {\n this.helpWidth = undefined;\n this.minWidthToWrap = 40;\n this.sortSubcommands = false;\n this.sortOptions = false;\n this.showGlobalOptions = false;\n }\n\n /**\n * prepareContext is called by Commander after applying overrides from `Command.configureHelp()`\n * and just before calling `formatHelp()`.\n *\n * Commander just uses the helpWidth and the rest is provided for optional use by more complex subclasses.\n *\n * @param {{ error?: boolean, helpWidth?: number, outputHasColors?: boolean }} contextOptions\n */\n prepareContext(contextOptions) {\n this.helpWidth = this.helpWidth ?? contextOptions.helpWidth ?? 80;\n }\n\n /**\n * Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one.\n *\n * @param {Command} cmd\n * @returns {Command[]}\n */\n\n visibleCommands(cmd) {\n const visibleCommands = cmd.commands.filter((cmd) => !cmd._hidden);\n const helpCommand = cmd._getHelpCommand();\n if (helpCommand && !helpCommand._hidden) {\n visibleCommands.push(helpCommand);\n }\n if (this.sortSubcommands) {\n visibleCommands.sort((a, b) => {\n // @ts-ignore: because overloaded return type\n return a.name().localeCompare(b.name());\n });\n }\n return visibleCommands;\n }\n\n /**\n * Compare options for sort.\n *\n * @param {Option} a\n * @param {Option} b\n * @returns {number}\n */\n compareOptions(a, b) {\n const getSortKey = (option) => {\n // WYSIWYG for order displayed in help. Short used for comparison if present. No special handling for negated.\n return option.short\n ? option.short.replace(/^-/, '')\n : option.long.replace(/^--/, '');\n };\n return getSortKey(a).localeCompare(getSortKey(b));\n }\n\n /**\n * Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one.\n *\n * @param {Command} cmd\n * @returns {Option[]}\n */\n\n visibleOptions(cmd) {\n const visibleOptions = cmd.options.filter((option) => !option.hidden);\n // Built-in help option.\n const helpOption = cmd._getHelpOption();\n if (helpOption && !helpOption.hidden) {\n // Automatically hide conflicting flags. Bit dubious but a historical behaviour that is convenient for single-command programs.\n const removeShort = helpOption.short && cmd._findOption(helpOption.short);\n const removeLong = helpOption.long && cmd._findOption(helpOption.long);\n if (!removeShort && !removeLong) {\n visibleOptions.push(helpOption); // no changes needed\n } else if (helpOption.long && !removeLong) {\n visibleOptions.push(\n cmd.createOption(helpOption.long, helpOption.description),\n );\n } else if (helpOption.short && !removeShort) {\n visibleOptions.push(\n cmd.createOption(helpOption.short, helpOption.description),\n );\n }\n }\n if (this.sortOptions) {\n visibleOptions.sort(this.compareOptions);\n }\n return visibleOptions;\n }\n\n /**\n * Get an array of the visible global options. (Not including help.)\n *\n * @param {Command} cmd\n * @returns {Option[]}\n */\n\n visibleGlobalOptions(cmd) {\n if (!this.showGlobalOptions) return [];\n\n const globalOptions = [];\n for (\n let ancestorCmd = cmd.parent;\n ancestorCmd;\n ancestorCmd = ancestorCmd.parent\n ) {\n const visibleOptions = ancestorCmd.options.filter(\n (option) => !option.hidden,\n );\n globalOptions.push(...visibleOptions);\n }\n if (this.sortOptions) {\n globalOptions.sort(this.compareOptions);\n }\n return globalOptions;\n }\n\n /**\n * Get an array of the arguments if any have a description.\n *\n * @param {Command} cmd\n * @returns {Argument[]}\n */\n\n visibleArguments(cmd) {\n // Side effect! Apply the legacy descriptions before the arguments are displayed.\n if (cmd._argsDescription) {\n cmd.registeredArguments.forEach((argument) => {\n argument.description =\n argument.description || cmd._argsDescription[argument.name()] || '';\n });\n }\n\n // If there are any arguments with a description then return all the arguments.\n if (cmd.registeredArguments.find((argument) => argument.description)) {\n return cmd.registeredArguments;\n }\n return [];\n }\n\n /**\n * Get the command term to show in the list of subcommands.\n *\n * @param {Command} cmd\n * @returns {string}\n */\n\n subcommandTerm(cmd) {\n // Legacy. Ignores custom usage string, and nested commands.\n const args = cmd.registeredArguments\n .map((arg) => humanReadableArgName(arg))\n .join(' ');\n return (\n cmd._name +\n (cmd._aliases[0] ? '|' + cmd._aliases[0] : '') +\n (cmd.options.length ? ' [options]' : '') + // simplistic check for non-help option\n (args ? ' ' + args : '')\n );\n }\n\n /**\n * Get the option term to show in the list of options.\n *\n * @param {Option} option\n * @returns {string}\n */\n\n optionTerm(option) {\n return option.flags;\n }\n\n /**\n * Get the argument term to show in the list of arguments.\n *\n * @param {Argument} argument\n * @returns {string}\n */\n\n argumentTerm(argument) {\n return argument.name();\n }\n\n /**\n * Get the longest command term length.\n *\n * @param {Command} cmd\n * @param {Help} helper\n * @returns {number}\n */\n\n longestSubcommandTermLength(cmd, helper) {\n return helper.visibleCommands(cmd).reduce((max, command) => {\n return Math.max(\n max,\n this.displayWidth(\n helper.styleSubcommandTerm(helper.subcommandTerm(command)),\n ),\n );\n }, 0);\n }\n\n /**\n * Get the longest option term length.\n *\n * @param {Command} cmd\n * @param {Help} helper\n * @returns {number}\n */\n\n longestOptionTermLength(cmd, helper) {\n return helper.visibleOptions(cmd).reduce((max, option) => {\n return Math.max(\n max,\n this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option))),\n );\n }, 0);\n }\n\n /**\n * Get the longest global option term length.\n *\n * @param {Command} cmd\n * @param {Help} helper\n * @returns {number}\n */\n\n longestGlobalOptionTermLength(cmd, helper) {\n return helper.visibleGlobalOptions(cmd).reduce((max, option) => {\n return Math.max(\n max,\n this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option))),\n );\n }, 0);\n }\n\n /**\n * Get the longest argument term length.\n *\n * @param {Command} cmd\n * @param {Help} helper\n * @returns {number}\n */\n\n longestArgumentTermLength(cmd, helper) {\n return helper.visibleArguments(cmd).reduce((max, argument) => {\n return Math.max(\n max,\n this.displayWidth(\n helper.styleArgumentTerm(helper.argumentTerm(argument)),\n ),\n );\n }, 0);\n }\n\n /**\n * Get the command usage to be displayed at the top of the built-in help.\n *\n * @param {Command} cmd\n * @returns {string}\n */\n\n commandUsage(cmd) {\n // Usage\n let cmdName = cmd._name;\n if (cmd._aliases[0]) {\n cmdName = cmdName + '|' + cmd._aliases[0];\n }\n let ancestorCmdNames = '';\n for (\n let ancestorCmd = cmd.parent;\n ancestorCmd;\n ancestorCmd = ancestorCmd.parent\n ) {\n ancestorCmdNames = ancestorCmd.name() + ' ' + ancestorCmdNames;\n }\n return ancestorCmdNames + cmdName + ' ' + cmd.usage();\n }\n\n /**\n * Get the description for the command.\n *\n * @param {Command} cmd\n * @returns {string}\n */\n\n commandDescription(cmd) {\n // @ts-ignore: because overloaded return type\n return cmd.description();\n }\n\n /**\n * Get the subcommand summary to show in the list of subcommands.\n * (Fallback to description for backwards compatibility.)\n *\n * @param {Command} cmd\n * @returns {string}\n */\n\n subcommandDescription(cmd) {\n // @ts-ignore: because overloaded return type\n return cmd.summary() || cmd.description();\n }\n\n /**\n * Get the option description to show in the list of options.\n *\n * @param {Option} option\n * @return {string}\n */\n\n optionDescription(option) {\n const extraInfo = [];\n\n if (option.argChoices) {\n extraInfo.push(\n // use stringify to match the display of the default value\n `choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(', ')}`,\n );\n }\n if (option.defaultValue !== undefined) {\n // default for boolean and negated more for programmer than end user,\n // but show true/false for boolean option as may be for hand-rolled env or config processing.\n const showDefault =\n option.required ||\n option.optional ||\n (option.isBoolean() && typeof option.defaultValue === 'boolean');\n if (showDefault) {\n extraInfo.push(\n `default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`,\n );\n }\n }\n // preset for boolean and negated are more for programmer than end user\n if (option.presetArg !== undefined && option.optional) {\n extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`);\n }\n if (option.envVar !== undefined) {\n extraInfo.push(`env: ${option.envVar}`);\n }\n if (extraInfo.length > 0) {\n const extraDescription = `(${extraInfo.join(', ')})`;\n if (option.description) {\n return `${option.description} ${extraDescription}`;\n }\n return extraDescription;\n }\n\n return option.description;\n }\n\n /**\n * Get the argument description to show in the list of arguments.\n *\n * @param {Argument} argument\n * @return {string}\n */\n\n argumentDescription(argument) {\n const extraInfo = [];\n if (argument.argChoices) {\n extraInfo.push(\n // use stringify to match the display of the default value\n `choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(', ')}`,\n );\n }\n if (argument.defaultValue !== undefined) {\n extraInfo.push(\n `default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`,\n );\n }\n if (extraInfo.length > 0) {\n const extraDescription = `(${extraInfo.join(', ')})`;\n if (argument.description) {\n return `${argument.description} ${extraDescription}`;\n }\n return extraDescription;\n }\n return argument.description;\n }\n\n /**\n * Format a list of items, given a heading and an array of formatted items.\n *\n * @param {string} heading\n * @param {string[]} items\n * @param {Help} helper\n * @returns string[]\n */\n formatItemList(heading, items, helper) {\n if (items.length === 0) return [];\n\n return [helper.styleTitle(heading), ...items, ''];\n }\n\n /**\n * Group items by their help group heading.\n *\n * @param {Command[] | Option[]} unsortedItems\n * @param {Command[] | Option[]} visibleItems\n * @param {Function} getGroup\n * @returns {Map<string, Command[] | Option[]>}\n */\n groupItems(unsortedItems, visibleItems, getGroup) {\n const result = new Map();\n // Add groups in order of appearance in unsortedItems.\n unsortedItems.forEach((item) => {\n const group = getGroup(item);\n if (!result.has(group)) result.set(group, []);\n });\n // Add items in order of appearance in visibleItems.\n visibleItems.forEach((item) => {\n const group = getGroup(item);\n if (!result.has(group)) {\n result.set(group, []);\n }\n result.get(group).push(item);\n });\n return result;\n }\n\n /**\n * Generate the built-in help text.\n *\n * @param {Command} cmd\n * @param {Help} helper\n * @returns {string}\n */\n\n formatHelp(cmd, helper) {\n const termWidth = helper.padWidth(cmd, helper);\n const helpWidth = helper.helpWidth ?? 80; // in case prepareContext() was not called\n\n function callFormatItem(term, description) {\n return helper.formatItem(term, termWidth, description, helper);\n }\n\n // Usage\n let output = [\n `${helper.styleTitle('Usage:')} ${helper.styleUsage(helper.commandUsage(cmd))}`,\n '',\n ];\n\n // Description\n const commandDescription = helper.commandDescription(cmd);\n if (commandDescription.length > 0) {\n output = output.concat([\n helper.boxWrap(\n helper.styleCommandDescription(commandDescription),\n helpWidth,\n ),\n '',\n ]);\n }\n\n // Arguments\n const argumentList = helper.visibleArguments(cmd).map((argument) => {\n return callFormatItem(\n helper.styleArgumentTerm(helper.argumentTerm(argument)),\n helper.styleArgumentDescription(helper.argumentDescription(argument)),\n );\n });\n output = output.concat(\n this.formatItemList('Arguments:', argumentList, helper),\n );\n\n // Options\n const optionGroups = this.groupItems(\n cmd.options,\n helper.visibleOptions(cmd),\n (option) => option.helpGroupHeading ?? 'Options:',\n );\n optionGroups.forEach((options, group) => {\n const optionList = options.map((option) => {\n return callFormatItem(\n helper.styleOptionTerm(helper.optionTerm(option)),\n helper.styleOptionDescription(helper.optionDescription(option)),\n );\n });\n output = output.concat(this.formatItemList(group, optionList, helper));\n });\n\n if (helper.showGlobalOptions) {\n const globalOptionList = helper\n .visibleGlobalOptions(cmd)\n .map((option) => {\n return callFormatItem(\n helper.styleOptionTerm(helper.optionTerm(option)),\n helper.styleOptionDescription(helper.optionDescription(option)),\n );\n });\n output = output.concat(\n this.formatItemList('Global Options:', globalOptionList, helper),\n );\n }\n\n // Commands\n const commandGroups = this.groupItems(\n cmd.commands,\n helper.visibleCommands(cmd),\n (sub) => sub.helpGroup() || 'Commands:',\n );\n commandGroups.forEach((commands, group) => {\n const commandList = commands.map((sub) => {\n return callFormatItem(\n helper.styleSubcommandTerm(helper.subcommandTerm(sub)),\n helper.styleSubcommandDescription(helper.subcommandDescription(sub)),\n );\n });\n output = output.concat(this.formatItemList(group, commandList, helper));\n });\n\n return output.join('\\n');\n }\n\n /**\n * Return display width of string, ignoring ANSI escape sequences. Used in padding and wrapping calculations.\n *\n * @param {string} str\n * @returns {number}\n */\n displayWidth(str) {\n return stripColor(str).length;\n }\n\n /**\n * Style the title for displaying in the help. Called with 'Usage:', 'Options:', etc.\n *\n * @param {string} str\n * @returns {string}\n */\n styleTitle(str) {\n return str;\n }\n\n styleUsage(str) {\n // Usage has lots of parts the user might like to color separately! Assume default usage string which is formed like:\n // command subcommand [options] [command] <foo> [bar]\n return str\n .split(' ')\n .map((word) => {\n if (word === '[options]') return this.styleOptionText(word);\n if (word === '[command]') return this.styleSubcommandText(word);\n if (word[0] === '[' || word[0] === '<')\n return this.styleArgumentText(word);\n return this.styleCommandText(word); // Restrict to initial words?\n })\n .join(' ');\n }\n styleCommandDescription(str) {\n return this.styleDescriptionText(str);\n }\n styleOptionDescription(str) {\n return this.styleDescriptionText(str);\n }\n styleSubcommandDescription(str) {\n return this.styleDescriptionText(str);\n }\n styleArgumentDescription(str) {\n return this.styleDescriptionText(str);\n }\n styleDescriptionText(str) {\n return str;\n }\n styleOptionTerm(str) {\n return this.styleOptionText(str);\n }\n styleSubcommandTerm(str) {\n // This is very like usage with lots of parts! Assume default string which is formed like:\n // subcommand [options] <foo> [bar]\n return str\n .split(' ')\n .map((word) => {\n if (word === '[options]') return this.styleOptionText(word);\n if (word[0] === '[' || word[0] === '<')\n return this.styleArgumentText(word);\n return this.styleSubcommandText(word); // Restrict to initial words?\n })\n .join(' ');\n }\n styleArgumentTerm(str) {\n return this.styleArgumentText(str);\n }\n styleOptionText(str) {\n return str;\n }\n styleArgumentText(str) {\n return str;\n }\n styleSubcommandText(str) {\n return str;\n }\n styleCommandText(str) {\n return str;\n }\n\n /**\n * Calculate the pad width from the maximum term length.\n *\n * @param {Command} cmd\n * @param {Help} helper\n * @returns {number}\n */\n\n padWidth(cmd, helper) {\n return Math.max(\n helper.longestOptionTermLength(cmd, helper),\n helper.longestGlobalOptionTermLength(cmd, helper),\n helper.longestSubcommandTermLength(cmd, helper),\n helper.longestArgumentTermLength(cmd, helper),\n );\n }\n\n /**\n * Detect manually wrapped and indented strings by checking for line break followed by whitespace.\n *\n * @param {string} str\n * @returns {boolean}\n */\n preformatted(str) {\n return /\\n[^\\S\\r\\n]/.test(str);\n }\n\n /**\n * Format the \"item\", which consists of a term and description. Pad the term and wrap the description, indenting the following lines.\n *\n * So \"TTT\", 5, \"DDD DDDD DD DDD\" might be formatted for this.helpWidth=17 like so:\n * TTT DDD DDDD\n * DD DDD\n *\n * @param {string} term\n * @param {number} termWidth\n * @param {string} description\n * @param {Help} helper\n * @returns {string}\n */\n formatItem(term, termWidth, description, helper) {\n const itemIndent = 2;\n const itemIndentStr = ' '.repeat(itemIndent);\n if (!description) return itemIndentStr + term;\n\n // Pad the term out to a consistent width, so descriptions are aligned.\n const paddedTerm = term.padEnd(\n termWidth + term.length - helper.displayWidth(term),\n );\n\n // Format the description.\n const spacerWidth = 2; // between term and description\n const helpWidth = this.helpWidth ?? 80; // in case prepareContext() was not called\n const remainingWidth = helpWidth - termWidth - spacerWidth - itemIndent;\n let formattedDescription;\n if (\n remainingWidth < this.minWidthToWrap ||\n helper.preformatted(description)\n ) {\n formattedDescription = description;\n } else {\n const wrappedDescription = helper.boxWrap(description, remainingWidth);\n formattedDescription = wrappedDescription.replace(\n /\\n/g,\n '\\n' + ' '.repeat(termWidth + spacerWidth),\n );\n }\n\n // Construct and overall indent.\n return (\n itemIndentStr +\n paddedTerm +\n ' '.repeat(spacerWidth) +\n formattedDescription.replace(/\\n/g, `\\n${itemIndentStr}`)\n );\n }\n\n /**\n * Wrap a string at whitespace, preserving existing line breaks.\n * Wrapping is skipped if the width is less than `minWidthToWrap`.\n *\n * @param {string} str\n * @param {number} width\n * @returns {string}\n */\n boxWrap(str, width) {\n if (width < this.minWidthToWrap) return str;\n\n const rawLines = str.split(/\\r\\n|\\n/);\n // split up text by whitespace\n const chunkPattern = /[\\s]*[^\\s]+/g;\n const wrappedLines = [];\n rawLines.forEach((line) => {\n const chunks = line.match(chunkPattern);\n if (chunks === null) {\n wrappedLines.push('');\n return;\n }\n\n let sumChunks = [chunks.shift()];\n let sumWidth = this.displayWidth(sumChunks[0]);\n chunks.forEach((chunk) => {\n const visibleWidth = this.displayWidth(chunk);\n // Accumulate chunks while they fit into width.\n if (sumWidth + visibleWidth <= width) {\n sumChunks.push(chunk);\n sumWidth += visibleWidth;\n return;\n }\n wrappedLines.push(sumChunks.join(''));\n\n const nextChunk = chunk.trimStart(); // trim space at line break\n sumChunks = [nextChunk];\n sumWidth = this.displayWidth(nextChunk);\n });\n wrappedLines.push(sumChunks.join(''));\n });\n\n return wrappedLines.join('\\n');\n }\n}\n\n/**\n * Strip style ANSI escape sequences from the string. In particular, SGR (Select Graphic Rendition) codes.\n *\n * @param {string} str\n * @returns {string}\n * @package\n */\n\nfunction stripColor(str) {\n // eslint-disable-next-line no-control-regex\n const sgrPattern = /\\x1b\\[\\d*(;\\d*)*m/g;\n return str.replace(sgrPattern, '');\n}\n\nexports.Help = Help;\nexports.stripColor = stripColor;\n",
8
- "const { InvalidArgumentError } = require('./error.js');\n\nclass Option {\n /**\n * Initialize a new `Option` with the given `flags` and `description`.\n *\n * @param {string} flags\n * @param {string} [description]\n */\n\n constructor(flags, description) {\n this.flags = flags;\n this.description = description || '';\n\n this.required = flags.includes('<'); // A value must be supplied when the option is specified.\n this.optional = flags.includes('['); // A value is optional when the option is specified.\n // variadic test ignores <value,...> et al which might be used to describe custom splitting of single argument\n this.variadic = /\\w\\.\\.\\.[>\\]]$/.test(flags); // The option can take multiple values.\n this.mandatory = false; // The option must have a value after parsing, which usually means it must be specified on command line.\n const optionFlags = splitOptionFlags(flags);\n this.short = optionFlags.shortFlag; // May be a short flag, undefined, or even a long flag (if option has two long flags).\n this.long = optionFlags.longFlag;\n this.negate = false;\n if (this.long) {\n this.negate = this.long.startsWith('--no-');\n }\n this.defaultValue = undefined;\n this.defaultValueDescription = undefined;\n this.presetArg = undefined;\n this.envVar = undefined;\n this.parseArg = undefined;\n this.hidden = false;\n this.argChoices = undefined;\n this.conflictsWith = [];\n this.implied = undefined;\n this.helpGroupHeading = undefined; // soft initialised when option added to command\n }\n\n /**\n * Set the default value, and optionally supply the description to be displayed in the help.\n *\n * @param {*} value\n * @param {string} [description]\n * @return {Option}\n */\n\n default(value, description) {\n this.defaultValue = value;\n this.defaultValueDescription = description;\n return this;\n }\n\n /**\n * Preset to use when option used without option-argument, especially optional but also boolean and negated.\n * The custom processing (parseArg) is called.\n *\n * @example\n * new Option('--color').default('GREYSCALE').preset('RGB');\n * new Option('--donate [amount]').preset('20').argParser(parseFloat);\n *\n * @param {*} arg\n * @return {Option}\n */\n\n preset(arg) {\n this.presetArg = arg;\n return this;\n }\n\n /**\n * Add option name(s) that conflict with this option.\n * An error will be displayed if conflicting options are found during parsing.\n *\n * @example\n * new Option('--rgb').conflicts('cmyk');\n * new Option('--js').conflicts(['ts', 'jsx']);\n *\n * @param {(string | string[])} names\n * @return {Option}\n */\n\n conflicts(names) {\n this.conflictsWith = this.conflictsWith.concat(names);\n return this;\n }\n\n /**\n * Specify implied option values for when this option is set and the implied options are not.\n *\n * The custom processing (parseArg) is not called on the implied values.\n *\n * @example\n * program\n * .addOption(new Option('--log', 'write logging information to file'))\n * .addOption(new Option('--trace', 'log extra details').implies({ log: 'trace.txt' }));\n *\n * @param {object} impliedOptionValues\n * @return {Option}\n */\n implies(impliedOptionValues) {\n let newImplied = impliedOptionValues;\n if (typeof impliedOptionValues === 'string') {\n // string is not documented, but easy mistake and we can do what user probably intended.\n newImplied = { [impliedOptionValues]: true };\n }\n this.implied = Object.assign(this.implied || {}, newImplied);\n return this;\n }\n\n /**\n * Set environment variable to check for option value.\n *\n * An environment variable is only used if when processed the current option value is\n * undefined, or the source of the current value is 'default' or 'config' or 'env'.\n *\n * @param {string} name\n * @return {Option}\n */\n\n env(name) {\n this.envVar = name;\n return this;\n }\n\n /**\n * Set the custom handler for processing CLI option arguments into option values.\n *\n * @param {Function} [fn]\n * @return {Option}\n */\n\n argParser(fn) {\n this.parseArg = fn;\n return this;\n }\n\n /**\n * Whether the option is mandatory and must have a value after parsing.\n *\n * @param {boolean} [mandatory=true]\n * @return {Option}\n */\n\n makeOptionMandatory(mandatory = true) {\n this.mandatory = !!mandatory;\n return this;\n }\n\n /**\n * Hide option in help.\n *\n * @param {boolean} [hide=true]\n * @return {Option}\n */\n\n hideHelp(hide = true) {\n this.hidden = !!hide;\n return this;\n }\n\n /**\n * @package\n */\n\n _collectValue(value, previous) {\n if (previous === this.defaultValue || !Array.isArray(previous)) {\n return [value];\n }\n\n previous.push(value);\n return previous;\n }\n\n /**\n * Only allow option value to be one of choices.\n *\n * @param {string[]} values\n * @return {Option}\n */\n\n choices(values) {\n this.argChoices = values.slice();\n this.parseArg = (arg, previous) => {\n if (!this.argChoices.includes(arg)) {\n throw new InvalidArgumentError(\n `Allowed choices are ${this.argChoices.join(', ')}.`,\n );\n }\n if (this.variadic) {\n return this._collectValue(arg, previous);\n }\n return arg;\n };\n return this;\n }\n\n /**\n * Return option name.\n *\n * @return {string}\n */\n\n name() {\n if (this.long) {\n return this.long.replace(/^--/, '');\n }\n return this.short.replace(/^-/, '');\n }\n\n /**\n * Return option name, in a camelcase format that can be used\n * as an object attribute key.\n *\n * @return {string}\n */\n\n attributeName() {\n if (this.negate) {\n return camelcase(this.name().replace(/^no-/, ''));\n }\n return camelcase(this.name());\n }\n\n /**\n * Set the help group heading.\n *\n * @param {string} heading\n * @return {Option}\n */\n helpGroup(heading) {\n this.helpGroupHeading = heading;\n return this;\n }\n\n /**\n * Check if `arg` matches the short or long flag.\n *\n * @param {string} arg\n * @return {boolean}\n * @package\n */\n\n is(arg) {\n return this.short === arg || this.long === arg;\n }\n\n /**\n * Return whether a boolean option.\n *\n * Options are one of boolean, negated, required argument, or optional argument.\n *\n * @return {boolean}\n * @package\n */\n\n isBoolean() {\n return !this.required && !this.optional && !this.negate;\n }\n}\n\n/**\n * This class is to make it easier to work with dual options, without changing the existing\n * implementation. We support separate dual options for separate positive and negative options,\n * like `--build` and `--no-build`, which share a single option value. This works nicely for some\n * use cases, but is tricky for others where we want separate behaviours despite\n * the single shared option value.\n */\nclass DualOptions {\n /**\n * @param {Option[]} options\n */\n constructor(options) {\n this.positiveOptions = new Map();\n this.negativeOptions = new Map();\n this.dualOptions = new Set();\n options.forEach((option) => {\n if (option.negate) {\n this.negativeOptions.set(option.attributeName(), option);\n } else {\n this.positiveOptions.set(option.attributeName(), option);\n }\n });\n this.negativeOptions.forEach((value, key) => {\n if (this.positiveOptions.has(key)) {\n this.dualOptions.add(key);\n }\n });\n }\n\n /**\n * Did the value come from the option, and not from possible matching dual option?\n *\n * @param {*} value\n * @param {Option} option\n * @returns {boolean}\n */\n valueFromOption(value, option) {\n const optionKey = option.attributeName();\n if (!this.dualOptions.has(optionKey)) return true;\n\n // Use the value to deduce if (probably) came from the option.\n const preset = this.negativeOptions.get(optionKey).presetArg;\n const negativeValue = preset !== undefined ? preset : false;\n return option.negate === (negativeValue === value);\n }\n}\n\n/**\n * Convert string from kebab-case to camelCase.\n *\n * @param {string} str\n * @return {string}\n * @private\n */\n\nfunction camelcase(str) {\n return str.split('-').reduce((str, word) => {\n return str + word[0].toUpperCase() + word.slice(1);\n });\n}\n\n/**\n * Split the short and long flag out of something like '-m,--mixed <value>'\n *\n * @private\n */\n\nfunction splitOptionFlags(flags) {\n let shortFlag;\n let longFlag;\n // short flag, single dash and single character\n const shortFlagExp = /^-[^-]$/;\n // long flag, double dash and at least one character\n const longFlagExp = /^--[^-]/;\n\n const flagParts = flags.split(/[ |,]+/).concat('guard');\n // Normal is short and/or long.\n if (shortFlagExp.test(flagParts[0])) shortFlag = flagParts.shift();\n if (longFlagExp.test(flagParts[0])) longFlag = flagParts.shift();\n // Long then short. Rarely used but fine.\n if (!shortFlag && shortFlagExp.test(flagParts[0]))\n shortFlag = flagParts.shift();\n // Allow two long flags, like '--ws, --workspace'\n // This is the supported way to have a shortish option flag.\n if (!shortFlag && longFlagExp.test(flagParts[0])) {\n shortFlag = longFlag;\n longFlag = flagParts.shift();\n }\n\n // Check for unprocessed flag. Fail noisily rather than silently ignore.\n if (flagParts[0].startsWith('-')) {\n const unsupportedFlag = flagParts[0];\n const baseError = `option creation failed due to '${unsupportedFlag}' in option flags '${flags}'`;\n if (/^-[^-][^-]/.test(unsupportedFlag))\n throw new Error(\n `${baseError}\n- a short flag is a single dash and a single character\n - either use a single dash and a single character (for a short flag)\n - or use a double dash for a long option (and can have two, like '--ws, --workspace')`,\n );\n if (shortFlagExp.test(unsupportedFlag))\n throw new Error(`${baseError}\n- too many short flags`);\n if (longFlagExp.test(unsupportedFlag))\n throw new Error(`${baseError}\n- too many long flags`);\n\n throw new Error(`${baseError}\n- unrecognised flag format`);\n }\n if (shortFlag === undefined && longFlag === undefined)\n throw new Error(\n `option creation failed due to no flags found in '${flags}'.`,\n );\n\n return { shortFlag, longFlag };\n}\n\nexports.Option = Option;\nexports.DualOptions = DualOptions;\n",
9
- "const maxDistance = 3;\n\nfunction editDistance(a, b) {\n // https://en.wikipedia.org/wiki/Damerau–Levenshtein_distance\n // Calculating optimal string alignment distance, no substring is edited more than once.\n // (Simple implementation.)\n\n // Quick early exit, return worst case.\n if (Math.abs(a.length - b.length) > maxDistance)\n return Math.max(a.length, b.length);\n\n // distance between prefix substrings of a and b\n const d = [];\n\n // pure deletions turn a into empty string\n for (let i = 0; i <= a.length; i++) {\n d[i] = [i];\n }\n // pure insertions turn empty string into b\n for (let j = 0; j <= b.length; j++) {\n d[0][j] = j;\n }\n\n // fill matrix\n for (let j = 1; j <= b.length; j++) {\n for (let i = 1; i <= a.length; i++) {\n let cost = 1;\n if (a[i - 1] === b[j - 1]) {\n cost = 0;\n } else {\n cost = 1;\n }\n d[i][j] = Math.min(\n d[i - 1][j] + 1, // deletion\n d[i][j - 1] + 1, // insertion\n d[i - 1][j - 1] + cost, // substitution\n );\n // transposition\n if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {\n d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);\n }\n }\n }\n\n return d[a.length][b.length];\n}\n\n/**\n * Find close matches, restricted to same number of edits.\n *\n * @param {string} word\n * @param {string[]} candidates\n * @returns {string}\n */\n\nfunction suggestSimilar(word, candidates) {\n if (!candidates || candidates.length === 0) return '';\n // remove possible duplicates\n candidates = Array.from(new Set(candidates));\n\n const searchingOptions = word.startsWith('--');\n if (searchingOptions) {\n word = word.slice(2);\n candidates = candidates.map((candidate) => candidate.slice(2));\n }\n\n let similar = [];\n let bestDistance = maxDistance;\n const minSimilarity = 0.4;\n candidates.forEach((candidate) => {\n if (candidate.length <= 1) return; // no one character guesses\n\n const distance = editDistance(word, candidate);\n const length = Math.max(word.length, candidate.length);\n const similarity = (length - distance) / length;\n if (similarity > minSimilarity) {\n if (distance < bestDistance) {\n // better edit distance, throw away previous worse matches\n bestDistance = distance;\n similar = [candidate];\n } else if (distance === bestDistance) {\n similar.push(candidate);\n }\n }\n });\n\n similar.sort((a, b) => a.localeCompare(b));\n if (searchingOptions) {\n similar = similar.map((candidate) => `--${candidate}`);\n }\n\n if (similar.length > 1) {\n return `\\n(Did you mean one of ${similar.join(', ')}?)`;\n }\n if (similar.length === 1) {\n return `\\n(Did you mean ${similar[0]}?)`;\n }\n return '';\n}\n\nexports.suggestSimilar = suggestSimilar;\n",
10
- "const EventEmitter = require('node:events').EventEmitter;\nconst childProcess = require('node:child_process');\nconst path = require('node:path');\nconst fs = require('node:fs');\nconst process = require('node:process');\n\nconst { Argument, humanReadableArgName } = require('./argument.js');\nconst { CommanderError } = require('./error.js');\nconst { Help, stripColor } = require('./help.js');\nconst { Option, DualOptions } = require('./option.js');\nconst { suggestSimilar } = require('./suggestSimilar');\n\nclass Command extends EventEmitter {\n /**\n * Initialize a new `Command`.\n *\n * @param {string} [name]\n */\n\n constructor(name) {\n super();\n /** @type {Command[]} */\n this.commands = [];\n /** @type {Option[]} */\n this.options = [];\n this.parent = null;\n this._allowUnknownOption = false;\n this._allowExcessArguments = false;\n /** @type {Argument[]} */\n this.registeredArguments = [];\n this._args = this.registeredArguments; // deprecated old name\n /** @type {string[]} */\n this.args = []; // cli args with options removed\n this.rawArgs = [];\n this.processedArgs = []; // like .args but after custom processing and collecting variadic\n this._scriptPath = null;\n this._name = name || '';\n this._optionValues = {};\n this._optionValueSources = {}; // default, env, cli etc\n this._storeOptionsAsProperties = false;\n this._actionHandler = null;\n this._executableHandler = false;\n this._executableFile = null; // custom name for executable\n this._executableDir = null; // custom search directory for subcommands\n this._defaultCommandName = null;\n this._exitCallback = null;\n this._aliases = [];\n this._combineFlagAndOptionalValue = true;\n this._description = '';\n this._summary = '';\n this._argsDescription = undefined; // legacy\n this._enablePositionalOptions = false;\n this._passThroughOptions = false;\n this._lifeCycleHooks = {}; // a hash of arrays\n /** @type {(boolean | string)} */\n this._showHelpAfterError = false;\n this._showSuggestionAfterError = true;\n this._savedState = null; // used in save/restoreStateBeforeParse\n\n // see configureOutput() for docs\n this._outputConfiguration = {\n writeOut: (str) => process.stdout.write(str),\n writeErr: (str) => process.stderr.write(str),\n outputError: (str, write) => write(str),\n getOutHelpWidth: () =>\n process.stdout.isTTY ? process.stdout.columns : undefined,\n getErrHelpWidth: () =>\n process.stderr.isTTY ? process.stderr.columns : undefined,\n getOutHasColors: () =>\n useColor() ?? (process.stdout.isTTY && process.stdout.hasColors?.()),\n getErrHasColors: () =>\n useColor() ?? (process.stderr.isTTY && process.stderr.hasColors?.()),\n stripColor: (str) => stripColor(str),\n };\n\n this._hidden = false;\n /** @type {(Option | null | undefined)} */\n this._helpOption = undefined; // Lazy created on demand. May be null if help option is disabled.\n this._addImplicitHelpCommand = undefined; // undecided whether true or false yet, not inherited\n /** @type {Command} */\n this._helpCommand = undefined; // lazy initialised, inherited\n this._helpConfiguration = {};\n /** @type {string | undefined} */\n this._helpGroupHeading = undefined; // soft initialised when added to parent\n /** @type {string | undefined} */\n this._defaultCommandGroup = undefined;\n /** @type {string | undefined} */\n this._defaultOptionGroup = undefined;\n }\n\n /**\n * Copy settings that are useful to have in common across root command and subcommands.\n *\n * (Used internally when adding a command using `.command()` so subcommands inherit parent settings.)\n *\n * @param {Command} sourceCommand\n * @return {Command} `this` command for chaining\n */\n copyInheritedSettings(sourceCommand) {\n this._outputConfiguration = sourceCommand._outputConfiguration;\n this._helpOption = sourceCommand._helpOption;\n this._helpCommand = sourceCommand._helpCommand;\n this._helpConfiguration = sourceCommand._helpConfiguration;\n this._exitCallback = sourceCommand._exitCallback;\n this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;\n this._combineFlagAndOptionalValue =\n sourceCommand._combineFlagAndOptionalValue;\n this._allowExcessArguments = sourceCommand._allowExcessArguments;\n this._enablePositionalOptions = sourceCommand._enablePositionalOptions;\n this._showHelpAfterError = sourceCommand._showHelpAfterError;\n this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;\n\n return this;\n }\n\n /**\n * @returns {Command[]}\n * @private\n */\n\n _getCommandAndAncestors() {\n const result = [];\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n for (let command = this; command; command = command.parent) {\n result.push(command);\n }\n return result;\n }\n\n /**\n * Define a command.\n *\n * There are two styles of command: pay attention to where to put the description.\n *\n * @example\n * // Command implemented using action handler (description is supplied separately to `.command`)\n * program\n * .command('clone <source> [destination]')\n * .description('clone a repository into a newly created directory')\n * .action((source, destination) => {\n * console.log('clone command called');\n * });\n *\n * // Command implemented using separate executable file (description is second parameter to `.command`)\n * program\n * .command('start <service>', 'start named service')\n * .command('stop [service]', 'stop named service, or all if no name supplied');\n *\n * @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`\n * @param {(object | string)} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)\n * @param {object} [execOpts] - configuration options (for executable)\n * @return {Command} returns new command for action handler, or `this` for executable command\n */\n\n command(nameAndArgs, actionOptsOrExecDesc, execOpts) {\n let desc = actionOptsOrExecDesc;\n let opts = execOpts;\n if (typeof desc === 'object' && desc !== null) {\n opts = desc;\n desc = null;\n }\n opts = opts || {};\n const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);\n\n const cmd = this.createCommand(name);\n if (desc) {\n cmd.description(desc);\n cmd._executableHandler = true;\n }\n if (opts.isDefault) this._defaultCommandName = cmd._name;\n cmd._hidden = !!(opts.noHelp || opts.hidden); // noHelp is deprecated old name for hidden\n cmd._executableFile = opts.executableFile || null; // Custom name for executable file, set missing to null to match constructor\n if (args) cmd.arguments(args);\n this._registerCommand(cmd);\n cmd.parent = this;\n cmd.copyInheritedSettings(this);\n\n if (desc) return this;\n return cmd;\n }\n\n /**\n * Factory routine to create a new unattached command.\n *\n * See .command() for creating an attached subcommand, which uses this routine to\n * create the command. You can override createCommand to customise subcommands.\n *\n * @param {string} [name]\n * @return {Command} new command\n */\n\n createCommand(name) {\n return new Command(name);\n }\n\n /**\n * You can customise the help with a subclass of Help by overriding createHelp,\n * or by overriding Help properties using configureHelp().\n *\n * @return {Help}\n */\n\n createHelp() {\n return Object.assign(new Help(), this.configureHelp());\n }\n\n /**\n * You can customise the help by overriding Help properties using configureHelp(),\n * or with a subclass of Help by overriding createHelp().\n *\n * @param {object} [configuration] - configuration options\n * @return {(Command | object)} `this` command for chaining, or stored configuration\n */\n\n configureHelp(configuration) {\n if (configuration === undefined) return this._helpConfiguration;\n\n this._helpConfiguration = configuration;\n return this;\n }\n\n /**\n * The default output goes to stdout and stderr. You can customise this for special\n * applications. You can also customise the display of errors by overriding outputError.\n *\n * The configuration properties are all functions:\n *\n * // change how output being written, defaults to stdout and stderr\n * writeOut(str)\n * writeErr(str)\n * // change how output being written for errors, defaults to writeErr\n * outputError(str, write) // used for displaying errors and not used for displaying help\n * // specify width for wrapping help\n * getOutHelpWidth()\n * getErrHelpWidth()\n * // color support, currently only used with Help\n * getOutHasColors()\n * getErrHasColors()\n * stripColor() // used to remove ANSI escape codes if output does not have colors\n *\n * @param {object} [configuration] - configuration options\n * @return {(Command | object)} `this` command for chaining, or stored configuration\n */\n\n configureOutput(configuration) {\n if (configuration === undefined) return this._outputConfiguration;\n\n this._outputConfiguration = {\n ...this._outputConfiguration,\n ...configuration,\n };\n return this;\n }\n\n /**\n * Display the help or a custom message after an error occurs.\n *\n * @param {(boolean|string)} [displayHelp]\n * @return {Command} `this` command for chaining\n */\n showHelpAfterError(displayHelp = true) {\n if (typeof displayHelp !== 'string') displayHelp = !!displayHelp;\n this._showHelpAfterError = displayHelp;\n return this;\n }\n\n /**\n * Display suggestion of similar commands for unknown commands, or options for unknown options.\n *\n * @param {boolean} [displaySuggestion]\n * @return {Command} `this` command for chaining\n */\n showSuggestionAfterError(displaySuggestion = true) {\n this._showSuggestionAfterError = !!displaySuggestion;\n return this;\n }\n\n /**\n * Add a prepared subcommand.\n *\n * See .command() for creating an attached subcommand which inherits settings from its parent.\n *\n * @param {Command} cmd - new subcommand\n * @param {object} [opts] - configuration options\n * @return {Command} `this` command for chaining\n */\n\n addCommand(cmd, opts) {\n if (!cmd._name) {\n throw new Error(`Command passed to .addCommand() must have a name\n- specify the name in Command constructor or using .name()`);\n }\n\n opts = opts || {};\n if (opts.isDefault) this._defaultCommandName = cmd._name;\n if (opts.noHelp || opts.hidden) cmd._hidden = true; // modifying passed command due to existing implementation\n\n this._registerCommand(cmd);\n cmd.parent = this;\n cmd._checkForBrokenPassThrough();\n\n return this;\n }\n\n /**\n * Factory routine to create a new unattached argument.\n *\n * See .argument() for creating an attached argument, which uses this routine to\n * create the argument. You can override createArgument to return a custom argument.\n *\n * @param {string} name\n * @param {string} [description]\n * @return {Argument} new argument\n */\n\n createArgument(name, description) {\n return new Argument(name, description);\n }\n\n /**\n * Define argument syntax for command.\n *\n * The default is that the argument is required, and you can explicitly\n * indicate this with <> around the name. Put [] around the name for an optional argument.\n *\n * @example\n * program.argument('<input-file>');\n * program.argument('[output-file]');\n *\n * @param {string} name\n * @param {string} [description]\n * @param {(Function|*)} [parseArg] - custom argument processing function or default value\n * @param {*} [defaultValue]\n * @return {Command} `this` command for chaining\n */\n argument(name, description, parseArg, defaultValue) {\n const argument = this.createArgument(name, description);\n if (typeof parseArg === 'function') {\n argument.default(defaultValue).argParser(parseArg);\n } else {\n argument.default(parseArg);\n }\n this.addArgument(argument);\n return this;\n }\n\n /**\n * Define argument syntax for command, adding multiple at once (without descriptions).\n *\n * See also .argument().\n *\n * @example\n * program.arguments('<cmd> [env]');\n *\n * @param {string} names\n * @return {Command} `this` command for chaining\n */\n\n arguments(names) {\n names\n .trim()\n .split(/ +/)\n .forEach((detail) => {\n this.argument(detail);\n });\n return this;\n }\n\n /**\n * Define argument syntax for command, adding a prepared argument.\n *\n * @param {Argument} argument\n * @return {Command} `this` command for chaining\n */\n addArgument(argument) {\n const previousArgument = this.registeredArguments.slice(-1)[0];\n if (previousArgument?.variadic) {\n throw new Error(\n `only the last argument can be variadic '${previousArgument.name()}'`,\n );\n }\n if (\n argument.required &&\n argument.defaultValue !== undefined &&\n argument.parseArg === undefined\n ) {\n throw new Error(\n `a default value for a required argument is never used: '${argument.name()}'`,\n );\n }\n this.registeredArguments.push(argument);\n return this;\n }\n\n /**\n * Customise or override default help command. By default a help command is automatically added if your command has subcommands.\n *\n * @example\n * program.helpCommand('help [cmd]');\n * program.helpCommand('help [cmd]', 'show help');\n * program.helpCommand(false); // suppress default help command\n * program.helpCommand(true); // add help command even if no subcommands\n *\n * @param {string|boolean} enableOrNameAndArgs - enable with custom name and/or arguments, or boolean to override whether added\n * @param {string} [description] - custom description\n * @return {Command} `this` command for chaining\n */\n\n helpCommand(enableOrNameAndArgs, description) {\n if (typeof enableOrNameAndArgs === 'boolean') {\n this._addImplicitHelpCommand = enableOrNameAndArgs;\n if (enableOrNameAndArgs && this._defaultCommandGroup) {\n // make the command to store the group\n this._initCommandGroup(this._getHelpCommand());\n }\n return this;\n }\n\n const nameAndArgs = enableOrNameAndArgs ?? 'help [command]';\n const [, helpName, helpArgs] = nameAndArgs.match(/([^ ]+) *(.*)/);\n const helpDescription = description ?? 'display help for command';\n\n const helpCommand = this.createCommand(helpName);\n helpCommand.helpOption(false);\n if (helpArgs) helpCommand.arguments(helpArgs);\n if (helpDescription) helpCommand.description(helpDescription);\n\n this._addImplicitHelpCommand = true;\n this._helpCommand = helpCommand;\n // init group unless lazy create\n if (enableOrNameAndArgs || description) this._initCommandGroup(helpCommand);\n\n return this;\n }\n\n /**\n * Add prepared custom help command.\n *\n * @param {(Command|string|boolean)} helpCommand - custom help command, or deprecated enableOrNameAndArgs as for `.helpCommand()`\n * @param {string} [deprecatedDescription] - deprecated custom description used with custom name only\n * @return {Command} `this` command for chaining\n */\n addHelpCommand(helpCommand, deprecatedDescription) {\n // If not passed an object, call through to helpCommand for backwards compatibility,\n // as addHelpCommand was originally used like helpCommand is now.\n if (typeof helpCommand !== 'object') {\n this.helpCommand(helpCommand, deprecatedDescription);\n return this;\n }\n\n this._addImplicitHelpCommand = true;\n this._helpCommand = helpCommand;\n this._initCommandGroup(helpCommand);\n return this;\n }\n\n /**\n * Lazy create help command.\n *\n * @return {(Command|null)}\n * @package\n */\n _getHelpCommand() {\n const hasImplicitHelpCommand =\n this._addImplicitHelpCommand ??\n (this.commands.length &&\n !this._actionHandler &&\n !this._findCommand('help'));\n\n if (hasImplicitHelpCommand) {\n if (this._helpCommand === undefined) {\n this.helpCommand(undefined, undefined); // use default name and description\n }\n return this._helpCommand;\n }\n return null;\n }\n\n /**\n * Add hook for life cycle event.\n *\n * @param {string} event\n * @param {Function} listener\n * @return {Command} `this` command for chaining\n */\n\n hook(event, listener) {\n const allowedValues = ['preSubcommand', 'preAction', 'postAction'];\n if (!allowedValues.includes(event)) {\n throw new Error(`Unexpected value for event passed to hook : '${event}'.\nExpecting one of '${allowedValues.join(\"', '\")}'`);\n }\n if (this._lifeCycleHooks[event]) {\n this._lifeCycleHooks[event].push(listener);\n } else {\n this._lifeCycleHooks[event] = [listener];\n }\n return this;\n }\n\n /**\n * Register callback to use as replacement for calling process.exit.\n *\n * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing\n * @return {Command} `this` command for chaining\n */\n\n exitOverride(fn) {\n if (fn) {\n this._exitCallback = fn;\n } else {\n this._exitCallback = (err) => {\n if (err.code !== 'commander.executeSubCommandAsync') {\n throw err;\n } else {\n // Async callback from spawn events, not useful to throw.\n }\n };\n }\n return this;\n }\n\n /**\n * Call process.exit, and _exitCallback if defined.\n *\n * @param {number} exitCode exit code for using with process.exit\n * @param {string} code an id string representing the error\n * @param {string} message human-readable description of the error\n * @return never\n * @private\n */\n\n _exit(exitCode, code, message) {\n if (this._exitCallback) {\n this._exitCallback(new CommanderError(exitCode, code, message));\n // Expecting this line is not reached.\n }\n process.exit(exitCode);\n }\n\n /**\n * Register callback `fn` for the command.\n *\n * @example\n * program\n * .command('serve')\n * .description('start service')\n * .action(function() {\n * // do work here\n * });\n *\n * @param {Function} fn\n * @return {Command} `this` command for chaining\n */\n\n action(fn) {\n const listener = (args) => {\n // The .action callback takes an extra parameter which is the command or options.\n const expectedArgsCount = this.registeredArguments.length;\n const actionArgs = args.slice(0, expectedArgsCount);\n if (this._storeOptionsAsProperties) {\n actionArgs[expectedArgsCount] = this; // backwards compatible \"options\"\n } else {\n actionArgs[expectedArgsCount] = this.opts();\n }\n actionArgs.push(this);\n\n return fn.apply(this, actionArgs);\n };\n this._actionHandler = listener;\n return this;\n }\n\n /**\n * Factory routine to create a new unattached option.\n *\n * See .option() for creating an attached option, which uses this routine to\n * create the option. You can override createOption to return a custom option.\n *\n * @param {string} flags\n * @param {string} [description]\n * @return {Option} new option\n */\n\n createOption(flags, description) {\n return new Option(flags, description);\n }\n\n /**\n * Wrap parseArgs to catch 'commander.invalidArgument'.\n *\n * @param {(Option | Argument)} target\n * @param {string} value\n * @param {*} previous\n * @param {string} invalidArgumentMessage\n * @private\n */\n\n _callParseArg(target, value, previous, invalidArgumentMessage) {\n try {\n return target.parseArg(value, previous);\n } catch (err) {\n if (err.code === 'commander.invalidArgument') {\n const message = `${invalidArgumentMessage} ${err.message}`;\n this.error(message, { exitCode: err.exitCode, code: err.code });\n }\n throw err;\n }\n }\n\n /**\n * Check for option flag conflicts.\n * Register option if no conflicts found, or throw on conflict.\n *\n * @param {Option} option\n * @private\n */\n\n _registerOption(option) {\n const matchingOption =\n (option.short && this._findOption(option.short)) ||\n (option.long && this._findOption(option.long));\n if (matchingOption) {\n const matchingFlag =\n option.long && this._findOption(option.long)\n ? option.long\n : option.short;\n throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'\n- already used by option '${matchingOption.flags}'`);\n }\n\n this._initOptionGroup(option);\n this.options.push(option);\n }\n\n /**\n * Check for command name and alias conflicts with existing commands.\n * Register command if no conflicts found, or throw on conflict.\n *\n * @param {Command} command\n * @private\n */\n\n _registerCommand(command) {\n const knownBy = (cmd) => {\n return [cmd.name()].concat(cmd.aliases());\n };\n\n const alreadyUsed = knownBy(command).find((name) =>\n this._findCommand(name),\n );\n if (alreadyUsed) {\n const existingCmd = knownBy(this._findCommand(alreadyUsed)).join('|');\n const newCmd = knownBy(command).join('|');\n throw new Error(\n `cannot add command '${newCmd}' as already have command '${existingCmd}'`,\n );\n }\n\n this._initCommandGroup(command);\n this.commands.push(command);\n }\n\n /**\n * Add an option.\n *\n * @param {Option} option\n * @return {Command} `this` command for chaining\n */\n addOption(option) {\n this._registerOption(option);\n\n const oname = option.name();\n const name = option.attributeName();\n\n // store default value\n if (option.negate) {\n // --no-foo is special and defaults foo to true, unless a --foo option is already defined\n const positiveLongFlag = option.long.replace(/^--no-/, '--');\n if (!this._findOption(positiveLongFlag)) {\n this.setOptionValueWithSource(\n name,\n option.defaultValue === undefined ? true : option.defaultValue,\n 'default',\n );\n }\n } else if (option.defaultValue !== undefined) {\n this.setOptionValueWithSource(name, option.defaultValue, 'default');\n }\n\n // handler for cli and env supplied values\n const handleOptionValue = (val, invalidValueMessage, valueSource) => {\n // val is null for optional option used without an optional-argument.\n // val is undefined for boolean and negated option.\n if (val == null && option.presetArg !== undefined) {\n val = option.presetArg;\n }\n\n // custom processing\n const oldValue = this.getOptionValue(name);\n if (val !== null && option.parseArg) {\n val = this._callParseArg(option, val, oldValue, invalidValueMessage);\n } else if (val !== null && option.variadic) {\n val = option._collectValue(val, oldValue);\n }\n\n // Fill-in appropriate missing values. Long winded but easy to follow.\n if (val == null) {\n if (option.negate) {\n val = false;\n } else if (option.isBoolean() || option.optional) {\n val = true;\n } else {\n val = ''; // not normal, parseArg might have failed or be a mock function for testing\n }\n }\n this.setOptionValueWithSource(name, val, valueSource);\n };\n\n this.on('option:' + oname, (val) => {\n const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;\n handleOptionValue(val, invalidValueMessage, 'cli');\n });\n\n if (option.envVar) {\n this.on('optionEnv:' + oname, (val) => {\n const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;\n handleOptionValue(val, invalidValueMessage, 'env');\n });\n }\n\n return this;\n }\n\n /**\n * Internal implementation shared by .option() and .requiredOption()\n *\n * @return {Command} `this` command for chaining\n * @private\n */\n _optionEx(config, flags, description, fn, defaultValue) {\n if (typeof flags === 'object' && flags instanceof Option) {\n throw new Error(\n 'To add an Option object use addOption() instead of option() or requiredOption()',\n );\n }\n const option = this.createOption(flags, description);\n option.makeOptionMandatory(!!config.mandatory);\n if (typeof fn === 'function') {\n option.default(defaultValue).argParser(fn);\n } else if (fn instanceof RegExp) {\n // deprecated\n const regex = fn;\n fn = (val, def) => {\n const m = regex.exec(val);\n return m ? m[0] : def;\n };\n option.default(defaultValue).argParser(fn);\n } else {\n option.default(fn);\n }\n\n return this.addOption(option);\n }\n\n /**\n * Define option with `flags`, `description`, and optional argument parsing function or `defaultValue` or both.\n *\n * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. A required\n * option-argument is indicated by `<>` and an optional option-argument by `[]`.\n *\n * See the README for more details, and see also addOption() and requiredOption().\n *\n * @example\n * program\n * .option('-p, --pepper', 'add pepper')\n * .option('--pt, --pizza-type <TYPE>', 'type of pizza') // required option-argument\n * .option('-c, --cheese [CHEESE]', 'add extra cheese', 'mozzarella') // optional option-argument with default\n * .option('-t, --tip <VALUE>', 'add tip to purchase cost', parseFloat) // custom parse function\n *\n * @param {string} flags\n * @param {string} [description]\n * @param {(Function|*)} [parseArg] - custom option processing function or default value\n * @param {*} [defaultValue]\n * @return {Command} `this` command for chaining\n */\n\n option(flags, description, parseArg, defaultValue) {\n return this._optionEx({}, flags, description, parseArg, defaultValue);\n }\n\n /**\n * Add a required option which must have a value after parsing. This usually means\n * the option must be specified on the command line. (Otherwise the same as .option().)\n *\n * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.\n *\n * @param {string} flags\n * @param {string} [description]\n * @param {(Function|*)} [parseArg] - custom option processing function or default value\n * @param {*} [defaultValue]\n * @return {Command} `this` command for chaining\n */\n\n requiredOption(flags, description, parseArg, defaultValue) {\n return this._optionEx(\n { mandatory: true },\n flags,\n description,\n parseArg,\n defaultValue,\n );\n }\n\n /**\n * Alter parsing of short flags with optional values.\n *\n * @example\n * // for `.option('-f,--flag [value]'):\n * program.combineFlagAndOptionalValue(true); // `-f80` is treated like `--flag=80`, this is the default behaviour\n * program.combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`\n *\n * @param {boolean} [combine] - if `true` or omitted, an optional value can be specified directly after the flag.\n * @return {Command} `this` command for chaining\n */\n combineFlagAndOptionalValue(combine = true) {\n this._combineFlagAndOptionalValue = !!combine;\n return this;\n }\n\n /**\n * Allow unknown options on the command line.\n *\n * @param {boolean} [allowUnknown] - if `true` or omitted, no error will be thrown for unknown options.\n * @return {Command} `this` command for chaining\n */\n allowUnknownOption(allowUnknown = true) {\n this._allowUnknownOption = !!allowUnknown;\n return this;\n }\n\n /**\n * Allow excess command-arguments on the command line. Pass false to make excess arguments an error.\n *\n * @param {boolean} [allowExcess] - if `true` or omitted, no error will be thrown for excess arguments.\n * @return {Command} `this` command for chaining\n */\n allowExcessArguments(allowExcess = true) {\n this._allowExcessArguments = !!allowExcess;\n return this;\n }\n\n /**\n * Enable positional options. Positional means global options are specified before subcommands which lets\n * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.\n * The default behaviour is non-positional and global options may appear anywhere on the command line.\n *\n * @param {boolean} [positional]\n * @return {Command} `this` command for chaining\n */\n enablePositionalOptions(positional = true) {\n this._enablePositionalOptions = !!positional;\n return this;\n }\n\n /**\n * Pass through options that come after command-arguments rather than treat them as command-options,\n * so actual command-options come before command-arguments. Turning this on for a subcommand requires\n * positional options to have been enabled on the program (parent commands).\n * The default behaviour is non-positional and options may appear before or after command-arguments.\n *\n * @param {boolean} [passThrough] for unknown options.\n * @return {Command} `this` command for chaining\n */\n passThroughOptions(passThrough = true) {\n this._passThroughOptions = !!passThrough;\n this._checkForBrokenPassThrough();\n return this;\n }\n\n /**\n * @private\n */\n\n _checkForBrokenPassThrough() {\n if (\n this.parent &&\n this._passThroughOptions &&\n !this.parent._enablePositionalOptions\n ) {\n throw new Error(\n `passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`,\n );\n }\n }\n\n /**\n * Whether to store option values as properties on command object,\n * or store separately (specify false). In both cases the option values can be accessed using .opts().\n *\n * @param {boolean} [storeAsProperties=true]\n * @return {Command} `this` command for chaining\n */\n\n storeOptionsAsProperties(storeAsProperties = true) {\n if (this.options.length) {\n throw new Error('call .storeOptionsAsProperties() before adding options');\n }\n if (Object.keys(this._optionValues).length) {\n throw new Error(\n 'call .storeOptionsAsProperties() before setting option values',\n );\n }\n this._storeOptionsAsProperties = !!storeAsProperties;\n return this;\n }\n\n /**\n * Retrieve option value.\n *\n * @param {string} key\n * @return {object} value\n */\n\n getOptionValue(key) {\n if (this._storeOptionsAsProperties) {\n return this[key];\n }\n return this._optionValues[key];\n }\n\n /**\n * Store option value.\n *\n * @param {string} key\n * @param {object} value\n * @return {Command} `this` command for chaining\n */\n\n setOptionValue(key, value) {\n return this.setOptionValueWithSource(key, value, undefined);\n }\n\n /**\n * Store option value and where the value came from.\n *\n * @param {string} key\n * @param {object} value\n * @param {string} source - expected values are default/config/env/cli/implied\n * @return {Command} `this` command for chaining\n */\n\n setOptionValueWithSource(key, value, source) {\n if (this._storeOptionsAsProperties) {\n this[key] = value;\n } else {\n this._optionValues[key] = value;\n }\n this._optionValueSources[key] = source;\n return this;\n }\n\n /**\n * Get source of option value.\n * Expected values are default | config | env | cli | implied\n *\n * @param {string} key\n * @return {string}\n */\n\n getOptionValueSource(key) {\n return this._optionValueSources[key];\n }\n\n /**\n * Get source of option value. See also .optsWithGlobals().\n * Expected values are default | config | env | cli | implied\n *\n * @param {string} key\n * @return {string}\n */\n\n getOptionValueSourceWithGlobals(key) {\n // global overwrites local, like optsWithGlobals\n let source;\n this._getCommandAndAncestors().forEach((cmd) => {\n if (cmd.getOptionValueSource(key) !== undefined) {\n source = cmd.getOptionValueSource(key);\n }\n });\n return source;\n }\n\n /**\n * Get user arguments from implied or explicit arguments.\n * Side-effects: set _scriptPath if args included script. Used for default program name, and subcommand searches.\n *\n * @private\n */\n\n _prepareUserArgs(argv, parseOptions) {\n if (argv !== undefined && !Array.isArray(argv)) {\n throw new Error('first parameter to parse must be array or undefined');\n }\n parseOptions = parseOptions || {};\n\n // auto-detect argument conventions if nothing supplied\n if (argv === undefined && parseOptions.from === undefined) {\n if (process.versions?.electron) {\n parseOptions.from = 'electron';\n }\n // check node specific options for scenarios where user CLI args follow executable without scriptname\n const execArgv = process.execArgv ?? [];\n if (\n execArgv.includes('-e') ||\n execArgv.includes('--eval') ||\n execArgv.includes('-p') ||\n execArgv.includes('--print')\n ) {\n parseOptions.from = 'eval'; // internal usage, not documented\n }\n }\n\n // default to using process.argv\n if (argv === undefined) {\n argv = process.argv;\n }\n this.rawArgs = argv.slice();\n\n // extract the user args and scriptPath\n let userArgs;\n switch (parseOptions.from) {\n case undefined:\n case 'node':\n this._scriptPath = argv[1];\n userArgs = argv.slice(2);\n break;\n case 'electron':\n // @ts-ignore: because defaultApp is an unknown property\n if (process.defaultApp) {\n this._scriptPath = argv[1];\n userArgs = argv.slice(2);\n } else {\n userArgs = argv.slice(1);\n }\n break;\n case 'user':\n userArgs = argv.slice(0);\n break;\n case 'eval':\n userArgs = argv.slice(1);\n break;\n default:\n throw new Error(\n `unexpected parse option { from: '${parseOptions.from}' }`,\n );\n }\n\n // Find default name for program from arguments.\n if (!this._name && this._scriptPath)\n this.nameFromFilename(this._scriptPath);\n this._name = this._name || 'program';\n\n return userArgs;\n }\n\n /**\n * Parse `argv`, setting options and invoking commands when defined.\n *\n * Use parseAsync instead of parse if any of your action handlers are async.\n *\n * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!\n *\n * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:\n * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that\n * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged\n * - `'user'`: just user arguments\n *\n * @example\n * program.parse(); // parse process.argv and auto-detect electron and special node flags\n * program.parse(process.argv); // assume argv[0] is app and argv[1] is script\n * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]\n *\n * @param {string[]} [argv] - optional, defaults to process.argv\n * @param {object} [parseOptions] - optionally specify style of options with from: node/user/electron\n * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'\n * @return {Command} `this` command for chaining\n */\n\n parse(argv, parseOptions) {\n this._prepareForParse();\n const userArgs = this._prepareUserArgs(argv, parseOptions);\n this._parseCommand([], userArgs);\n\n return this;\n }\n\n /**\n * Parse `argv`, setting options and invoking commands when defined.\n *\n * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!\n *\n * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:\n * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that\n * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged\n * - `'user'`: just user arguments\n *\n * @example\n * await program.parseAsync(); // parse process.argv and auto-detect electron and special node flags\n * await program.parseAsync(process.argv); // assume argv[0] is app and argv[1] is script\n * await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]\n *\n * @param {string[]} [argv]\n * @param {object} [parseOptions]\n * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'\n * @return {Promise}\n */\n\n async parseAsync(argv, parseOptions) {\n this._prepareForParse();\n const userArgs = this._prepareUserArgs(argv, parseOptions);\n await this._parseCommand([], userArgs);\n\n return this;\n }\n\n _prepareForParse() {\n if (this._savedState === null) {\n this.saveStateBeforeParse();\n } else {\n this.restoreStateBeforeParse();\n }\n }\n\n /**\n * Called the first time parse is called to save state and allow a restore before subsequent calls to parse.\n * Not usually called directly, but available for subclasses to save their custom state.\n *\n * This is called in a lazy way. Only commands used in parsing chain will have state saved.\n */\n saveStateBeforeParse() {\n this._savedState = {\n // name is stable if supplied by author, but may be unspecified for root command and deduced during parsing\n _name: this._name,\n // option values before parse have default values (including false for negated options)\n // shallow clones\n _optionValues: { ...this._optionValues },\n _optionValueSources: { ...this._optionValueSources },\n };\n }\n\n /**\n * Restore state before parse for calls after the first.\n * Not usually called directly, but available for subclasses to save their custom state.\n *\n * This is called in a lazy way. Only commands used in parsing chain will have state restored.\n */\n restoreStateBeforeParse() {\n if (this._storeOptionsAsProperties)\n throw new Error(`Can not call parse again when storeOptionsAsProperties is true.\n- either make a new Command for each call to parse, or stop storing options as properties`);\n\n // clear state from _prepareUserArgs\n this._name = this._savedState._name;\n this._scriptPath = null;\n this.rawArgs = [];\n // clear state from setOptionValueWithSource\n this._optionValues = { ...this._savedState._optionValues };\n this._optionValueSources = { ...this._savedState._optionValueSources };\n // clear state from _parseCommand\n this.args = [];\n // clear state from _processArguments\n this.processedArgs = [];\n }\n\n /**\n * Throw if expected executable is missing. Add lots of help for author.\n *\n * @param {string} executableFile\n * @param {string} executableDir\n * @param {string} subcommandName\n */\n _checkForMissingExecutable(executableFile, executableDir, subcommandName) {\n if (fs.existsSync(executableFile)) return;\n\n const executableDirMessage = executableDir\n ? `searched for local subcommand relative to directory '${executableDir}'`\n : 'no directory for search for local subcommand, use .executableDir() to supply a custom directory';\n const executableMissing = `'${executableFile}' does not exist\n - if '${subcommandName}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead\n - if the default executable name is not suitable, use the executableFile option to supply a custom name or path\n - ${executableDirMessage}`;\n throw new Error(executableMissing);\n }\n\n /**\n * Execute a sub-command executable.\n *\n * @private\n */\n\n _executeSubCommand(subcommand, args) {\n args = args.slice();\n let launchWithNode = false; // Use node for source targets so do not need to get permissions correct, and on Windows.\n const sourceExt = ['.js', '.ts', '.tsx', '.mjs', '.cjs'];\n\n function findFile(baseDir, baseName) {\n // Look for specified file\n const localBin = path.resolve(baseDir, baseName);\n if (fs.existsSync(localBin)) return localBin;\n\n // Stop looking if candidate already has an expected extension.\n if (sourceExt.includes(path.extname(baseName))) return undefined;\n\n // Try all the extensions.\n const foundExt = sourceExt.find((ext) =>\n fs.existsSync(`${localBin}${ext}`),\n );\n if (foundExt) return `${localBin}${foundExt}`;\n\n return undefined;\n }\n\n // Not checking for help first. Unlikely to have mandatory and executable, and can't robustly test for help flags in external command.\n this._checkForMissingMandatoryOptions();\n this._checkForConflictingOptions();\n\n // executableFile and executableDir might be full path, or just a name\n let executableFile =\n subcommand._executableFile || `${this._name}-${subcommand._name}`;\n let executableDir = this._executableDir || '';\n if (this._scriptPath) {\n let resolvedScriptPath; // resolve possible symlink for installed npm binary\n try {\n resolvedScriptPath = fs.realpathSync(this._scriptPath);\n } catch {\n resolvedScriptPath = this._scriptPath;\n }\n executableDir = path.resolve(\n path.dirname(resolvedScriptPath),\n executableDir,\n );\n }\n\n // Look for a local file in preference to a command in PATH.\n if (executableDir) {\n let localFile = findFile(executableDir, executableFile);\n\n // Legacy search using prefix of script name instead of command name\n if (!localFile && !subcommand._executableFile && this._scriptPath) {\n const legacyName = path.basename(\n this._scriptPath,\n path.extname(this._scriptPath),\n );\n if (legacyName !== this._name) {\n localFile = findFile(\n executableDir,\n `${legacyName}-${subcommand._name}`,\n );\n }\n }\n executableFile = localFile || executableFile;\n }\n\n launchWithNode = sourceExt.includes(path.extname(executableFile));\n\n let proc;\n if (process.platform !== 'win32') {\n if (launchWithNode) {\n args.unshift(executableFile);\n // add executable arguments to spawn\n args = incrementNodeInspectorPort(process.execArgv).concat(args);\n\n proc = childProcess.spawn(process.argv[0], args, { stdio: 'inherit' });\n } else {\n proc = childProcess.spawn(executableFile, args, { stdio: 'inherit' });\n }\n } else {\n this._checkForMissingExecutable(\n executableFile,\n executableDir,\n subcommand._name,\n );\n args.unshift(executableFile);\n // add executable arguments to spawn\n args = incrementNodeInspectorPort(process.execArgv).concat(args);\n proc = childProcess.spawn(process.execPath, args, { stdio: 'inherit' });\n }\n\n if (!proc.killed) {\n // testing mainly to avoid leak warnings during unit tests with mocked spawn\n const signals = ['SIGUSR1', 'SIGUSR2', 'SIGTERM', 'SIGINT', 'SIGHUP'];\n signals.forEach((signal) => {\n process.on(signal, () => {\n if (proc.killed === false && proc.exitCode === null) {\n // @ts-ignore because signals not typed to known strings\n proc.kill(signal);\n }\n });\n });\n }\n\n // By default terminate process when spawned process terminates.\n const exitCallback = this._exitCallback;\n proc.on('close', (code) => {\n code = code ?? 1; // code is null if spawned process terminated due to a signal\n if (!exitCallback) {\n process.exit(code);\n } else {\n exitCallback(\n new CommanderError(\n code,\n 'commander.executeSubCommandAsync',\n '(close)',\n ),\n );\n }\n });\n proc.on('error', (err) => {\n // @ts-ignore: because err.code is an unknown property\n if (err.code === 'ENOENT') {\n this._checkForMissingExecutable(\n executableFile,\n executableDir,\n subcommand._name,\n );\n // @ts-ignore: because err.code is an unknown property\n } else if (err.code === 'EACCES') {\n throw new Error(`'${executableFile}' not executable`);\n }\n if (!exitCallback) {\n process.exit(1);\n } else {\n const wrappedError = new CommanderError(\n 1,\n 'commander.executeSubCommandAsync',\n '(error)',\n );\n wrappedError.nestedError = err;\n exitCallback(wrappedError);\n }\n });\n\n // Store the reference to the child process\n this.runningCommand = proc;\n }\n\n /**\n * @private\n */\n\n _dispatchSubcommand(commandName, operands, unknown) {\n const subCommand = this._findCommand(commandName);\n if (!subCommand) this.help({ error: true });\n\n subCommand._prepareForParse();\n let promiseChain;\n promiseChain = this._chainOrCallSubCommandHook(\n promiseChain,\n subCommand,\n 'preSubcommand',\n );\n promiseChain = this._chainOrCall(promiseChain, () => {\n if (subCommand._executableHandler) {\n this._executeSubCommand(subCommand, operands.concat(unknown));\n } else {\n return subCommand._parseCommand(operands, unknown);\n }\n });\n return promiseChain;\n }\n\n /**\n * Invoke help directly if possible, or dispatch if necessary.\n * e.g. help foo\n *\n * @private\n */\n\n _dispatchHelpCommand(subcommandName) {\n if (!subcommandName) {\n this.help();\n }\n const subCommand = this._findCommand(subcommandName);\n if (subCommand && !subCommand._executableHandler) {\n subCommand.help();\n }\n\n // Fallback to parsing the help flag to invoke the help.\n return this._dispatchSubcommand(\n subcommandName,\n [],\n [this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? '--help'],\n );\n }\n\n /**\n * Check this.args against expected this.registeredArguments.\n *\n * @private\n */\n\n _checkNumberOfArguments() {\n // too few\n this.registeredArguments.forEach((arg, i) => {\n if (arg.required && this.args[i] == null) {\n this.missingArgument(arg.name());\n }\n });\n // too many\n if (\n this.registeredArguments.length > 0 &&\n this.registeredArguments[this.registeredArguments.length - 1].variadic\n ) {\n return;\n }\n if (this.args.length > this.registeredArguments.length) {\n this._excessArguments(this.args);\n }\n }\n\n /**\n * Process this.args using this.registeredArguments and save as this.processedArgs!\n *\n * @private\n */\n\n _processArguments() {\n const myParseArg = (argument, value, previous) => {\n // Extra processing for nice error message on parsing failure.\n let parsedValue = value;\n if (value !== null && argument.parseArg) {\n const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;\n parsedValue = this._callParseArg(\n argument,\n value,\n previous,\n invalidValueMessage,\n );\n }\n return parsedValue;\n };\n\n this._checkNumberOfArguments();\n\n const processedArgs = [];\n this.registeredArguments.forEach((declaredArg, index) => {\n let value = declaredArg.defaultValue;\n if (declaredArg.variadic) {\n // Collect together remaining arguments for passing together as an array.\n if (index < this.args.length) {\n value = this.args.slice(index);\n if (declaredArg.parseArg) {\n value = value.reduce((processed, v) => {\n return myParseArg(declaredArg, v, processed);\n }, declaredArg.defaultValue);\n }\n } else if (value === undefined) {\n value = [];\n }\n } else if (index < this.args.length) {\n value = this.args[index];\n if (declaredArg.parseArg) {\n value = myParseArg(declaredArg, value, declaredArg.defaultValue);\n }\n }\n processedArgs[index] = value;\n });\n this.processedArgs = processedArgs;\n }\n\n /**\n * Once we have a promise we chain, but call synchronously until then.\n *\n * @param {(Promise|undefined)} promise\n * @param {Function} fn\n * @return {(Promise|undefined)}\n * @private\n */\n\n _chainOrCall(promise, fn) {\n // thenable\n if (promise?.then && typeof promise.then === 'function') {\n // already have a promise, chain callback\n return promise.then(() => fn());\n }\n // callback might return a promise\n return fn();\n }\n\n /**\n *\n * @param {(Promise|undefined)} promise\n * @param {string} event\n * @return {(Promise|undefined)}\n * @private\n */\n\n _chainOrCallHooks(promise, event) {\n let result = promise;\n const hooks = [];\n this._getCommandAndAncestors()\n .reverse()\n .filter((cmd) => cmd._lifeCycleHooks[event] !== undefined)\n .forEach((hookedCommand) => {\n hookedCommand._lifeCycleHooks[event].forEach((callback) => {\n hooks.push({ hookedCommand, callback });\n });\n });\n if (event === 'postAction') {\n hooks.reverse();\n }\n\n hooks.forEach((hookDetail) => {\n result = this._chainOrCall(result, () => {\n return hookDetail.callback(hookDetail.hookedCommand, this);\n });\n });\n return result;\n }\n\n /**\n *\n * @param {(Promise|undefined)} promise\n * @param {Command} subCommand\n * @param {string} event\n * @return {(Promise|undefined)}\n * @private\n */\n\n _chainOrCallSubCommandHook(promise, subCommand, event) {\n let result = promise;\n if (this._lifeCycleHooks[event] !== undefined) {\n this._lifeCycleHooks[event].forEach((hook) => {\n result = this._chainOrCall(result, () => {\n return hook(this, subCommand);\n });\n });\n }\n return result;\n }\n\n /**\n * Process arguments in context of this command.\n * Returns action result, in case it is a promise.\n *\n * @private\n */\n\n _parseCommand(operands, unknown) {\n const parsed = this.parseOptions(unknown);\n this._parseOptionsEnv(); // after cli, so parseArg not called on both cli and env\n this._parseOptionsImplied();\n operands = operands.concat(parsed.operands);\n unknown = parsed.unknown;\n this.args = operands.concat(unknown);\n\n if (operands && this._findCommand(operands[0])) {\n return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);\n }\n if (\n this._getHelpCommand() &&\n operands[0] === this._getHelpCommand().name()\n ) {\n return this._dispatchHelpCommand(operands[1]);\n }\n if (this._defaultCommandName) {\n this._outputHelpIfRequested(unknown); // Run the help for default command from parent rather than passing to default command\n return this._dispatchSubcommand(\n this._defaultCommandName,\n operands,\n unknown,\n );\n }\n if (\n this.commands.length &&\n this.args.length === 0 &&\n !this._actionHandler &&\n !this._defaultCommandName\n ) {\n // probably missing subcommand and no handler, user needs help (and exit)\n this.help({ error: true });\n }\n\n this._outputHelpIfRequested(parsed.unknown);\n this._checkForMissingMandatoryOptions();\n this._checkForConflictingOptions();\n\n // We do not always call this check to avoid masking a \"better\" error, like unknown command.\n const checkForUnknownOptions = () => {\n if (parsed.unknown.length > 0) {\n this.unknownOption(parsed.unknown[0]);\n }\n };\n\n const commandEvent = `command:${this.name()}`;\n if (this._actionHandler) {\n checkForUnknownOptions();\n this._processArguments();\n\n let promiseChain;\n promiseChain = this._chainOrCallHooks(promiseChain, 'preAction');\n promiseChain = this._chainOrCall(promiseChain, () =>\n this._actionHandler(this.processedArgs),\n );\n if (this.parent) {\n promiseChain = this._chainOrCall(promiseChain, () => {\n this.parent.emit(commandEvent, operands, unknown); // legacy\n });\n }\n promiseChain = this._chainOrCallHooks(promiseChain, 'postAction');\n return promiseChain;\n }\n if (this.parent?.listenerCount(commandEvent)) {\n checkForUnknownOptions();\n this._processArguments();\n this.parent.emit(commandEvent, operands, unknown); // legacy\n } else if (operands.length) {\n if (this._findCommand('*')) {\n // legacy default command\n return this._dispatchSubcommand('*', operands, unknown);\n }\n if (this.listenerCount('command:*')) {\n // skip option check, emit event for possible misspelling suggestion\n this.emit('command:*', operands, unknown);\n } else if (this.commands.length) {\n this.unknownCommand();\n } else {\n checkForUnknownOptions();\n this._processArguments();\n }\n } else if (this.commands.length) {\n checkForUnknownOptions();\n // This command has subcommands and nothing hooked up at this level, so display help (and exit).\n this.help({ error: true });\n } else {\n checkForUnknownOptions();\n this._processArguments();\n // fall through for caller to handle after calling .parse()\n }\n }\n\n /**\n * Find matching command.\n *\n * @private\n * @return {Command | undefined}\n */\n _findCommand(name) {\n if (!name) return undefined;\n return this.commands.find(\n (cmd) => cmd._name === name || cmd._aliases.includes(name),\n );\n }\n\n /**\n * Return an option matching `arg` if any.\n *\n * @param {string} arg\n * @return {Option}\n * @package\n */\n\n _findOption(arg) {\n return this.options.find((option) => option.is(arg));\n }\n\n /**\n * Display an error message if a mandatory option does not have a value.\n * Called after checking for help flags in leaf subcommand.\n *\n * @private\n */\n\n _checkForMissingMandatoryOptions() {\n // Walk up hierarchy so can call in subcommand after checking for displaying help.\n this._getCommandAndAncestors().forEach((cmd) => {\n cmd.options.forEach((anOption) => {\n if (\n anOption.mandatory &&\n cmd.getOptionValue(anOption.attributeName()) === undefined\n ) {\n cmd.missingMandatoryOptionValue(anOption);\n }\n });\n });\n }\n\n /**\n * Display an error message if conflicting options are used together in this.\n *\n * @private\n */\n _checkForConflictingLocalOptions() {\n const definedNonDefaultOptions = this.options.filter((option) => {\n const optionKey = option.attributeName();\n if (this.getOptionValue(optionKey) === undefined) {\n return false;\n }\n return this.getOptionValueSource(optionKey) !== 'default';\n });\n\n const optionsWithConflicting = definedNonDefaultOptions.filter(\n (option) => option.conflictsWith.length > 0,\n );\n\n optionsWithConflicting.forEach((option) => {\n const conflictingAndDefined = definedNonDefaultOptions.find((defined) =>\n option.conflictsWith.includes(defined.attributeName()),\n );\n if (conflictingAndDefined) {\n this._conflictingOption(option, conflictingAndDefined);\n }\n });\n }\n\n /**\n * Display an error message if conflicting options are used together.\n * Called after checking for help flags in leaf subcommand.\n *\n * @private\n */\n _checkForConflictingOptions() {\n // Walk up hierarchy so can call in subcommand after checking for displaying help.\n this._getCommandAndAncestors().forEach((cmd) => {\n cmd._checkForConflictingLocalOptions();\n });\n }\n\n /**\n * Parse options from `argv` removing known options,\n * and return argv split into operands and unknown arguments.\n *\n * Side effects: modifies command by storing options. Does not reset state if called again.\n *\n * Examples:\n *\n * argv => operands, unknown\n * --known kkk op => [op], []\n * op --known kkk => [op], []\n * sub --unknown uuu op => [sub], [--unknown uuu op]\n * sub -- --unknown uuu op => [sub --unknown uuu op], []\n *\n * @param {string[]} args\n * @return {{operands: string[], unknown: string[]}}\n */\n\n parseOptions(args) {\n const operands = []; // operands, not options or values\n const unknown = []; // first unknown option and remaining unknown args\n let dest = operands;\n\n function maybeOption(arg) {\n return arg.length > 1 && arg[0] === '-';\n }\n\n const negativeNumberArg = (arg) => {\n // return false if not a negative number\n if (!/^-(\\d+|\\d*\\.\\d+)(e[+-]?\\d+)?$/.test(arg)) return false;\n // negative number is ok unless digit used as an option in command hierarchy\n return !this._getCommandAndAncestors().some((cmd) =>\n cmd.options\n .map((opt) => opt.short)\n .some((short) => /^-\\d$/.test(short)),\n );\n };\n\n // parse options\n let activeVariadicOption = null;\n let activeGroup = null; // working through group of short options, like -abc\n let i = 0;\n while (i < args.length || activeGroup) {\n const arg = activeGroup ?? args[i++];\n activeGroup = null;\n\n // literal\n if (arg === '--') {\n if (dest === unknown) dest.push(arg);\n dest.push(...args.slice(i));\n break;\n }\n\n if (\n activeVariadicOption &&\n (!maybeOption(arg) || negativeNumberArg(arg))\n ) {\n this.emit(`option:${activeVariadicOption.name()}`, arg);\n continue;\n }\n activeVariadicOption = null;\n\n if (maybeOption(arg)) {\n const option = this._findOption(arg);\n // recognised option, call listener to assign value with possible custom processing\n if (option) {\n if (option.required) {\n const value = args[i++];\n if (value === undefined) this.optionMissingArgument(option);\n this.emit(`option:${option.name()}`, value);\n } else if (option.optional) {\n let value = null;\n // historical behaviour is optional value is following arg unless an option\n if (\n i < args.length &&\n (!maybeOption(args[i]) || negativeNumberArg(args[i]))\n ) {\n value = args[i++];\n }\n this.emit(`option:${option.name()}`, value);\n } else {\n // boolean flag\n this.emit(`option:${option.name()}`);\n }\n activeVariadicOption = option.variadic ? option : null;\n continue;\n }\n }\n\n // Look for combo options following single dash, eat first one if known.\n if (arg.length > 2 && arg[0] === '-' && arg[1] !== '-') {\n const option = this._findOption(`-${arg[1]}`);\n if (option) {\n if (\n option.required ||\n (option.optional && this._combineFlagAndOptionalValue)\n ) {\n // option with value following in same argument\n this.emit(`option:${option.name()}`, arg.slice(2));\n } else {\n // boolean option\n this.emit(`option:${option.name()}`);\n // remove the processed option and keep processing group\n activeGroup = `-${arg.slice(2)}`;\n }\n continue;\n }\n }\n\n // Look for known long flag with value, like --foo=bar\n if (/^--[^=]+=/.test(arg)) {\n const index = arg.indexOf('=');\n const option = this._findOption(arg.slice(0, index));\n if (option && (option.required || option.optional)) {\n this.emit(`option:${option.name()}`, arg.slice(index + 1));\n continue;\n }\n }\n\n // Not a recognised option by this command.\n // Might be a command-argument, or subcommand option, or unknown option, or help command or option.\n\n // An unknown option means further arguments also classified as unknown so can be reprocessed by subcommands.\n // A negative number in a leaf command is not an unknown option.\n if (\n dest === operands &&\n maybeOption(arg) &&\n !(this.commands.length === 0 && negativeNumberArg(arg))\n ) {\n dest = unknown;\n }\n\n // If using positionalOptions, stop processing our options at subcommand.\n if (\n (this._enablePositionalOptions || this._passThroughOptions) &&\n operands.length === 0 &&\n unknown.length === 0\n ) {\n if (this._findCommand(arg)) {\n operands.push(arg);\n unknown.push(...args.slice(i));\n break;\n } else if (\n this._getHelpCommand() &&\n arg === this._getHelpCommand().name()\n ) {\n operands.push(arg, ...args.slice(i));\n break;\n } else if (this._defaultCommandName) {\n unknown.push(arg, ...args.slice(i));\n break;\n }\n }\n\n // If using passThroughOptions, stop processing options at first command-argument.\n if (this._passThroughOptions) {\n dest.push(arg, ...args.slice(i));\n break;\n }\n\n // add arg\n dest.push(arg);\n }\n\n return { operands, unknown };\n }\n\n /**\n * Return an object containing local option values as key-value pairs.\n *\n * @return {object}\n */\n opts() {\n if (this._storeOptionsAsProperties) {\n // Preserve original behaviour so backwards compatible when still using properties\n const result = {};\n const len = this.options.length;\n\n for (let i = 0; i < len; i++) {\n const key = this.options[i].attributeName();\n result[key] =\n key === this._versionOptionName ? this._version : this[key];\n }\n return result;\n }\n\n return this._optionValues;\n }\n\n /**\n * Return an object containing merged local and global option values as key-value pairs.\n *\n * @return {object}\n */\n optsWithGlobals() {\n // globals overwrite locals\n return this._getCommandAndAncestors().reduce(\n (combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()),\n {},\n );\n }\n\n /**\n * Display error message and exit (or call exitOverride).\n *\n * @param {string} message\n * @param {object} [errorOptions]\n * @param {string} [errorOptions.code] - an id string representing the error\n * @param {number} [errorOptions.exitCode] - used with process.exit\n */\n error(message, errorOptions) {\n // output handling\n this._outputConfiguration.outputError(\n `${message}\\n`,\n this._outputConfiguration.writeErr,\n );\n if (typeof this._showHelpAfterError === 'string') {\n this._outputConfiguration.writeErr(`${this._showHelpAfterError}\\n`);\n } else if (this._showHelpAfterError) {\n this._outputConfiguration.writeErr('\\n');\n this.outputHelp({ error: true });\n }\n\n // exit handling\n const config = errorOptions || {};\n const exitCode = config.exitCode || 1;\n const code = config.code || 'commander.error';\n this._exit(exitCode, code, message);\n }\n\n /**\n * Apply any option related environment variables, if option does\n * not have a value from cli or client code.\n *\n * @private\n */\n _parseOptionsEnv() {\n this.options.forEach((option) => {\n if (option.envVar && option.envVar in process.env) {\n const optionKey = option.attributeName();\n // Priority check. Do not overwrite cli or options from unknown source (client-code).\n if (\n this.getOptionValue(optionKey) === undefined ||\n ['default', 'config', 'env'].includes(\n this.getOptionValueSource(optionKey),\n )\n ) {\n if (option.required || option.optional) {\n // option can take a value\n // keep very simple, optional always takes value\n this.emit(`optionEnv:${option.name()}`, process.env[option.envVar]);\n } else {\n // boolean\n // keep very simple, only care that envVar defined and not the value\n this.emit(`optionEnv:${option.name()}`);\n }\n }\n }\n });\n }\n\n /**\n * Apply any implied option values, if option is undefined or default value.\n *\n * @private\n */\n _parseOptionsImplied() {\n const dualHelper = new DualOptions(this.options);\n const hasCustomOptionValue = (optionKey) => {\n return (\n this.getOptionValue(optionKey) !== undefined &&\n !['default', 'implied'].includes(this.getOptionValueSource(optionKey))\n );\n };\n this.options\n .filter(\n (option) =>\n option.implied !== undefined &&\n hasCustomOptionValue(option.attributeName()) &&\n dualHelper.valueFromOption(\n this.getOptionValue(option.attributeName()),\n option,\n ),\n )\n .forEach((option) => {\n Object.keys(option.implied)\n .filter((impliedKey) => !hasCustomOptionValue(impliedKey))\n .forEach((impliedKey) => {\n this.setOptionValueWithSource(\n impliedKey,\n option.implied[impliedKey],\n 'implied',\n );\n });\n });\n }\n\n /**\n * Argument `name` is missing.\n *\n * @param {string} name\n * @private\n */\n\n missingArgument(name) {\n const message = `error: missing required argument '${name}'`;\n this.error(message, { code: 'commander.missingArgument' });\n }\n\n /**\n * `Option` is missing an argument.\n *\n * @param {Option} option\n * @private\n */\n\n optionMissingArgument(option) {\n const message = `error: option '${option.flags}' argument missing`;\n this.error(message, { code: 'commander.optionMissingArgument' });\n }\n\n /**\n * `Option` does not have a value, and is a mandatory option.\n *\n * @param {Option} option\n * @private\n */\n\n missingMandatoryOptionValue(option) {\n const message = `error: required option '${option.flags}' not specified`;\n this.error(message, { code: 'commander.missingMandatoryOptionValue' });\n }\n\n /**\n * `Option` conflicts with another option.\n *\n * @param {Option} option\n * @param {Option} conflictingOption\n * @private\n */\n _conflictingOption(option, conflictingOption) {\n // The calling code does not know whether a negated option is the source of the\n // value, so do some work to take an educated guess.\n const findBestOptionFromValue = (option) => {\n const optionKey = option.attributeName();\n const optionValue = this.getOptionValue(optionKey);\n const negativeOption = this.options.find(\n (target) => target.negate && optionKey === target.attributeName(),\n );\n const positiveOption = this.options.find(\n (target) => !target.negate && optionKey === target.attributeName(),\n );\n if (\n negativeOption &&\n ((negativeOption.presetArg === undefined && optionValue === false) ||\n (negativeOption.presetArg !== undefined &&\n optionValue === negativeOption.presetArg))\n ) {\n return negativeOption;\n }\n return positiveOption || option;\n };\n\n const getErrorMessage = (option) => {\n const bestOption = findBestOptionFromValue(option);\n const optionKey = bestOption.attributeName();\n const source = this.getOptionValueSource(optionKey);\n if (source === 'env') {\n return `environment variable '${bestOption.envVar}'`;\n }\n return `option '${bestOption.flags}'`;\n };\n\n const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;\n this.error(message, { code: 'commander.conflictingOption' });\n }\n\n /**\n * Unknown option `flag`.\n *\n * @param {string} flag\n * @private\n */\n\n unknownOption(flag) {\n if (this._allowUnknownOption) return;\n let suggestion = '';\n\n if (flag.startsWith('--') && this._showSuggestionAfterError) {\n // Looping to pick up the global options too\n let candidateFlags = [];\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n let command = this;\n do {\n const moreFlags = command\n .createHelp()\n .visibleOptions(command)\n .filter((option) => option.long)\n .map((option) => option.long);\n candidateFlags = candidateFlags.concat(moreFlags);\n command = command.parent;\n } while (command && !command._enablePositionalOptions);\n suggestion = suggestSimilar(flag, candidateFlags);\n }\n\n const message = `error: unknown option '${flag}'${suggestion}`;\n this.error(message, { code: 'commander.unknownOption' });\n }\n\n /**\n * Excess arguments, more than expected.\n *\n * @param {string[]} receivedArgs\n * @private\n */\n\n _excessArguments(receivedArgs) {\n if (this._allowExcessArguments) return;\n\n const expected = this.registeredArguments.length;\n const s = expected === 1 ? '' : 's';\n const forSubcommand = this.parent ? ` for '${this.name()}'` : '';\n const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;\n this.error(message, { code: 'commander.excessArguments' });\n }\n\n /**\n * Unknown command.\n *\n * @private\n */\n\n unknownCommand() {\n const unknownName = this.args[0];\n let suggestion = '';\n\n if (this._showSuggestionAfterError) {\n const candidateNames = [];\n this.createHelp()\n .visibleCommands(this)\n .forEach((command) => {\n candidateNames.push(command.name());\n // just visible alias\n if (command.alias()) candidateNames.push(command.alias());\n });\n suggestion = suggestSimilar(unknownName, candidateNames);\n }\n\n const message = `error: unknown command '${unknownName}'${suggestion}`;\n this.error(message, { code: 'commander.unknownCommand' });\n }\n\n /**\n * Get or set the program version.\n *\n * This method auto-registers the \"-V, --version\" option which will print the version number.\n *\n * You can optionally supply the flags and description to override the defaults.\n *\n * @param {string} [str]\n * @param {string} [flags]\n * @param {string} [description]\n * @return {(this | string | undefined)} `this` command for chaining, or version string if no arguments\n */\n\n version(str, flags, description) {\n if (str === undefined) return this._version;\n this._version = str;\n flags = flags || '-V, --version';\n description = description || 'output the version number';\n const versionOption = this.createOption(flags, description);\n this._versionOptionName = versionOption.attributeName();\n this._registerOption(versionOption);\n\n this.on('option:' + versionOption.name(), () => {\n this._outputConfiguration.writeOut(`${str}\\n`);\n this._exit(0, 'commander.version', str);\n });\n return this;\n }\n\n /**\n * Set the description.\n *\n * @param {string} [str]\n * @param {object} [argsDescription]\n * @return {(string|Command)}\n */\n description(str, argsDescription) {\n if (str === undefined && argsDescription === undefined)\n return this._description;\n this._description = str;\n if (argsDescription) {\n this._argsDescription = argsDescription;\n }\n return this;\n }\n\n /**\n * Set the summary. Used when listed as subcommand of parent.\n *\n * @param {string} [str]\n * @return {(string|Command)}\n */\n summary(str) {\n if (str === undefined) return this._summary;\n this._summary = str;\n return this;\n }\n\n /**\n * Set an alias for the command.\n *\n * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.\n *\n * @param {string} [alias]\n * @return {(string|Command)}\n */\n\n alias(alias) {\n if (alias === undefined) return this._aliases[0]; // just return first, for backwards compatibility\n\n /** @type {Command} */\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n let command = this;\n if (\n this.commands.length !== 0 &&\n this.commands[this.commands.length - 1]._executableHandler\n ) {\n // assume adding alias for last added executable subcommand, rather than this\n command = this.commands[this.commands.length - 1];\n }\n\n if (alias === command._name)\n throw new Error(\"Command alias can't be the same as its name\");\n const matchingCommand = this.parent?._findCommand(alias);\n if (matchingCommand) {\n // c.f. _registerCommand\n const existingCmd = [matchingCommand.name()]\n .concat(matchingCommand.aliases())\n .join('|');\n throw new Error(\n `cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`,\n );\n }\n\n command._aliases.push(alias);\n return this;\n }\n\n /**\n * Set aliases for the command.\n *\n * Only the first alias is shown in the auto-generated help.\n *\n * @param {string[]} [aliases]\n * @return {(string[]|Command)}\n */\n\n aliases(aliases) {\n // Getter for the array of aliases is the main reason for having aliases() in addition to alias().\n if (aliases === undefined) return this._aliases;\n\n aliases.forEach((alias) => this.alias(alias));\n return this;\n }\n\n /**\n * Set / get the command usage `str`.\n *\n * @param {string} [str]\n * @return {(string|Command)}\n */\n\n usage(str) {\n if (str === undefined) {\n if (this._usage) return this._usage;\n\n const args = this.registeredArguments.map((arg) => {\n return humanReadableArgName(arg);\n });\n return []\n .concat(\n this.options.length || this._helpOption !== null ? '[options]' : [],\n this.commands.length ? '[command]' : [],\n this.registeredArguments.length ? args : [],\n )\n .join(' ');\n }\n\n this._usage = str;\n return this;\n }\n\n /**\n * Get or set the name of the command.\n *\n * @param {string} [str]\n * @return {(string|Command)}\n */\n\n name(str) {\n if (str === undefined) return this._name;\n this._name = str;\n return this;\n }\n\n /**\n * Set/get the help group heading for this subcommand in parent command's help.\n *\n * @param {string} [heading]\n * @return {Command | string}\n */\n\n helpGroup(heading) {\n if (heading === undefined) return this._helpGroupHeading ?? '';\n this._helpGroupHeading = heading;\n return this;\n }\n\n /**\n * Set/get the default help group heading for subcommands added to this command.\n * (This does not override a group set directly on the subcommand using .helpGroup().)\n *\n * @example\n * program.commandsGroup('Development Commands:);\n * program.command('watch')...\n * program.command('lint')...\n * ...\n *\n * @param {string} [heading]\n * @returns {Command | string}\n */\n commandsGroup(heading) {\n if (heading === undefined) return this._defaultCommandGroup ?? '';\n this._defaultCommandGroup = heading;\n return this;\n }\n\n /**\n * Set/get the default help group heading for options added to this command.\n * (This does not override a group set directly on the option using .helpGroup().)\n *\n * @example\n * program\n * .optionsGroup('Development Options:')\n * .option('-d, --debug', 'output extra debugging')\n * .option('-p, --profile', 'output profiling information')\n *\n * @param {string} [heading]\n * @returns {Command | string}\n */\n optionsGroup(heading) {\n if (heading === undefined) return this._defaultOptionGroup ?? '';\n this._defaultOptionGroup = heading;\n return this;\n }\n\n /**\n * @param {Option} option\n * @private\n */\n _initOptionGroup(option) {\n if (this._defaultOptionGroup && !option.helpGroupHeading)\n option.helpGroup(this._defaultOptionGroup);\n }\n\n /**\n * @param {Command} cmd\n * @private\n */\n _initCommandGroup(cmd) {\n if (this._defaultCommandGroup && !cmd.helpGroup())\n cmd.helpGroup(this._defaultCommandGroup);\n }\n\n /**\n * Set the name of the command from script filename, such as process.argv[1],\n * or require.main.filename, or __filename.\n *\n * (Used internally and public although not documented in README.)\n *\n * @example\n * program.nameFromFilename(require.main.filename);\n *\n * @param {string} filename\n * @return {Command}\n */\n\n nameFromFilename(filename) {\n this._name = path.basename(filename, path.extname(filename));\n\n return this;\n }\n\n /**\n * Get or set the directory for searching for executable subcommands of this command.\n *\n * @example\n * program.executableDir(__dirname);\n * // or\n * program.executableDir('subcommands');\n *\n * @param {string} [path]\n * @return {(string|null|Command)}\n */\n\n executableDir(path) {\n if (path === undefined) return this._executableDir;\n this._executableDir = path;\n return this;\n }\n\n /**\n * Return program help documentation.\n *\n * @param {{ error: boolean }} [contextOptions] - pass {error:true} to wrap for stderr instead of stdout\n * @return {string}\n */\n\n helpInformation(contextOptions) {\n const helper = this.createHelp();\n const context = this._getOutputContext(contextOptions);\n helper.prepareContext({\n error: context.error,\n helpWidth: context.helpWidth,\n outputHasColors: context.hasColors,\n });\n const text = helper.formatHelp(this, helper);\n if (context.hasColors) return text;\n return this._outputConfiguration.stripColor(text);\n }\n\n /**\n * @typedef HelpContext\n * @type {object}\n * @property {boolean} error\n * @property {number} helpWidth\n * @property {boolean} hasColors\n * @property {function} write - includes stripColor if needed\n *\n * @returns {HelpContext}\n * @private\n */\n\n _getOutputContext(contextOptions) {\n contextOptions = contextOptions || {};\n const error = !!contextOptions.error;\n let baseWrite;\n let hasColors;\n let helpWidth;\n if (error) {\n baseWrite = (str) => this._outputConfiguration.writeErr(str);\n hasColors = this._outputConfiguration.getErrHasColors();\n helpWidth = this._outputConfiguration.getErrHelpWidth();\n } else {\n baseWrite = (str) => this._outputConfiguration.writeOut(str);\n hasColors = this._outputConfiguration.getOutHasColors();\n helpWidth = this._outputConfiguration.getOutHelpWidth();\n }\n const write = (str) => {\n if (!hasColors) str = this._outputConfiguration.stripColor(str);\n return baseWrite(str);\n };\n return { error, write, hasColors, helpWidth };\n }\n\n /**\n * Output help information for this command.\n *\n * Outputs built-in help, and custom text added using `.addHelpText()`.\n *\n * @param {{ error: boolean } | Function} [contextOptions] - pass {error:true} to write to stderr instead of stdout\n */\n\n outputHelp(contextOptions) {\n let deprecatedCallback;\n if (typeof contextOptions === 'function') {\n deprecatedCallback = contextOptions;\n contextOptions = undefined;\n }\n\n const outputContext = this._getOutputContext(contextOptions);\n /** @type {HelpTextEventContext} */\n const eventContext = {\n error: outputContext.error,\n write: outputContext.write,\n command: this,\n };\n\n this._getCommandAndAncestors()\n .reverse()\n .forEach((command) => command.emit('beforeAllHelp', eventContext));\n this.emit('beforeHelp', eventContext);\n\n let helpInformation = this.helpInformation({ error: outputContext.error });\n if (deprecatedCallback) {\n helpInformation = deprecatedCallback(helpInformation);\n if (\n typeof helpInformation !== 'string' &&\n !Buffer.isBuffer(helpInformation)\n ) {\n throw new Error('outputHelp callback must return a string or a Buffer');\n }\n }\n outputContext.write(helpInformation);\n\n if (this._getHelpOption()?.long) {\n this.emit(this._getHelpOption().long); // deprecated\n }\n this.emit('afterHelp', eventContext);\n this._getCommandAndAncestors().forEach((command) =>\n command.emit('afterAllHelp', eventContext),\n );\n }\n\n /**\n * You can pass in flags and a description to customise the built-in help option.\n * Pass in false to disable the built-in help option.\n *\n * @example\n * program.helpOption('-?, --help' 'show help'); // customise\n * program.helpOption(false); // disable\n *\n * @param {(string | boolean)} flags\n * @param {string} [description]\n * @return {Command} `this` command for chaining\n */\n\n helpOption(flags, description) {\n // Support enabling/disabling built-in help option.\n if (typeof flags === 'boolean') {\n if (flags) {\n if (this._helpOption === null) this._helpOption = undefined; // reenable\n if (this._defaultOptionGroup) {\n // make the option to store the group\n this._initOptionGroup(this._getHelpOption());\n }\n } else {\n this._helpOption = null; // disable\n }\n return this;\n }\n\n // Customise flags and description.\n this._helpOption = this.createOption(\n flags ?? '-h, --help',\n description ?? 'display help for command',\n );\n // init group unless lazy create\n if (flags || description) this._initOptionGroup(this._helpOption);\n\n return this;\n }\n\n /**\n * Lazy create help option.\n * Returns null if has been disabled with .helpOption(false).\n *\n * @returns {(Option | null)} the help option\n * @package\n */\n _getHelpOption() {\n // Lazy create help option on demand.\n if (this._helpOption === undefined) {\n this.helpOption(undefined, undefined);\n }\n return this._helpOption;\n }\n\n /**\n * Supply your own option to use for the built-in help option.\n * This is an alternative to using helpOption() to customise the flags and description etc.\n *\n * @param {Option} option\n * @return {Command} `this` command for chaining\n */\n addHelpOption(option) {\n this._helpOption = option;\n this._initOptionGroup(option);\n return this;\n }\n\n /**\n * Output help information and exit.\n *\n * Outputs built-in help, and custom text added using `.addHelpText()`.\n *\n * @param {{ error: boolean }} [contextOptions] - pass {error:true} to write to stderr instead of stdout\n */\n\n help(contextOptions) {\n this.outputHelp(contextOptions);\n let exitCode = Number(process.exitCode ?? 0); // process.exitCode does allow a string or an integer, but we prefer just a number\n if (\n exitCode === 0 &&\n contextOptions &&\n typeof contextOptions !== 'function' &&\n contextOptions.error\n ) {\n exitCode = 1;\n }\n // message: do not have all displayed text available so only passing placeholder.\n this._exit(exitCode, 'commander.help', '(outputHelp)');\n }\n\n /**\n * // Do a little typing to coordinate emit and listener for the help text events.\n * @typedef HelpTextEventContext\n * @type {object}\n * @property {boolean} error\n * @property {Command} command\n * @property {function} write\n */\n\n /**\n * Add additional text to be displayed with the built-in help.\n *\n * Position is 'before' or 'after' to affect just this command,\n * and 'beforeAll' or 'afterAll' to affect this command and all its subcommands.\n *\n * @param {string} position - before or after built-in help\n * @param {(string | Function)} text - string to add, or a function returning a string\n * @return {Command} `this` command for chaining\n */\n\n addHelpText(position, text) {\n const allowedValues = ['beforeAll', 'before', 'after', 'afterAll'];\n if (!allowedValues.includes(position)) {\n throw new Error(`Unexpected value for position to addHelpText.\nExpecting one of '${allowedValues.join(\"', '\")}'`);\n }\n\n const helpEvent = `${position}Help`;\n this.on(helpEvent, (/** @type {HelpTextEventContext} */ context) => {\n let helpStr;\n if (typeof text === 'function') {\n helpStr = text({ error: context.error, command: context.command });\n } else {\n helpStr = text;\n }\n // Ignore falsy value when nothing to output.\n if (helpStr) {\n context.write(`${helpStr}\\n`);\n }\n });\n return this;\n }\n\n /**\n * Output help information if help flags specified\n *\n * @param {Array} args - array of options to search for help flags\n * @private\n */\n\n _outputHelpIfRequested(args) {\n const helpOption = this._getHelpOption();\n const helpRequested = helpOption && args.find((arg) => helpOption.is(arg));\n if (helpRequested) {\n this.outputHelp();\n // (Do not have all displayed text available so only passing placeholder.)\n this._exit(0, 'commander.helpDisplayed', '(outputHelp)');\n }\n }\n}\n\n/**\n * Scan arguments and increment port number for inspect calls (to avoid conflicts when spawning new command).\n *\n * @param {string[]} args - array of arguments from node.execArgv\n * @returns {string[]}\n * @private\n */\n\nfunction incrementNodeInspectorPort(args) {\n // Testing for these options:\n // --inspect[=[host:]port]\n // --inspect-brk[=[host:]port]\n // --inspect-port=[host:]port\n return args.map((arg) => {\n if (!arg.startsWith('--inspect')) {\n return arg;\n }\n let debugOption;\n let debugHost = '127.0.0.1';\n let debugPort = '9229';\n let match;\n if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) {\n // e.g. --inspect\n debugOption = match[1];\n } else if (\n (match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null\n ) {\n debugOption = match[1];\n if (/^\\d+$/.test(match[3])) {\n // e.g. --inspect=1234\n debugPort = match[3];\n } else {\n // e.g. --inspect=localhost\n debugHost = match[3];\n }\n } else if (\n (match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\\d+)$/)) !== null\n ) {\n // e.g. --inspect=localhost:1234\n debugOption = match[1];\n debugHost = match[3];\n debugPort = match[4];\n }\n\n if (debugOption && debugPort !== '0') {\n return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;\n }\n return arg;\n });\n}\n\n/**\n * @returns {boolean | undefined}\n * @package\n */\nfunction useColor() {\n // Test for common conventions.\n // NB: the observed behaviour is in combination with how author adds color! For example:\n // - we do not test NODE_DISABLE_COLORS, but util:styletext does\n // - we do test NO_COLOR, but Chalk does not\n //\n // References:\n // https://no-color.org\n // https://bixense.com/clicolors/\n // https://github.com/nodejs/node/blob/0a00217a5f67ef4a22384cfc80eb6dd9a917fdc1/lib/internal/tty.js#L109\n // https://github.com/chalk/supports-color/blob/c214314a14bcb174b12b3014b2b0a8de375029ae/index.js#L33\n // (https://force-color.org recent web page from 2023, does not match major javascript implementations)\n\n if (\n process.env.NO_COLOR ||\n process.env.FORCE_COLOR === '0' ||\n process.env.FORCE_COLOR === 'false'\n )\n return false;\n if (process.env.FORCE_COLOR || process.env.CLICOLOR_FORCE !== undefined)\n return true;\n return undefined;\n}\n\nexports.Command = Command;\nexports.useColor = useColor; // exporting for tests\n",
11
- "const { Argument } = require('./lib/argument.js');\nconst { Command } = require('./lib/command.js');\nconst { CommanderError, InvalidArgumentError } = require('./lib/error.js');\nconst { Help } = require('./lib/help.js');\nconst { Option } = require('./lib/option.js');\n\nexports.program = new Command();\n\nexports.createCommand = (name) => new Command(name);\nexports.createOption = (flags, description) => new Option(flags, description);\nexports.createArgument = (name, description) => new Argument(name, description);\n\n/**\n * Expose classes\n */\n\nexports.Command = Command;\nexports.Option = Option;\nexports.Argument = Argument;\nexports.Help = Help;\n\nexports.CommanderError = CommanderError;\nexports.InvalidArgumentError = InvalidArgumentError;\nexports.InvalidOptionArgumentError = InvalidArgumentError; // Deprecated\n",
12
- "'use strict'\nconst ParserEND = 0x110000\nclass ParserError extends Error {\n /* istanbul ignore next */\n constructor (msg, filename, linenumber) {\n super('[ParserError] ' + msg, filename, linenumber)\n this.name = 'ParserError'\n this.code = 'ParserError'\n if (Error.captureStackTrace) Error.captureStackTrace(this, ParserError)\n }\n}\nclass State {\n constructor (parser) {\n this.parser = parser\n this.buf = ''\n this.returned = null\n this.result = null\n this.resultTable = null\n this.resultArr = null\n }\n}\nclass Parser {\n constructor () {\n this.pos = 0\n this.col = 0\n this.line = 0\n this.obj = {}\n this.ctx = this.obj\n this.stack = []\n this._buf = ''\n this.char = null\n this.ii = 0\n this.state = new State(this.parseStart)\n }\n\n parse (str) {\n /* istanbul ignore next */\n if (str.length === 0 || str.length == null) return\n\n this._buf = String(str)\n this.ii = -1\n this.char = -1\n let getNext\n while (getNext === false || this.nextChar()) {\n getNext = this.runOne()\n }\n this._buf = null\n }\n nextChar () {\n if (this.char === 0x0A) {\n ++this.line\n this.col = -1\n }\n ++this.ii\n this.char = this._buf.codePointAt(this.ii)\n ++this.pos\n ++this.col\n return this.haveBuffer()\n }\n haveBuffer () {\n return this.ii < this._buf.length\n }\n runOne () {\n return this.state.parser.call(this, this.state.returned)\n }\n finish () {\n this.char = ParserEND\n let last\n do {\n last = this.state.parser\n this.runOne()\n } while (this.state.parser !== last)\n\n this.ctx = null\n this.state = null\n this._buf = null\n\n return this.obj\n }\n next (fn) {\n /* istanbul ignore next */\n if (typeof fn !== 'function') throw new ParserError('Tried to set state to non-existent state: ' + JSON.stringify(fn))\n this.state.parser = fn\n }\n goto (fn) {\n this.next(fn)\n return this.runOne()\n }\n call (fn, returnWith) {\n if (returnWith) this.next(returnWith)\n this.stack.push(this.state)\n this.state = new State(fn)\n }\n callNow (fn, returnWith) {\n this.call(fn, returnWith)\n return this.runOne()\n }\n return (value) {\n /* istanbul ignore next */\n if (this.stack.length === 0) throw this.error(new ParserError('Stack underflow'))\n if (value === undefined) value = this.state.buf\n this.state = this.stack.pop()\n this.state.returned = value\n }\n returnNow (value) {\n this.return(value)\n return this.runOne()\n }\n consume () {\n /* istanbul ignore next */\n if (this.char === ParserEND) throw this.error(new ParserError('Unexpected end-of-buffer'))\n this.state.buf += this._buf[this.ii]\n }\n error (err) {\n err.line = this.line\n err.col = this.col\n err.pos = this.pos\n return err\n }\n /* istanbul ignore next */\n parseStart () {\n throw new ParserError('Must declare a parseStart method')\n }\n}\nParser.END = ParserEND\nParser.Error = ParserError\nmodule.exports = Parser\n",
13
- "'use strict'\nmodule.exports = value => {\n const date = new Date(value)\n /* istanbul ignore if */\n if (isNaN(date)) {\n throw new TypeError('Invalid Datetime')\n } else {\n return date\n }\n}\n",
14
- "'use strict'\nmodule.exports = (d, num) => {\n num = String(num)\n while (num.length < d) num = '0' + num\n return num\n}\n",
15
- "'use strict'\nconst f = require('./format-num.js')\n\nclass FloatingDateTime extends Date {\n constructor (value) {\n super(value + 'Z')\n this.isFloating = true\n }\n toISOString () {\n const date = `${this.getUTCFullYear()}-${f(2, this.getUTCMonth() + 1)}-${f(2, this.getUTCDate())}`\n const time = `${f(2, this.getUTCHours())}:${f(2, this.getUTCMinutes())}:${f(2, this.getUTCSeconds())}.${f(3, this.getUTCMilliseconds())}`\n return `${date}T${time}`\n }\n}\n\nmodule.exports = value => {\n const date = new FloatingDateTime(value)\n /* istanbul ignore if */\n if (isNaN(date)) {\n throw new TypeError('Invalid Datetime')\n } else {\n return date\n }\n}\n",
16
- "'use strict'\nconst f = require('./format-num.js')\nconst DateTime = global.Date\n\nclass Date extends DateTime {\n constructor (value) {\n super(value)\n this.isDate = true\n }\n toISOString () {\n return `${this.getUTCFullYear()}-${f(2, this.getUTCMonth() + 1)}-${f(2, this.getUTCDate())}`\n }\n}\n\nmodule.exports = value => {\n const date = new Date(value)\n /* istanbul ignore if */\n if (isNaN(date)) {\n throw new TypeError('Invalid Datetime')\n } else {\n return date\n }\n}\n",
17
- "'use strict'\nconst f = require('./format-num.js')\n\nclass Time extends Date {\n constructor (value) {\n super(`0000-01-01T${value}Z`)\n this.isTime = true\n }\n toISOString () {\n return `${f(2, this.getUTCHours())}:${f(2, this.getUTCMinutes())}:${f(2, this.getUTCSeconds())}.${f(3, this.getUTCMilliseconds())}`\n }\n}\n\nmodule.exports = value => {\n const date = new Time(value)\n /* istanbul ignore if */\n if (isNaN(date)) {\n throw new TypeError('Invalid Datetime')\n } else {\n return date\n }\n}\n",
18
- "'use strict'\n/* eslint-disable no-new-wrappers, no-eval, camelcase, operator-linebreak */\nmodule.exports = makeParserClass(require('./parser.js'))\nmodule.exports.makeParserClass = makeParserClass\n\nclass TomlError extends Error {\n constructor (msg) {\n super(msg)\n this.name = 'TomlError'\n /* istanbul ignore next */\n if (Error.captureStackTrace) Error.captureStackTrace(this, TomlError)\n this.fromTOML = true\n this.wrapped = null\n }\n}\nTomlError.wrap = err => {\n const terr = new TomlError(err.message)\n terr.code = err.code\n terr.wrapped = err\n return terr\n}\nmodule.exports.TomlError = TomlError\n\nconst createDateTime = require('./create-datetime.js')\nconst createDateTimeFloat = require('./create-datetime-float.js')\nconst createDate = require('./create-date.js')\nconst createTime = require('./create-time.js')\n\nconst CTRL_I = 0x09\nconst CTRL_J = 0x0A\nconst CTRL_M = 0x0D\nconst CTRL_CHAR_BOUNDARY = 0x1F // the last non-character in the latin1 region of unicode, except DEL\nconst CHAR_SP = 0x20\nconst CHAR_QUOT = 0x22\nconst CHAR_NUM = 0x23\nconst CHAR_APOS = 0x27\nconst CHAR_PLUS = 0x2B\nconst CHAR_COMMA = 0x2C\nconst CHAR_HYPHEN = 0x2D\nconst CHAR_PERIOD = 0x2E\nconst CHAR_0 = 0x30\nconst CHAR_1 = 0x31\nconst CHAR_7 = 0x37\nconst CHAR_9 = 0x39\nconst CHAR_COLON = 0x3A\nconst CHAR_EQUALS = 0x3D\nconst CHAR_A = 0x41\nconst CHAR_E = 0x45\nconst CHAR_F = 0x46\nconst CHAR_T = 0x54\nconst CHAR_U = 0x55\nconst CHAR_Z = 0x5A\nconst CHAR_LOWBAR = 0x5F\nconst CHAR_a = 0x61\nconst CHAR_b = 0x62\nconst CHAR_e = 0x65\nconst CHAR_f = 0x66\nconst CHAR_i = 0x69\nconst CHAR_l = 0x6C\nconst CHAR_n = 0x6E\nconst CHAR_o = 0x6F\nconst CHAR_r = 0x72\nconst CHAR_s = 0x73\nconst CHAR_t = 0x74\nconst CHAR_u = 0x75\nconst CHAR_x = 0x78\nconst CHAR_z = 0x7A\nconst CHAR_LCUB = 0x7B\nconst CHAR_RCUB = 0x7D\nconst CHAR_LSQB = 0x5B\nconst CHAR_BSOL = 0x5C\nconst CHAR_RSQB = 0x5D\nconst CHAR_DEL = 0x7F\nconst SURROGATE_FIRST = 0xD800\nconst SURROGATE_LAST = 0xDFFF\n\nconst escapes = {\n [CHAR_b]: '\\u0008',\n [CHAR_t]: '\\u0009',\n [CHAR_n]: '\\u000A',\n [CHAR_f]: '\\u000C',\n [CHAR_r]: '\\u000D',\n [CHAR_QUOT]: '\\u0022',\n [CHAR_BSOL]: '\\u005C'\n}\n\nfunction isDigit (cp) {\n return cp >= CHAR_0 && cp <= CHAR_9\n}\nfunction isHexit (cp) {\n return (cp >= CHAR_A && cp <= CHAR_F) || (cp >= CHAR_a && cp <= CHAR_f) || (cp >= CHAR_0 && cp <= CHAR_9)\n}\nfunction isBit (cp) {\n return cp === CHAR_1 || cp === CHAR_0\n}\nfunction isOctit (cp) {\n return (cp >= CHAR_0 && cp <= CHAR_7)\n}\nfunction isAlphaNumQuoteHyphen (cp) {\n return (cp >= CHAR_A && cp <= CHAR_Z)\n || (cp >= CHAR_a && cp <= CHAR_z)\n || (cp >= CHAR_0 && cp <= CHAR_9)\n || cp === CHAR_APOS\n || cp === CHAR_QUOT\n || cp === CHAR_LOWBAR\n || cp === CHAR_HYPHEN\n}\nfunction isAlphaNumHyphen (cp) {\n return (cp >= CHAR_A && cp <= CHAR_Z)\n || (cp >= CHAR_a && cp <= CHAR_z)\n || (cp >= CHAR_0 && cp <= CHAR_9)\n || cp === CHAR_LOWBAR\n || cp === CHAR_HYPHEN\n}\nconst _type = Symbol('type')\nconst _declared = Symbol('declared')\n\nconst hasOwnProperty = Object.prototype.hasOwnProperty\nconst defineProperty = Object.defineProperty\nconst descriptor = {configurable: true, enumerable: true, writable: true, value: undefined}\n\nfunction hasKey (obj, key) {\n if (hasOwnProperty.call(obj, key)) return true\n if (key === '__proto__') defineProperty(obj, '__proto__', descriptor)\n return false\n}\n\nconst INLINE_TABLE = Symbol('inline-table')\nfunction InlineTable () {\n return Object.defineProperties({}, {\n [_type]: {value: INLINE_TABLE}\n })\n}\nfunction isInlineTable (obj) {\n if (obj === null || typeof (obj) !== 'object') return false\n return obj[_type] === INLINE_TABLE\n}\n\nconst TABLE = Symbol('table')\nfunction Table () {\n return Object.defineProperties({}, {\n [_type]: {value: TABLE},\n [_declared]: {value: false, writable: true}\n })\n}\nfunction isTable (obj) {\n if (obj === null || typeof (obj) !== 'object') return false\n return obj[_type] === TABLE\n}\n\nconst _contentType = Symbol('content-type')\nconst INLINE_LIST = Symbol('inline-list')\nfunction InlineList (type) {\n return Object.defineProperties([], {\n [_type]: {value: INLINE_LIST},\n [_contentType]: {value: type}\n })\n}\nfunction isInlineList (obj) {\n if (obj === null || typeof (obj) !== 'object') return false\n return obj[_type] === INLINE_LIST\n}\n\nconst LIST = Symbol('list')\nfunction List () {\n return Object.defineProperties([], {\n [_type]: {value: LIST}\n })\n}\nfunction isList (obj) {\n if (obj === null || typeof (obj) !== 'object') return false\n return obj[_type] === LIST\n}\n\n// in an eval, to let bundlers not slurp in a util proxy\nlet _custom\ntry {\n const utilInspect = eval(\"require('util').inspect\")\n _custom = utilInspect.custom\n} catch (_) {\n /* eval require not available in transpiled bundle */\n}\n/* istanbul ignore next */\nconst _inspect = _custom || 'inspect'\n\nclass BoxedBigInt {\n constructor (value) {\n try {\n this.value = global.BigInt.asIntN(64, value)\n } catch (_) {\n /* istanbul ignore next */\n this.value = null\n }\n Object.defineProperty(this, _type, {value: INTEGER})\n }\n isNaN () {\n return this.value === null\n }\n /* istanbul ignore next */\n toString () {\n return String(this.value)\n }\n /* istanbul ignore next */\n [_inspect] () {\n return `[BigInt: ${this.toString()}]}`\n }\n valueOf () {\n return this.value\n }\n}\n\nconst INTEGER = Symbol('integer')\nfunction Integer (value) {\n let num = Number(value)\n // -0 is a float thing, not an int thing\n if (Object.is(num, -0)) num = 0\n /* istanbul ignore else */\n if (global.BigInt && !Number.isSafeInteger(num)) {\n return new BoxedBigInt(value)\n } else {\n /* istanbul ignore next */\n return Object.defineProperties(new Number(num), {\n isNaN: {value: function () { return isNaN(this) }},\n [_type]: {value: INTEGER},\n [_inspect]: {value: () => `[Integer: ${value}]`}\n })\n }\n}\nfunction isInteger (obj) {\n if (obj === null || typeof (obj) !== 'object') return false\n return obj[_type] === INTEGER\n}\n\nconst FLOAT = Symbol('float')\nfunction Float (value) {\n /* istanbul ignore next */\n return Object.defineProperties(new Number(value), {\n [_type]: {value: FLOAT},\n [_inspect]: {value: () => `[Float: ${value}]`}\n })\n}\nfunction isFloat (obj) {\n if (obj === null || typeof (obj) !== 'object') return false\n return obj[_type] === FLOAT\n}\n\nfunction tomlType (value) {\n const type = typeof value\n if (type === 'object') {\n /* istanbul ignore if */\n if (value === null) return 'null'\n if (value instanceof Date) return 'datetime'\n /* istanbul ignore else */\n if (_type in value) {\n switch (value[_type]) {\n case INLINE_TABLE: return 'inline-table'\n case INLINE_LIST: return 'inline-list'\n /* istanbul ignore next */\n case TABLE: return 'table'\n /* istanbul ignore next */\n case LIST: return 'list'\n case FLOAT: return 'float'\n case INTEGER: return 'integer'\n }\n }\n }\n return type\n}\n\nfunction makeParserClass (Parser) {\n class TOMLParser extends Parser {\n constructor () {\n super()\n this.ctx = this.obj = Table()\n }\n\n /* MATCH HELPER */\n atEndOfWord () {\n return this.char === CHAR_NUM || this.char === CTRL_I || this.char === CHAR_SP || this.atEndOfLine()\n }\n atEndOfLine () {\n return this.char === Parser.END || this.char === CTRL_J || this.char === CTRL_M\n }\n\n parseStart () {\n if (this.char === Parser.END) {\n return null\n } else if (this.char === CHAR_LSQB) {\n return this.call(this.parseTableOrList)\n } else if (this.char === CHAR_NUM) {\n return this.call(this.parseComment)\n } else if (this.char === CTRL_J || this.char === CHAR_SP || this.char === CTRL_I || this.char === CTRL_M) {\n return null\n } else if (isAlphaNumQuoteHyphen(this.char)) {\n return this.callNow(this.parseAssignStatement)\n } else {\n throw this.error(new TomlError(`Unknown character \"${this.char}\"`))\n }\n }\n\n // HELPER, this strips any whitespace and comments to the end of the line\n // then RETURNS. Last state in a production.\n parseWhitespaceToEOL () {\n if (this.char === CHAR_SP || this.char === CTRL_I || this.char === CTRL_M) {\n return null\n } else if (this.char === CHAR_NUM) {\n return this.goto(this.parseComment)\n } else if (this.char === Parser.END || this.char === CTRL_J) {\n return this.return()\n } else {\n throw this.error(new TomlError('Unexpected character, expected only whitespace or comments till end of line'))\n }\n }\n\n /* ASSIGNMENT: key = value */\n parseAssignStatement () {\n return this.callNow(this.parseAssign, this.recordAssignStatement)\n }\n recordAssignStatement (kv) {\n let target = this.ctx\n let finalKey = kv.key.pop()\n for (let kw of kv.key) {\n if (hasKey(target, kw) && (!isTable(target[kw]) || target[kw][_declared])) {\n throw this.error(new TomlError(\"Can't redefine existing key\"))\n }\n target = target[kw] = target[kw] || Table()\n }\n if (hasKey(target, finalKey)) {\n throw this.error(new TomlError(\"Can't redefine existing key\"))\n }\n // unbox our numbers\n if (isInteger(kv.value) || isFloat(kv.value)) {\n target[finalKey] = kv.value.valueOf()\n } else {\n target[finalKey] = kv.value\n }\n return this.goto(this.parseWhitespaceToEOL)\n }\n\n /* ASSSIGNMENT expression, key = value possibly inside an inline table */\n parseAssign () {\n return this.callNow(this.parseKeyword, this.recordAssignKeyword)\n }\n recordAssignKeyword (key) {\n if (this.state.resultTable) {\n this.state.resultTable.push(key)\n } else {\n this.state.resultTable = [key]\n }\n return this.goto(this.parseAssignKeywordPreDot)\n }\n parseAssignKeywordPreDot () {\n if (this.char === CHAR_PERIOD) {\n return this.next(this.parseAssignKeywordPostDot)\n } else if (this.char !== CHAR_SP && this.char !== CTRL_I) {\n return this.goto(this.parseAssignEqual)\n }\n }\n parseAssignKeywordPostDot () {\n if (this.char !== CHAR_SP && this.char !== CTRL_I) {\n return this.callNow(this.parseKeyword, this.recordAssignKeyword)\n }\n }\n\n parseAssignEqual () {\n if (this.char === CHAR_EQUALS) {\n return this.next(this.parseAssignPreValue)\n } else {\n throw this.error(new TomlError('Invalid character, expected \"=\"'))\n }\n }\n parseAssignPreValue () {\n if (this.char === CHAR_SP || this.char === CTRL_I) {\n return null\n } else {\n return this.callNow(this.parseValue, this.recordAssignValue)\n }\n }\n recordAssignValue (value) {\n return this.returnNow({key: this.state.resultTable, value: value})\n }\n\n /* COMMENTS: #...eol */\n parseComment () {\n do {\n if (this.char === Parser.END || this.char === CTRL_J) {\n return this.return()\n }\n } while (this.nextChar())\n }\n\n /* TABLES AND LISTS, [foo] and [[foo]] */\n parseTableOrList () {\n if (this.char === CHAR_LSQB) {\n this.next(this.parseList)\n } else {\n return this.goto(this.parseTable)\n }\n }\n\n /* TABLE [foo.bar.baz] */\n parseTable () {\n this.ctx = this.obj\n return this.goto(this.parseTableNext)\n }\n parseTableNext () {\n if (this.char === CHAR_SP || this.char === CTRL_I) {\n return null\n } else {\n return this.callNow(this.parseKeyword, this.parseTableMore)\n }\n }\n parseTableMore (keyword) {\n if (this.char === CHAR_SP || this.char === CTRL_I) {\n return null\n } else if (this.char === CHAR_RSQB) {\n if (hasKey(this.ctx, keyword) && (!isTable(this.ctx[keyword]) || this.ctx[keyword][_declared])) {\n throw this.error(new TomlError(\"Can't redefine existing key\"))\n } else {\n this.ctx = this.ctx[keyword] = this.ctx[keyword] || Table()\n this.ctx[_declared] = true\n }\n return this.next(this.parseWhitespaceToEOL)\n } else if (this.char === CHAR_PERIOD) {\n if (!hasKey(this.ctx, keyword)) {\n this.ctx = this.ctx[keyword] = Table()\n } else if (isTable(this.ctx[keyword])) {\n this.ctx = this.ctx[keyword]\n } else if (isList(this.ctx[keyword])) {\n this.ctx = this.ctx[keyword][this.ctx[keyword].length - 1]\n } else {\n throw this.error(new TomlError(\"Can't redefine existing key\"))\n }\n return this.next(this.parseTableNext)\n } else {\n throw this.error(new TomlError('Unexpected character, expected whitespace, . or ]'))\n }\n }\n\n /* LIST [[a.b.c]] */\n parseList () {\n this.ctx = this.obj\n return this.goto(this.parseListNext)\n }\n parseListNext () {\n if (this.char === CHAR_SP || this.char === CTRL_I) {\n return null\n } else {\n return this.callNow(this.parseKeyword, this.parseListMore)\n }\n }\n parseListMore (keyword) {\n if (this.char === CHAR_SP || this.char === CTRL_I) {\n return null\n } else if (this.char === CHAR_RSQB) {\n if (!hasKey(this.ctx, keyword)) {\n this.ctx[keyword] = List()\n }\n if (isInlineList(this.ctx[keyword])) {\n throw this.error(new TomlError(\"Can't extend an inline array\"))\n } else if (isList(this.ctx[keyword])) {\n const next = Table()\n this.ctx[keyword].push(next)\n this.ctx = next\n } else {\n throw this.error(new TomlError(\"Can't redefine an existing key\"))\n }\n return this.next(this.parseListEnd)\n } else if (this.char === CHAR_PERIOD) {\n if (!hasKey(this.ctx, keyword)) {\n this.ctx = this.ctx[keyword] = Table()\n } else if (isInlineList(this.ctx[keyword])) {\n throw this.error(new TomlError(\"Can't extend an inline array\"))\n } else if (isInlineTable(this.ctx[keyword])) {\n throw this.error(new TomlError(\"Can't extend an inline table\"))\n } else if (isList(this.ctx[keyword])) {\n this.ctx = this.ctx[keyword][this.ctx[keyword].length - 1]\n } else if (isTable(this.ctx[keyword])) {\n this.ctx = this.ctx[keyword]\n } else {\n throw this.error(new TomlError(\"Can't redefine an existing key\"))\n }\n return this.next(this.parseListNext)\n } else {\n throw this.error(new TomlError('Unexpected character, expected whitespace, . or ]'))\n }\n }\n parseListEnd (keyword) {\n if (this.char === CHAR_RSQB) {\n return this.next(this.parseWhitespaceToEOL)\n } else {\n throw this.error(new TomlError('Unexpected character, expected whitespace, . or ]'))\n }\n }\n\n /* VALUE string, number, boolean, inline list, inline object */\n parseValue () {\n if (this.char === Parser.END) {\n throw this.error(new TomlError('Key without value'))\n } else if (this.char === CHAR_QUOT) {\n return this.next(this.parseDoubleString)\n } if (this.char === CHAR_APOS) {\n return this.next(this.parseSingleString)\n } else if (this.char === CHAR_HYPHEN || this.char === CHAR_PLUS) {\n return this.goto(this.parseNumberSign)\n } else if (this.char === CHAR_i) {\n return this.next(this.parseInf)\n } else if (this.char === CHAR_n) {\n return this.next(this.parseNan)\n } else if (isDigit(this.char)) {\n return this.goto(this.parseNumberOrDateTime)\n } else if (this.char === CHAR_t || this.char === CHAR_f) {\n return this.goto(this.parseBoolean)\n } else if (this.char === CHAR_LSQB) {\n return this.call(this.parseInlineList, this.recordValue)\n } else if (this.char === CHAR_LCUB) {\n return this.call(this.parseInlineTable, this.recordValue)\n } else {\n throw this.error(new TomlError('Unexpected character, expecting string, number, datetime, boolean, inline array or inline table'))\n }\n }\n recordValue (value) {\n return this.returnNow(value)\n }\n\n parseInf () {\n if (this.char === CHAR_n) {\n return this.next(this.parseInf2)\n } else {\n throw this.error(new TomlError('Unexpected character, expected \"inf\", \"+inf\" or \"-inf\"'))\n }\n }\n parseInf2 () {\n if (this.char === CHAR_f) {\n if (this.state.buf === '-') {\n return this.return(-Infinity)\n } else {\n return this.return(Infinity)\n }\n } else {\n throw this.error(new TomlError('Unexpected character, expected \"inf\", \"+inf\" or \"-inf\"'))\n }\n }\n\n parseNan () {\n if (this.char === CHAR_a) {\n return this.next(this.parseNan2)\n } else {\n throw this.error(new TomlError('Unexpected character, expected \"nan\"'))\n }\n }\n parseNan2 () {\n if (this.char === CHAR_n) {\n return this.return(NaN)\n } else {\n throw this.error(new TomlError('Unexpected character, expected \"nan\"'))\n }\n }\n\n /* KEYS, barewords or basic, literal, or dotted */\n parseKeyword () {\n if (this.char === CHAR_QUOT) {\n return this.next(this.parseBasicString)\n } else if (this.char === CHAR_APOS) {\n return this.next(this.parseLiteralString)\n } else {\n return this.goto(this.parseBareKey)\n }\n }\n\n /* KEYS: barewords */\n parseBareKey () {\n do {\n if (this.char === Parser.END) {\n throw this.error(new TomlError('Key ended without value'))\n } else if (isAlphaNumHyphen(this.char)) {\n this.consume()\n } else if (this.state.buf.length === 0) {\n throw this.error(new TomlError('Empty bare keys are not allowed'))\n } else {\n return this.returnNow()\n }\n } while (this.nextChar())\n }\n\n /* STRINGS, single quoted (literal) */\n parseSingleString () {\n if (this.char === CHAR_APOS) {\n return this.next(this.parseLiteralMultiStringMaybe)\n } else {\n return this.goto(this.parseLiteralString)\n }\n }\n parseLiteralString () {\n do {\n if (this.char === CHAR_APOS) {\n return this.return()\n } else if (this.atEndOfLine()) {\n throw this.error(new TomlError('Unterminated string'))\n } else if (this.char === CHAR_DEL || (this.char <= CTRL_CHAR_BOUNDARY && this.char !== CTRL_I)) {\n throw this.errorControlCharInString()\n } else {\n this.consume()\n }\n } while (this.nextChar())\n }\n parseLiteralMultiStringMaybe () {\n if (this.char === CHAR_APOS) {\n return this.next(this.parseLiteralMultiString)\n } else {\n return this.returnNow()\n }\n }\n parseLiteralMultiString () {\n if (this.char === CTRL_M) {\n return null\n } else if (this.char === CTRL_J) {\n return this.next(this.parseLiteralMultiStringContent)\n } else {\n return this.goto(this.parseLiteralMultiStringContent)\n }\n }\n parseLiteralMultiStringContent () {\n do {\n if (this.char === CHAR_APOS) {\n return this.next(this.parseLiteralMultiEnd)\n } else if (this.char === Parser.END) {\n throw this.error(new TomlError('Unterminated multi-line string'))\n } else if (this.char === CHAR_DEL || (this.char <= CTRL_CHAR_BOUNDARY && this.char !== CTRL_I && this.char !== CTRL_J && this.char !== CTRL_M)) {\n throw this.errorControlCharInString()\n } else {\n this.consume()\n }\n } while (this.nextChar())\n }\n parseLiteralMultiEnd () {\n if (this.char === CHAR_APOS) {\n return this.next(this.parseLiteralMultiEnd2)\n } else {\n this.state.buf += \"'\"\n return this.goto(this.parseLiteralMultiStringContent)\n }\n }\n parseLiteralMultiEnd2 () {\n if (this.char === CHAR_APOS) {\n return this.return()\n } else {\n this.state.buf += \"''\"\n return this.goto(this.parseLiteralMultiStringContent)\n }\n }\n\n /* STRINGS double quoted */\n parseDoubleString () {\n if (this.char === CHAR_QUOT) {\n return this.next(this.parseMultiStringMaybe)\n } else {\n return this.goto(this.parseBasicString)\n }\n }\n parseBasicString () {\n do {\n if (this.char === CHAR_BSOL) {\n return this.call(this.parseEscape, this.recordEscapeReplacement)\n } else if (this.char === CHAR_QUOT) {\n return this.return()\n } else if (this.atEndOfLine()) {\n throw this.error(new TomlError('Unterminated string'))\n } else if (this.char === CHAR_DEL || (this.char <= CTRL_CHAR_BOUNDARY && this.char !== CTRL_I)) {\n throw this.errorControlCharInString()\n } else {\n this.consume()\n }\n } while (this.nextChar())\n }\n recordEscapeReplacement (replacement) {\n this.state.buf += replacement\n return this.goto(this.parseBasicString)\n }\n parseMultiStringMaybe () {\n if (this.char === CHAR_QUOT) {\n return this.next(this.parseMultiString)\n } else {\n return this.returnNow()\n }\n }\n parseMultiString () {\n if (this.char === CTRL_M) {\n return null\n } else if (this.char === CTRL_J) {\n return this.next(this.parseMultiStringContent)\n } else {\n return this.goto(this.parseMultiStringContent)\n }\n }\n parseMultiStringContent () {\n do {\n if (this.char === CHAR_BSOL) {\n return this.call(this.parseMultiEscape, this.recordMultiEscapeReplacement)\n } else if (this.char === CHAR_QUOT) {\n return this.next(this.parseMultiEnd)\n } else if (this.char === Parser.END) {\n throw this.error(new TomlError('Unterminated multi-line string'))\n } else if (this.char === CHAR_DEL || (this.char <= CTRL_CHAR_BOUNDARY && this.char !== CTRL_I && this.char !== CTRL_J && this.char !== CTRL_M)) {\n throw this.errorControlCharInString()\n } else {\n this.consume()\n }\n } while (this.nextChar())\n }\n errorControlCharInString () {\n let displayCode = '\\\\u00'\n if (this.char < 16) {\n displayCode += '0'\n }\n displayCode += this.char.toString(16)\n\n return this.error(new TomlError(`Control characters (codes < 0x1f and 0x7f) are not allowed in strings, use ${displayCode} instead`))\n }\n recordMultiEscapeReplacement (replacement) {\n this.state.buf += replacement\n return this.goto(this.parseMultiStringContent)\n }\n parseMultiEnd () {\n if (this.char === CHAR_QUOT) {\n return this.next(this.parseMultiEnd2)\n } else {\n this.state.buf += '\"'\n return this.goto(this.parseMultiStringContent)\n }\n }\n parseMultiEnd2 () {\n if (this.char === CHAR_QUOT) {\n return this.return()\n } else {\n this.state.buf += '\"\"'\n return this.goto(this.parseMultiStringContent)\n }\n }\n parseMultiEscape () {\n if (this.char === CTRL_M || this.char === CTRL_J) {\n return this.next(this.parseMultiTrim)\n } else if (this.char === CHAR_SP || this.char === CTRL_I) {\n return this.next(this.parsePreMultiTrim)\n } else {\n return this.goto(this.parseEscape)\n }\n }\n parsePreMultiTrim () {\n if (this.char === CHAR_SP || this.char === CTRL_I) {\n return null\n } else if (this.char === CTRL_M || this.char === CTRL_J) {\n return this.next(this.parseMultiTrim)\n } else {\n throw this.error(new TomlError(\"Can't escape whitespace\"))\n }\n }\n parseMultiTrim () {\n // explicitly whitespace here, END should follow the same path as chars\n if (this.char === CTRL_J || this.char === CHAR_SP || this.char === CTRL_I || this.char === CTRL_M) {\n return null\n } else {\n return this.returnNow()\n }\n }\n parseEscape () {\n if (this.char in escapes) {\n return this.return(escapes[this.char])\n } else if (this.char === CHAR_u) {\n return this.call(this.parseSmallUnicode, this.parseUnicodeReturn)\n } else if (this.char === CHAR_U) {\n return this.call(this.parseLargeUnicode, this.parseUnicodeReturn)\n } else {\n throw this.error(new TomlError('Unknown escape character: ' + this.char))\n }\n }\n parseUnicodeReturn (char) {\n try {\n const codePoint = parseInt(char, 16)\n if (codePoint >= SURROGATE_FIRST && codePoint <= SURROGATE_LAST) {\n throw this.error(new TomlError('Invalid unicode, character in range 0xD800 - 0xDFFF is reserved'))\n }\n return this.returnNow(String.fromCodePoint(codePoint))\n } catch (err) {\n throw this.error(TomlError.wrap(err))\n }\n }\n parseSmallUnicode () {\n if (!isHexit(this.char)) {\n throw this.error(new TomlError('Invalid character in unicode sequence, expected hex'))\n } else {\n this.consume()\n if (this.state.buf.length >= 4) return this.return()\n }\n }\n parseLargeUnicode () {\n if (!isHexit(this.char)) {\n throw this.error(new TomlError('Invalid character in unicode sequence, expected hex'))\n } else {\n this.consume()\n if (this.state.buf.length >= 8) return this.return()\n }\n }\n\n /* NUMBERS */\n parseNumberSign () {\n this.consume()\n return this.next(this.parseMaybeSignedInfOrNan)\n }\n parseMaybeSignedInfOrNan () {\n if (this.char === CHAR_i) {\n return this.next(this.parseInf)\n } else if (this.char === CHAR_n) {\n return this.next(this.parseNan)\n } else {\n return this.callNow(this.parseNoUnder, this.parseNumberIntegerStart)\n }\n }\n parseNumberIntegerStart () {\n if (this.char === CHAR_0) {\n this.consume()\n return this.next(this.parseNumberIntegerExponentOrDecimal)\n } else {\n return this.goto(this.parseNumberInteger)\n }\n }\n parseNumberIntegerExponentOrDecimal () {\n if (this.char === CHAR_PERIOD) {\n this.consume()\n return this.call(this.parseNoUnder, this.parseNumberFloat)\n } else if (this.char === CHAR_E || this.char === CHAR_e) {\n this.consume()\n return this.next(this.parseNumberExponentSign)\n } else {\n return this.returnNow(Integer(this.state.buf))\n }\n }\n parseNumberInteger () {\n if (isDigit(this.char)) {\n this.consume()\n } else if (this.char === CHAR_LOWBAR) {\n return this.call(this.parseNoUnder)\n } else if (this.char === CHAR_E || this.char === CHAR_e) {\n this.consume()\n return this.next(this.parseNumberExponentSign)\n } else if (this.char === CHAR_PERIOD) {\n this.consume()\n return this.call(this.parseNoUnder, this.parseNumberFloat)\n } else {\n const result = Integer(this.state.buf)\n /* istanbul ignore if */\n if (result.isNaN()) {\n throw this.error(new TomlError('Invalid number'))\n } else {\n return this.returnNow(result)\n }\n }\n }\n parseNoUnder () {\n if (this.char === CHAR_LOWBAR || this.char === CHAR_PERIOD || this.char === CHAR_E || this.char === CHAR_e) {\n throw this.error(new TomlError('Unexpected character, expected digit'))\n } else if (this.atEndOfWord()) {\n throw this.error(new TomlError('Incomplete number'))\n }\n return this.returnNow()\n }\n parseNoUnderHexOctBinLiteral () {\n if (this.char === CHAR_LOWBAR || this.char === CHAR_PERIOD) {\n throw this.error(new TomlError('Unexpected character, expected digit'))\n } else if (this.atEndOfWord()) {\n throw this.error(new TomlError('Incomplete number'))\n }\n return this.returnNow()\n }\n parseNumberFloat () {\n if (this.char === CHAR_LOWBAR) {\n return this.call(this.parseNoUnder, this.parseNumberFloat)\n } else if (isDigit(this.char)) {\n this.consume()\n } else if (this.char === CHAR_E || this.char === CHAR_e) {\n this.consume()\n return this.next(this.parseNumberExponentSign)\n } else {\n return this.returnNow(Float(this.state.buf))\n }\n }\n parseNumberExponentSign () {\n if (isDigit(this.char)) {\n return this.goto(this.parseNumberExponent)\n } else if (this.char === CHAR_HYPHEN || this.char === CHAR_PLUS) {\n this.consume()\n this.call(this.parseNoUnder, this.parseNumberExponent)\n } else {\n throw this.error(new TomlError('Unexpected character, expected -, + or digit'))\n }\n }\n parseNumberExponent () {\n if (isDigit(this.char)) {\n this.consume()\n } else if (this.char === CHAR_LOWBAR) {\n return this.call(this.parseNoUnder)\n } else {\n return this.returnNow(Float(this.state.buf))\n }\n }\n\n /* NUMBERS or DATETIMES */\n parseNumberOrDateTime () {\n if (this.char === CHAR_0) {\n this.consume()\n return this.next(this.parseNumberBaseOrDateTime)\n } else {\n return this.goto(this.parseNumberOrDateTimeOnly)\n }\n }\n parseNumberOrDateTimeOnly () {\n // note, if two zeros are in a row then it MUST be a date\n if (this.char === CHAR_LOWBAR) {\n return this.call(this.parseNoUnder, this.parseNumberInteger)\n } else if (isDigit(this.char)) {\n this.consume()\n if (this.state.buf.length > 4) this.next(this.parseNumberInteger)\n } else if (this.char === CHAR_E || this.char === CHAR_e) {\n this.consume()\n return this.next(this.parseNumberExponentSign)\n } else if (this.char === CHAR_PERIOD) {\n this.consume()\n return this.call(this.parseNoUnder, this.parseNumberFloat)\n } else if (this.char === CHAR_HYPHEN) {\n return this.goto(this.parseDateTime)\n } else if (this.char === CHAR_COLON) {\n return this.goto(this.parseOnlyTimeHour)\n } else {\n return this.returnNow(Integer(this.state.buf))\n }\n }\n parseDateTimeOnly () {\n if (this.state.buf.length < 4) {\n if (isDigit(this.char)) {\n return this.consume()\n } else if (this.char === CHAR_COLON) {\n return this.goto(this.parseOnlyTimeHour)\n } else {\n throw this.error(new TomlError('Expected digit while parsing year part of a date'))\n }\n } else {\n if (this.char === CHAR_HYPHEN) {\n return this.goto(this.parseDateTime)\n } else {\n throw this.error(new TomlError('Expected hyphen (-) while parsing year part of date'))\n }\n }\n }\n parseNumberBaseOrDateTime () {\n if (this.char === CHAR_b) {\n this.consume()\n return this.call(this.parseNoUnderHexOctBinLiteral, this.parseIntegerBin)\n } else if (this.char === CHAR_o) {\n this.consume()\n return this.call(this.parseNoUnderHexOctBinLiteral, this.parseIntegerOct)\n } else if (this.char === CHAR_x) {\n this.consume()\n return this.call(this.parseNoUnderHexOctBinLiteral, this.parseIntegerHex)\n } else if (this.char === CHAR_PERIOD) {\n return this.goto(this.parseNumberInteger)\n } else if (isDigit(this.char)) {\n return this.goto(this.parseDateTimeOnly)\n } else {\n return this.returnNow(Integer(this.state.buf))\n }\n }\n parseIntegerHex () {\n if (isHexit(this.char)) {\n this.consume()\n } else if (this.char === CHAR_LOWBAR) {\n return this.call(this.parseNoUnderHexOctBinLiteral)\n } else {\n const result = Integer(this.state.buf)\n /* istanbul ignore if */\n if (result.isNaN()) {\n throw this.error(new TomlError('Invalid number'))\n } else {\n return this.returnNow(result)\n }\n }\n }\n parseIntegerOct () {\n if (isOctit(this.char)) {\n this.consume()\n } else if (this.char === CHAR_LOWBAR) {\n return this.call(this.parseNoUnderHexOctBinLiteral)\n } else {\n const result = Integer(this.state.buf)\n /* istanbul ignore if */\n if (result.isNaN()) {\n throw this.error(new TomlError('Invalid number'))\n } else {\n return this.returnNow(result)\n }\n }\n }\n parseIntegerBin () {\n if (isBit(this.char)) {\n this.consume()\n } else if (this.char === CHAR_LOWBAR) {\n return this.call(this.parseNoUnderHexOctBinLiteral)\n } else {\n const result = Integer(this.state.buf)\n /* istanbul ignore if */\n if (result.isNaN()) {\n throw this.error(new TomlError('Invalid number'))\n } else {\n return this.returnNow(result)\n }\n }\n }\n\n /* DATETIME */\n parseDateTime () {\n // we enter here having just consumed the year and about to consume the hyphen\n if (this.state.buf.length < 4) {\n throw this.error(new TomlError('Years less than 1000 must be zero padded to four characters'))\n }\n this.state.result = this.state.buf\n this.state.buf = ''\n return this.next(this.parseDateMonth)\n }\n parseDateMonth () {\n if (this.char === CHAR_HYPHEN) {\n if (this.state.buf.length < 2) {\n throw this.error(new TomlError('Months less than 10 must be zero padded to two characters'))\n }\n this.state.result += '-' + this.state.buf\n this.state.buf = ''\n return this.next(this.parseDateDay)\n } else if (isDigit(this.char)) {\n this.consume()\n } else {\n throw this.error(new TomlError('Incomplete datetime'))\n }\n }\n parseDateDay () {\n if (this.char === CHAR_T || this.char === CHAR_SP) {\n if (this.state.buf.length < 2) {\n throw this.error(new TomlError('Days less than 10 must be zero padded to two characters'))\n }\n this.state.result += '-' + this.state.buf\n this.state.buf = ''\n return this.next(this.parseStartTimeHour)\n } else if (this.atEndOfWord()) {\n return this.returnNow(createDate(this.state.result + '-' + this.state.buf))\n } else if (isDigit(this.char)) {\n this.consume()\n } else {\n throw this.error(new TomlError('Incomplete datetime'))\n }\n }\n parseStartTimeHour () {\n if (this.atEndOfWord()) {\n return this.returnNow(createDate(this.state.result))\n } else {\n return this.goto(this.parseTimeHour)\n }\n }\n parseTimeHour () {\n if (this.char === CHAR_COLON) {\n if (this.state.buf.length < 2) {\n throw this.error(new TomlError('Hours less than 10 must be zero padded to two characters'))\n }\n this.state.result += 'T' + this.state.buf\n this.state.buf = ''\n return this.next(this.parseTimeMin)\n } else if (isDigit(this.char)) {\n this.consume()\n } else {\n throw this.error(new TomlError('Incomplete datetime'))\n }\n }\n parseTimeMin () {\n if (this.state.buf.length < 2 && isDigit(this.char)) {\n this.consume()\n } else if (this.state.buf.length === 2 && this.char === CHAR_COLON) {\n this.state.result += ':' + this.state.buf\n this.state.buf = ''\n return this.next(this.parseTimeSec)\n } else {\n throw this.error(new TomlError('Incomplete datetime'))\n }\n }\n parseTimeSec () {\n if (isDigit(this.char)) {\n this.consume()\n if (this.state.buf.length === 2) {\n this.state.result += ':' + this.state.buf\n this.state.buf = ''\n return this.next(this.parseTimeZoneOrFraction)\n }\n } else {\n throw this.error(new TomlError('Incomplete datetime'))\n }\n }\n\n parseOnlyTimeHour () {\n /* istanbul ignore else */\n if (this.char === CHAR_COLON) {\n if (this.state.buf.length < 2) {\n throw this.error(new TomlError('Hours less than 10 must be zero padded to two characters'))\n }\n this.state.result = this.state.buf\n this.state.buf = ''\n return this.next(this.parseOnlyTimeMin)\n } else {\n throw this.error(new TomlError('Incomplete time'))\n }\n }\n parseOnlyTimeMin () {\n if (this.state.buf.length < 2 && isDigit(this.char)) {\n this.consume()\n } else if (this.state.buf.length === 2 && this.char === CHAR_COLON) {\n this.state.result += ':' + this.state.buf\n this.state.buf = ''\n return this.next(this.parseOnlyTimeSec)\n } else {\n throw this.error(new TomlError('Incomplete time'))\n }\n }\n parseOnlyTimeSec () {\n if (isDigit(this.char)) {\n this.consume()\n if (this.state.buf.length === 2) {\n return this.next(this.parseOnlyTimeFractionMaybe)\n }\n } else {\n throw this.error(new TomlError('Incomplete time'))\n }\n }\n parseOnlyTimeFractionMaybe () {\n this.state.result += ':' + this.state.buf\n if (this.char === CHAR_PERIOD) {\n this.state.buf = ''\n this.next(this.parseOnlyTimeFraction)\n } else {\n return this.return(createTime(this.state.result))\n }\n }\n parseOnlyTimeFraction () {\n if (isDigit(this.char)) {\n this.consume()\n } else if (this.atEndOfWord()) {\n if (this.state.buf.length === 0) throw this.error(new TomlError('Expected digit in milliseconds'))\n return this.returnNow(createTime(this.state.result + '.' + this.state.buf))\n } else {\n throw this.error(new TomlError('Unexpected character in datetime, expected period (.), minus (-), plus (+) or Z'))\n }\n }\n\n parseTimeZoneOrFraction () {\n if (this.char === CHAR_PERIOD) {\n this.consume()\n this.next(this.parseDateTimeFraction)\n } else if (this.char === CHAR_HYPHEN || this.char === CHAR_PLUS) {\n this.consume()\n this.next(this.parseTimeZoneHour)\n } else if (this.char === CHAR_Z) {\n this.consume()\n return this.return(createDateTime(this.state.result + this.state.buf))\n } else if (this.atEndOfWord()) {\n return this.returnNow(createDateTimeFloat(this.state.result + this.state.buf))\n } else {\n throw this.error(new TomlError('Unexpected character in datetime, expected period (.), minus (-), plus (+) or Z'))\n }\n }\n parseDateTimeFraction () {\n if (isDigit(this.char)) {\n this.consume()\n } else if (this.state.buf.length === 1) {\n throw this.error(new TomlError('Expected digit in milliseconds'))\n } else if (this.char === CHAR_HYPHEN || this.char === CHAR_PLUS) {\n this.consume()\n this.next(this.parseTimeZoneHour)\n } else if (this.char === CHAR_Z) {\n this.consume()\n return this.return(createDateTime(this.state.result + this.state.buf))\n } else if (this.atEndOfWord()) {\n return this.returnNow(createDateTimeFloat(this.state.result + this.state.buf))\n } else {\n throw this.error(new TomlError('Unexpected character in datetime, expected period (.), minus (-), plus (+) or Z'))\n }\n }\n parseTimeZoneHour () {\n if (isDigit(this.char)) {\n this.consume()\n // FIXME: No more regexps\n if (/\\d\\d$/.test(this.state.buf)) return this.next(this.parseTimeZoneSep)\n } else {\n throw this.error(new TomlError('Unexpected character in datetime, expected digit'))\n }\n }\n parseTimeZoneSep () {\n if (this.char === CHAR_COLON) {\n this.consume()\n this.next(this.parseTimeZoneMin)\n } else {\n throw this.error(new TomlError('Unexpected character in datetime, expected colon'))\n }\n }\n parseTimeZoneMin () {\n if (isDigit(this.char)) {\n this.consume()\n if (/\\d\\d$/.test(this.state.buf)) return this.return(createDateTime(this.state.result + this.state.buf))\n } else {\n throw this.error(new TomlError('Unexpected character in datetime, expected digit'))\n }\n }\n\n /* BOOLEAN */\n parseBoolean () {\n /* istanbul ignore else */\n if (this.char === CHAR_t) {\n this.consume()\n return this.next(this.parseTrue_r)\n } else if (this.char === CHAR_f) {\n this.consume()\n return this.next(this.parseFalse_a)\n }\n }\n parseTrue_r () {\n if (this.char === CHAR_r) {\n this.consume()\n return this.next(this.parseTrue_u)\n } else {\n throw this.error(new TomlError('Invalid boolean, expected true or false'))\n }\n }\n parseTrue_u () {\n if (this.char === CHAR_u) {\n this.consume()\n return this.next(this.parseTrue_e)\n } else {\n throw this.error(new TomlError('Invalid boolean, expected true or false'))\n }\n }\n parseTrue_e () {\n if (this.char === CHAR_e) {\n return this.return(true)\n } else {\n throw this.error(new TomlError('Invalid boolean, expected true or false'))\n }\n }\n\n parseFalse_a () {\n if (this.char === CHAR_a) {\n this.consume()\n return this.next(this.parseFalse_l)\n } else {\n throw this.error(new TomlError('Invalid boolean, expected true or false'))\n }\n }\n\n parseFalse_l () {\n if (this.char === CHAR_l) {\n this.consume()\n return this.next(this.parseFalse_s)\n } else {\n throw this.error(new TomlError('Invalid boolean, expected true or false'))\n }\n }\n\n parseFalse_s () {\n if (this.char === CHAR_s) {\n this.consume()\n return this.next(this.parseFalse_e)\n } else {\n throw this.error(new TomlError('Invalid boolean, expected true or false'))\n }\n }\n\n parseFalse_e () {\n if (this.char === CHAR_e) {\n return this.return(false)\n } else {\n throw this.error(new TomlError('Invalid boolean, expected true or false'))\n }\n }\n\n /* INLINE LISTS */\n parseInlineList () {\n if (this.char === CHAR_SP || this.char === CTRL_I || this.char === CTRL_M || this.char === CTRL_J) {\n return null\n } else if (this.char === Parser.END) {\n throw this.error(new TomlError('Unterminated inline array'))\n } else if (this.char === CHAR_NUM) {\n return this.call(this.parseComment)\n } else if (this.char === CHAR_RSQB) {\n return this.return(this.state.resultArr || InlineList())\n } else {\n return this.callNow(this.parseValue, this.recordInlineListValue)\n }\n }\n recordInlineListValue (value) {\n if (this.state.resultArr) {\n const listType = this.state.resultArr[_contentType]\n const valueType = tomlType(value)\n if (listType !== valueType) {\n throw this.error(new TomlError(`Inline lists must be a single type, not a mix of ${listType} and ${valueType}`))\n }\n } else {\n this.state.resultArr = InlineList(tomlType(value))\n }\n if (isFloat(value) || isInteger(value)) {\n // unbox now that we've verified they're ok\n this.state.resultArr.push(value.valueOf())\n } else {\n this.state.resultArr.push(value)\n }\n return this.goto(this.parseInlineListNext)\n }\n parseInlineListNext () {\n if (this.char === CHAR_SP || this.char === CTRL_I || this.char === CTRL_M || this.char === CTRL_J) {\n return null\n } else if (this.char === CHAR_NUM) {\n return this.call(this.parseComment)\n } else if (this.char === CHAR_COMMA) {\n return this.next(this.parseInlineList)\n } else if (this.char === CHAR_RSQB) {\n return this.goto(this.parseInlineList)\n } else {\n throw this.error(new TomlError('Invalid character, expected whitespace, comma (,) or close bracket (])'))\n }\n }\n\n /* INLINE TABLE */\n parseInlineTable () {\n if (this.char === CHAR_SP || this.char === CTRL_I) {\n return null\n } else if (this.char === Parser.END || this.char === CHAR_NUM || this.char === CTRL_J || this.char === CTRL_M) {\n throw this.error(new TomlError('Unterminated inline array'))\n } else if (this.char === CHAR_RCUB) {\n return this.return(this.state.resultTable || InlineTable())\n } else {\n if (!this.state.resultTable) this.state.resultTable = InlineTable()\n return this.callNow(this.parseAssign, this.recordInlineTableValue)\n }\n }\n recordInlineTableValue (kv) {\n let target = this.state.resultTable\n let finalKey = kv.key.pop()\n for (let kw of kv.key) {\n if (hasKey(target, kw) && (!isTable(target[kw]) || target[kw][_declared])) {\n throw this.error(new TomlError(\"Can't redefine existing key\"))\n }\n target = target[kw] = target[kw] || Table()\n }\n if (hasKey(target, finalKey)) {\n throw this.error(new TomlError(\"Can't redefine existing key\"))\n }\n if (isInteger(kv.value) || isFloat(kv.value)) {\n target[finalKey] = kv.value.valueOf()\n } else {\n target[finalKey] = kv.value\n }\n return this.goto(this.parseInlineTableNext)\n }\n parseInlineTableNext () {\n if (this.char === CHAR_SP || this.char === CTRL_I) {\n return null\n } else if (this.char === Parser.END || this.char === CHAR_NUM || this.char === CTRL_J || this.char === CTRL_M) {\n throw this.error(new TomlError('Unterminated inline array'))\n } else if (this.char === CHAR_COMMA) {\n return this.next(this.parseInlineTable)\n } else if (this.char === CHAR_RCUB) {\n return this.goto(this.parseInlineTable)\n } else {\n throw this.error(new TomlError('Invalid character, expected whitespace, comma (,) or close bracket (])'))\n }\n }\n }\n return TOMLParser\n}\n",
19
- "'use strict'\nmodule.exports = prettyError\n\nfunction prettyError (err, buf) {\n /* istanbul ignore if */\n if (err.pos == null || err.line == null) return err\n let msg = err.message\n msg += ` at row ${err.line + 1}, col ${err.col + 1}, pos ${err.pos}:\\n`\n\n /* istanbul ignore else */\n if (buf && buf.split) {\n const lines = buf.split(/\\n/)\n const lineNumWidth = String(Math.min(lines.length, err.line + 3)).length\n let linePadding = ' '\n while (linePadding.length < lineNumWidth) linePadding += ' '\n for (let ii = Math.max(0, err.line - 1); ii < Math.min(lines.length, err.line + 2); ++ii) {\n let lineNum = String(ii + 1)\n if (lineNum.length < lineNumWidth) lineNum = ' ' + lineNum\n if (err.line === ii) {\n msg += lineNum + '> ' + lines[ii] + '\\n'\n msg += linePadding + ' '\n for (let hh = 0; hh < err.col; ++hh) {\n msg += ' '\n }\n msg += '^\\n'\n } else {\n msg += lineNum + ': ' + lines[ii] + '\\n'\n }\n }\n }\n err.message = msg + '\\n'\n return err\n}\n",
20
- "'use strict'\nmodule.exports = parseString\n\nconst TOMLParser = require('./lib/toml-parser.js')\nconst prettyError = require('./parse-pretty-error.js')\n\nfunction parseString (str) {\n if (global.Buffer && global.Buffer.isBuffer(str)) {\n str = str.toString('utf8')\n }\n const parser = new TOMLParser()\n try {\n parser.parse(str)\n return parser.finish()\n } catch (err) {\n throw prettyError(err, str)\n }\n}\n",
21
- "'use strict'\nmodule.exports = parseAsync\n\nconst TOMLParser = require('./lib/toml-parser.js')\nconst prettyError = require('./parse-pretty-error.js')\n\nfunction parseAsync (str, opts) {\n if (!opts) opts = {}\n const index = 0\n const blocksize = opts.blocksize || 40960\n const parser = new TOMLParser()\n return new Promise((resolve, reject) => {\n setImmediate(parseAsyncNext, index, blocksize, resolve, reject)\n })\n function parseAsyncNext (index, blocksize, resolve, reject) {\n if (index >= str.length) {\n try {\n return resolve(parser.finish())\n } catch (err) {\n return reject(prettyError(err, str))\n }\n }\n try {\n parser.parse(str.slice(index, index + blocksize))\n setImmediate(parseAsyncNext, index + blocksize, blocksize, resolve, reject)\n } catch (err) {\n reject(prettyError(err, str))\n }\n }\n}\n",
22
- "'use strict'\nmodule.exports = parseStream\n\nconst stream = require('stream')\nconst TOMLParser = require('./lib/toml-parser.js')\n\nfunction parseStream (stm) {\n if (stm) {\n return parseReadable(stm)\n } else {\n return parseTransform(stm)\n }\n}\n\nfunction parseReadable (stm) {\n const parser = new TOMLParser()\n stm.setEncoding('utf8')\n return new Promise((resolve, reject) => {\n let readable\n let ended = false\n let errored = false\n function finish () {\n ended = true\n if (readable) return\n try {\n resolve(parser.finish())\n } catch (err) {\n reject(err)\n }\n }\n function error (err) {\n errored = true\n reject(err)\n }\n stm.once('end', finish)\n stm.once('error', error)\n readNext()\n\n function readNext () {\n readable = true\n let data\n while ((data = stm.read()) !== null) {\n try {\n parser.parse(data)\n } catch (err) {\n return error(err)\n }\n }\n readable = false\n /* istanbul ignore if */\n if (ended) return finish()\n /* istanbul ignore if */\n if (errored) return\n stm.once('readable', readNext)\n }\n })\n}\n\nfunction parseTransform () {\n const parser = new TOMLParser()\n return new stream.Transform({\n objectMode: true,\n transform (chunk, encoding, cb) {\n try {\n parser.parse(chunk.toString(encoding))\n } catch (err) {\n this.emit('error', err)\n }\n cb()\n },\n flush (cb) {\n try {\n this.push(parser.finish())\n } catch (err) {\n this.emit('error', err)\n }\n cb()\n }\n })\n}\n",
23
- "'use strict'\nmodule.exports = require('./parse-string.js')\nmodule.exports.async = require('./parse-async.js')\nmodule.exports.stream = require('./parse-stream.js')\nmodule.exports.prettyError = require('./parse-pretty-error.js')\n",
24
- "'use strict'\nmodule.exports = stringify\nmodule.exports.value = stringifyInline\n\nfunction stringify (obj) {\n if (obj === null) throw typeError('null')\n if (obj === void (0)) throw typeError('undefined')\n if (typeof obj !== 'object') throw typeError(typeof obj)\n\n if (typeof obj.toJSON === 'function') obj = obj.toJSON()\n if (obj == null) return null\n const type = tomlType(obj)\n if (type !== 'table') throw typeError(type)\n return stringifyObject('', '', obj)\n}\n\nfunction typeError (type) {\n return new Error('Can only stringify objects, not ' + type)\n}\n\nfunction arrayOneTypeError () {\n return new Error(\"Array values can't have mixed types\")\n}\n\nfunction getInlineKeys (obj) {\n return Object.keys(obj).filter(key => isInline(obj[key]))\n}\nfunction getComplexKeys (obj) {\n return Object.keys(obj).filter(key => !isInline(obj[key]))\n}\n\nfunction toJSON (obj) {\n let nobj = Array.isArray(obj) ? [] : Object.prototype.hasOwnProperty.call(obj, '__proto__') ? {['__proto__']: undefined} : {}\n for (let prop of Object.keys(obj)) {\n if (obj[prop] && typeof obj[prop].toJSON === 'function' && !('toISOString' in obj[prop])) {\n nobj[prop] = obj[prop].toJSON()\n } else {\n nobj[prop] = obj[prop]\n }\n }\n return nobj\n}\n\nfunction stringifyObject (prefix, indent, obj) {\n obj = toJSON(obj)\n var inlineKeys\n var complexKeys\n inlineKeys = getInlineKeys(obj)\n complexKeys = getComplexKeys(obj)\n var result = []\n var inlineIndent = indent || ''\n inlineKeys.forEach(key => {\n var type = tomlType(obj[key])\n if (type !== 'undefined' && type !== 'null') {\n result.push(inlineIndent + stringifyKey(key) + ' = ' + stringifyAnyInline(obj[key], true))\n }\n })\n if (result.length > 0) result.push('')\n var complexIndent = prefix && inlineKeys.length > 0 ? indent + ' ' : ''\n complexKeys.forEach(key => {\n result.push(stringifyComplex(prefix, complexIndent, key, obj[key]))\n })\n return result.join('\\n')\n}\n\nfunction isInline (value) {\n switch (tomlType(value)) {\n case 'undefined':\n case 'null':\n case 'integer':\n case 'nan':\n case 'float':\n case 'boolean':\n case 'string':\n case 'datetime':\n return true\n case 'array':\n return value.length === 0 || tomlType(value[0]) !== 'table'\n case 'table':\n return Object.keys(value).length === 0\n /* istanbul ignore next */\n default:\n return false\n }\n}\n\nfunction tomlType (value) {\n if (value === undefined) {\n return 'undefined'\n } else if (value === null) {\n return 'null'\n /* eslint-disable valid-typeof */\n } else if (typeof value === 'bigint' || (Number.isInteger(value) && !Object.is(value, -0))) {\n return 'integer'\n } else if (typeof value === 'number') {\n return 'float'\n } else if (typeof value === 'boolean') {\n return 'boolean'\n } else if (typeof value === 'string') {\n return 'string'\n } else if ('toISOString' in value) {\n return isNaN(value) ? 'undefined' : 'datetime'\n } else if (Array.isArray(value)) {\n return 'array'\n } else {\n return 'table'\n }\n}\n\nfunction stringifyKey (key) {\n var keyStr = String(key)\n if (/^[-A-Za-z0-9_]+$/.test(keyStr)) {\n return keyStr\n } else {\n return stringifyBasicString(keyStr)\n }\n}\n\nfunction stringifyBasicString (str) {\n return '\"' + escapeString(str).replace(/\"/g, '\\\\\"') + '\"'\n}\n\nfunction stringifyLiteralString (str) {\n return \"'\" + str + \"'\"\n}\n\nfunction numpad (num, str) {\n while (str.length < num) str = '0' + str\n return str\n}\n\nfunction escapeString (str) {\n return str.replace(/\\\\/g, '\\\\\\\\')\n .replace(/[\\b]/g, '\\\\b')\n .replace(/\\t/g, '\\\\t')\n .replace(/\\n/g, '\\\\n')\n .replace(/\\f/g, '\\\\f')\n .replace(/\\r/g, '\\\\r')\n /* eslint-disable no-control-regex */\n .replace(/([\\u0000-\\u001f\\u007f])/, c => '\\\\u' + numpad(4, c.codePointAt(0).toString(16)))\n /* eslint-enable no-control-regex */\n}\n\nfunction stringifyMultilineString (str) {\n let escaped = str.split(/\\n/).map(str => {\n return escapeString(str).replace(/\"(?=\"\")/g, '\\\\\"')\n }).join('\\n')\n if (escaped.slice(-1) === '\"') escaped += '\\\\\\n'\n return '\"\"\"\\n' + escaped + '\"\"\"'\n}\n\nfunction stringifyAnyInline (value, multilineOk) {\n let type = tomlType(value)\n if (type === 'string') {\n if (multilineOk && /\\n/.test(value)) {\n type = 'string-multiline'\n } else if (!/[\\b\\t\\n\\f\\r']/.test(value) && /\"/.test(value)) {\n type = 'string-literal'\n }\n }\n return stringifyInline(value, type)\n}\n\nfunction stringifyInline (value, type) {\n /* istanbul ignore if */\n if (!type) type = tomlType(value)\n switch (type) {\n case 'string-multiline':\n return stringifyMultilineString(value)\n case 'string':\n return stringifyBasicString(value)\n case 'string-literal':\n return stringifyLiteralString(value)\n case 'integer':\n return stringifyInteger(value)\n case 'float':\n return stringifyFloat(value)\n case 'boolean':\n return stringifyBoolean(value)\n case 'datetime':\n return stringifyDatetime(value)\n case 'array':\n return stringifyInlineArray(value.filter(_ => tomlType(_) !== 'null' && tomlType(_) !== 'undefined' && tomlType(_) !== 'nan'))\n case 'table':\n return stringifyInlineTable(value)\n /* istanbul ignore next */\n default:\n throw typeError(type)\n }\n}\n\nfunction stringifyInteger (value) {\n /* eslint-disable security/detect-unsafe-regex */\n return String(value).replace(/\\B(?=(\\d{3})+(?!\\d))/g, '_')\n}\n\nfunction stringifyFloat (value) {\n if (value === Infinity) {\n return 'inf'\n } else if (value === -Infinity) {\n return '-inf'\n } else if (Object.is(value, NaN)) {\n return 'nan'\n } else if (Object.is(value, -0)) {\n return '-0.0'\n }\n var chunks = String(value).split('.')\n var int = chunks[0]\n var dec = chunks[1] || 0\n return stringifyInteger(int) + '.' + dec\n}\n\nfunction stringifyBoolean (value) {\n return String(value)\n}\n\nfunction stringifyDatetime (value) {\n return value.toISOString()\n}\n\nfunction isNumber (type) {\n return type === 'float' || type === 'integer'\n}\nfunction arrayType (values) {\n var contentType = tomlType(values[0])\n if (values.every(_ => tomlType(_) === contentType)) return contentType\n // mixed integer/float, emit as floats\n if (values.every(_ => isNumber(tomlType(_)))) return 'float'\n return 'mixed'\n}\nfunction validateArray (values) {\n const type = arrayType(values)\n if (type === 'mixed') {\n throw arrayOneTypeError()\n }\n return type\n}\n\nfunction stringifyInlineArray (values) {\n values = toJSON(values)\n const type = validateArray(values)\n var result = '['\n var stringified = values.map(_ => stringifyInline(_, type))\n if (stringified.join(', ').length > 60 || /\\n/.test(stringified)) {\n result += '\\n ' + stringified.join(',\\n ') + '\\n'\n } else {\n result += ' ' + stringified.join(', ') + (stringified.length > 0 ? ' ' : '')\n }\n return result + ']'\n}\n\nfunction stringifyInlineTable (value) {\n value = toJSON(value)\n var result = []\n Object.keys(value).forEach(key => {\n result.push(stringifyKey(key) + ' = ' + stringifyAnyInline(value[key], false))\n })\n return '{ ' + result.join(', ') + (result.length > 0 ? ' ' : '') + '}'\n}\n\nfunction stringifyComplex (prefix, indent, key, value) {\n var valueType = tomlType(value)\n /* istanbul ignore else */\n if (valueType === 'array') {\n return stringifyArrayOfTables(prefix, indent, key, value)\n } else if (valueType === 'table') {\n return stringifyComplexTable(prefix, indent, key, value)\n } else {\n throw typeError(valueType)\n }\n}\n\nfunction stringifyArrayOfTables (prefix, indent, key, values) {\n values = toJSON(values)\n validateArray(values)\n var firstValueType = tomlType(values[0])\n /* istanbul ignore if */\n if (firstValueType !== 'table') throw typeError(firstValueType)\n var fullKey = prefix + stringifyKey(key)\n var result = ''\n values.forEach(table => {\n if (result.length > 0) result += '\\n'\n result += indent + '[[' + fullKey + ']]\\n'\n result += stringifyObject(fullKey + '.', indent, table)\n })\n return result\n}\n\nfunction stringifyComplexTable (prefix, indent, key, value) {\n var fullKey = prefix + stringifyKey(key)\n var result = ''\n if (getInlineKeys(value).length > 0) {\n result += indent + '[' + fullKey + ']\\n'\n }\n return result + stringifyObject(fullKey + '.', indent, value)\n}\n",
25
- "'use strict'\nexports.parse = require('./parse.js')\nexports.stringify = require('./stringify.js')\n",
26
- "import commander from './index.js';\n\n// wrapper to provide named exports for ESM.\nexport const {\n program,\n createCommand,\n createArgument,\n createOption,\n CommanderError,\n InvalidArgumentError,\n InvalidOptionArgumentError, // deprecated old name\n Command,\n Argument,\n Option,\n Help,\n} = commander;\n",
27
- "/**\n * Profile schema — mirrors agent.toml on disk (§5.1).\n */\n\nexport type BackendName = 'claude-code' | 'copilot-cli' | (string & {});\n\nexport type PermissionLevel = 'ask' | 'auto' | 'yolo';\n\nexport type OutputFormat = 'text' | 'json' | 'stream-json';\n\nexport interface RuntimeConfig {\n default: BackendName;\n model?: string;\n}\n\nexport interface SoulConfig {\n prompt_file: string;\n}\n\nexport interface DefaultsConfig {\n max_turns?: number;\n permission_mode?: PermissionLevel;\n output_format?: OutputFormat;\n}\n\nexport interface BackendOverrideConfig {\n permission_mode_raw?: string;\n extra_args?: string[];\n model?: string;\n}\n\nexport interface Profile {\n name: string;\n description?: string;\n runtime: RuntimeConfig;\n soul: SoulConfig;\n defaults: DefaultsConfig;\n /** Backend-specific escape hatches keyed by backend name. */\n runtimeOverrides: Record<string, BackendOverrideConfig>;\n}\n\nexport const AGENT_NAME_PATTERN = /^[a-z][a-z0-9-]{0,62}$/;\n",
28
- "/**\n * Exit codes (§6.4). Throw KmanError with one of these to control exit.\n */\nexport const ExitCode = {\n Success: 0,\n AgentError: 1,\n UserError: 2,\n HookBlocked: 3,\n BackendUnavailable: 4,\n Interrupted: 130,\n} as const;\n\nexport type ExitCodeValue = (typeof ExitCode)[keyof typeof ExitCode];\n\nexport class KmanError extends Error {\n public readonly code: ExitCodeValue;\n constructor(code: ExitCodeValue, message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = 'KmanError';\n this.code = code;\n }\n}\n\nexport class UserError extends KmanError {\n constructor(message: string, options?: ErrorOptions) {\n super(ExitCode.UserError, message, options);\n this.name = 'UserError';\n }\n}\n\nexport class BackendUnavailableError extends KmanError {\n constructor(message: string, options?: ErrorOptions) {\n super(ExitCode.BackendUnavailable, message, options);\n this.name = 'BackendUnavailableError';\n }\n}\n",
29
- "import { mkdir, readdir, rename, rm, stat, writeFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { Command } from 'commander';\nimport {\n agentDir,\n agentsRoot,\n agentSoulPath,\n defaultProfile,\n readProfile,\n validateAgentName,\n writeProfile,\n} from '@kman/core';\nimport { UserError } from '@kman/types';\nimport { readStdinLine } from '../common/stdin.js';\n\nexport function buildAgentCommand(): Command {\n const cmd = new Command('agent').description('Agent lifecycle: create, list, show, delete, rename.');\n\n cmd\n .command('create <name>')\n .description('Create a new agent (~/.kman/agents/<name>/).')\n .option('--runtime <backend>', 'Default backend (claude-code | copilot-cli).')\n .option('--model <id>', 'Default model id.')\n .option('--description <text>', 'Free-form description.')\n .option('--soul <text>', 'Initial soul prompt content.')\n .action(async (name: string, opts: { runtime?: string; model?: string; description?: string; soul?: string }) => {\n validateAgentName(name);\n\n const dir = agentDir(name);\n if (await pathExists(dir)) {\n throw new UserError(`Agent \"${name}\" already exists at ${dir}.`);\n }\n\n await mkdir(dir, { recursive: true });\n await mkdir(join(dir, 'skills'), { recursive: true });\n await mkdir(join(dir, 'hooks'), { recursive: true });\n await mkdir(join(dir, 'scripts'), { recursive: true });\n\n const profileInit: Parameters<typeof defaultProfile>[1] = {};\n if (opts.description) profileInit.description = opts.description;\n if (opts.runtime) profileInit.runtime = { default: opts.runtime };\n if (opts.model) {\n profileInit.runtime = { ...(profileInit.runtime ?? { default: 'claude-code' }), model: opts.model };\n }\n const profile = defaultProfile(name, profileInit);\n await writeProfile(profile);\n\n const soulContent =\n opts.soul ?? `# ${name}\\n\\nYou are ${name}. Replace this file with your agent's system prompt.\\n`;\n await writeFile(agentSoulPath(name, profile.soul.prompt_file), soulContent, 'utf8');\n\n await writeFile(join(dir, '.mcp.json'), JSON.stringify({ mcpServers: {} }, null, 2) + '\\n', 'utf8');\n\n process.stdout.write(`Created agent \"${name}\" at ${dir}\\n`);\n });\n\n cmd\n .command('list')\n .description('List all agents.')\n .action(async () => {\n const root = agentsRoot();\n let entries;\n try {\n entries = await readdir(root, { withFileTypes: true });\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') {\n process.stdout.write('(no agents)\\n');\n return;\n }\n throw err;\n }\n const names = entries.filter((e) => e.isDirectory()).map((e) => e.name).sort();\n if (names.length === 0) {\n process.stdout.write('(no agents)\\n');\n return;\n }\n for (const name of names) process.stdout.write(`${name}\\n`);\n });\n\n cmd\n .command('show <name>')\n .description('Show profile + paths for an agent.')\n .action(async (name: string) => {\n const profile = await readProfile(name);\n process.stdout.write(`name: ${profile.name}\\n`);\n if (profile.description) process.stdout.write(`description: ${profile.description}\\n`);\n process.stdout.write(`directory: ${agentDir(profile.name)}\\n`);\n process.stdout.write(`runtime: ${profile.runtime.default}`);\n if (profile.runtime.model) process.stdout.write(` (model=${profile.runtime.model})`);\n process.stdout.write('\\n');\n process.stdout.write(`soul: ${profile.soul.prompt_file}\\n`);\n process.stdout.write(`defaults: permission=${profile.defaults.permission_mode ?? 'ask'} `);\n process.stdout.write(`output=${profile.defaults.output_format ?? 'text'}`);\n if (profile.defaults.max_turns !== undefined) process.stdout.write(` max_turns=${profile.defaults.max_turns}`);\n process.stdout.write('\\n');\n const overrides = Object.keys(profile.runtimeOverrides);\n if (overrides.length > 0) process.stdout.write(`overrides: ${overrides.join(', ')}\\n`);\n });\n\n cmd\n .command('delete <name>')\n .description('Delete an agent directory.')\n .option('--yes', 'Skip confirmation prompt.')\n .action(async (name: string, opts: { yes?: boolean }) => {\n validateAgentName(name);\n const dir = agentDir(name);\n if (!(await pathExists(dir))) {\n throw new UserError(`Agent \"${name}\" not found.`);\n }\n if (!opts.yes) {\n if (!process.stdin.isTTY) {\n throw new UserError(`Pass --yes to delete \"${name}\" non-interactively.`);\n }\n process.stdout.write(`Delete agent \"${name}\" at ${dir}? [y/N] `);\n const answer = await readStdinLine();\n if (!/^y(es)?$/i.test(answer.trim())) {\n process.stdout.write('Aborted.\\n');\n return;\n }\n }\n await rm(dir, { recursive: true, force: true });\n process.stdout.write(`Deleted ${dir}\\n`);\n });\n\n cmd\n .command('rename <from> <to>')\n .description('Rename an agent.')\n .action(async (from: string, to: string) => {\n validateAgentName(from);\n validateAgentName(to);\n const src = agentDir(from);\n const dst = agentDir(to);\n if (!(await pathExists(src))) {\n throw new UserError(`Agent \"${from}\" not found.`);\n }\n if (await pathExists(dst)) {\n throw new UserError(`Agent \"${to}\" already exists.`);\n }\n await rename(src, dst);\n const profile = await readProfile(to);\n await writeProfile({ ...profile, name: to });\n process.stdout.write(`Renamed ${from} → ${to}\\n`);\n });\n\n return cmd;\n}\n\nasync function pathExists(p: string): Promise<boolean> {\n try {\n await stat(p);\n return true;\n } catch {\n return false;\n }\n}\n\n",
30
- "import { homedir } from 'node:os';\nimport { join } from 'node:path';\n\n/** Root of kman's per-user state (§4). */\nexport function kmanHome(): string {\n const override = process.env['KMAN_HOME'];\n return override && override.length > 0 ? override : join(homedir(), '.kman');\n}\n\nexport function agentsRoot(): string {\n return join(kmanHome(), 'agents');\n}\n\nexport function agentDir(name: string): string {\n return join(agentsRoot(), name);\n}\n\nexport function agentProfilePath(name: string): string {\n return join(agentDir(name), 'agent.toml');\n}\n\nexport function agentSoulPath(name: string, soulFile = 'soul.md'): string {\n return join(agentDir(name), soulFile);\n}\n\nexport function agentSkillsDir(name: string): string {\n return join(agentDir(name), 'skills');\n}\n\nexport function agentLogsDir(name: string): string {\n return join(agentDir(name), 'logs');\n}\n",
31
- "import type {\n BackendName,\n DefaultsConfig,\n OutputFormat,\n PermissionLevel,\n Profile,\n} from '@kman/types';\n\nexport const KNOWN_BACKENDS: readonly BackendName[] = ['claude-code', 'copilot-cli'];\nexport const PERMISSION_LEVELS: readonly PermissionLevel[] = ['ask', 'auto', 'yolo'];\nexport const OUTPUT_FORMATS: readonly OutputFormat[] = ['text', 'json', 'stream-json'];\n\nexport const DEFAULT_DEFAULTS: Required<Pick<DefaultsConfig, 'permission_mode' | 'output_format'>> = {\n permission_mode: 'ask',\n output_format: 'text',\n};\n\nexport function defaultProfile(name: string, overrides: Partial<Profile> = {}): Profile {\n return {\n name,\n description: overrides.description,\n runtime: {\n default: overrides.runtime?.default ?? 'claude-code',\n ...(overrides.runtime?.model !== undefined ? { model: overrides.runtime.model } : {}),\n },\n soul: {\n prompt_file: overrides.soul?.prompt_file ?? 'soul.md',\n },\n defaults: {\n max_turns: overrides.defaults?.max_turns,\n permission_mode: overrides.defaults?.permission_mode ?? DEFAULT_DEFAULTS.permission_mode,\n output_format: overrides.defaults?.output_format ?? DEFAULT_DEFAULTS.output_format,\n },\n runtimeOverrides: overrides.runtimeOverrides ?? {},\n };\n}\n",
32
- "import { readFile } from 'node:fs/promises';\nimport TOML from '@iarna/toml';\nimport {\n type BackendOverrideConfig,\n type DefaultsConfig,\n type Profile,\n UserError,\n} from '@kman/types';\nimport { agentProfilePath } from '../paths.js';\nimport { defaultProfile } from './schema.js';\nimport { validateProfile } from './validate.js';\n\n/**\n * Parse a raw TOML object into a Profile.\n * The raw object can contain backend-specific tables like\n * `[runtime.claude-code]` which TOML.parse models as nested objects under `runtime`.\n */\nexport function parseProfileToml(name: string, raw: unknown): Profile {\n if (typeof raw !== 'object' || raw === null) {\n throw new UserError(`Profile \"${name}\" is not a valid TOML object.`);\n }\n const obj = raw as Record<string, unknown>;\n\n const description = typeof obj['description'] === 'string' ? (obj['description'] as string) : undefined;\n\n const runtimeRaw = (obj['runtime'] as Record<string, unknown> | undefined) ?? {};\n // Per design, `default` and `model` are top-level inside [runtime]; backend names map to nested\n // tables (e.g. [runtime.claude-code]). Extract them and treat any object-typed siblings as overrides.\n const runtimeDefault =\n typeof runtimeRaw['default'] === 'string' ? (runtimeRaw['default'] as string) : 'claude-code';\n const runtimeModel =\n typeof runtimeRaw['model'] === 'string' ? (runtimeRaw['model'] as string) : undefined;\n\n const runtimeOverrides: Record<string, BackendOverrideConfig> = {};\n for (const [key, value] of Object.entries(runtimeRaw)) {\n if (key === 'default' || key === 'model') continue;\n if (typeof value === 'object' && value !== null && !Array.isArray(value)) {\n const v = value as Record<string, unknown>;\n const override: BackendOverrideConfig = {};\n if (typeof v['permission_mode_raw'] === 'string') {\n override.permission_mode_raw = v['permission_mode_raw'] as string;\n }\n if (Array.isArray(v['extra_args'])) {\n override.extra_args = (v['extra_args'] as unknown[]).filter(\n (x): x is string => typeof x === 'string',\n );\n }\n if (typeof v['model'] === 'string') {\n override.model = v['model'] as string;\n }\n runtimeOverrides[key] = override;\n }\n }\n\n const soulRaw = (obj['soul'] as Record<string, unknown> | undefined) ?? {};\n const soulFile = typeof soulRaw['prompt_file'] === 'string' ? (soulRaw['prompt_file'] as string) : 'soul.md';\n\n const defaultsRaw = (obj['defaults'] as Record<string, unknown> | undefined) ?? {};\n const defaults: DefaultsConfig = {\n max_turns:\n typeof defaultsRaw['max_turns'] === 'number' ? (defaultsRaw['max_turns'] as number) : undefined,\n permission_mode:\n typeof defaultsRaw['permission_mode'] === 'string'\n ? (defaultsRaw['permission_mode'] as Profile['defaults']['permission_mode'])\n : undefined,\n output_format:\n typeof defaultsRaw['output_format'] === 'string'\n ? (defaultsRaw['output_format'] as Profile['defaults']['output_format'])\n : undefined,\n };\n\n const profile = defaultProfile(name, {\n description,\n runtime: {\n default: runtimeDefault,\n ...(runtimeModel !== undefined ? { model: runtimeModel } : {}),\n },\n soul: { prompt_file: soulFile },\n defaults,\n runtimeOverrides,\n });\n validateProfile(profile);\n return profile;\n}\n\nexport async function readProfile(name: string): Promise<Profile> {\n const path = agentProfilePath(name);\n let raw: string;\n try {\n raw = await readFile(path, 'utf8');\n } catch (cause) {\n if ((cause as NodeJS.ErrnoException).code === 'ENOENT') {\n throw new UserError(`Agent \"${name}\" not found at ${path}.`);\n }\n throw new UserError(`Failed to read profile for \"${name}\": ${(cause as Error).message}`, { cause });\n }\n let parsed: TOML.JsonMap;\n try {\n parsed = TOML.parse(raw);\n } catch (cause) {\n throw new UserError(`Failed to parse ${path}: ${(cause as Error).message}`, { cause });\n }\n\n // Profile.name on disk may not match the directory — directory wins (case-sensitive).\n return parseProfileToml(name, { ...parsed, name });\n}\n",
33
- "import {\n AGENT_NAME_PATTERN,\n type Profile,\n UserError,\n} from '@kman/types';\nimport { OUTPUT_FORMATS, PERMISSION_LEVELS } from './schema.js';\n\nexport function validateAgentName(name: string): void {\n if (!AGENT_NAME_PATTERN.test(name)) {\n throw new UserError(\n `Invalid agent name \"${name}\". Must match ${AGENT_NAME_PATTERN.source} (lowercase kebab-case, 1–63 chars).`,\n );\n }\n}\n\nexport function validateProfile(profile: Profile): void {\n validateAgentName(profile.name);\n\n if (!profile.runtime || typeof profile.runtime.default !== 'string') {\n throw new UserError(`Profile \"${profile.name}\" is missing runtime.default.`);\n }\n\n const pm = profile.defaults.permission_mode;\n if (pm !== undefined && !PERMISSION_LEVELS.includes(pm)) {\n throw new UserError(\n `Profile \"${profile.name}\" has invalid permission_mode \"${pm}\". Expected one of: ${PERMISSION_LEVELS.join(', ')}.`,\n );\n }\n\n const of = profile.defaults.output_format;\n if (of !== undefined && !OUTPUT_FORMATS.includes(of)) {\n throw new UserError(\n `Profile \"${profile.name}\" has invalid output_format \"${of}\". Expected one of: ${OUTPUT_FORMATS.join(', ')}.`,\n );\n }\n\n if (\n profile.defaults.max_turns !== undefined &&\n (!Number.isInteger(profile.defaults.max_turns) || profile.defaults.max_turns <= 0)\n ) {\n throw new UserError(\n `Profile \"${profile.name}\" has invalid max_turns ${profile.defaults.max_turns}. Expected positive integer.`,\n );\n }\n}\n",
34
- "import { writeFile, mkdir } from 'node:fs/promises';\nimport { dirname } from 'node:path';\nimport TOML from '@iarna/toml';\nimport type { Profile } from '@kman/types';\nimport { agentProfilePath } from '../paths.js';\nimport { validateProfile } from './validate.js';\n\n/** Serialize a Profile to TOML, expanding runtimeOverrides into nested tables. */\nexport function serializeProfile(profile: Profile): string {\n validateProfile(profile);\n const out: TOML.JsonMap = {\n name: profile.name,\n };\n if (profile.description !== undefined) out['description'] = profile.description;\n\n const runtime: TOML.JsonMap = { default: profile.runtime.default };\n if (profile.runtime.model !== undefined) runtime['model'] = profile.runtime.model;\n for (const [backend, override] of Object.entries(profile.runtimeOverrides)) {\n const t: TOML.JsonMap = {};\n if (override.permission_mode_raw !== undefined) t['permission_mode_raw'] = override.permission_mode_raw;\n if (override.extra_args !== undefined) t['extra_args'] = [...override.extra_args];\n if (override.model !== undefined) t['model'] = override.model;\n if (Object.keys(t).length > 0) runtime[backend] = t;\n }\n out['runtime'] = runtime;\n\n out['soul'] = { prompt_file: profile.soul.prompt_file };\n\n const defaults: TOML.JsonMap = {};\n if (profile.defaults.max_turns !== undefined) defaults['max_turns'] = profile.defaults.max_turns;\n if (profile.defaults.permission_mode !== undefined) defaults['permission_mode'] = profile.defaults.permission_mode;\n if (profile.defaults.output_format !== undefined) defaults['output_format'] = profile.defaults.output_format;\n out['defaults'] = defaults;\n\n return TOML.stringify(out);\n}\n\nexport async function writeProfile(profile: Profile): Promise<string> {\n const path = agentProfilePath(profile.name);\n await mkdir(dirname(path), { recursive: true });\n const body = serializeProfile(profile);\n await writeFile(path, body, 'utf8');\n return path;\n}\n",
35
- "import { readFile } from 'node:fs/promises';\nimport { isAbsolute, join } from 'node:path';\nimport {\n type AgentContext,\n type ContextOverrides,\n type Profile,\n UserError,\n} from '@kman/types';\nimport { agentDir, agentSoulPath } from '../paths.js';\n\n/**\n * Build an immutable AgentContext (§3.2) from profile + CLI overrides.\n * Soul prompt is read from disk; everything else is computed.\n */\nexport async function buildContext(\n profile: Profile,\n overrides: ContextOverrides = {},\n): Promise<AgentContext> {\n const dir = agentDir(profile.name);\n\n const soulPath = isAbsolute(profile.soul.prompt_file)\n ? profile.soul.prompt_file\n : join(dir, profile.soul.prompt_file);\n\n let soul = '';\n try {\n soul = await readFile(soulPath, 'utf8');\n } catch (cause) {\n if ((cause as NodeJS.ErrnoException).code === 'ENOENT') {\n // Permit missing soul file; fall back to empty string. Backend layer decides whether\n // that's acceptable based on `supportsAppendSystemPrompt`.\n soul = '';\n } else {\n throw new UserError(\n `Failed to read soul prompt at ${soulPath}: ${(cause as Error).message}`,\n { cause },\n );\n }\n }\n\n const backend = overrides.backend ?? profile.runtime.default;\n const backendOverride = profile.runtimeOverrides[backend] ?? {};\n const model = overrides.model ?? backendOverride.model ?? profile.runtime.model;\n const permission = overrides.permission ?? profile.defaults.permission_mode ?? 'ask';\n const outputFormat =\n overrides.outputFormat ?? (overrides.stream ? 'stream-json' : profile.defaults.output_format ?? 'text');\n const stream = overrides.stream === true || outputFormat === 'stream-json';\n\n const extraArgs: string[] = [\n ...(backendOverride.extra_args ?? []),\n ...(overrides.runtimeFlags ?? []),\n ];\n\n const env: Record<string, string> = { ...overrides.env };\n\n const ctx: AgentContext = {\n profile,\n agentDir: dir,\n soulPrompt: soul,\n backend,\n ...(model !== undefined ? { model } : {}),\n permission,\n outputFormat,\n ...(profile.defaults.max_turns !== undefined ? { maxTurns: profile.defaults.max_turns } : {}),\n cwd: overrides.cwd ?? process.cwd(),\n extraArgs,\n ...(backendOverride.permission_mode_raw !== undefined\n ? { permissionModeRaw: backendOverride.permission_mode_raw }\n : {}),\n env,\n ...(overrides.task !== undefined ? { task: overrides.task } : {}),\n stream,\n };\n\n return ctx;\n}\n",
36
- "import type { ChildProcess } from 'node:child_process';\nimport {\n BackendUnavailableError,\n ExitCode,\n type AgentContext,\n type Backend,\n} from '@kman/types';\n\nexport interface LaunchResult {\n exitCode: number;\n}\n\n/**\n * Spawn the backend and wait for it to exit. stdio is wired straight through.\n * Forwards SIGINT/SIGTERM to the child so the user's Ctrl-C reaches the backend.\n */\nexport async function launchRun(backend: Backend, ctx: AgentContext): Promise<LaunchResult> {\n return launch(backend, ctx, 'run');\n}\n\nexport async function launchChat(backend: Backend, ctx: AgentContext): Promise<LaunchResult> {\n return launch(backend, ctx, 'chat');\n}\n\nasync function launch(\n backend: Backend,\n ctx: AgentContext,\n mode: 'run' | 'chat',\n): Promise<LaunchResult> {\n // Fail-fast capability check for soul prompt (§3.3).\n if (ctx.soulPrompt.trim().length > 0 && !backend.capabilities.supportsAppendSystemPrompt) {\n throw new BackendUnavailableError(\n `Backend \"${backend.name}\" does not support append-system-prompt; cannot inject soul.md.`,\n );\n }\n\n let child: ChildProcess;\n try {\n child = mode === 'run' ? await backend.spawn(ctx) : await backend.chat(ctx);\n } catch (cause) {\n const err = cause as NodeJS.ErrnoException;\n if (err.code === 'ENOENT') {\n throw new BackendUnavailableError(\n `Backend \"${backend.name}\" binary not found on PATH. Install it before running.`,\n { cause },\n );\n }\n throw cause;\n }\n\n const forward = (sig: NodeJS.Signals) => {\n if (!child.killed) child.kill(sig);\n };\n process.on('SIGINT', forward);\n process.on('SIGTERM', forward);\n\n try {\n return await new Promise<LaunchResult>((resolve, reject) => {\n child.on('error', (err) => {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') {\n reject(\n new BackendUnavailableError(\n `Backend \"${backend.name}\" binary not found on PATH. Install it before running.`,\n { cause: err },\n ),\n );\n } else {\n reject(err);\n }\n });\n child.on('exit', (code, signal) => {\n if (signal === 'SIGINT' || signal === 'SIGTERM') {\n resolve({ exitCode: ExitCode.Interrupted });\n } else {\n resolve({ exitCode: code ?? 0 });\n }\n });\n });\n } finally {\n process.off('SIGINT', forward);\n process.off('SIGTERM', forward);\n }\n}\n",
37
- "/**\n * Read a single line (one stdin chunk, really) from process.stdin. Pauses\n * stdin afterward so the event loop can exit naturally once the command\n * finishes — without this, the data listener leaves stdin in flowing mode\n * and the process hangs on completion.\n */\nexport function readStdinLine(): Promise<string> {\n return new Promise((resolve) => {\n process.stdin.setEncoding('utf8');\n const onData = (chunk: string) => {\n process.stdin.off('data', onData);\n process.stdin.pause();\n resolve(chunk);\n };\n process.stdin.on('data', onData);\n });\n}\n",
38
- "import { isAbsolute, resolve } from 'node:path';\nimport { UserError } from '@kman/types';\n\nexport type ParsedSource =\n | { kind: 'local'; path: string; subpath?: string; ref?: string }\n | { kind: 'git'; url: string; subpath?: string; ref?: string }\n | { kind: 'github'; owner: string; repo: string; subpath?: string; ref?: string }\n | { kind: 'gitlab'; owner: string; repo: string; subpath?: string; ref?: string }\n | { kind: 'well-known'; name: string; ref?: string };\n\nconst GITHUB_SHORTHAND = /^([A-Za-z0-9._-]+)\\/([A-Za-z0-9._-]+)(?:\\/([^@\\s]+))?(?:@(.+))?$/;\nconst WELL_KNOWN = new Set(['anthropic-skills']);\n\n/**\n * Parse a `--source` argument into a typed source descriptor. Mirrors the\n * vercel-labs/skills source model referenced in design §5.4.\n *\n * Supported forms:\n * - Local path: ./relative, ../relative, /abs, C:\\abs, file:///…\n * - GitHub URL: https://github.com/owner/repo[/path][@ref]\n * - GitLab URL: https://gitlab.com/owner/repo[/path][@ref]\n * - Generic git: git+https://…, ssh://…, git@host:path\n * - GitHub shorthand: owner/repo[/path][@ref]\n * - Well-known: bare name without slash (e.g. anthropic-skills)\n */\nexport function parseSource(input: string, refOverride?: string): ParsedSource {\n const raw = input.trim();\n if (raw.length === 0) {\n throw new UserError('Source cannot be empty.');\n }\n\n // Local: starts with ., /, ~, or has a drive letter, or is a file: URL.\n if (\n raw.startsWith('.') ||\n raw.startsWith('/') ||\n raw.startsWith('~') ||\n raw.startsWith('file://') ||\n /^[A-Za-z]:[\\\\/]/.test(raw) ||\n isAbsolute(raw)\n ) {\n let p = raw.startsWith('file://') ? raw.slice(7) : raw;\n if (p.startsWith('~')) p = p.replace(/^~/, process.env['HOME'] ?? process.env['USERPROFILE'] ?? '~');\n return { kind: 'local', path: resolve(p), ...(refOverride ? { ref: refOverride } : {}) };\n }\n\n // GitHub URL\n const githubUrl = raw.match(\n /^https?:\\/\\/github\\.com\\/([A-Za-z0-9._-]+)\\/([A-Za-z0-9._-]+?)(?:\\.git)?(?:\\/tree\\/([^/]+))?(?:\\/(.+))?$/,\n );\n if (githubUrl) {\n const [, owner = '', repo = '', refFromTree, subpath] = githubUrl;\n const out: ParsedSource = { kind: 'github', owner, repo };\n if (subpath) out.subpath = sanitizeSubpath(subpath);\n const ref = refOverride ?? refFromTree;\n if (ref) out.ref = ref;\n return out;\n }\n\n // GitLab URL\n const gitlabUrl = raw.match(\n /^https?:\\/\\/gitlab\\.com\\/([A-Za-z0-9._-]+)\\/([A-Za-z0-9._-]+?)(?:\\.git)?(?:\\/-\\/tree\\/([^/]+))?(?:\\/(.+))?$/,\n );\n if (gitlabUrl) {\n const [, owner = '', repo = '', refFromTree, subpath] = gitlabUrl;\n const out: ParsedSource = { kind: 'gitlab', owner, repo };\n if (subpath) out.subpath = sanitizeSubpath(subpath);\n const ref = refOverride ?? refFromTree;\n if (ref) out.ref = ref;\n return out;\n }\n\n // Generic git URL: git+…, ssh://…, git@host:path\n if (\n raw.startsWith('git+') ||\n raw.startsWith('ssh://') ||\n /^git@[^:]+:/.test(raw) ||\n raw.endsWith('.git')\n ) {\n const out: ParsedSource = { kind: 'git', url: raw.startsWith('git+') ? raw.slice(4) : raw };\n if (refOverride) out.ref = refOverride;\n return out;\n }\n\n // GitHub shorthand: owner/repo[/path][@ref]\n const m = raw.match(GITHUB_SHORTHAND);\n if (m) {\n const [, owner = '', repo = '', subpath, refMatch] = m;\n const out: ParsedSource = { kind: 'github', owner, repo };\n if (subpath) out.subpath = sanitizeSubpath(subpath);\n const ref = refOverride ?? refMatch;\n if (ref) out.ref = ref;\n return out;\n }\n\n // Well-known: single token w/o slash.\n if (!raw.includes('/') && WELL_KNOWN.has(raw)) {\n const out: ParsedSource = { kind: 'well-known', name: raw };\n if (refOverride) out.ref = refOverride;\n return out;\n }\n\n throw new UserError(\n `Unrecognized source \"${input}\". Use a local path, GitHub/GitLab URL, owner/repo[/path][@ref], git URL, or well-known name.`,\n );\n}\n\n/** Reject path traversal attempts (§5.4: \"Subpaths must be sanitized\"). */\nexport function sanitizeSubpath(subpath: string): string {\n const normalized = subpath.replace(/\\\\/g, '/').replace(/^\\/+|\\/+$/g, '');\n if (normalized.length === 0) {\n throw new UserError('Empty source subpath after sanitization.');\n }\n const parts = normalized.split('/');\n for (const p of parts) {\n if (p === '..' || p === '.' || p.length === 0) {\n throw new UserError(`Invalid source subpath segment \"${p}\" in \"${subpath}\".`);\n }\n }\n return parts.join('/');\n}\n",
39
- "import { readdir, stat } from 'node:fs/promises';\nimport { basename, join, relative } from 'node:path';\nimport { UserError } from '@kman/types';\n\nexport interface DiscoveredSkill {\n /** Skill name derived from its directory basename. */\n name: string;\n /** Absolute path to the directory that contains SKILL.md. */\n dir: string;\n /** Path of dir relative to the materialized source root. */\n relPath: string;\n}\n\nconst COMMON_ROOTS = ['', 'skills', '.claude/skills'];\nconst MAX_DEPTH = 4;\nconst IGNORE = new Set(['node_modules', '.git', '.turbo', 'dist', 'build', '.cache']);\n\n/**\n * Discover SKILL.md directories inside a materialized source (§5.4).\n * If `subpath` is provided, search is anchored at <rootDir>/<subpath>.\n */\nexport async function discoverSkills(rootDir: string, subpath?: string): Promise<DiscoveredSkill[]> {\n const anchor = subpath ? join(rootDir, subpath) : rootDir;\n const anchorStat = await safeStat(anchor);\n if (!anchorStat?.isDirectory()) {\n throw new UserError(`Source path does not exist or is not a directory: ${anchor}`);\n }\n\n // 1. Direct check on the anchor itself.\n const found: DiscoveredSkill[] = [];\n if (await hasSkillMd(anchor)) {\n found.push({ name: basename(anchor), dir: anchor, relPath: relative(rootDir, anchor) || '.' });\n return found;\n }\n\n // 2. Common skill roots.\n for (const root of COMMON_ROOTS) {\n const candidate = root ? join(anchor, root) : anchor;\n const s = await safeStat(candidate);\n if (!s?.isDirectory()) continue;\n const direct = await listSkillDirs(candidate);\n for (const d of direct) {\n found.push({ name: basename(d), dir: d, relPath: relative(rootDir, d) });\n }\n if (found.length > 0) return dedupe(found);\n }\n\n // 3. Bounded recursive search.\n await recurse(anchor, 0, rootDir, found);\n if (found.length === 0) {\n throw new UserError(`No SKILL.md found anywhere under ${anchor}.`);\n }\n return dedupe(found);\n}\n\nasync function listSkillDirs(parent: string): Promise<string[]> {\n let entries;\n try {\n entries = await readdir(parent, { withFileTypes: true });\n } catch {\n return [];\n }\n const out: string[] = [];\n for (const e of entries) {\n if (!e.isDirectory() || IGNORE.has(e.name)) continue;\n const child = join(parent, e.name);\n if (await hasSkillMd(child)) out.push(child);\n }\n return out;\n}\n\nasync function recurse(dir: string, depth: number, rootDir: string, found: DiscoveredSkill[]): Promise<void> {\n if (depth > MAX_DEPTH) return;\n let entries;\n try {\n entries = await readdir(dir, { withFileTypes: true });\n } catch {\n return;\n }\n if (await hasSkillMd(dir)) {\n found.push({ name: basename(dir), dir, relPath: relative(rootDir, dir) || '.' });\n return; // Don't descend into a skill dir.\n }\n for (const e of entries) {\n if (!e.isDirectory() || IGNORE.has(e.name)) continue;\n await recurse(join(dir, e.name), depth + 1, rootDir, found);\n }\n}\n\nasync function hasSkillMd(dir: string): Promise<boolean> {\n const s = await safeStat(join(dir, 'SKILL.md'));\n return !!s?.isFile();\n}\n\nasync function safeStat(p: string) {\n try {\n return await stat(p);\n } catch {\n return null;\n }\n}\n\nfunction dedupe(list: DiscoveredSkill[]): DiscoveredSkill[] {\n const seen = new Set<string>();\n const out: DiscoveredSkill[] = [];\n for (const s of list) {\n if (seen.has(s.dir)) continue;\n seen.add(s.dir);\n out.push(s);\n }\n return out;\n}\n",
40
- "import { cp, mkdir, stat } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { agentSkillsDir } from '@kman/core';\nimport { UserError } from '@kman/types';\nimport type { DiscoveredSkill } from './discover.js';\nimport { formatSourceString, sourceUrl, writeManifest, type SkillManifest } from './manifest.js';\nimport type { ParsedSource } from './source-parser.js';\n\nexport interface VendorOptions {\n agent: string;\n source: ParsedSource;\n skill: DiscoveredSkill;\n /** Override `name` (default: skill.name). */\n installName?: string;\n /** Overwrite if a skill with this name already exists. */\n force?: boolean;\n}\n\nexport interface VendorResult {\n installedPath: string;\n manifest: SkillManifest;\n}\n\n/**\n * Copy a discovered SKILL.md directory into <agent>/skills/<installName>/\n * and write the .kman-skill.json manifest (§5.4).\n */\nexport async function vendorSkill(opts: VendorOptions): Promise<VendorResult> {\n const name = opts.installName ?? opts.skill.name;\n const dest = join(agentSkillsDir(opts.agent), name);\n\n const exists = await pathExists(dest);\n if (exists && !opts.force) {\n throw new UserError(`Skill \"${name}\" already exists at ${dest}. Use --force to overwrite.`);\n }\n\n await mkdir(agentSkillsDir(opts.agent), { recursive: true });\n\n if (exists) {\n // Replace with a fresh copy: remove old, then copy.\n await cp(opts.skill.dir, dest, { recursive: true, force: true });\n } else {\n await cp(opts.skill.dir, dest, { recursive: true });\n }\n\n const manifest: SkillManifest = {\n source: formatSourceString(opts.source),\n installed_at: new Date().toISOString(),\n };\n const url = sourceUrl(opts.source);\n if (url) manifest.source_url = url;\n if ('ref' in opts.source && opts.source.ref) manifest.ref = opts.source.ref;\n await writeManifest(dest, manifest);\n\n return { installedPath: dest, manifest };\n}\n\nasync function pathExists(p: string): Promise<boolean> {\n try {\n await stat(p);\n return true;\n } catch {\n return false;\n }\n}\n",
41
- "import { readFile, writeFile, stat } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport type { ParsedSource } from './source-parser.js';\n\nexport interface SkillManifest {\n source: string;\n source_url?: string;\n ref?: string;\n installed_at: string;\n version?: string;\n checksum?: string;\n}\n\nexport const MANIFEST_FILENAME = '.kman-skill.json';\n\nexport function manifestPath(skillDir: string): string {\n return join(skillDir, MANIFEST_FILENAME);\n}\n\nexport async function readManifest(skillDir: string): Promise<SkillManifest | null> {\n try {\n const raw = await readFile(manifestPath(skillDir), 'utf8');\n return JSON.parse(raw) as SkillManifest;\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') return null;\n throw err;\n }\n}\n\nexport async function writeManifest(skillDir: string, manifest: SkillManifest): Promise<void> {\n await writeFile(manifestPath(skillDir), JSON.stringify(manifest, null, 2) + '\\n', 'utf8');\n}\n\nexport async function manifestInstalledAt(skillDir: string): Promise<Date | null> {\n try {\n const s = await stat(manifestPath(skillDir));\n return s.mtime;\n } catch {\n return null;\n }\n}\n\n/** Format the source descriptor as the persisted `source` string. */\nexport function formatSourceString(source: ParsedSource): string {\n switch (source.kind) {\n case 'local':\n return source.path;\n case 'github':\n return source.subpath ? `${source.owner}/${source.repo}/${source.subpath}` : `${source.owner}/${source.repo}`;\n case 'gitlab':\n return source.subpath\n ? `gitlab:${source.owner}/${source.repo}/${source.subpath}`\n : `gitlab:${source.owner}/${source.repo}`;\n case 'git':\n return source.url;\n case 'well-known':\n return source.name;\n }\n}\n\nexport function sourceUrl(source: ParsedSource): string | undefined {\n switch (source.kind) {\n case 'github':\n return `https://github.com/${source.owner}/${source.repo}`;\n case 'gitlab':\n return `https://gitlab.com/${source.owner}/${source.repo}`;\n case 'git':\n return source.url;\n default:\n return undefined;\n }\n}\n",
42
- "import { readdir, stat } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { agentSkillsDir } from '@kman/core';\nimport { UserError } from '@kman/types';\nimport { discoverSkills } from './discover.js';\nimport { materialize } from './fetch.js';\nimport {\n manifestInstalledAt,\n readManifest,\n type SkillManifest,\n} from './manifest.js';\nimport { parseSource } from './source-parser.js';\nimport { vendorSkill } from './vendor.js';\n\nexport interface UpdateOptions {\n agent: string;\n skill: string;\n /** Bypass mtime > installed_at safety check. */\n force?: boolean;\n}\n\n/**\n * Re-fetch a skill from its recorded source and overwrite its directory.\n * Refuses if a file inside the installed directory has been modified after\n * the manifest was written, unless --force is passed (§5.4).\n */\nexport async function updateSkill(opts: UpdateOptions): Promise<{ installedPath: string }> {\n const dir = join(agentSkillsDir(opts.agent), opts.skill);\n const manifest = await readManifest(dir);\n if (!manifest) {\n throw new UserError(\n `Skill \"${opts.skill}\" has no .kman-skill.json manifest; cannot update. Use \"skills remove\" then \"skills add\".`,\n );\n }\n\n if (!opts.force) {\n const installedAt = await manifestInstalledAt(dir);\n if (installedAt) {\n const newest = await newestMtime(dir);\n if (newest && newest.getTime() > installedAt.getTime() + 1000) {\n throw new UserError(\n `Skill \"${opts.skill}\" has local modifications newer than the manifest. ` +\n `Re-running update would overwrite them. Pass --force or \"skills remove\" first.`,\n );\n }\n }\n }\n\n const source = parseSource(manifest.source, manifest.ref);\n const mat = await materialize(source);\n try {\n const discovered = await discoverSkills(mat.rootDir, mat.subpath);\n const match = discovered.find((s) => s.name === opts.skill) ?? discovered[0];\n if (!match) throw new UserError(`No skill named \"${opts.skill}\" in source ${manifest.source}.`);\n const { installedPath } = await vendorSkill({\n agent: opts.agent,\n source,\n skill: match,\n installName: opts.skill,\n force: true,\n });\n return { installedPath };\n } finally {\n await mat.cleanup();\n }\n}\n\nasync function newestMtime(dir: string): Promise<Date | null> {\n let newest: Date | null = null;\n const stack = [dir];\n while (stack.length > 0) {\n const cur = stack.pop()!;\n let entries;\n try {\n entries = await readdir(cur, { withFileTypes: true });\n } catch {\n continue;\n }\n for (const e of entries) {\n const p = join(cur, e.name);\n // Skip the manifest itself — it's expected to share install time.\n if (e.isDirectory()) {\n stack.push(p);\n continue;\n }\n if (e.name === '.kman-skill.json') continue;\n try {\n const s = await stat(p);\n if (!newest || s.mtime > newest) newest = s.mtime;\n } catch {\n /* ignore */\n }\n }\n }\n return newest;\n}\n\n/** Look up the recorded source for an installed skill. */\nexport async function recordedSource(agent: string, skill: string): Promise<SkillManifest | null> {\n const dir = join(agentSkillsDir(agent), skill);\n return readManifest(dir);\n}\n",
43
- "import { spawn } from 'node:child_process';\nimport { mkdtemp, rm } from 'node:fs/promises';\nimport { tmpdir } from 'node:os';\nimport { join } from 'node:path';\nimport { BackendUnavailableError, UserError } from '@kman/types';\nimport type { ParsedSource } from './source-parser.js';\n\n/**\n * Result of \"materializing\" a source into a local directory ready for SKILL.md discovery.\n * `cleanup` removes any temporary directory created during fetch.\n */\nexport interface MaterializedSource {\n rootDir: string;\n /** Optional subpath inside rootDir (relative). */\n subpath: string | undefined;\n cleanup: () => Promise<void>;\n}\n\n/**\n * Resolve a parsed source to a local directory. Local paths are used directly;\n * GitHub/GitLab/git sources are cloned (shallow, optionally to a ref) into a tmp dir.\n * Well-known names map to canonical repos.\n */\nexport async function materialize(source: ParsedSource): Promise<MaterializedSource> {\n switch (source.kind) {\n case 'local':\n return { rootDir: source.path, subpath: source.subpath, cleanup: async () => {} };\n\n case 'github':\n return cloneGit(`https://github.com/${source.owner}/${source.repo}.git`, source.ref, source.subpath);\n\n case 'gitlab':\n return cloneGit(`https://gitlab.com/${source.owner}/${source.repo}.git`, source.ref, source.subpath);\n\n case 'git':\n return cloneGit(source.url, source.ref, source.subpath);\n\n case 'well-known': {\n const mapping: Record<string, string> = {\n 'anthropic-skills': 'https://github.com/anthropics/skills.git',\n };\n const url = mapping[source.name];\n if (!url) throw new UserError(`Unknown well-known skill source \"${source.name}\".`);\n return cloneGit(url, source.ref, undefined);\n }\n\n default: {\n const exhaustive: never = source;\n void exhaustive;\n throw new UserError('Unsupported source kind.');\n }\n }\n}\n\nasync function cloneGit(\n url: string,\n ref: string | undefined,\n subpath: string | undefined,\n): Promise<MaterializedSource> {\n const dir = await mkdtemp(join(tmpdir(), 'kman-skill-'));\n // Shallow clone first; if a ref is provided, fetch + checkout it (works for branch/tag/sha).\n await runGit(['clone', '--depth', '1', url, dir]);\n if (ref) {\n try {\n await runGit(['fetch', '--depth', '1', 'origin', ref], dir);\n await runGit(['checkout', 'FETCH_HEAD'], dir);\n } catch {\n // Fallback: full fetch then checkout (covers commit SHAs not reachable via shallow ref fetch).\n await runGit(['fetch', '--unshallow'], dir).catch(() => {});\n await runGit(['checkout', ref], dir);\n }\n }\n return {\n rootDir: dir,\n subpath,\n cleanup: () => rm(dir, { recursive: true, force: true }),\n };\n}\n\nfunction runGit(args: string[], cwd?: string): Promise<void> {\n return new Promise<void>((res, rej) => {\n const child = spawn('git', args, { cwd, stdio: ['ignore', 'pipe', 'pipe'] });\n let stderr = '';\n child.stderr?.on('data', (d) => {\n stderr += d.toString();\n });\n child.on('error', (err) => {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') {\n rej(new BackendUnavailableError('git not found on PATH; cannot fetch skill sources.'));\n } else {\n rej(err);\n }\n });\n child.on('exit', (code) => {\n if (code === 0) res();\n else rej(new UserError(`git ${args.join(' ')} failed: ${stderr.trim()}`));\n });\n });\n}\n",
44
- "import { rm, stat } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { agentSkillsDir } from '@kman/core';\nimport { UserError } from '@kman/types';\n\nexport async function removeSkill(agent: string, skill: string): Promise<string> {\n const dir = join(agentSkillsDir(agent), skill);\n try {\n const s = await stat(dir);\n if (!s.isDirectory()) {\n throw new UserError(`Skill path is not a directory: ${dir}`);\n }\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') {\n throw new UserError(`Skill \"${skill}\" not found for agent \"${agent}\".`);\n }\n throw err;\n }\n await rm(dir, { recursive: true, force: true });\n return dir;\n}\n",
45
- "import { readdir } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { agentSkillsDir } from '@kman/core';\nimport { readManifest, type SkillManifest } from './manifest.js';\n\nexport interface InstalledSkill {\n name: string;\n dir: string;\n manifest: SkillManifest | null;\n}\n\nexport async function listInstalledSkills(agent: string): Promise<InstalledSkill[]> {\n const root = agentSkillsDir(agent);\n let entries;\n try {\n entries = await readdir(root, { withFileTypes: true });\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') return [];\n throw err;\n }\n const out: InstalledSkill[] = [];\n for (const e of entries) {\n if (!e.isDirectory()) continue;\n const dir = join(root, e.name);\n const manifest = await readManifest(dir);\n out.push({ name: e.name, dir, manifest });\n }\n return out.sort((a, b) => a.name.localeCompare(b.name));\n}\n",
46
- "import { UserError } from '@kman/types';\n\nexport interface ExtractResult {\n rest: string[];\n agent: string | undefined;\n}\n\n/**\n * Pull `-a <name>` / `--agent <name>` / `--agent=<name>` out of argv so it\n * can be placed before *or* after the subcommand. Multiple occurrences error\n * out per §6 (\"If --agent appears more than once, kman exits with code 2\").\n */\nexport function extractAgentOption(argv: string[]): ExtractResult {\n const rest: string[] = [];\n let agent: string | undefined;\n for (let i = 0; i < argv.length; i++) {\n const tok = argv[i]!;\n if (tok === '-a' || tok === '--agent') {\n const next = argv[i + 1];\n if (next === undefined || next.startsWith('-')) {\n throw new UserError(`Missing value for ${tok}.`);\n }\n assertSingle(agent);\n agent = next;\n i++;\n continue;\n }\n if (tok.startsWith('--agent=')) {\n assertSingle(agent);\n agent = tok.slice('--agent='.length);\n continue;\n }\n if (tok.startsWith('-a=')) {\n assertSingle(agent);\n agent = tok.slice(3);\n continue;\n }\n rest.push(tok);\n }\n return { rest, agent };\n}\n\nfunction assertSingle(current: string | undefined): void {\n if (current !== undefined) {\n throw new UserError('--agent specified more than once.');\n }\n}\n\nexport function requireAgent(): string {\n const a = process.env['KMAN_SELECTED_AGENT'];\n if (!a) {\n throw new UserError('Missing required --agent <name>. Agent-scoped commands need a target agent.');\n }\n return a;\n}\n\nexport function optionalAgent(): string | undefined {\n return process.env['KMAN_SELECTED_AGENT'] || undefined;\n}\n\nexport function rejectAgent(commandName: string): void {\n if (process.env['KMAN_SELECTED_AGENT']) {\n throw new UserError(`Subcommand \"${commandName}\" does not accept --agent.`);\n }\n}\n",
47
- "import { Command } from 'commander';\nimport {\n discoverSkills,\n listInstalledSkills,\n materialize,\n parseSource,\n removeSkill,\n updateSkill,\n vendorSkill,\n type DiscoveredSkill,\n} from '@kman/skills';\nimport { UserError } from '@kman/types';\nimport { requireAgent } from '../common/agent-option.js';\nimport { readStdinLine } from '../common/stdin.js';\n\nexport function buildSkillsCommand(): Command {\n const cmd = new Command('skills').description(\n 'Per-agent skills management (add | list | show | update | remove).',\n );\n\n cmd\n .command('add')\n .description('Install one or more skills from a source.')\n .requiredOption('--source <source>', 'Source (path, owner/repo[/path][@ref], URL, or well-known name).')\n .option('--skill <name>', 'Skill name to install (repeatable).', collect, [] as string[])\n .option('--all', 'Install every skill discovered in the source.')\n .option('--ref <ref>', 'Pin a branch, tag, or commit.')\n .option('--force', 'Overwrite an existing skill of the same name.')\n .action(async (opts: { source: string; skill: string[]; all?: boolean; ref?: string; force?: boolean }) => {\n const agent = requireAgent();\n const source = parseSource(opts.source, opts.ref);\n const mat = await materialize(source);\n try {\n const discovered = await discoverSkills(mat.rootDir, mat.subpath);\n const selection = await selectSkills(discovered, opts.skill.length > 0 ? opts.skill : undefined, opts.all === true);\n for (const skill of selection) {\n const res = await vendorSkill({\n agent,\n source,\n skill,\n force: opts.force === true,\n });\n process.stdout.write(`Installed ${skill.name} → ${res.installedPath}\\n`);\n }\n } finally {\n await mat.cleanup();\n }\n });\n\n cmd\n .command('list')\n .description('List installed skills for an agent.')\n .action(async () => {\n const agent = requireAgent();\n const skills = await listInstalledSkills(agent);\n if (skills.length === 0) {\n process.stdout.write(`(no skills installed for ${agent})\\n`);\n return;\n }\n for (const s of skills) {\n const src = s.manifest?.source ?? 'local';\n const ref = s.manifest?.ref ? `@${s.manifest.ref}` : '';\n process.stdout.write(`${s.name}\\t${src}${ref}\\n`);\n }\n });\n\n cmd\n .command('show')\n .description('Show details for an installed skill.')\n .requiredOption('--skill <name>', 'Skill name.')\n .action(async (opts: { skill: string }) => {\n const agent = requireAgent();\n const installed = await listInstalledSkills(agent);\n const match = installed.find((s) => s.name === opts.skill);\n if (!match) {\n throw new UserError(`Skill \"${opts.skill}\" not installed for agent \"${agent}\".`);\n }\n process.stdout.write(`name: ${match.name}\\n`);\n process.stdout.write(`directory: ${match.dir}\\n`);\n if (match.manifest) {\n process.stdout.write(`source: ${match.manifest.source}\\n`);\n if (match.manifest.source_url) process.stdout.write(`source_url: ${match.manifest.source_url}\\n`);\n if (match.manifest.ref) process.stdout.write(`ref: ${match.manifest.ref}\\n`);\n process.stdout.write(`installed_at: ${match.manifest.installed_at}\\n`);\n } else {\n process.stdout.write('(no manifest — local skill, detached)\\n');\n }\n });\n\n cmd\n .command('update')\n .description('Re-fetch an installed skill from its recorded source.')\n .option('--skill <name>', 'Skill name to update.')\n .option('--all', 'Update every installed skill.')\n .option('--force', 'Bypass local-modification safety check.')\n .action(async (opts: { skill?: string; all?: boolean; force?: boolean }) => {\n const agent = requireAgent();\n if (!opts.skill && !opts.all) {\n throw new UserError('Pass --skill <name> or --all.');\n }\n const targets = opts.all\n ? (await listInstalledSkills(agent)).filter((s) => !!s.manifest).map((s) => s.name)\n : [opts.skill as string];\n for (const skill of targets) {\n const res = await updateSkill({ agent, skill, force: opts.force === true });\n process.stdout.write(`Updated ${skill} → ${res.installedPath}\\n`);\n }\n });\n\n cmd\n .command('remove')\n .description('Remove an installed skill.')\n .requiredOption('--skill <name>', 'Skill name.')\n .action(async (opts: { skill: string }) => {\n const agent = requireAgent();\n const removed = await removeSkill(agent, opts.skill);\n process.stdout.write(`Removed ${removed}\\n`);\n });\n\n return cmd;\n}\n\nfunction collect(value: string, previous: string[]): string[] {\n return [...previous, value];\n}\n\nasync function selectSkills(\n discovered: DiscoveredSkill[],\n filter: string[] | undefined,\n all: boolean,\n): Promise<DiscoveredSkill[]> {\n if (discovered.length === 0) {\n throw new UserError('No SKILL.md found in source.');\n }\n if (filter && filter.length > 0) {\n const out = discovered.filter((s) => filter.includes(s.name));\n if (out.length === 0) {\n throw new UserError(\n `Requested skills not found in source. Available: ${discovered.map((s) => s.name).join(', ')}.`,\n );\n }\n return out;\n }\n if (all) return discovered;\n if (discovered.length === 1) return discovered;\n\n if (process.stdin.isTTY && process.stdout.isTTY) {\n return pickInteractive(discovered);\n }\n throw new UserError(\n `Source contains multiple skills. Pass --skill <name> (repeatable) or --all. Discovered: ${discovered\n .map((s) => s.name)\n .join(', ')}.`,\n );\n}\n\nasync function pickInteractive(discovered: DiscoveredSkill[]): Promise<DiscoveredSkill[]> {\n process.stdout.write('Multiple skills discovered. Enter a comma-separated list of names to install (or \"all\"):\\n');\n for (const [i, s] of discovered.entries()) {\n process.stdout.write(` ${i + 1}. ${s.name} (${s.relPath})\\n`);\n }\n process.stdout.write('> ');\n const answer = (await readStdinLine()).trim();\n if (answer.toLowerCase() === 'all') return discovered;\n const wanted = answer.split(',').map((s) => s.trim()).filter(Boolean);\n const out = discovered.filter((s) => wanted.includes(s.name));\n if (out.length === 0) {\n throw new UserError(`No matching skills selected. Wanted: ${wanted.join(', ')}.`);\n }\n return out;\n}\n\n",
48
- "import { spawn, type ChildProcess, type SpawnOptions } from 'node:child_process';\nimport type { AgentContext } from '@kman/types';\n\nexport interface SpawnArgs {\n command: string;\n args: string[];\n /** Mode: 'run' uses stdio inherit; 'chat' uses stdio inherit but you may override. */\n options?: SpawnOptions;\n}\n\n/**\n * Spawn a backend binary with stdio inherited so the child speaks directly to the user.\n * Merges the AgentContext env into the spawn env without leaking unrelated parent env.\n */\nexport function spawnBackend(ctx: AgentContext, args: SpawnArgs): ChildProcess {\n const baseEnv: NodeJS.ProcessEnv = {\n ...process.env,\n ...ctx.env,\n };\n const opts: SpawnOptions = {\n cwd: ctx.cwd,\n env: baseEnv,\n stdio: 'inherit',\n shell: false,\n ...args.options,\n };\n return spawn(args.command, args.args, opts);\n}\n",
49
- "import type { ChildProcess } from 'node:child_process';\nimport { spawnBackend } from '@kman/backend-base';\nimport type {\n AgentContext,\n Backend,\n BackendCapabilities,\n ChatOptions,\n PermissionLevel,\n RunOptions,\n} from '@kman/types';\n\n/**\n * Claude Code adapter (§3.3). Loads agent dir directly via --plugin-dir.\n *\n * Permission mapping (abstract → claude-code's --permission-mode):\n * ask → default\n * auto → acceptEdits\n * yolo → bypassPermissions\n */\nconst PERMISSION_MAP: Record<PermissionLevel, string> = {\n ask: 'default',\n auto: 'acceptEdits',\n yolo: 'bypassPermissions',\n};\n\nexport class ClaudeCodeBackend implements Backend {\n readonly name = 'claude-code';\n readonly capabilities: BackendCapabilities = {\n supportClaudeCodePlugin: true,\n supportsAppendSystemPrompt: true,\n supportsNativeResume: true,\n };\n\n private readonly binary: string;\n\n constructor(binary?: string) {\n this.binary = binary ?? process.env['KMAN_CLAUDE_BIN'] ?? 'claude';\n }\n\n mapPermission(level: PermissionLevel): string {\n return PERMISSION_MAP[level] ?? 'default';\n }\n\n async spawn(ctx: AgentContext, _opts?: RunOptions): Promise<ChildProcess> {\n const args = this.buildArgs(ctx, /* interactive */ false);\n return spawnBackend(ctx, { command: this.binary, args });\n }\n\n async chat(ctx: AgentContext, _opts?: ChatOptions): Promise<ChildProcess> {\n const args = this.buildArgs(ctx, /* interactive */ true);\n return spawnBackend(ctx, { command: this.binary, args });\n }\n\n private buildArgs(ctx: AgentContext, interactive: boolean): string[] {\n const args: string[] = [];\n\n // Plugin directory — load the agent dir as a Claude Code plugin (§4, §3.3).\n args.push('--plugin-dir', ctx.agentDir);\n\n // Soul prompt as append-system-prompt (§3.2).\n if (ctx.soulPrompt.trim().length > 0) {\n args.push('--append-system-prompt', ctx.soulPrompt);\n }\n\n // Model override.\n if (ctx.model) {\n args.push('--model', ctx.model);\n }\n\n // Permission mode: raw escape hatch wins over abstract.\n const pmode = ctx.permissionModeRaw ?? this.mapPermission(ctx.permission);\n args.push('--permission-mode', pmode);\n\n // Max turns.\n if (ctx.maxTurns !== undefined) {\n args.push('--max-turns', String(ctx.maxTurns));\n }\n\n // Output format — only meaningful in non-interactive mode.\n if (!interactive) {\n args.push('--output-format', ctx.outputFormat);\n if (ctx.stream && ctx.outputFormat === 'stream-json') {\n args.push('--include-partial-messages');\n }\n }\n\n // Extra backend-native args from profile + --runtime-flag.\n for (const extra of ctx.extraArgs) {\n args.push(extra);\n }\n\n // Task: passed via -p/--print in non-interactive mode.\n if (!interactive && ctx.task !== undefined) {\n args.push('--print', ctx.task);\n }\n\n return args;\n }\n}\n\nexport function createClaudeCodeBackend(binary?: string): ClaudeCodeBackend {\n return new ClaudeCodeBackend(binary);\n}\n",
50
- "import type { ChildProcess } from 'node:child_process';\nimport { spawnBackend } from '@kman/backend-base';\nimport type {\n AgentContext,\n Backend,\n BackendCapabilities,\n ChatOptions,\n PermissionLevel,\n RunOptions,\n} from '@kman/types';\n\n/**\n * GitHub Copilot CLI adapter. v1 honest capability flags: Copilot CLI does not\n * load Claude Code plugins natively, but accepts a system-prompt override via\n * `--system-prompt` and supports prompt-on-run via `--prompt`.\n *\n * Adapters for plugin features (skills, hooks, MCP) are left to future work;\n * the design doc treats this as the adapter's responsibility (§3.3).\n */\nconst PERMISSION_MAP: Record<PermissionLevel, string> = {\n ask: 'ask',\n auto: 'auto',\n yolo: 'all',\n};\n\nexport class CopilotCliBackend implements Backend {\n readonly name = 'copilot-cli';\n readonly capabilities: BackendCapabilities = {\n supportClaudeCodePlugin: false,\n supportsAppendSystemPrompt: true,\n supportsNativeResume: true,\n };\n\n private readonly binary: string;\n\n constructor(binary?: string) {\n this.binary = binary ?? process.env['KMAN_COPILOT_BIN'] ?? 'copilot';\n }\n\n mapPermission(level: PermissionLevel): string {\n return PERMISSION_MAP[level] ?? 'ask';\n }\n\n async spawn(ctx: AgentContext, _opts?: RunOptions): Promise<ChildProcess> {\n const args = this.buildArgs(ctx, /* interactive */ false);\n return spawnBackend(ctx, { command: this.binary, args });\n }\n\n async chat(ctx: AgentContext, _opts?: ChatOptions): Promise<ChildProcess> {\n const args = this.buildArgs(ctx, /* interactive */ true);\n return spawnBackend(ctx, { command: this.binary, args });\n }\n\n private buildArgs(ctx: AgentContext, interactive: boolean): string[] {\n const args: string[] = [];\n\n if (ctx.soulPrompt.trim().length > 0) {\n args.push('--system-prompt', ctx.soulPrompt);\n }\n\n if (ctx.model) {\n args.push('--model', ctx.model);\n }\n\n const pmode = ctx.permissionModeRaw ?? this.mapPermission(ctx.permission);\n args.push('--approve-mode', pmode);\n\n for (const extra of ctx.extraArgs) {\n args.push(extra);\n }\n\n if (!interactive && ctx.task !== undefined) {\n args.push('--prompt', ctx.task);\n }\n\n return args;\n }\n}\n\nexport function createCopilotCliBackend(binary?: string): CopilotCliBackend {\n return new CopilotCliBackend(binary);\n}\n",
51
- "import { createClaudeCodeBackend } from '@kman/backend-claude-code';\nimport { createCopilotCliBackend } from '@kman/backend-copilot-cli';\nimport { UserError, type Backend, type BackendName } from '@kman/types';\n\nconst BACKENDS: Record<string, () => Backend> = {\n 'claude-code': createClaudeCodeBackend,\n 'copilot-cli': createCopilotCliBackend,\n};\n\nexport function resolveBackend(name: BackendName): Backend {\n const factory = BACKENDS[name];\n if (!factory) {\n throw new UserError(\n `Unknown backend \"${name}\". Built-in backends: ${Object.keys(BACKENDS).join(', ')}.`,\n );\n }\n return factory();\n}\n\nexport function listBackends(): string[] {\n return Object.keys(BACKENDS);\n}\n",
52
- "import { UserError } from '@kman/types';\n\nexport function parsePermission(value: string): 'ask' | 'auto' | 'yolo' {\n if (value === 'ask' || value === 'auto' || value === 'yolo') return value;\n throw new UserError(`Invalid --permission \"${value}\". Expected: ask | auto | yolo.`);\n}\n\nexport function parseOutputFormat(value: string): 'text' | 'json' | 'stream-json' {\n if (value === 'text' || value === 'json' || value === 'stream-json') return value;\n throw new UserError(`Invalid --output \"${value}\". Expected: text | json | stream-json.`);\n}\n",
53
- "import { Command } from 'commander';\nimport { buildContext, launchRun, readProfile } from '@kman/core';\nimport { UserError, type OutputFormat, type PermissionLevel } from '@kman/types';\nimport { requireAgent } from '../common/agent-option.js';\nimport { resolveBackend } from '../common/backend-registry.js';\nimport { parseOutputFormat, parsePermission } from '../common/run-args.js';\n\nexport function buildRunCommand(): Command {\n return new Command('run')\n .description('One-shot run of an agent.')\n .option('--task <text>', 'Task prompt passed to the backend.')\n .option('--runtime <backend>', 'Override the agent\\'s default backend.')\n .option('--model <id>', 'Override model id.')\n .option('--permission <level>', 'ask | auto | yolo')\n .option('--runtime-flag <flag>', 'Raw backend-native flag (repeatable).', collect, [] as string[])\n .option('--output <format>', 'text | json | stream-json')\n .option('--stream', 'Implies --output stream-json.')\n .option('--cwd <path>', 'Working directory for the backend.')\n .action(\n async (opts: {\n task?: string;\n runtime?: string;\n model?: string;\n permission?: string;\n runtimeFlag: string[];\n output?: string;\n stream?: boolean;\n cwd?: string;\n }) => {\n const agent = requireAgent();\n const profile = await readProfile(agent);\n\n if (opts.stream && opts.output && opts.output !== 'stream-json') {\n throw new UserError('--stream conflicts with --output of a different value.');\n }\n\n const ctx = await buildContext(profile, {\n ...(opts.runtime ? { backend: opts.runtime } : {}),\n ...(opts.model ? { model: opts.model } : {}),\n ...(opts.permission ? { permission: parsePermission(opts.permission) as PermissionLevel } : {}),\n ...(opts.output ? { outputFormat: parseOutputFormat(opts.output) as OutputFormat } : {}),\n ...(opts.stream !== undefined ? { stream: opts.stream === true } : {}),\n ...(opts.cwd ? { cwd: opts.cwd } : {}),\n ...(opts.task !== undefined ? { task: opts.task } : {}),\n runtimeFlags: expandRuntimeFlags(opts.runtimeFlag),\n });\n\n const backend = resolveBackend(ctx.backend);\n const { exitCode } = await launchRun(backend, ctx);\n process.exit(exitCode);\n },\n );\n}\n\nfunction collect(value: string, previous: string[]): string[] {\n return [...previous, value];\n}\n\nfunction expandRuntimeFlags(values: string[]): string[] {\n const out: string[] = [];\n for (const item of values) {\n if (item.includes('=') && !item.startsWith('--')) {\n const eq = item.indexOf('=');\n const k = item.slice(0, eq);\n const v = item.slice(eq + 1);\n out.push(`--${k}`, v);\n } else {\n out.push(item);\n }\n }\n return out;\n}\n",
54
- "import { Command } from 'commander';\nimport { buildContext, launchChat, readProfile } from '@kman/core';\nimport type { PermissionLevel } from '@kman/types';\nimport { requireAgent } from '../common/agent-option.js';\nimport { resolveBackend } from '../common/backend-registry.js';\nimport { parsePermission } from '../common/run-args.js';\n\nexport function buildChatCommand(): Command {\n return new Command('chat')\n .description('Interactive REPL with an agent.')\n .option('--runtime <backend>', 'Override the agent\\'s default backend.')\n .option('--model <id>', 'Override model id.')\n .option('--permission <level>', 'ask | auto | yolo')\n .option('--runtime-flag <flag>', 'Raw backend-native flag (repeatable).', collect, [] as string[])\n .option('--cwd <path>', 'Working directory for the backend.')\n .action(\n async (opts: {\n runtime?: string;\n model?: string;\n permission?: string;\n runtimeFlag: string[];\n cwd?: string;\n }) => {\n const agent = requireAgent();\n const profile = await readProfile(agent);\n\n const ctx = await buildContext(profile, {\n ...(opts.runtime ? { backend: opts.runtime } : {}),\n ...(opts.model ? { model: opts.model } : {}),\n ...(opts.permission ? { permission: parsePermission(opts.permission) as PermissionLevel } : {}),\n ...(opts.cwd ? { cwd: opts.cwd } : {}),\n runtimeFlags: expandRuntimeFlags(opts.runtimeFlag),\n });\n\n const backend = resolveBackend(ctx.backend);\n const { exitCode } = await launchChat(backend, ctx);\n process.exit(exitCode);\n },\n );\n}\n\nfunction collect(value: string, previous: string[]): string[] {\n return [...previous, value];\n}\n\nfunction expandRuntimeFlags(values: string[]): string[] {\n const out: string[] = [];\n for (const item of values) {\n if (item.includes('=') && !item.startsWith('--')) {\n const eq = item.indexOf('=');\n const k = item.slice(0, eq);\n const v = item.slice(eq + 1);\n out.push(`--${k}`, v);\n } else {\n out.push(item);\n }\n }\n return out;\n}\n",
55
- "import { Command } from 'commander';\n\nexport function buildVersionCommand(): Command {\n return new Command('version').description('Print kman CLI version.').action(() => {\n process.stdout.write('kman 0.0.2\\n');\n });\n}\n",
56
- "import { Command, CommanderError } from 'commander';\nimport { KmanError, ExitCode } from '@kman/types';\nimport { buildAgentCommand } from './commands/agent.js';\nimport { buildSkillsCommand } from './commands/skills.js';\nimport { buildRunCommand } from './commands/run.js';\nimport { buildChatCommand } from './commands/chat.js';\nimport { buildVersionCommand } from './commands/version.js';\nimport { extractAgentOption } from './common/agent-option.js';\n\nfunction die(err: unknown): never {\n if (err instanceof KmanError) {\n if (err.message) process.stderr.write(`kman: ${err.message}\\n`);\n process.exit(err.code);\n }\n // commander throws CommanderError for usage / unknown-command / missing-arg.\n if (err instanceof CommanderError) {\n // commander already prints to stderr for these. Map common ones to our exit codes.\n const code = err.code === 'commander.help' || err.code === 'commander.helpDisplayed' ? 0 : ExitCode.UserError;\n process.exit(code);\n }\n const message = err instanceof Error ? err.message : String(err);\n process.stderr.write(`kman: unexpected error: ${message}\\n`);\n if (process.env['KMAN_DEBUG'] && err instanceof Error && err.stack) {\n process.stderr.write(err.stack + '\\n');\n }\n process.exit(ExitCode.AgentError);\n}\n\nconst program = new Command();\nprogram\n .name('kman')\n .description('Multi-agent orchestration engine (inspired by Kingsman).')\n .version('0.0.2', '-v, --version', 'Print kman CLI version.')\n .helpOption('-h, --help', 'Show help.')\n .showHelpAfterError()\n .exitOverride();\n\n// Global option declared for help-text discoverability. Real parsing happens\n// in `extractAgentOption` so that `-a` may appear before *or* after the\n// subcommand (§6).\nprogram.option('-a, --agent <name>', 'Target agent name (lowercase kebab-case). Required by agent-scoped subcommands.');\n\nprogram.addCommand(buildAgentCommand());\nprogram.addCommand(buildSkillsCommand());\nprogram.addCommand(buildRunCommand());\nprogram.addCommand(buildChatCommand());\nprogram.addCommand(buildVersionCommand());\n\nlet rawArgs: string[];\ntry {\n const argv = process.argv.slice(2);\n const { rest, agent } = extractAgentOption(argv);\n if (agent !== undefined) process.env['KMAN_SELECTED_AGENT'] = agent;\n rawArgs = rest;\n} catch (err) {\n die(err);\n}\n\nif (rawArgs.length === 0) {\n program.outputHelp();\n process.exit(ExitCode.UserError);\n}\n\ntry {\n await program.parseAsync(rawArgs, { from: 'user' });\n} catch (err) {\n die(err);\n}\n"
57
- ],
58
- "mappings": "4nBAGA,MAAM,WAAuB,KAAM,CAOjC,WAAW,CAAC,EAAU,EAAM,EAAS,CACnC,MAAM,CAAO,EAEb,MAAM,kBAAkB,KAAM,KAAK,WAAW,EAC9C,KAAK,KAAO,KAAK,YAAY,KAC7B,KAAK,KAAO,EACZ,KAAK,SAAW,EAChB,KAAK,YAAc,OAEvB,CAKA,MAAM,WAA6B,EAAe,CAKhD,WAAW,CAAC,EAAS,CACnB,MAAM,EAAG,4BAA6B,CAAO,EAE7C,MAAM,kBAAkB,KAAM,KAAK,WAAW,EAC9C,KAAK,KAAO,KAAK,YAAY,KAEjC,CAEQ,kBAAiB,GACjB,wBAAuB,qBCtC/B,IAAQ,8BAER,MAAM,EAAS,CAUb,WAAW,CAAC,EAAM,EAAa,CAQ7B,OAPA,KAAK,YAAc,GAA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