hacksh 0.16.0 → 0.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["parseNodeArgs","#owner","details","#interactive","#inputValue","#printEvent","#bufferedKeys","#terminal","#signal","#print","#run"],"sources":["../src/options.ts","../src/schema.ts","../src/command.ts","../src/environment.ts","../src/parser.ts","../src/command-output.ts","../src/terminal.ts","../src/logger.ts","../src/package-version.ts","../src/prompts.ts","../src/output.ts","../src/usage.ts","../src/run.ts"],"sourcesContent":["export function kebabCase(value: string): string {\n return value.replaceAll(/([a-z0-9])([A-Z])/g, \"$1-$2\").toLowerCase();\n}\n\nexport function aliasList(value: string | readonly string[]): readonly string[] {\n return typeof value === \"string\" ? [value] : value;\n}\n","import { globalRegistry, type $ZodObject, type $ZodType, type JSONSchemaMeta } from \"zod/v4/core\";\nimport type {} from \"zod\";\nimport type {} from \"zod/v4\";\n\ninterface ArgumentMeta extends JSONSchemaMeta {\n alias?: string | readonly string[];\n env?: string | false;\n valueName?: string;\n}\n\ndeclare module \"zod\" {\n interface GlobalMeta extends ArgumentMeta {}\n}\n\ndeclare module \"zod/v4\" {\n interface GlobalMeta extends ArgumentMeta {}\n}\n\nexport type ArgsSchema = $ZodObject;\nexport type EmptyArgs = $ZodObject<{}>;\n\nexport const POSITIONALS_KEY = \"positionals\";\n\nexport interface ArgInfo {\n readonly takesValue: boolean;\n readonly required: boolean;\n readonly defaultValue: unknown;\n readonly description: string | undefined;\n readonly title: string | undefined;\n readonly alias: string | readonly string[] | undefined;\n readonly valueName: string | undefined;\n readonly env: string | false | undefined;\n readonly choices: readonly string[] | undefined;\n}\n\nexport interface Positional {\n readonly schema: $ZodType;\n readonly label: string;\n}\n\nexport interface Positionals {\n readonly items: readonly Positional[];\n readonly rest: Positional | undefined;\n}\n\ntype ZodDef = Record<string, unknown> & { type: string };\n\nfunction definition(schema: $ZodType): ZodDef {\n return schema._zod.def as ZodDef;\n}\n\nfunction innerSchema(def: ZodDef): $ZodType | undefined {\n switch (def.type) {\n case \"optional\":\n case \"nonoptional\":\n case \"nullable\":\n case \"default\":\n case \"prefault\":\n case \"catch\":\n case \"readonly\":\n return def.innerType as $ZodType;\n case \"pipe\":\n return def.in as $ZodType;\n default:\n return undefined;\n }\n}\n\n/** Read only the common zod/v4/core definition and registry structures. */\nexport function readArgInfo(schema: $ZodType): ArgInfo {\n let current: $ZodType | undefined = schema;\n let required = true;\n let defaultValue: unknown;\n let description: string | undefined;\n let title: string | undefined;\n let alias: string | readonly string[] | undefined;\n let valueName: string | undefined;\n let env: string | false | undefined;\n\n while (current) {\n const metadata = globalRegistry.get(current);\n if (metadata) {\n if (\n metadata.alias !== undefined &&\n typeof metadata.alias !== \"string\" &&\n !(\n Array.isArray(metadata.alias) &&\n metadata.alias.every((value) => typeof value === \"string\")\n )\n ) {\n throw new TypeError(\"Argument metadata `alias` must be a string or an array of strings\");\n }\n if (\n metadata.env !== undefined &&\n typeof metadata.env !== \"string\" &&\n metadata.env !== false\n ) {\n throw new TypeError(\"Argument metadata `env` must be a string or false\");\n }\n for (const key of [\"valueName\", \"title\", \"description\"] as const) {\n if (metadata[key] !== undefined && typeof metadata[key] !== \"string\") {\n throw new TypeError(`Argument metadata \\`${key}\\` must be a string`);\n }\n }\n alias ??= metadata.alias;\n valueName ??= metadata.valueName;\n env ??= metadata.env;\n }\n description ??= metadata?.description;\n title ??= metadata?.title;\n\n const def = definition(current);\n if (def.type === \"optional\" || def.type === \"default\" || def.type === \"prefault\") {\n required = false;\n }\n if (def.type === \"default\" && defaultValue === undefined) defaultValue = def.defaultValue;\n current = innerSchema(def);\n }\n\n const base = unwrapInput(schema);\n return {\n takesValue: definition(base).type !== \"boolean\",\n required,\n defaultValue,\n description,\n title,\n alias,\n valueName,\n env,\n choices: enumChoices(base),\n };\n}\n\n/** Read the `positionals` tuple or array schema that declares positional arguments. */\nexport function readPositionals(shape: Record<string, $ZodType>): Positionals | undefined {\n const field = shape[POSITIONALS_KEY];\n if (!field) return undefined;\n const def = definition(unwrapInput(field));\n let items: readonly $ZodType[];\n let rest: $ZodType | undefined;\n if (def.type === \"tuple\") {\n items = def.items as readonly $ZodType[];\n rest = (def.rest as $ZodType | null) ?? undefined;\n } else if (def.type === \"array\") {\n items = [];\n rest = def.element as $ZodType;\n } else {\n throw new TypeError(\"Positional arguments `positionals` must use a tuple or array schema\");\n }\n return {\n items: items.map((schema, index) => ({\n schema,\n label: readArgInfo(schema).title ?? `ARG${index + 1}`,\n })),\n rest: rest && { schema: rest, label: readArgInfo(rest).title ?? \"ARGS\" },\n };\n}\n\nfunction enumChoices(schema: $ZodType): readonly string[] | undefined {\n const def = definition(schema);\n const candidate = def.type === \"array\" ? unwrapInput(def.element as $ZodType) : schema;\n const candidateDef = definition(candidate);\n if (candidateDef.type !== \"enum\") return undefined;\n const values = candidate._zod.values;\n return values ? [...values].map(String) : undefined;\n}\n\n/** Whether the schema accepts an array after removing supported input wrappers. */\nexport function isArrayInput(schema: $ZodType): boolean {\n return definition(unwrapInput(schema)).type === \"array\";\n}\n\n/** Whether the schema accepts an object after removing supported input wrappers. */\nexport function isObjectInput(schema: $ZodType): boolean {\n return definition(unwrapInput(schema)).type === \"object\";\n}\n\nfunction unwrapInput(schema: $ZodType): $ZodType {\n let current = schema;\n for (;;) {\n const inner = innerSchema(definition(current));\n if (!inner) return current;\n current = inner;\n }\n}\n\nexport function schemaShape(schema: ArgsSchema): Record<string, $ZodType> {\n return schema._zod.def.shape as Record<string, $ZodType>;\n}\n","import type { output } from \"zod/v4/core\";\nimport type { Output } from \"./command-output.ts\";\nimport type { Exec } from \"./exec.ts\";\nimport type { Logger } from \"./logger.ts\";\nimport type { Prompter } from \"./prompts.ts\";\nimport { aliasList } from \"./options.ts\";\nimport {\n isArrayInput,\n isObjectInput,\n POSITIONALS_KEY,\n readArgInfo,\n readPositionals,\n schemaShape,\n type ArgsSchema,\n type EmptyArgs,\n} from \"./schema.ts\";\n\nexport interface CommandContext<S extends ArgsSchema> {\n command: CommandDef<S>;\n args: output<S>;\n input: {\n argv: string[];\n unknown: string[];\n passthrough: string[];\n };\n output: Output;\n logger: Logger;\n prompt: Prompter;\n exec: Exec;\n signal: AbortSignal;\n}\n\nexport interface CommandDef<\n S extends ArgsSchema = EmptyArgs,\n R = unknown,\n Children extends Record<string, AnyCommandDef> = Record<string, AnyCommandDef>,\n> {\n name?: string;\n version?: string;\n description?: string;\n hidden?: boolean;\n /** Keep unknown options and excess positionals in input.unknown. Inherits from the parent; defaults to false. */\n allowUnknownArgs?: boolean;\n args?: S;\n subCommands?: Children;\n run?(context: CommandContext<S>): R;\n}\n\nexport type AnyCommandDef = CommandDef<ArgsSchema>;\n\nexport function defineCommand<\n S extends ArgsSchema = EmptyArgs,\n R = never,\n Children extends Record<string, AnyCommandDef> = {},\n>(def: CommandDef<S, R, Children>): CommandDef<S, NoInfer<R>, NoInfer<Children>> {\n if (def.allowUnknownArgs !== undefined && typeof def.allowUnknownArgs !== \"boolean\") {\n throw new TypeError(\"allowUnknownArgs must be a boolean\");\n }\n const shape = def.args ? schemaShape(def.args) : {};\n const positionals = readPositionals(shape);\n\n if (positionals) {\n let sawOptional = false;\n for (const { schema, label } of positionals.items) {\n const info = readArgInfo(schema);\n if (info.alias !== undefined || info.env !== undefined || info.valueName !== undefined) {\n throw new TypeError(\n `Positional argument \\`${label}\\` cannot have alias, env, or valueName metadata`,\n );\n }\n if (isArrayInput(schema)) {\n throw new TypeError(\n `Positional argument \\`${label}\\` cannot be an array; use a tuple rest`,\n );\n }\n if (!info.takesValue) {\n throw new TypeError(`Boolean argument \\`${label}\\` cannot be positional`);\n }\n if (sawOptional && info.required) {\n throw new TypeError(\n `Required positional \\`${label}\\` cannot follow an optional positional`,\n );\n }\n sawOptional ||= !info.required;\n }\n if (positionals.rest) {\n const info = readArgInfo(positionals.rest.schema);\n if (info.alias !== undefined || info.env !== undefined || info.valueName !== undefined) {\n throw new TypeError(\n `Positional argument \\`${positionals.rest.label}\\` cannot have alias, env, or valueName metadata`,\n );\n }\n }\n if (def.subCommands && Object.keys(def.subCommands).length > 0) {\n throw new TypeError(\"A command cannot define both positional arguments and subcommands\");\n }\n }\n\n const usedAliases = new Set<string>();\n for (const [key, schema] of Object.entries(shape)) {\n const options = readArgInfo(schema);\n if (key === POSITIONALS_KEY) {\n if (\n options.alias !== undefined ||\n options.env !== undefined ||\n options.valueName !== undefined\n ) {\n throw new TypeError(\"Positional arguments cannot have alias, env, or valueName metadata\");\n }\n continue;\n }\n if (options.env !== undefined) {\n if (options.env === \"\") {\n throw new TypeError(`Environment variable name for \\`${key}\\` cannot be empty`);\n }\n if (isArrayInput(schema)) {\n throw new TypeError(\n `Option \\`${key}\\` cannot use an environment variable because it accepts an array`,\n );\n }\n if (isObjectInput(schema)) {\n throw new TypeError(\n `Option \\`${key}\\` cannot use an environment variable because it accepts an object`,\n );\n }\n }\n if (options.alias === undefined) continue;\n for (const alias of aliasList(options.alias)) {\n if (alias.length !== 1)\n throw new TypeError(`Alias \\`${alias}\\` must be exactly one character`);\n if (usedAliases.has(alias)) throw new TypeError(`Duplicate alias \\`${alias}\\``);\n usedAliases.add(alias);\n }\n }\n\n for (const key of Object.keys(shape)) {\n if (key === \"help\" || key === \"version\") {\n throw new TypeError(`Option \\`${key}\\` conflicts with the builtin --${key}`);\n }\n if (key !== POSITIONALS_KEY && /^no[-A-Z]/.test(key)) {\n throw new TypeError(`Option \\`${key}\\` conflicts with --no- negation`);\n }\n }\n\n return def;\n}\n","import type { AnyCommandDef } from \"./command.ts\";\nimport { kebabCase } from \"./options.ts\";\nimport {\n isArrayInput,\n isObjectInput,\n POSITIONALS_KEY,\n readArgInfo,\n schemaShape,\n} from \"./schema.ts\";\n\nconst commandPaths = new WeakMap<AnyCommandDef, readonly string[] | undefined>();\n\nexport function registerCommandPath(\n command: AnyCommandDef,\n path: readonly string[] | undefined,\n): void {\n commandPaths.set(command, path);\n}\n\nexport function commandEnvPath(command: AnyCommandDef): readonly string[] | undefined {\n if (!commandPaths.has(command)) return command.name ? [command.name] : undefined;\n return commandPaths.get(command);\n}\n\nfunction envSegment(segment: string): string {\n return kebabCase(segment)\n .replaceAll(/[^A-Za-z0-9]+/g, \"_\")\n .toUpperCase();\n}\n\nexport function optionEnvNames(\n command: AnyCommandDef,\n path: readonly string[] | undefined,\n): ReadonlyMap<string, string> {\n const names = new Map<string, string>();\n if (!command.args) return names;\n for (const [key, schema] of Object.entries(schemaShape(command.args))) {\n if (key === POSITIONALS_KEY) continue;\n if (isArrayInput(schema) || isObjectInput(schema)) continue;\n const configured = readArgInfo(schema).env;\n if (configured === false) continue;\n if (typeof configured === \"string\") {\n names.set(key, configured);\n continue;\n }\n if (path === undefined || path.length === 0) continue;\n names.set(key, [...path, key].map(envSegment).join(\"_\"));\n }\n return names;\n}\n\nfunction envOptionLabel(path: readonly string[] | undefined, key: string): string {\n const flag = `--${kebabCase(key)}`;\n const command = path?.slice(1).join(\" \");\n return command ? `${command} ${flag}` : flag;\n}\n\nexport function assertUniqueEnvNames(\n segments: readonly {\n command: AnyCommandDef;\n path: readonly string[] | undefined;\n }[],\n): void {\n const owners = new Map<string, string>();\n for (const segment of segments) {\n for (const [key, envName] of optionEnvNames(segment.command, segment.path)) {\n const label = envOptionLabel(segment.path, key);\n const previous = owners.get(envName);\n if (previous !== undefined) {\n throw new TypeError(\n `Environment variable \\`${envName}\\` is used by both \\`${previous}\\` and \\`${label}\\``,\n );\n }\n owners.set(envName, label);\n }\n }\n}\n\nexport function readEnvValue(\n env: Readonly<Record<string, string | undefined>>,\n name: string,\n): string | undefined {\n try {\n const value = env[name];\n return typeof value === \"string\" ? value : undefined;\n } catch {\n return undefined;\n }\n}\n","import { parseArgs as parseNodeArgs } from \"node:util\";\nimport { safeParseAsync, type $ZodIssue, type output } from \"zod/v4/core\";\nimport type { AnyCommandDef, CommandDef } from \"./command.ts\";\nimport { assertUniqueEnvNames, optionEnvNames, readEnvValue } from \"./environment.ts\";\nimport { HackshValidationError, type HackshIssue } from \"./errors.ts\";\nimport { aliasList, kebabCase } from \"./options.ts\";\nimport {\n POSITIONALS_KEY,\n readArgInfo,\n readPositionals,\n schemaShape,\n type ArgsSchema,\n type Positionals,\n} from \"./schema.ts\";\n\nexport interface ParsedCommand<S extends ArgsSchema> {\n args: output<S>;\n passthrough: string[];\n extraArgs: string[];\n}\n\ninterface OptionDefinition {\n readonly key: string;\n readonly kebabName: string;\n readonly takesValue: boolean;\n}\n\ninterface OptionModel {\n readonly definitions: Map<string, OptionDefinition>;\n readonly parserOptions: Record<string, { type: \"string\" | \"boolean\"; short?: string }>;\n readonly aliases: Set<string>;\n}\n\ninterface KnownOptionToken {\n readonly kind: \"known-option\";\n readonly index: number;\n readonly definition: OptionDefinition;\n readonly value: string | boolean;\n}\n\ninterface UnknownOptionToken {\n readonly kind: \"unknown-option\";\n readonly index: number;\n readonly value: string;\n}\n\ninterface PositionalToken {\n readonly kind: \"positional\";\n readonly index: number;\n readonly value: string;\n}\n\ntype CommandToken = KnownOptionToken | UnknownOptionToken | PositionalToken;\n\nexport interface TokenizedCommandArgs {\n readonly tokens: readonly CommandToken[];\n readonly passthrough: string[];\n readonly issues: readonly IndexedIssue[];\n readonly help: boolean;\n readonly helpIndex: number | undefined;\n readonly version: boolean;\n readonly versionIndex: number | undefined;\n}\n\ninterface IndexedIssue {\n readonly index: number;\n readonly issue: HackshIssue;\n}\n\nfunction optionModel(command: AnyCommandDef): OptionModel {\n const definitions = new Map<string, OptionDefinition>();\n const parserOptions: OptionModel[\"parserOptions\"] = {};\n const allAliases = new Set<string>();\n\n if (command.args) {\n for (const [key, schema] of Object.entries(schemaShape(command.args))) {\n if (key === POSITIONALS_KEY) continue;\n const info = readArgInfo(schema);\n const aliases = info.alias === undefined ? [] : aliasList(info.alias);\n const definition: OptionDefinition = {\n key,\n kebabName: kebabCase(key),\n takesValue: info.takesValue,\n };\n const type = definition.takesValue ? \"string\" : \"boolean\";\n for (const name of new Set([key, definition.kebabName])) {\n definitions.set(name, definition);\n parserOptions[name] = { type };\n }\n for (const alias of aliases) {\n allAliases.add(alias);\n definitions.set(alias, definition);\n parserOptions[alias] = { type, short: alias };\n }\n }\n }\n return { definitions, parserOptions, aliases: allAliases };\n}\n\nfunction commandPositionals(command: AnyCommandDef): Positionals | undefined {\n return command.args ? readPositionals(schemaShape(command.args)) : undefined;\n}\n\nfunction displayName(command: AnyCommandDef, path: readonly PropertyKey[]): string {\n const [first, index] = path;\n if (typeof first !== \"string\") return \"arguments\";\n if (first !== POSITIONALS_KEY) return `--${kebabCase(first)}`;\n const positionals = commandPositionals(command);\n if (!positionals || typeof index !== \"number\") return \"arguments\";\n const item = positionals.items[index];\n if (item) return `<${item.label}>`;\n return positionals.rest ? `<${positionals.rest.label}...>` : \"arguments\";\n}\n\nexport function tokenizeCommandArgs(\n command: AnyCommandDef,\n rawArgs: readonly string[],\n): TokenizedCommandArgs {\n const model = optionModel(command);\n const separator = rawArgs.indexOf(\"--\");\n const beforeSeparator = separator === -1 ? [...rawArgs] : rawArgs.slice(0, separator);\n const passthrough = separator === -1 ? [] : rawArgs.slice(separator + 1);\n const negativeIndexes = new Set<number>();\n const valuedNegativeIndexes = new Set<number>();\n const issues: IndexedIssue[] = [];\n let recordedMissingValue = false;\n const parserArgs = beforeSeparator.map((raw, index) => {\n if (!raw.startsWith(\"--no-\")) return raw;\n const equals = raw.indexOf(\"=\");\n const name = raw.slice(5, equals === -1 ? undefined : equals);\n const definition = model.definitions.get(name);\n if (!definition || definition.takesValue) return raw;\n negativeIndexes.add(index);\n if (equals !== -1) {\n valuedNegativeIndexes.add(index);\n return `--${definition.key}${raw.slice(equals)}`;\n }\n return `--${definition.key}`;\n });\n\n const parsed = parseNodeArgs({\n args: parserArgs,\n options: model.parserOptions,\n allowPositionals: true,\n strict: false,\n tokens: true,\n });\n const tokens: CommandToken[] = [];\n const unknownIndexes = new Set<number>();\n let help = false;\n let helpIndex: number | undefined;\n let version = false;\n let versionIndex: number | undefined;\n for (const token of parsed.tokens) {\n if (token.kind === \"positional\") {\n tokens.push({ kind: \"positional\", index: token.index, value: token.value });\n continue;\n }\n if (token.kind !== \"option\") continue;\n const isHelp =\n token.rawName === \"--help\" || (token.rawName === \"-h\" && !model.aliases.has(\"h\"));\n const isVersion =\n token.rawName === \"--version\" || (token.rawName === \"-v\" && !model.aliases.has(\"v\"));\n if (isHelp) {\n help = true;\n helpIndex ??= token.index;\n }\n if (isVersion) {\n version = true;\n versionIndex ??= token.index;\n }\n const definition = model.definitions.get(token.name);\n if (definition) {\n if (\n definition.takesValue &&\n (token.value === undefined ||\n (!token.inlineValue && token.value.startsWith(\"-\") && token.value !== \"-\"))\n ) {\n if (!recordedMissingValue) {\n issues.push({\n index: token.index,\n issue: { arg: `--${definition.kebabName}`, message: \"requires a value\" },\n });\n recordedMissingValue = true;\n }\n }\n let value: string | boolean = token.value ?? true;\n if (!definition.takesValue) {\n if (valuedNegativeIndexes.has(token.index)) {\n const rawName = beforeSeparator[token.index]!.split(\"=\", 1)[0]!;\n issues.push({\n index: token.index,\n issue: { arg: rawName, message: \"does not accept a value\" },\n });\n value = false;\n } else if (negativeIndexes.has(token.index)) {\n value = false;\n } else if (token.inlineValue) {\n if (token.value === \"true\") value = true;\n else if (token.value === \"false\") value = false;\n else {\n issues.push({\n index: token.index,\n issue: { arg: token.rawName, message: \"expects true or false\" },\n });\n }\n }\n }\n tokens.push({\n kind: \"known-option\",\n index: token.index,\n definition,\n value: definition.takesValue ? (token.value ?? \"\") : value,\n });\n } else if (!unknownIndexes.has(token.index)) {\n unknownIndexes.add(token.index);\n tokens.push({\n kind: \"unknown-option\",\n index: token.index,\n value: beforeSeparator[token.index]!,\n });\n }\n }\n\n return {\n tokens,\n passthrough,\n issues,\n help,\n helpIndex,\n version,\n versionIndex,\n };\n}\n\nexport function tokenizedBefore(\n tokenized: TokenizedCommandArgs,\n endIndex: number,\n): TokenizedCommandArgs {\n const help = tokenized.helpIndex !== undefined && tokenized.helpIndex < endIndex;\n const version = tokenized.versionIndex !== undefined && tokenized.versionIndex < endIndex;\n return {\n tokens: tokenized.tokens.filter((token) => token.index < endIndex),\n passthrough: [],\n issues: tokenized.issues.filter(({ index }) => index < endIndex),\n help,\n helpIndex: help ? tokenized.helpIndex : undefined,\n version,\n versionIndex: version ? tokenized.versionIndex : undefined,\n };\n}\n\nfunction zodIssues(\n command: AnyCommandDef,\n issues: readonly $ZodIssue[],\n envSources: ReadonlyMap<string, string>,\n): HackshIssue[] {\n return issues.map((issue) => {\n const key = issue.path[0];\n const envName = typeof key === \"string\" ? envSources.get(key) : undefined;\n return {\n arg: envName ?? displayName(command, issue.path),\n message: issue.message,\n issue,\n };\n });\n}\n\nexport async function parseCommandArgs<S extends ArgsSchema>(\n command: CommandDef<S>,\n rawArgs: string[],\n tokenized: TokenizedCommandArgs = tokenizeCommandArgs(command, rawArgs),\n env?: Readonly<Record<string, string | undefined>>,\n envPath?: readonly string[],\n): Promise<ParsedCommand<S>> {\n if (tokenized.issues.length > 0) {\n throw new HackshValidationError(\n command,\n tokenized.issues.map(({ issue }) => issue),\n );\n }\n\n const input: Record<string, string | boolean | string[] | undefined> = {};\n const positionals = commandPositionals(command);\n const positionalValues: string[] = [];\n if (positionals) input[POSITIONALS_KEY] = positionalValues;\n const extraArgs: string[] = [];\n for (const token of tokenized.tokens) {\n if (token.kind === \"known-option\") input[token.definition.key] = token.value;\n else if (token.kind === \"unknown-option\") extraArgs.push(token.value);\n else if (\n positionals &&\n (positionals.rest || positionalValues.length < positionals.items.length)\n ) {\n positionalValues.push(token.value);\n } else extraArgs.push(token.value);\n }\n\n if (!command.allowUnknownArgs && extraArgs.length > 0) {\n throw new HackshValidationError(\n command,\n extraArgs.map((arg) => ({ arg, message: \"unexpected argument\" })),\n );\n }\n\n const envSources = new Map<string, string>();\n if (env && command.args) {\n const shape = schemaShape(command.args);\n const envIssues: HackshIssue[] = [];\n for (const [key, envName] of optionEnvNames(command, envPath)) {\n if (input[key] !== undefined) continue;\n const value = readEnvValue(env, envName);\n if (value === undefined) continue;\n if (readArgInfo(shape[key]!).takesValue) {\n input[key] = value;\n } else if (value === \"true\" || value === \"false\") {\n input[key] = value === \"true\";\n } else {\n envIssues.push({ arg: envName, message: \"expects true or false\" });\n continue;\n }\n envSources.set(key, envName);\n }\n if (envIssues.length > 0) throw new HackshValidationError(command, envIssues);\n }\n\n if (!command.args)\n return { args: input as output<S>, passthrough: tokenized.passthrough, extraArgs };\n const result = await safeParseAsync(command.args, input);\n if (!result.success) {\n throw new HackshValidationError(command, zodIssues(command, result.error.issues, envSources));\n }\n return { args: result.data, passthrough: tokenized.passthrough, extraArgs };\n}\n\n/**\n * Parse and validate one command segment without routing, builtin handling, or output.\n * Environment variables are read only when `options.env` is provided.\n */\nexport async function parseArgs<S extends ArgsSchema>(\n command: CommandDef<S>,\n argv: string[],\n options?: { readonly env?: Readonly<Record<string, string | undefined>> },\n): Promise<output<S>> {\n const envPath = command.name ? [command.name] : undefined;\n if (options?.env !== undefined) assertUniqueEnvNames([{ command, path: envPath }]);\n return (\n await parseCommandArgs(command, argv, tokenizeCommandArgs(command, argv), options?.env, envPath)\n ).args;\n}\n","import type { Printer } from \"./printer.ts\";\n\n/** Writes a command's results to stdout, separately from logs. */\nexport interface Output {\n /** Write text exactly as given. */\n print(text: string): void;\n /** Write text followed by a newline. */\n println(text?: string): void;\n /** Write a JSON value. */\n json(value: unknown): void;\n}\n\n/** Create the output for one command invocation. */\nexport function createOutput(printer: Printer): Output {\n function print(text: string): void {\n void printer.print({ type: \"output\", kind: \"text\", text });\n }\n return {\n print,\n println: (text = \"\") => print(`${text}\\n`),\n json: (data) => void printer.print({ type: \"output\", kind: \"json\", data }),\n };\n}\n","export type TerminalOwner = \"prompt\" | \"exec\";\n\nexport class TerminalLock {\n #owner: TerminalOwner | undefined;\n\n get owner(): TerminalOwner | undefined {\n return this.#owner;\n }\n\n acquire(owner: TerminalOwner): boolean {\n if (this.#owner !== undefined) return false;\n this.#owner = owner;\n return true;\n }\n\n release(): void {\n this.#owner = undefined;\n }\n}\n","import type { Printer } from \"./printer.ts\";\nimport { summarizeErrors } from \"./errors.ts\";\n\nexport type LogLevel = \"trace\" | \"debug\" | \"info\" | \"warning\" | \"error\" | \"fatal\";\n\nexport type LogKind = \"message\" | \"step\" | \"success\";\n\nexport type LogProperties = Record<string, unknown>;\n\n/** A structured message emitted by a command's logger. */\nexport interface LogRecord {\n level: LogLevel;\n kind: LogKind;\n category: readonly string[];\n message: string;\n rawMessage: string;\n properties: LogProperties;\n timestamp: number;\n}\n\nexport interface Logger {\n readonly category: readonly string[];\n trace(message: string, properties?: LogProperties): void;\n debug(message: string, properties?: LogProperties): void;\n info(message: string, properties?: LogProperties): void;\n warn(message: string, properties?: LogProperties): void;\n error(message: string | Error, properties?: LogProperties): void;\n fatal(message: string | Error, properties?: LogProperties): void;\n step(message: string, properties?: LogProperties): void;\n success(message: string, properties?: LogProperties): void;\n with(properties: LogProperties): Logger;\n getChild(category: string): Logger;\n}\n\nfunction interpolate(message: string, properties: LogProperties): string {\n return message.replace(/\\{([^{}]+)\\}/g, (placeholder, key: string) => {\n if (!Object.hasOwn(properties, key)) return placeholder;\n try {\n return String(properties[key]);\n } catch {\n return placeholder;\n }\n });\n}\n\nfunction createBoundLogger(\n printer: Printer,\n category: readonly string[],\n boundProperties: LogProperties,\n): Logger {\n function emit(\n level: LogLevel,\n kind: LogKind,\n input: string | Error,\n properties: LogProperties = {},\n ): void {\n const rawMessage = input instanceof Error ? input.message : input;\n const mergedProperties = { ...boundProperties, ...properties };\n if (input instanceof Error) mergedProperties.error = input;\n const summarizedProperties = summarizeErrors(mergedProperties) as LogProperties;\n\n void printer.print({\n type: \"log\",\n record: {\n level,\n kind,\n category,\n message: interpolate(rawMessage, mergedProperties),\n rawMessage,\n properties: summarizedProperties,\n timestamp: Date.now(),\n },\n });\n }\n\n return {\n category,\n trace: (message, properties) => emit(\"trace\", \"message\", message, properties),\n debug: (message, properties) => emit(\"debug\", \"message\", message, properties),\n info: (message, properties) => emit(\"info\", \"message\", message, properties),\n warn: (message, properties) => emit(\"warning\", \"message\", message, properties),\n error: (message, properties) => emit(\"error\", \"message\", message, properties),\n fatal: (message, properties) => emit(\"fatal\", \"message\", message, properties),\n step: (message, properties) => emit(\"info\", \"step\", message, properties),\n success: (message, properties) => emit(\"info\", \"success\", message, properties),\n with: (properties) =>\n createBoundLogger(printer, category, { ...boundProperties, ...properties }),\n getChild: (child) => createBoundLogger(printer, [...category, child], boundProperties),\n };\n}\n\n/** Create the logger for one command invocation. */\nexport function createLogger(printer: Printer, category: readonly string[]): Logger {\n return createBoundLogger(printer, [...category], {});\n}\n","import { readFile, realpath } from \"node:fs/promises\";\nimport { dirname, join } from \"node:path\";\n\nexport async function findPackageVersion(entry: string | undefined): Promise<string | undefined> {\n if (!entry) return undefined;\n let directory: string;\n try {\n directory = dirname(await realpath(entry));\n } catch {\n return undefined;\n }\n for (;;) {\n const version = await readPackageVersion(join(directory, \"package.json\"));\n if (version !== undefined) return version;\n const parent = dirname(directory);\n if (parent === directory) return undefined;\n directory = parent;\n }\n}\n\nasync function readPackageVersion(path: string): Promise<string | undefined> {\n let text: string;\n try {\n text = await readFile(path, \"utf8\");\n } catch {\n return undefined;\n }\n try {\n const { version } = JSON.parse(text) as { version?: unknown };\n return typeof version === \"string\" ? version : undefined;\n } catch {\n return undefined;\n }\n}\n","import { emitKeypressEvents } from \"node:readline\";\nimport { PassThrough } from \"node:stream\";\nimport type { HackshPromptErrorReason, PromptErrorDetails, PromptKind } from \"./errors.ts\";\nimport { HackshPromptError } from \"./errors.ts\";\nimport type {\n ConfirmPromptState,\n Printer,\n PromptState,\n PromptStatus,\n SelectPromptState,\n TerminalInput,\n TextPromptState,\n} from \"./printer.ts\";\nimport { TerminalLock } from \"./terminal.ts\";\n\nexport interface SelectOption<T extends string> {\n value: T;\n label?: string;\n hint?: string;\n}\n\nexport interface SelectOptions<T extends string> {\n message: string;\n options: readonly SelectOption<T>[];\n initialValue?: T;\n}\n\nexport interface ConfirmOptions {\n message: string;\n initialValue?: boolean;\n}\n\nexport interface TextOptions {\n message: string;\n placeholder?: string;\n validate?(value: string): string | undefined;\n}\n\nexport interface Prompter {\n select<const T extends string>(options: SelectOptions<T>): Promise<T>;\n confirm(options: ConfirmOptions): Promise<boolean>;\n text(options: TextOptions): Promise<string>;\n}\n\ninterface Key {\n name?: string;\n ctrl?: boolean;\n meta?: boolean;\n sequence?: string;\n}\n\ninterface PromptControllerOptions {\n interactive: boolean;\n input: TerminalInput;\n print(event: Parameters<Printer[\"print\"]>[0]): Promise<void>;\n terminal: TerminalLock;\n signal: AbortSignal;\n}\n\ninterface BufferedKeypress {\n character: string | undefined;\n key: Key;\n}\n\nfunction details(\n kind: PromptKind,\n message: unknown,\n choices?: readonly string[],\n): PromptErrorDetails {\n let normalizedMessage: string;\n try {\n normalizedMessage = typeof message === \"string\" ? message : String(message);\n } catch {\n normalizedMessage = \"[Unserializable prompt message]\";\n }\n return {\n kind,\n message: normalizedMessage,\n ...(choices === undefined ? {} : { choices }),\n };\n}\n\nfunction promptError(\n reason: HackshPromptErrorReason,\n prompt: PromptErrorDetails,\n message: string,\n cause?: unknown,\n): HackshPromptError {\n return new HackshPromptError(\n reason,\n prompt,\n message,\n cause === undefined ? undefined : { cause },\n );\n}\n\nfunction validateMessage(kind: PromptKind, message: unknown, choices?: readonly string[]): void {\n if (typeof message !== \"string\" || message.length === 0) {\n throw promptError(\n \"invalid-options\",\n details(kind, message, choices),\n `Invalid ${kind} prompt: message must be a non-empty string`,\n );\n }\n}\n\nfunction asInput(value: TerminalInput, prompt: PromptErrorDetails): TerminalInput {\n if (\n typeof value !== \"object\" ||\n value === null ||\n typeof Reflect.get(value, \"on\") !== \"function\" ||\n typeof Reflect.get(value, \"removeListener\") !== \"function\" ||\n typeof Reflect.get(value, \"resume\") !== \"function\" ||\n typeof Reflect.get(value, \"pause\") !== \"function\"\n ) {\n throw promptError(\"input-error\", prompt, \"Interactive input is not a readable stream\");\n }\n return value;\n}\n\nexport class PromptController implements Prompter {\n readonly #interactive: boolean;\n readonly #inputValue: TerminalInput;\n readonly #printEvent: PromptControllerOptions[\"print\"];\n readonly #bufferedKeys: BufferedKeypress[] = [];\n readonly #terminal: TerminalLock;\n readonly #signal: AbortSignal;\n\n constructor(options: PromptControllerOptions) {\n this.#interactive = options.interactive;\n this.#inputValue = options.input;\n this.#printEvent = (event) => options.print(event);\n this.#terminal = options.terminal;\n this.#signal = options.signal;\n }\n\n async #print(state: PromptState, prompt: PromptErrorDetails): Promise<void> {\n try {\n await this.#printEvent({ type: \"prompt\", prompt: state });\n } catch (cause) {\n throw promptError(\"printer-error\", prompt, \"The prompt could not be displayed\", cause);\n }\n }\n\n async #run<T>(\n prompt: PromptErrorDetails,\n initial: PromptState,\n accept: (character: string, key: Key) => T | undefined,\n update: (character: string, key: Key) => PromptState | undefined,\n submitted: (value: T) => PromptState,\n closed: () => PromptState,\n ): Promise<T> {\n if (!this.#interactive) {\n throw promptError(\n \"non-interactive\",\n prompt,\n `Cannot request ${prompt.kind} input in non-interactive mode: ${prompt.message}`,\n );\n }\n if (this.#signal.aborted) {\n throw promptError(\"aborted\", prompt, \"Prompt aborted\", this.#signal.reason);\n }\n const input = asInput(this.#inputValue, prompt);\n if (!this.#terminal.acquire(\"prompt\")) {\n throw promptError(\n \"overlapping\",\n prompt,\n this.#terminal.owner === \"exec\"\n ? \"A command is using the terminal\"\n : \"Another prompt is already active\",\n );\n }\n let originallyFlowing = false;\n let rawChanged = false;\n let outcome: { ok: true; value: T } | { ok: false; error: unknown };\n try {\n originallyFlowing = input.readableFlowing === true;\n if (input.setRawMode && input.isRaw !== true) {\n input.setRawMode(true);\n rawChanged = true;\n }\n await this.#print(initial, prompt);\n\n const value = await new Promise<T>((resolve, reject) => {\n const keypressInput = new PassThrough();\n emitKeypressEvents(keypressInput);\n let settled = false;\n let draining = false;\n let finalized = false;\n let completion: (() => void) | undefined;\n const queuedKeys = this.#bufferedKeys.splice(0);\n const finalize = (): void => {\n if (finalized || !settled || draining) return;\n finalized = true;\n cleanup();\n completion?.();\n };\n const finish = (action: () => void): void => {\n if (settled) return;\n settled = true;\n completion = action;\n finalize();\n };\n const fail = (reason: HackshPromptErrorReason, message: string, cause?: unknown): void => {\n finish(() => reject(promptError(reason, prompt, message, cause)));\n };\n const handleKeypress = async (\n character: string | undefined,\n key: Key = {},\n ): Promise<void> => {\n if (settled) return;\n if ((key.ctrl && key.name === \"c\") || key.name === \"escape\") {\n fail(\"cancelled\", \"Prompt cancelled\");\n return;\n }\n if (key.ctrl && key.name === \"d\") {\n fail(\"eof\", \"Prompt input ended before a value was submitted\");\n return;\n }\n try {\n const value = accept(character ?? \"\", key);\n if (value !== undefined) {\n finish(() => resolve(value));\n return;\n }\n const state = update(character ?? \"\", key);\n if (state) await this.#print(state, prompt);\n } catch (cause) {\n if (cause instanceof HackshPromptError) finish(() => reject(cause));\n else fail(\"input-error\", \"Prompt input could not be processed\", cause);\n }\n };\n const drainKeys = async (): Promise<void> => {\n if (draining || finalized) return;\n draining = true;\n try {\n while (queuedKeys.length > 0) {\n if (settled) {\n this.#bufferedKeys.push(...queuedKeys.splice(0));\n break;\n }\n const next = queuedKeys.shift()!;\n await handleKeypress(next.character, next.key);\n }\n } finally {\n draining = false;\n finalize();\n }\n };\n const onKeypress = (character: string | undefined, key: Key = {}): void => {\n queuedKeys.push({ character, key });\n void drainKeys().catch((cause: unknown) =>\n fail(\"input-error\", \"Prompt input could not be processed\", cause),\n );\n };\n const onEnd = (): void => fail(\"eof\", \"Prompt input ended before a value was submitted\");\n const onError = (cause: unknown): void => fail(\"input-error\", \"Prompt input failed\", cause);\n const onAbort = (): void => fail(\"aborted\", \"Prompt aborted\", this.#signal.reason);\n const onData = (chunk: unknown): void => {\n if (typeof chunk === \"string\" || chunk instanceof Uint8Array) keypressInput.write(chunk);\n else fail(\"input-error\", \"Prompt input produced a non-byte value\");\n };\n const cleanup = (): void => {\n keypressInput.removeListener(\"keypress\", onKeypress);\n keypressInput.destroy();\n input.removeListener(\"data\", onData as (...args: never[]) => void);\n input.removeListener(\"end\", onEnd as (...args: never[]) => void);\n input.removeListener(\"close\", onEnd as (...args: never[]) => void);\n input.removeListener(\"error\", onError as (...args: never[]) => void);\n this.#signal.removeEventListener(\"abort\", onAbort);\n };\n keypressInput.on(\"keypress\", onKeypress);\n input.on(\"data\", onData as (...args: never[]) => void);\n input.on(\"end\", onEnd as (...args: never[]) => void);\n input.on(\"close\", onEnd as (...args: never[]) => void);\n input.on(\"error\", onError as (...args: never[]) => void);\n this.#signal.addEventListener(\"abort\", onAbort, { once: true });\n if (this.#signal.aborted) onAbort();\n input.resume();\n void drainKeys().catch((cause: unknown) =>\n fail(\"input-error\", \"Prompt input could not be processed\", cause),\n );\n });\n outcome = { ok: true, value };\n } catch (cause) {\n outcome = {\n ok: false,\n error:\n cause instanceof HackshPromptError\n ? cause\n : promptError(\"input-error\", prompt, \"Prompt input could not be initialized\", cause),\n };\n }\n\n let restoreError: HackshPromptError | undefined;\n try {\n if (rawChanged) input.setRawMode?.(false);\n if (!originallyFlowing) input.pause();\n } catch (cause) {\n restoreError = promptError(\n \"input-error\",\n prompt,\n \"Prompt input could not be restored\",\n cause,\n );\n }\n const closeWithFailure = async (failure: unknown): Promise<never> => {\n try {\n await this.#print(closed(), prompt);\n } catch {\n // Preserve the error that terminated the prompt, including an earlier printer failure.\n } finally {\n this.#terminal.release();\n }\n throw failure;\n };\n if (restoreError) return closeWithFailure(restoreError);\n if (!outcome.ok) return closeWithFailure(outcome.error);\n try {\n await this.#print(submitted(outcome.value), prompt);\n return outcome.value;\n } catch (error) {\n try {\n await this.#print(closed(), prompt);\n } catch {\n // The submitted-state failure remains the primary error.\n }\n throw error;\n } finally {\n this.#terminal.release();\n }\n }\n\n async select<const T extends string>(options: SelectOptions<T>): Promise<T> {\n const choices = Array.isArray(options?.options)\n ? options.options.map((option) =>\n typeof option === \"object\" && option !== null && typeof option.value === \"string\"\n ? option.value\n : \"[Invalid choice]\",\n )\n : [];\n const prompt = details(\"select\", options?.message, choices);\n validateMessage(\"select\", options?.message, choices);\n if (!Array.isArray(options.options) || options.options.length === 0) {\n throw promptError(\"invalid-options\", prompt, \"A select prompt requires at least one choice\");\n }\n const seen = new Set<string>();\n for (const option of options.options) {\n if (\n typeof option !== \"object\" ||\n option === null ||\n typeof option.value !== \"string\" ||\n option.value.length === 0 ||\n (option.label !== undefined && typeof option.label !== \"string\") ||\n (option.hint !== undefined && typeof option.hint !== \"string\")\n ) {\n throw promptError(\n \"invalid-options\",\n prompt,\n \"Select choices must have valid string values\",\n );\n }\n if (seen.has(option.value)) {\n throw promptError(\"invalid-options\", prompt, `Duplicate select choice: ${option.value}`);\n }\n seen.add(option.value);\n }\n let selected = options.initialValue === undefined ? 0 : choices.indexOf(options.initialValue);\n if (selected < 0) {\n throw promptError(\n \"invalid-options\",\n prompt,\n `Unknown initial select value: ${String(options.initialValue)}`,\n );\n }\n const state = (status: PromptStatus = \"active\"): SelectPromptState => ({\n kind: \"select\",\n message: options.message,\n status,\n value: options.options[selected]!.value,\n choices: options.options.map(({ value, label, hint }, index) => ({\n value,\n label: label ?? value,\n ...(hint === undefined ? {} : { hint }),\n selected: index === selected,\n })),\n });\n const value = await this.#run<T>(\n prompt,\n state(),\n (_character, key) =>\n key.name === \"return\" || key.name === \"enter\"\n ? options.options[selected]!.value\n : undefined,\n (_character, key) => {\n if (key.name !== \"up\" && key.name !== \"down\") return undefined;\n selected =\n (selected + (key.name === \"up\" ? -1 : 1) + options.options.length) %\n options.options.length;\n return state();\n },\n () => state(\"submitted\"),\n () => state(\"closed\"),\n );\n return value;\n }\n\n async confirm(options: ConfirmOptions): Promise<boolean> {\n const prompt = details(\"confirm\", options?.message);\n validateMessage(\"confirm\", options?.message);\n if (options.initialValue !== undefined && typeof options.initialValue !== \"boolean\") {\n throw promptError(\"invalid-options\", prompt, \"Confirm initialValue must be a boolean\");\n }\n const value = options.initialValue ?? false;\n const state = (result: boolean, status: PromptStatus = \"active\"): ConfirmPromptState => ({\n kind: \"confirm\",\n message: options.message,\n status,\n value: result,\n ...(options.initialValue === undefined ? {} : { defaultValue: options.initialValue }),\n });\n const result = await this.#run<boolean>(\n prompt,\n state(value),\n (character, key) => {\n if (key.name === \"return\" || key.name === \"enter\") return value;\n if (character.toLowerCase() === \"y\") return true;\n if (character.toLowerCase() === \"n\") return false;\n return undefined;\n },\n () => undefined,\n (submitted) => state(submitted, \"submitted\"),\n () => state(value, \"closed\"),\n );\n return result;\n }\n\n async text(options: TextOptions): Promise<string> {\n const prompt = details(\"text\", options?.message);\n validateMessage(\"text\", options?.message);\n if (options.placeholder !== undefined && typeof options.placeholder !== \"string\") {\n throw promptError(\"invalid-options\", prompt, \"Text placeholder must be a string\");\n }\n if (options.validate !== undefined && typeof options.validate !== \"function\") {\n throw promptError(\"invalid-options\", prompt, \"Text validate must be a function\");\n }\n let value = \"\";\n let validationError: string | undefined;\n const state = (\n status: PromptStatus = validationError ? \"error\" : \"active\",\n ): TextPromptState => ({\n kind: \"text\",\n message: options.message,\n status,\n value,\n ...(options.placeholder === undefined ? {} : { placeholder: options.placeholder }),\n ...(validationError === undefined ? {} : { error: validationError }),\n });\n const result = await this.#run<string>(\n prompt,\n state(),\n (_character, key) => {\n if (key.name !== \"return\" && key.name !== \"enter\") return undefined;\n let error: string | undefined;\n try {\n error = options.validate?.(value);\n } catch (cause) {\n throw promptError(\"input-error\", prompt, \"Text validation failed\", cause);\n }\n if (error !== undefined && typeof error !== \"string\") {\n throw promptError(\n \"input-error\",\n prompt,\n \"Text validation must return a string or undefined\",\n );\n }\n validationError = error || undefined;\n return validationError === undefined ? value : undefined;\n },\n (character, key) => {\n if (key.name === \"return\" || key.name === \"enter\") return state();\n validationError = undefined;\n if (key.name === \"backspace\") value = Array.from(value).slice(0, -1).join(\"\");\n else if (!key.ctrl && !key.meta && character.length > 0) value += character;\n else return undefined;\n return state();\n },\n () => state(\"submitted\"),\n () => state(\"closed\"),\n );\n return result;\n }\n}\n","import { createPrettyPrinter } from \"./pretty.ts\";\nimport {\n createJsonPrinter,\n resolveOutputMode,\n type OutputMode,\n type OutputPreference,\n type Printer,\n type TerminalInput,\n type TerminalOutput,\n} from \"./printer.ts\";\n\nexport interface OutputOptions {\n output?: OutputPreference;\n /** Use Unicode presentation symbols in pretty output. Defaults to true. */\n unicode?: boolean;\n env?: Readonly<Record<string, string | undefined>>;\n stdin?: TerminalInput;\n stdout?: TerminalOutput;\n stderr?: TerminalOutput;\n}\n\nfunction consoleWriter(method: \"log\" | \"error\", stream: TerminalOutput): TerminalOutput {\n return {\n get isTTY() {\n return stream.isTTY;\n },\n get columns() {\n return stream.columns;\n },\n write(text) {\n if (!text.endsWith(\"\\n\")) return stream.write(text);\n console[method](text.slice(0, -1));\n },\n };\n}\n\n/** Resolve the automatic output policy and select its printer for one operation. */\nexport function selectOutputPrinter(\n options: OutputOptions,\n override?: Printer,\n resolvedMode?: OutputMode,\n): Printer {\n const stdin = options.stdin ?? process.stdin;\n const stdout = options.stdout ?? process.stdout;\n const stderr = options.stderr ?? process.stderr;\n const mode =\n resolvedMode ??\n resolveOutputMode({\n output: options.output,\n env: options.env,\n inputIsTTY: stdin.isTTY,\n outputIsTTY: stdout.isTTY,\n errorOutputIsTTY: stderr.isTTY,\n });\n if (override) return override;\n if (mode.format === \"json\") return createJsonPrinter({ stdout, stderr });\n\n const useConsole = options.stdout === undefined && options.stderr === undefined;\n return createPrettyPrinter({\n color: mode.color,\n unicode: options.unicode ?? true,\n stdout: options.stdout ?? (useConsole ? consoleWriter(\"log\", stdout) : stdout),\n stderr: options.stderr ?? (useConsole ? consoleWriter(\"error\", process.stderr) : stderr),\n });\n}\n","import type { AnyCommandDef } from \"./command.ts\";\nimport { commandEnvPath, optionEnvNames } from \"./environment.ts\";\nimport { summarizeErrors } from \"./errors.ts\";\nimport { aliasList, kebabCase } from \"./options.ts\";\nimport type { Printer, PrintStream } from \"./printer.ts\";\nimport { POSITIONALS_KEY, readArgInfo, readPositionals, schemaShape } from \"./schema.ts\";\n\nfunction details(\n description: string | undefined,\n required: boolean,\n defaultValue: unknown,\n choices: readonly string[] | undefined,\n envName?: string,\n): string {\n const parts = [description];\n if (choices) parts.push(`(Choices: ${choices.join(\", \")})`);\n if (required) parts.push(\"(Required)\");\n if (defaultValue !== undefined) parts.push(`(Default: ${formatDefault(defaultValue)})`);\n if (envName !== undefined) parts.push(`(Env: ${envName})`);\n return parts.filter(Boolean).join(\" \");\n}\n\nfunction formatDefault(value: unknown): string {\n if (typeof value === \"string\") return value;\n if (typeof value === \"number\" || typeof value === \"boolean\" || typeof value === \"bigint\") {\n return value.toString();\n }\n if (value === null) return \"null\";\n try {\n return JSON.stringify(value) ?? \"undefined\";\n } catch {\n return \"[Unserializable]\";\n }\n}\n\nexport interface UsageArgumentSummary {\n name: string;\n required: boolean;\n variadic: boolean;\n description?: string;\n choices?: readonly string[];\n defaultValue?: unknown;\n}\n\nexport interface UsageOptionSummary {\n name: string;\n flags: readonly string[];\n takesValue: boolean;\n /** Whether the long flag also accepts a `--no-` prefixed form. */\n negatable: boolean;\n valueName?: string;\n required: boolean;\n description?: string;\n choices?: readonly string[];\n defaultValue?: unknown;\n env?: string;\n}\n\nexport interface UsageCommandSummary {\n name: string;\n description?: string;\n}\n\n/** A schema-free description of the useful help metadata for a command. */\nexport interface UsageSummary {\n name: string;\n heading?: string;\n version?: string;\n description?: string;\n synopsis: string;\n arguments: readonly UsageArgumentSummary[];\n options: readonly UsageOptionSummary[];\n commands: readonly UsageCommandSummary[];\n}\n\nfunction heading(command: AnyCommandDef): string | undefined {\n const identity = command.name\n ? `${command.name}${command.version ? ` v${command.version}` : \"\"}`\n : command.version\n ? `v${command.version}`\n : undefined;\n if (command.description && identity) return `${command.description} (${identity})`;\n return command.description ?? identity;\n}\n\n/** Build a serializable help summary without retaining command or schema objects. */\nexport function summarizeUsage(command: AnyCommandDef): UsageSummary {\n const shape = command.args ? schemaShape(command.args) : {};\n const positionals = readPositionals(shape);\n const positionalItems = positionals?.items ?? [];\n const syntax = positionalItems.map(({ schema, label }) =>\n readArgInfo(schema).required ? `<${label}>` : `[${label}]`,\n );\n if (positionals?.rest) syntax.push(`[${positionals.rest.label}...]`);\n if (command.subCommands && Object.keys(command.subCommands).length > 0) syntax.push(\"<COMMAND>\");\n\n const args: UsageArgumentSummary[] = positionalItems.map(({ schema, label }) => {\n const info = readArgInfo(schema);\n return {\n name: label,\n required: info.required,\n variadic: false,\n ...(info.description === undefined ? {} : { description: info.description }),\n ...(info.choices === undefined ? {} : { choices: info.choices }),\n ...(info.defaultValue === undefined\n ? {}\n : { defaultValue: summarizeErrors(info.defaultValue) }),\n };\n });\n if (positionals?.rest) {\n const info = readArgInfo(positionals.rest.schema);\n args.push({\n name: positionals.rest.label,\n required: false,\n variadic: true,\n ...(info.description === undefined ? {} : { description: info.description }),\n ...(info.choices === undefined ? {} : { choices: info.choices }),\n });\n }\n\n const envNames = optionEnvNames(command, commandEnvPath(command));\n const options = Object.entries(shape)\n .filter(([key]) => key !== POSITIONALS_KEY)\n .map(([key, schema]): UsageOptionSummary => {\n const info = readArgInfo(schema);\n const aliases =\n info.alias === undefined ? [] : aliasList(info.alias).map((item) => `-${item}`);\n const name = kebabCase(key);\n const valueName = info.valueName ?? name;\n const envName = envNames.get(key);\n return {\n name,\n flags: [...aliases, `--${name}`],\n takesValue: info.takesValue,\n negatable: !info.takesValue,\n required: info.required,\n ...(info.takesValue ? { valueName } : {}),\n ...(info.description === undefined ? {} : { description: info.description }),\n ...(info.choices === undefined ? {} : { choices: info.choices }),\n ...(info.defaultValue === undefined\n ? {}\n : { defaultValue: summarizeErrors(info.defaultValue) }),\n ...(envName === undefined ? {} : { env: envName }),\n };\n });\n\n const commands = Object.entries(command.subCommands ?? {})\n .filter(([, child]) => !child.hidden)\n .map(([name, child]) => ({\n name,\n ...(child.description === undefined ? {} : { description: child.description }),\n }));\n const name = command.name ?? \"command\";\n const title = heading(command);\n return {\n name,\n ...(title === undefined ? {} : { heading: title }),\n ...(command.version === undefined ? {} : { version: command.version }),\n ...(command.description === undefined ? {} : { description: command.description }),\n synopsis: `${name} [OPTIONS]${syntax.length ? ` ${syntax.join(\" \")}` : \"\"}`,\n arguments: args,\n options,\n commands,\n };\n}\n\nfunction formatUsage(summary: UsageSummary): string {\n const lines: string[] = [];\n if (summary.heading) lines.push(summary.heading, \"\");\n lines.push(`USAGE ${summary.synopsis}`);\n\n if (summary.arguments.length > 0) {\n lines.push(\"\", \"ARGUMENTS\", \"\");\n for (const argument of summary.arguments) {\n lines.push(\n ` ${argument.name}${argument.variadic ? \"...\" : \"\"} ${details(argument.description, argument.required, argument.defaultValue, argument.choices)}`.trimEnd(),\n );\n }\n }\n\n if (summary.options.length > 0) {\n lines.push(\"\", \"OPTIONS\", \"\");\n for (const option of summary.options) {\n const flags = option.flags.map((flag) => {\n if (!flag.startsWith(\"--\")) return flag;\n if (option.takesValue) return `${flag}=<${option.valueName}>`;\n if (option.negatable) return `--[no-]${flag.slice(2)}`;\n return flag;\n });\n lines.push(\n ` ${flags.join(\", \")} ${details(option.description, option.required, option.defaultValue, option.choices, option.env)}`.trimEnd(),\n );\n }\n }\n\n if (summary.commands.length > 0) {\n lines.push(\"\", \"COMMANDS\", \"\");\n for (const command of summary.commands) {\n lines.push(` ${command.name} ${command.description ?? \"\"}`.trimEnd());\n }\n }\n return lines.join(\"\\n\");\n}\n\nexport interface ShowUsageOptions {\n printer: Printer;\n stream?: PrintStream;\n}\n\n/** Generate usage text without writing to stdout or stderr. */\nexport function renderUsage(command: AnyCommandDef): string {\n return formatUsage(summarizeUsage(command));\n}\n\n/** Generate a usage event and await its printer. */\nexport async function showUsage(command: AnyCommandDef, options: ShowUsageOptions): Promise<void> {\n const usage = summarizeUsage(command);\n const text = formatUsage(usage);\n return options.printer.print({\n type: \"usage\",\n usage,\n text,\n stream: options.stream ?? \"stdout\",\n });\n}\n","import type { ArgsSchema } from \"./schema.ts\";\nimport type { AnyCommandDef, CommandDef } from \"./command.ts\";\nimport { assertUniqueEnvNames, commandEnvPath, registerCommandPath } from \"./environment.ts\";\nimport { HackshExitError, HackshPromptError, summarizeError, HackshUsageError } from \"./errors.ts\";\nimport { createOutput } from \"./command-output.ts\";\nimport { createExec, type ExecContext } from \"./exec.ts\";\nimport { createLogger } from \"./logger.ts\";\nimport { findPackageVersion } from \"./package-version.ts\";\nimport {\n parseCommandArgs,\n tokenizedBefore,\n tokenizeCommandArgs,\n type TokenizedCommandArgs,\n} from \"./parser.ts\";\nimport {\n createJsonPrinter,\n createPrintQueue,\n resolveOutputMode,\n type OutputFormat,\n type Printer,\n type PrintQueue,\n type TerminalInput,\n} from \"./printer.ts\";\nimport { PromptController } from \"./prompts.ts\";\nimport { TerminalLock } from \"./terminal.ts\";\nimport { selectOutputPrinter, type OutputOptions } from \"./output.ts\";\nimport { showUsage } from \"./usage.ts\";\n\nexport type { OutputOptions } from \"./output.ts\";\n\ninterface CommandSegment {\n command: AnyCommandDef;\n rawArgs: string[];\n tokenized: TokenizedCommandArgs;\n}\n\ninterface ResolvedCommand extends CommandSegment {\n parents: CommandSegment[];\n segments: CommandSegment[];\n}\n\nfunction resolveCommand(root: AnyCommandDef, rawArgs: string[]): ResolvedCommand {\n let command = root;\n let remaining = rawArgs;\n const parents: ResolvedCommand[\"parents\"] = [];\n const segments: ResolvedCommand[\"segments\"] = [];\n\n for (;;) {\n const tokenized = tokenizeCommandArgs(command, remaining);\n const index = command.subCommands\n ? tokenized.tokens.find((token) => token.kind === \"positional\")?.index\n : undefined;\n if (index === undefined) {\n const segment = { command, rawArgs: remaining, tokenized };\n segments.push(segment);\n assertUniqueEnvNames(\n segments.map(({ command }) => ({ command, path: commandEnvPath(command) })),\n );\n return { ...segment, parents, segments };\n }\n const key = remaining[index]!;\n const child = command.subCommands?.[key];\n if (!child) throw new HackshUsageError(`Unknown command \\`${key}\\``, command);\n const prefix = remaining.slice(0, index);\n const segment = { command, rawArgs: prefix, tokenized: tokenizedBefore(tokenized, index) };\n parents.push(segment);\n segments.push(segment);\n const parentPath = commandEnvPath(command);\n command = {\n ...child,\n name: child.name ?? key,\n allowUnknownArgs: child.allowUnknownArgs ?? command.allowUnknownArgs,\n };\n registerCommandPath(command, parentPath === undefined ? undefined : [...parentPath, key]);\n remaining = remaining.slice(index + 1);\n }\n}\n\nasync function executeCommand<S extends ArgsSchema>(\n root: CommandDef<S>,\n argv: string[],\n output: PreparedOutput,\n env: ExecContext[\"env\"],\n signal: AbortSignal,\n fallbackVersion: () => Promise<string | undefined> = async () => undefined,\n): Promise<unknown> {\n const { printer } = output;\n const argEnv = env ?? process.env;\n const resolved = resolveCommand(root, argv);\n if (resolved.segments[0]?.tokenized.version) {\n const version = root.version ?? (await fallbackVersion()) ?? \"\";\n await printer.print({ type: \"version\", version });\n return undefined;\n }\n if (resolved.segments.some(({ tokenized }) => tokenized.help)) {\n await showUsage(resolved.command, { printer });\n return undefined;\n }\n\n for (const parent of resolved.parents) {\n await parseCommandArgs(\n parent.command,\n parent.rawArgs,\n parent.tokenized,\n argEnv,\n commandEnvPath(parent.command),\n );\n }\n const parsed = await parseCommandArgs(\n resolved.command,\n resolved.rawArgs,\n resolved.tokenized,\n argEnv,\n commandEnvPath(resolved.command),\n );\n if (!resolved.command.run) {\n throw new HackshUsageError(\"No command specified\", resolved.command);\n }\n signal.throwIfAborted();\n const category = resolved.segments.flatMap(({ command }) =>\n command.name === undefined ? [] : [command.name],\n );\n return resolved.command.run({\n command: resolved.command,\n args: parsed.args,\n input: {\n argv: resolved.rawArgs,\n unknown: parsed.extraArgs,\n passthrough: parsed.passthrough,\n },\n output: createOutput(printer),\n logger: createLogger(printer, category),\n prompt: new PromptController({\n interactive: output.interactive,\n input: output.input,\n print: (event) => output.printChecked(event),\n terminal: output.terminal,\n signal,\n }),\n exec: createExec({\n env,\n mode: { format: output.format, interactive: output.interactive },\n print: (event) => printer.print(event),\n terminal: output.terminal,\n signal,\n }),\n signal,\n });\n}\n\nexport interface RunCommandOptions extends OutputOptions {\n printer?: Printer;\n signal?: AbortSignal;\n}\n\ninterface PreparedOutput extends PrintQueue {\n format: OutputFormat;\n interactive: boolean;\n input: TerminalInput;\n terminal: TerminalLock;\n}\n\nfunction prepareOutput(\n options: RunCommandOptions,\n env: Readonly<Record<string, string | undefined>>,\n): PreparedOutput {\n const input = options.stdin ?? process.stdin;\n const mode = resolveOutputMode({\n output: options.output,\n env,\n inputIsTTY: input.isTTY,\n outputIsTTY: (options.stdout ?? process.stdout).isTTY,\n errorOutputIsTTY: (options.stderr ?? process.stderr).isTTY,\n });\n return {\n ...createPrintQueue(selectOutputPrinter(options, options.printer, mode)),\n format: mode.format,\n interactive: mode.interactive,\n input,\n terminal: new TerminalLock(),\n };\n}\n\ntype HandlerResult<C> = C extends { run?: infer Handler }\n ? Handler extends (...args: never[]) => infer R\n ? Awaited<R>\n : never\n : never;\n\ntype CommandResult<C> =\n | HandlerResult<C>\n | (C extends { subCommands?: infer Children }\n ? Children extends Record<string, AnyCommandDef>\n ? string extends keyof Children\n ? unknown\n : CommandResult<Children[keyof Children]>\n : never\n : never);\n\nexport function runCommand<C extends AnyCommandDef>(\n root: C,\n argv: string[],\n options?: RunCommandOptions,\n): Promise<CommandResult<C> | undefined>;\nexport async function runCommand(\n root: AnyCommandDef,\n argv: string[],\n options: RunCommandOptions = {},\n): Promise<unknown> {\n const output = prepareOutput(options, options.env ?? process.env);\n try {\n return await executeCommand(\n root,\n argv,\n output,\n options.env,\n options.signal ?? new AbortController().signal,\n );\n } finally {\n await output.drain();\n }\n}\n\nexport interface RunMainOptions extends OutputOptions {\n onError?: (error: unknown) => void | Promise<void>;\n argv?: string[];\n printer?: Printer;\n}\n\nasync function drainAndExit(output: PrintQueue, code = 1): Promise<never> {\n try {\n await output.drain();\n } finally {\n process.exit(code);\n }\n}\n\nfunction commandErrorExitCode(error: unknown): number {\n if (error instanceof HackshExitError) return error.exitCode;\n return error instanceof HackshPromptError && error.reason === \"cancelled\" ? 130 : 1;\n}\n\nconst SIGNAL_EXIT_CODES = { SIGINT: 130, SIGTERM: 143 } as const;\n\nfunction listenForExitSignals() {\n const controller = new AbortController();\n let exitCode: number | undefined;\n const listeners = Object.entries(SIGNAL_EXIT_CODES).map(([signal, code]) => {\n const listener = (): void => {\n if (exitCode !== undefined) process.exit(code);\n exitCode = code;\n controller.abort(new DOMException(`Received ${signal}`, \"AbortError\"));\n };\n process.on(signal, listener);\n return [signal, listener] as const;\n });\n return {\n signal: controller.signal,\n exitCode: () => exitCode,\n release(): void {\n for (const [signal, listener] of listeners) process.removeListener(signal, listener);\n },\n };\n}\n\nasync function reportOutputSetupError(error: unknown, options: RunMainOptions): Promise<never> {\n if (options.onError) {\n await options.onError(error);\n return drainAndExit(createPrintQueue(options.printer ?? { print: () => undefined }));\n }\n\n const output = createPrintQueue(\n options.printer ??\n createJsonPrinter({\n stdout: options.stdout ?? process.stdout,\n stderr: options.stderr ?? process.stderr,\n }),\n );\n await output.printer.print({ type: \"error\", error: summarizeError(error) });\n return drainAndExit(output);\n}\n\nasync function reportCommandError(error: unknown, output: PrintQueue): Promise<void> {\n if (error instanceof HackshExitError && error.message === \"\") return;\n await output.printer.print({ type: \"error\", error: summarizeError(error) });\n if (error instanceof HackshUsageError) {\n await showUsage(error.command, { printer: output.printer, stream: \"stderr\" });\n }\n}\n\nexport async function runMain<S extends ArgsSchema>(\n command: CommandDef<S>,\n options: RunMainOptions = {},\n): Promise<void> {\n let output: PreparedOutput;\n try {\n output = prepareOutput(options, options.env ?? process.env);\n } catch (error) {\n return reportOutputSetupError(error, options);\n }\n const signals = listenForExitSignals();\n const exit = (code: number): Promise<never> => {\n signals.release();\n return drainAndExit(output, signals.exitCode() ?? code);\n };\n try {\n await executeCommand(\n command,\n options.argv ?? process.argv.slice(2),\n output,\n options.env,\n signals.signal,\n () => findPackageVersion(process.argv[1]),\n );\n } catch (error) {\n if (options.onError) {\n await options.onError(error);\n return exit(commandErrorExitCode(error));\n }\n try {\n await reportCommandError(error, output);\n } finally {\n await exit(commandErrorExitCode(error));\n }\n } finally {\n signals.release();\n }\n const signalExitCode = signals.exitCode();\n if (signalExitCode !== undefined) return drainAndExit(output, signalExitCode);\n await output.drain();\n}\n"],"mappings":";;;;;;;;AAAA,SAAgB,UAAU,OAAuB;CAC/C,OAAO,MAAM,WAAW,sBAAsB,OAAO,CAAC,CAAC,YAAY;AACrE;AAEA,SAAgB,UAAU,OAAsD;CAC9E,OAAO,OAAO,UAAU,WAAW,CAAC,KAAK,IAAI;AAC/C;;;ACeA,MAAa,kBAAkB;AA0B/B,SAAS,WAAW,QAA0B;CAC5C,OAAO,OAAO,KAAK;AACrB;AAEA,SAAS,YAAY,KAAmC;CACtD,QAAQ,IAAI,MAAZ;EACE,KAAK;EACL,KAAK;EACL,KAAK;EACL,KAAK;EACL,KAAK;EACL,KAAK;EACL,KAAK,YACH,OAAO,IAAI;EACb,KAAK,QACH,OAAO,IAAI;EACb,SACE;CACJ;AACF;;AAGA,SAAgB,YAAY,QAA2B;CACrD,IAAI,UAAgC;CACpC,IAAI,WAAW;CACf,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI;CAEJ,OAAO,SAAS;EACd,MAAM,WAAW,eAAe,IAAI,OAAO;EAC3C,IAAI,UAAU;GACZ,IACE,SAAS,UAAU,KAAA,KACnB,OAAO,SAAS,UAAU,YAC1B,EACE,MAAM,QAAQ,SAAS,KAAK,KAC5B,SAAS,MAAM,OAAO,UAAU,OAAO,UAAU,QAAQ,IAG3D,MAAM,IAAI,UAAU,mEAAmE;GAEzF,IACE,SAAS,QAAQ,KAAA,KACjB,OAAO,SAAS,QAAQ,YACxB,SAAS,QAAQ,OAEjB,MAAM,IAAI,UAAU,mDAAmD;GAEzE,KAAK,MAAM,OAAO;IAAC;IAAa;IAAS;GAAa,GACpD,IAAI,SAAS,SAAS,KAAA,KAAa,OAAO,SAAS,SAAS,UAC1D,MAAM,IAAI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AAe,mBAAmB,OAAgB,QAAmC;CACnF,IAAI,iBAAiB,mBAAmB,MAAM,YAAY,IAAI;CAC9D,MAAM,OAAO,QAAQ,MAAM;EAAE,MAAM;EAAS,OAAO,eAAe,KAAK;CAAE,CAAC;CAC1E,IAAI,iBAAiB,kBACnB,MAAM,UAAU,MAAM,SAAS;EAAE,SAAS,OAAO;EAAS,QAAQ;CAAS,CAAC;AAEhF;AAEA,eAAsB,QACpB,SACA,UAA0B,CAAC,GACZ;CACf,IAAI;CACJ,IAAI;EACF,SAAS,cAAc,SAAS,QAAQ,OAAO,QAAQ,GAAG;CAC5D,SAAS,OAAO;EACd,OAAO,uBAAuB,OAAO,OAAO;CAC9C;CACA,MAAM,UAAU,qBAAqB;CACrC,MAAM,QAAQ,SAAiC;EAC7C,QAAQ,QAAQ;EAChB,OAAO,aAAa,QAAQ,QAAQ,SAAS,KAAK,IAAI;CACxD;CACA,IAAI;EACF,MAAM,eACJ,SACA,QAAQ,QAAQ,QAAQ,KAAK,MAAM,CAAC,GACpC,QACA,QAAQ,KACR,QAAQ,cACF,mBAAmB,QAAQ,KAAK,EAAE,CAC1C;CACF,SAAS,OAAO;EACd,IAAI,QAAQ,SAAS;GACnB,MAAM,QAAQ,QAAQ,KAAK;GAC3B,OAAO,KAAK,qBAAqB,KAAK,CAAC;EACzC;EACA,IAAI;GACF,MAAM,mBAAmB,OAAO,MAAM;EACxC,UAAU;GACR,MAAM,KAAK,qBAAqB,KAAK,CAAC;EACxC;CACF,UAAU;EACR,QAAQ,QAAQ;CAClB;CACA,MAAM,iBAAiB,QAAQ,SAAS;CACxC,IAAI,mBAAmB,KAAA,GAAW,OAAO,aAAa,QAAQ,cAAc;CAC5E,MAAM,OAAO,MAAM;AACrB"}
1
+ {"version":3,"file":"index.js","names":["parseNodeArgs","#owner","details","#interactive","#inputValue","#printEvent","#bufferedKeys","#terminal","#signal","#print","#run"],"sources":["../src/options.ts","../src/schema.ts","../src/command.ts","../src/environment.ts","../src/parser.ts","../src/command-output.ts","../src/terminal.ts","../src/logger.ts","../src/package-version.ts","../src/prompts.ts","../src/output.ts","../src/usage.ts","../src/run.ts"],"sourcesContent":["export function kebabCase(value: string): string {\n return value.replaceAll(/([a-z0-9])([A-Z])/g, \"$1-$2\").toLowerCase();\n}\n\nexport function aliasList(value: string | readonly string[]): readonly string[] {\n return typeof value === \"string\" ? [value] : value;\n}\n","import { globalRegistry, type $ZodObject, type $ZodType, type JSONSchemaMeta } from \"zod/v4/core\";\nimport type {} from \"zod\";\nimport type {} from \"zod/v4\";\n\ninterface ArgumentMeta extends JSONSchemaMeta {\n alias?: string | readonly string[];\n env?: string | false;\n valueName?: string;\n}\n\ndeclare module \"zod\" {\n interface GlobalMeta extends ArgumentMeta {}\n}\n\ndeclare module \"zod/v4\" {\n interface GlobalMeta extends ArgumentMeta {}\n}\n\nexport type ArgsSchema = $ZodObject;\nexport type EmptyArgs = $ZodObject<{}>;\n\nexport const POSITIONALS_KEY = \"positionals\";\n\nexport interface ArgInfo {\n readonly takesValue: boolean;\n readonly required: boolean;\n readonly defaultValue: unknown;\n readonly description: string | undefined;\n readonly title: string | undefined;\n readonly alias: string | readonly string[] | undefined;\n readonly valueName: string | undefined;\n readonly env: string | false | undefined;\n readonly choices: readonly string[] | undefined;\n}\n\nexport interface Positional {\n readonly schema: $ZodType;\n readonly label: string;\n}\n\nexport interface Positionals {\n readonly items: readonly Positional[];\n readonly rest: Positional | undefined;\n}\n\ntype ZodDef = Record<string, unknown> & { type: string };\n\nfunction definition(schema: $ZodType): ZodDef {\n return schema._zod.def as ZodDef;\n}\n\nfunction innerSchema(def: ZodDef): $ZodType | undefined {\n switch (def.type) {\n case \"optional\":\n case \"nonoptional\":\n case \"nullable\":\n case \"default\":\n case \"prefault\":\n case \"catch\":\n case \"readonly\":\n return def.innerType as $ZodType;\n case \"pipe\":\n return def.in as $ZodType;\n default:\n return undefined;\n }\n}\n\n/** Read only the common zod/v4/core definition and registry structures. */\nexport function readArgInfo(schema: $ZodType): ArgInfo {\n let current: $ZodType | undefined = schema;\n let required = true;\n let defaultValue: unknown;\n let description: string | undefined;\n let title: string | undefined;\n let alias: string | readonly string[] | undefined;\n let valueName: string | undefined;\n let env: string | false | undefined;\n\n while (current) {\n const metadata = globalRegistry.get(current);\n if (metadata) {\n if (\n metadata.alias !== undefined &&\n typeof metadata.alias !== \"string\" &&\n !(\n Array.isArray(metadata.alias) &&\n metadata.alias.every((value) => typeof value === \"string\")\n )\n ) {\n throw new TypeError(\"Argument metadata `alias` must be a string or an array of strings\");\n }\n if (\n metadata.env !== undefined &&\n typeof metadata.env !== \"string\" &&\n metadata.env !== false\n ) {\n throw new TypeError(\"Argument metadata `env` must be a string or false\");\n }\n for (const key of [\"valueName\", \"title\", \"description\"] as const) {\n if (metadata[key] !== undefined && typeof metadata[key] !== \"string\") {\n throw new TypeError(`Argument metadata \\`${key}\\` must be a string`);\n }\n }\n alias ??= metadata.alias;\n valueName ??= metadata.valueName;\n env ??= metadata.env;\n }\n description ??= metadata?.description;\n title ??= metadata?.title;\n\n const def = definition(current);\n if (def.type === \"optional\" || def.type === \"default\" || def.type === \"prefault\") {\n required = false;\n }\n if (def.type === \"default\" && defaultValue === undefined) defaultValue = def.defaultValue;\n current = innerSchema(def);\n }\n\n const base = unwrapInput(schema);\n return {\n takesValue: definition(base).type !== \"boolean\",\n required,\n defaultValue,\n description,\n title,\n alias,\n valueName,\n env,\n choices: enumChoices(base),\n };\n}\n\n/** Read the `positionals` tuple or array schema that declares positional arguments. */\nexport function readPositionals(shape: Record<string, $ZodType>): Positionals | undefined {\n const field = shape[POSITIONALS_KEY];\n if (!field) return undefined;\n const def = definition(unwrapInput(field));\n let items: readonly $ZodType[];\n let rest: $ZodType | undefined;\n if (def.type === \"tuple\") {\n items = def.items as readonly $ZodType[];\n rest = (def.rest as $ZodType | null) ?? undefined;\n } else if (def.type === \"array\") {\n items = [];\n rest = def.element as $ZodType;\n } else {\n throw new TypeError(\"Positional arguments `positionals` must use a tuple or array schema\");\n }\n return {\n items: items.map((schema, index) => ({\n schema,\n label: readArgInfo(schema).title ?? `ARG${index + 1}`,\n })),\n rest: rest && { schema: rest, label: readArgInfo(rest).title ?? \"ARGS\" },\n };\n}\n\nfunction enumChoices(schema: $ZodType): readonly string[] | undefined {\n const def = definition(schema);\n const candidate = def.type === \"array\" ? unwrapInput(def.element as $ZodType) : schema;\n const candidateDef = definition(candidate);\n if (candidateDef.type !== \"enum\") return undefined;\n const values = candidate._zod.values;\n return values ? [...values].map(String) : undefined;\n}\n\n/** Whether the schema accepts an array after removing supported input wrappers. */\nexport function isArrayInput(schema: $ZodType): boolean {\n return definition(unwrapInput(schema)).type === \"array\";\n}\n\n/** Whether the schema accepts an object after removing supported input wrappers. */\nexport function isObjectInput(schema: $ZodType): boolean {\n return definition(unwrapInput(schema)).type === \"object\";\n}\n\nfunction unwrapInput(schema: $ZodType): $ZodType {\n let current = schema;\n for (;;) {\n const inner = innerSchema(definition(current));\n if (!inner) return current;\n current = inner;\n }\n}\n\nexport function schemaShape(schema: ArgsSchema): Record<string, $ZodType> {\n return schema._zod.def.shape as Record<string, $ZodType>;\n}\n","import type { output } from \"zod/v4/core\";\nimport type { Output } from \"./command-output.ts\";\nimport type { Exec } from \"./exec.ts\";\nimport type { Logger } from \"./logger.ts\";\nimport type { Prompter } from \"./prompts.ts\";\nimport { aliasList } from \"./options.ts\";\nimport {\n isArrayInput,\n isObjectInput,\n POSITIONALS_KEY,\n readArgInfo,\n readPositionals,\n schemaShape,\n type ArgsSchema,\n type EmptyArgs,\n} from \"./schema.ts\";\n\nexport interface CommandContext<S extends ArgsSchema> {\n command: CommandDef<S>;\n args: output<S>;\n input: {\n argv: string[];\n unknown: string[];\n passthrough: string[];\n };\n output: Output;\n logger: Logger;\n prompt: Prompter;\n exec: Exec;\n signal: AbortSignal;\n}\n\nexport interface CommandDef<\n S extends ArgsSchema = EmptyArgs,\n R = unknown,\n Children extends Record<string, AnyCommandDef> = Record<string, AnyCommandDef>,\n> {\n name?: string;\n version?: string;\n description?: string;\n hidden?: boolean;\n /** Keep unknown options and excess positionals in input.unknown. Inherits from the parent; defaults to false. */\n allowUnknownArgs?: boolean;\n args?: S;\n subCommands?: Children;\n run?(context: CommandContext<S>): R;\n}\n\nexport type AnyCommandDef = CommandDef<ArgsSchema>;\n\nexport function defineCommand<\n S extends ArgsSchema = EmptyArgs,\n R = never,\n Children extends Record<string, AnyCommandDef> = {},\n>(def: CommandDef<S, R, Children>): NoInfer<CommandDef<S, R, Children>> {\n if (def.allowUnknownArgs !== undefined && typeof def.allowUnknownArgs !== \"boolean\") {\n throw new TypeError(\"allowUnknownArgs must be a boolean\");\n }\n const shape = def.args ? schemaShape(def.args) : {};\n const positionals = readPositionals(shape);\n\n if (positionals) {\n let sawOptional = false;\n for (const { schema, label } of positionals.items) {\n const info = readArgInfo(schema);\n if (info.alias !== undefined || info.env !== undefined || info.valueName !== undefined) {\n throw new TypeError(\n `Positional argument \\`${label}\\` cannot have alias, env, or valueName metadata`,\n );\n }\n if (isArrayInput(schema)) {\n throw new TypeError(\n `Positional argument \\`${label}\\` cannot be an array; use a tuple rest`,\n );\n }\n if (!info.takesValue) {\n throw new TypeError(`Boolean argument \\`${label}\\` cannot be positional`);\n }\n if (sawOptional && info.required) {\n throw new TypeError(\n `Required positional \\`${label}\\` cannot follow an optional positional`,\n );\n }\n sawOptional ||= !info.required;\n }\n if (positionals.rest) {\n const info = readArgInfo(positionals.rest.schema);\n if (info.alias !== undefined || info.env !== undefined || info.valueName !== undefined) {\n throw new TypeError(\n `Positional argument \\`${positionals.rest.label}\\` cannot have alias, env, or valueName metadata`,\n );\n }\n }\n if (def.subCommands && Object.keys(def.subCommands).length > 0) {\n throw new TypeError(\"A command cannot define both positional arguments and subcommands\");\n }\n }\n\n const usedAliases = new Set<string>();\n for (const [key, schema] of Object.entries(shape)) {\n const options = readArgInfo(schema);\n if (key === POSITIONALS_KEY) {\n if (\n options.alias !== undefined ||\n options.env !== undefined ||\n options.valueName !== undefined\n ) {\n throw new TypeError(\"Positional arguments cannot have alias, env, or valueName metadata\");\n }\n continue;\n }\n if (options.env !== undefined) {\n if (options.env === \"\") {\n throw new TypeError(`Environment variable name for \\`${key}\\` cannot be empty`);\n }\n if (isArrayInput(schema)) {\n throw new TypeError(\n `Option \\`${key}\\` cannot use an environment variable because it accepts an array`,\n );\n }\n if (isObjectInput(schema)) {\n throw new TypeError(\n `Option \\`${key}\\` cannot use an environment variable because it accepts an object`,\n );\n }\n }\n if (options.alias === undefined) continue;\n for (const alias of aliasList(options.alias)) {\n if (alias.length !== 1)\n throw new TypeError(`Alias \\`${alias}\\` must be exactly one character`);\n if (usedAliases.has(alias)) throw new TypeError(`Duplicate alias \\`${alias}\\``);\n usedAliases.add(alias);\n }\n }\n\n for (const key of Object.keys(shape)) {\n if (key === \"help\" || key === \"version\") {\n throw new TypeError(`Option \\`${key}\\` conflicts with the builtin --${key}`);\n }\n if (key !== POSITIONALS_KEY && /^no[-A-Z]/.test(key)) {\n throw new TypeError(`Option \\`${key}\\` conflicts with --no- negation`);\n }\n }\n\n return def;\n}\n","import type { AnyCommandDef } from \"./command.ts\";\nimport { kebabCase } from \"./options.ts\";\nimport {\n isArrayInput,\n isObjectInput,\n POSITIONALS_KEY,\n readArgInfo,\n schemaShape,\n} from \"./schema.ts\";\n\nconst commandPaths = new WeakMap<AnyCommandDef, readonly string[] | undefined>();\n\nexport function registerCommandPath(\n command: AnyCommandDef,\n path: readonly string[] | undefined,\n): void {\n commandPaths.set(command, path);\n}\n\nexport function commandEnvPath(command: AnyCommandDef): readonly string[] | undefined {\n if (!commandPaths.has(command)) return command.name ? [command.name] : undefined;\n return commandPaths.get(command);\n}\n\nfunction envSegment(segment: string): string {\n return kebabCase(segment)\n .replaceAll(/[^A-Za-z0-9]+/g, \"_\")\n .toUpperCase();\n}\n\nexport function optionEnvNames(\n command: AnyCommandDef,\n path: readonly string[] | undefined,\n): ReadonlyMap<string, string> {\n const names = new Map<string, string>();\n if (!command.args) return names;\n for (const [key, schema] of Object.entries(schemaShape(command.args))) {\n if (key === POSITIONALS_KEY) continue;\n if (isArrayInput(schema) || isObjectInput(schema)) continue;\n const configured = readArgInfo(schema).env;\n if (configured === false) continue;\n if (typeof configured === \"string\") {\n names.set(key, configured);\n continue;\n }\n if (path === undefined || path.length === 0) continue;\n names.set(key, [...path, key].map(envSegment).join(\"_\"));\n }\n return names;\n}\n\nfunction envOptionLabel(path: readonly string[] | undefined, key: string): string {\n const flag = `--${kebabCase(key)}`;\n const command = path?.slice(1).join(\" \");\n return command ? `${command} ${flag}` : flag;\n}\n\nexport function assertUniqueEnvNames(\n segments: readonly {\n command: AnyCommandDef;\n path: readonly string[] | undefined;\n }[],\n): void {\n const owners = new Map<string, string>();\n for (const segment of segments) {\n for (const [key, envName] of optionEnvNames(segment.command, segment.path)) {\n const label = envOptionLabel(segment.path, key);\n const previous = owners.get(envName);\n if (previous !== undefined) {\n throw new TypeError(\n `Environment variable \\`${envName}\\` is used by both \\`${previous}\\` and \\`${label}\\``,\n );\n }\n owners.set(envName, label);\n }\n }\n}\n\nexport function readEnvValue(\n env: Readonly<Record<string, string | undefined>>,\n name: string,\n): string | undefined {\n try {\n const value = env[name];\n return typeof value === \"string\" ? value : undefined;\n } catch {\n return undefined;\n }\n}\n","import { parseArgs as parseNodeArgs } from \"node:util\";\nimport { safeParseAsync, type $ZodIssue, type output } from \"zod/v4/core\";\nimport type { AnyCommandDef, CommandDef } from \"./command.ts\";\nimport { assertUniqueEnvNames, optionEnvNames, readEnvValue } from \"./environment.ts\";\nimport { HackshValidationError, type HackshIssue } from \"./errors.ts\";\nimport { aliasList, kebabCase } from \"./options.ts\";\nimport {\n POSITIONALS_KEY,\n readArgInfo,\n readPositionals,\n schemaShape,\n type ArgsSchema,\n type Positionals,\n} from \"./schema.ts\";\n\nexport interface ParsedCommand<S extends ArgsSchema> {\n args: output<S>;\n passthrough: string[];\n extraArgs: string[];\n}\n\ninterface OptionDefinition {\n readonly key: string;\n readonly kebabName: string;\n readonly takesValue: boolean;\n}\n\ninterface OptionModel {\n readonly definitions: Map<string, OptionDefinition>;\n readonly parserOptions: Record<string, { type: \"string\" | \"boolean\"; short?: string }>;\n readonly aliases: Set<string>;\n}\n\ninterface KnownOptionToken {\n readonly kind: \"known-option\";\n readonly index: number;\n readonly definition: OptionDefinition;\n readonly value: string | boolean;\n}\n\ninterface UnknownOptionToken {\n readonly kind: \"unknown-option\";\n readonly index: number;\n readonly value: string;\n}\n\ninterface PositionalToken {\n readonly kind: \"positional\";\n readonly index: number;\n readonly value: string;\n}\n\ntype CommandToken = KnownOptionToken | UnknownOptionToken | PositionalToken;\n\nexport interface TokenizedCommandArgs {\n readonly tokens: readonly CommandToken[];\n readonly passthrough: string[];\n readonly issues: readonly IndexedIssue[];\n readonly help: boolean;\n readonly helpIndex: number | undefined;\n readonly version: boolean;\n readonly versionIndex: number | undefined;\n}\n\ninterface IndexedIssue {\n readonly index: number;\n readonly issue: HackshIssue;\n}\n\nfunction optionModel(command: AnyCommandDef): OptionModel {\n const definitions = new Map<string, OptionDefinition>();\n const parserOptions: OptionModel[\"parserOptions\"] = {};\n const allAliases = new Set<string>();\n\n if (command.args) {\n for (const [key, schema] of Object.entries(schemaShape(command.args))) {\n if (key === POSITIONALS_KEY) continue;\n const info = readArgInfo(schema);\n const aliases = info.alias === undefined ? [] : aliasList(info.alias);\n const definition: OptionDefinition = {\n key,\n kebabName: kebabCase(key),\n takesValue: info.takesValue,\n };\n const type = definition.takesValue ? \"string\" : \"boolean\";\n for (const name of new Set([key, definition.kebabName])) {\n definitions.set(name, definition);\n parserOptions[name] = { type };\n }\n for (const alias of aliases) {\n allAliases.add(alias);\n definitions.set(alias, definition);\n parserOptions[alias] = { type, short: alias };\n }\n }\n }\n return { definitions, parserOptions, aliases: allAliases };\n}\n\nfunction commandPositionals(command: AnyCommandDef): Positionals | undefined {\n return command.args ? readPositionals(schemaShape(command.args)) : undefined;\n}\n\nfunction displayName(command: AnyCommandDef, path: readonly PropertyKey[]): string {\n const [first, index] = path;\n if (typeof first !== \"string\") return \"arguments\";\n if (first !== POSITIONALS_KEY) return `--${kebabCase(first)}`;\n const positionals = commandPositionals(command);\n if (!positionals || typeof index !== \"number\") return \"arguments\";\n const item = positionals.items[index];\n if (item) return `<${item.label}>`;\n return positionals.rest ? `<${positionals.rest.label}...>` : \"arguments\";\n}\n\nexport function tokenizeCommandArgs(\n command: AnyCommandDef,\n rawArgs: readonly string[],\n): TokenizedCommandArgs {\n const model = optionModel(command);\n const separator = rawArgs.indexOf(\"--\");\n const beforeSeparator = separator === -1 ? [...rawArgs] : rawArgs.slice(0, separator);\n const passthrough = separator === -1 ? [] : rawArgs.slice(separator + 1);\n const negativeIndexes = new Set<number>();\n const valuedNegativeIndexes = new Set<number>();\n const issues: IndexedIssue[] = [];\n let recordedMissingValue = false;\n const parserArgs = beforeSeparator.map((raw, index) => {\n if (!raw.startsWith(\"--no-\")) return raw;\n const equals = raw.indexOf(\"=\");\n const name = raw.slice(5, equals === -1 ? undefined : equals);\n const definition = model.definitions.get(name);\n if (!definition || definition.takesValue) return raw;\n negativeIndexes.add(index);\n if (equals !== -1) {\n valuedNegativeIndexes.add(index);\n return `--${definition.key}${raw.slice(equals)}`;\n }\n return `--${definition.key}`;\n });\n\n const parsed = parseNodeArgs({\n args: parserArgs,\n options: model.parserOptions,\n allowPositionals: true,\n strict: false,\n tokens: true,\n });\n const tokens: CommandToken[] = [];\n const unknownIndexes = new Set<number>();\n let help = false;\n let helpIndex: number | undefined;\n let version = false;\n let versionIndex: number | undefined;\n for (const token of parsed.tokens) {\n if (token.kind === \"positional\") {\n tokens.push({ kind: \"positional\", index: token.index, value: token.value });\n continue;\n }\n if (token.kind !== \"option\") continue;\n const isHelp =\n token.rawName === \"--help\" || (token.rawName === \"-h\" && !model.aliases.has(\"h\"));\n const isVersion =\n token.rawName === \"--version\" || (token.rawName === \"-v\" && !model.aliases.has(\"v\"));\n if (isHelp) {\n help = true;\n helpIndex ??= token.index;\n }\n if (isVersion) {\n version = true;\n versionIndex ??= token.index;\n }\n const definition = model.definitions.get(token.name);\n if (definition) {\n if (\n definition.takesValue &&\n (token.value === undefined ||\n (!token.inlineValue && token.value.startsWith(\"-\") && token.value !== \"-\"))\n ) {\n if (!recordedMissingValue) {\n issues.push({\n index: token.index,\n issue: { arg: `--${definition.kebabName}`, message: \"requires a value\" },\n });\n recordedMissingValue = true;\n }\n }\n let value: string | boolean = token.value ?? true;\n if (!definition.takesValue) {\n if (valuedNegativeIndexes.has(token.index)) {\n const rawName = beforeSeparator[token.index]!.split(\"=\", 1)[0]!;\n issues.push({\n index: token.index,\n issue: { arg: rawName, message: \"does not accept a value\" },\n });\n value = false;\n } else if (negativeIndexes.has(token.index)) {\n value = false;\n } else if (token.inlineValue) {\n if (token.value === \"true\") value = true;\n else if (token.value === \"false\") value = false;\n else {\n issues.push({\n index: token.index,\n issue: { arg: token.rawName, message: \"expects true or false\" },\n });\n }\n }\n }\n tokens.push({\n kind: \"known-option\",\n index: token.index,\n definition,\n value: definition.takesValue ? (token.value ?? \"\") : value,\n });\n } else if (!unknownIndexes.has(token.index)) {\n unknownIndexes.add(token.index);\n tokens.push({\n kind: \"unknown-option\",\n index: token.index,\n value: beforeSeparator[token.index]!,\n });\n }\n }\n\n return {\n tokens,\n passthrough,\n issues,\n help,\n helpIndex,\n version,\n versionIndex,\n };\n}\n\nexport function tokenizedBefore(\n tokenized: TokenizedCommandArgs,\n endIndex: number,\n): TokenizedCommandArgs {\n const help = tokenized.helpIndex !== undefined && tokenized.helpIndex < endIndex;\n const version = tokenized.versionIndex !== undefined && tokenized.versionIndex < endIndex;\n return {\n tokens: tokenized.tokens.filter((token) => token.index < endIndex),\n passthrough: [],\n issues: tokenized.issues.filter(({ index }) => index < endIndex),\n help,\n helpIndex: help ? tokenized.helpIndex : undefined,\n version,\n versionIndex: version ? tokenized.versionIndex : undefined,\n };\n}\n\nfunction zodIssues(\n command: AnyCommandDef,\n issues: readonly $ZodIssue[],\n envSources: ReadonlyMap<string, string>,\n): HackshIssue[] {\n return issues.map((issue) => {\n const key = issue.path[0];\n const envName = typeof key === \"string\" ? envSources.get(key) : undefined;\n return {\n arg: envName ?? displayName(command, issue.path),\n message: issue.message,\n issue,\n };\n });\n}\n\nexport async function parseCommandArgs<S extends ArgsSchema>(\n command: CommandDef<S>,\n rawArgs: string[],\n tokenized: TokenizedCommandArgs = tokenizeCommandArgs(command, rawArgs),\n env?: Readonly<Record<string, string | undefined>>,\n envPath?: readonly string[],\n): Promise<ParsedCommand<S>> {\n if (tokenized.issues.length > 0) {\n throw new HackshValidationError(\n command,\n tokenized.issues.map(({ issue }) => issue),\n );\n }\n\n const input: Record<string, string | boolean | string[] | undefined> = {};\n const positionals = commandPositionals(command);\n const positionalValues: string[] = [];\n if (positionals) input[POSITIONALS_KEY] = positionalValues;\n const extraArgs: string[] = [];\n for (const token of tokenized.tokens) {\n if (token.kind === \"known-option\") input[token.definition.key] = token.value;\n else if (token.kind === \"unknown-option\") extraArgs.push(token.value);\n else if (\n positionals &&\n (positionals.rest || positionalValues.length < positionals.items.length)\n ) {\n positionalValues.push(token.value);\n } else extraArgs.push(token.value);\n }\n\n if (!command.allowUnknownArgs && extraArgs.length > 0) {\n throw new HackshValidationError(\n command,\n extraArgs.map((arg) => ({ arg, message: \"unexpected argument\" })),\n );\n }\n\n const envSources = new Map<string, string>();\n if (env && command.args) {\n const shape = schemaShape(command.args);\n const envIssues: HackshIssue[] = [];\n for (const [key, envName] of optionEnvNames(command, envPath)) {\n if (input[key] !== undefined) continue;\n const value = readEnvValue(env, envName);\n if (value === undefined) continue;\n if (readArgInfo(shape[key]!).takesValue) {\n input[key] = value;\n } else if (value === \"true\" || value === \"false\") {\n input[key] = value === \"true\";\n } else {\n envIssues.push({ arg: envName, message: \"expects true or false\" });\n continue;\n }\n envSources.set(key, envName);\n }\n if (envIssues.length > 0) throw new HackshValidationError(command, envIssues);\n }\n\n if (!command.args)\n return { args: input as output<S>, passthrough: tokenized.passthrough, extraArgs };\n const result = await safeParseAsync(command.args, input);\n if (!result.success) {\n throw new HackshValidationError(command, zodIssues(command, result.error.issues, envSources));\n }\n return { args: result.data, passthrough: tokenized.passthrough, extraArgs };\n}\n\n/**\n * Parse and validate one command segment without routing, builtin handling, or output.\n * Environment variables are read only when `options.env` is provided.\n */\nexport async function parseArgs<S extends ArgsSchema>(\n command: CommandDef<S>,\n argv: string[],\n options?: { readonly env?: Readonly<Record<string, string | undefined>> },\n): Promise<output<S>> {\n const envPath = command.name ? [command.name] : undefined;\n if (options?.env !== undefined) assertUniqueEnvNames([{ command, path: envPath }]);\n return (\n await parseCommandArgs(command, argv, tokenizeCommandArgs(command, argv), options?.env, envPath)\n ).args;\n}\n","import type { Printer } from \"./printer.ts\";\n\n/** Writes a command's results to stdout, separately from logs. */\nexport interface Output {\n /** Write text exactly as given. */\n print(text: string): void;\n /** Write text followed by a newline. */\n println(text?: string): void;\n /** Write a JSON value. */\n json(value: unknown): void;\n}\n\n/** Create the output for one command invocation. */\nexport function createOutput(printer: Printer): Output {\n function print(text: string): void {\n void printer.print({ type: \"output\", kind: \"text\", text });\n }\n return {\n print,\n println: (text = \"\") => print(`${text}\\n`),\n json: (data) => void printer.print({ type: \"output\", kind: \"json\", data }),\n };\n}\n","export type TerminalOwner = \"prompt\" | \"exec\";\n\nexport class TerminalLock {\n #owner: TerminalOwner | undefined;\n\n get owner(): TerminalOwner | undefined {\n return this.#owner;\n }\n\n acquire(owner: TerminalOwner): boolean {\n if (this.#owner !== undefined) return false;\n this.#owner = owner;\n return true;\n }\n\n release(): void {\n this.#owner = undefined;\n }\n}\n","import type { Printer } from \"./printer.ts\";\nimport { summarizeErrors } from \"./errors.ts\";\n\nexport type LogLevel = \"trace\" | \"debug\" | \"info\" | \"warning\" | \"error\" | \"fatal\";\n\nexport type LogKind = \"message\" | \"step\" | \"success\";\n\nexport type LogProperties = Record<string, unknown>;\n\n/** A structured message emitted by a command's logger. */\nexport interface LogRecord {\n level: LogLevel;\n kind: LogKind;\n category: readonly string[];\n message: string;\n rawMessage: string;\n properties: LogProperties;\n timestamp: number;\n}\n\nexport interface Logger {\n readonly category: readonly string[];\n trace(message: string, properties?: LogProperties): void;\n debug(message: string, properties?: LogProperties): void;\n info(message: string, properties?: LogProperties): void;\n warn(message: string, properties?: LogProperties): void;\n error(message: string | Error, properties?: LogProperties): void;\n fatal(message: string | Error, properties?: LogProperties): void;\n step(message: string, properties?: LogProperties): void;\n success(message: string, properties?: LogProperties): void;\n with(properties: LogProperties): Logger;\n getChild(category: string): Logger;\n}\n\nfunction interpolate(message: string, properties: LogProperties): string {\n return message.replace(/\\{([^{}]+)\\}/g, (placeholder, key: string) => {\n if (!Object.hasOwn(properties, key)) return placeholder;\n try {\n return String(properties[key]);\n } catch {\n return placeholder;\n }\n });\n}\n\nfunction createBoundLogger(\n printer: Printer,\n category: readonly string[],\n boundProperties: LogProperties,\n): Logger {\n function emit(\n level: LogLevel,\n kind: LogKind,\n input: string | Error,\n properties: LogProperties = {},\n ): void {\n const rawMessage = input instanceof Error ? input.message : input;\n const mergedProperties = { ...boundProperties, ...properties };\n if (input instanceof Error) mergedProperties.error = input;\n const summarizedProperties = summarizeErrors(mergedProperties) as LogProperties;\n\n void printer.print({\n type: \"log\",\n record: {\n level,\n kind,\n category,\n message: interpolate(rawMessage, mergedProperties),\n rawMessage,\n properties: summarizedProperties,\n timestamp: Date.now(),\n },\n });\n }\n\n return {\n category,\n trace: (message, properties) => emit(\"trace\", \"message\", message, properties),\n debug: (message, properties) => emit(\"debug\", \"message\", message, properties),\n info: (message, properties) => emit(\"info\", \"message\", message, properties),\n warn: (message, properties) => emit(\"warning\", \"message\", message, properties),\n error: (message, properties) => emit(\"error\", \"message\", message, properties),\n fatal: (message, properties) => emit(\"fatal\", \"message\", message, properties),\n step: (message, properties) => emit(\"info\", \"step\", message, properties),\n success: (message, properties) => emit(\"info\", \"success\", message, properties),\n with: (properties) =>\n createBoundLogger(printer, category, { ...boundProperties, ...properties }),\n getChild: (child) => createBoundLogger(printer, [...category, child], boundProperties),\n };\n}\n\n/** Create the logger for one command invocation. */\nexport function createLogger(printer: Printer, category: readonly string[]): Logger {\n return createBoundLogger(printer, [...category], {});\n}\n","import { readFile, realpath } from \"node:fs/promises\";\nimport { dirname, join } from \"node:path\";\n\nexport async function findPackageVersion(entry: string | undefined): Promise<string | undefined> {\n if (!entry) return undefined;\n let directory: string;\n try {\n directory = dirname(await realpath(entry));\n } catch {\n return undefined;\n }\n for (;;) {\n const version = await readPackageVersion(join(directory, \"package.json\"));\n if (version !== undefined) return version;\n const parent = dirname(directory);\n if (parent === directory) return undefined;\n directory = parent;\n }\n}\n\nasync function readPackageVersion(path: string): Promise<string | undefined> {\n let text: string;\n try {\n text = await readFile(path, \"utf8\");\n } catch {\n return undefined;\n }\n try {\n const { version } = JSON.parse(text) as { version?: unknown };\n return typeof version === \"string\" ? version : undefined;\n } catch {\n return undefined;\n }\n}\n","import { emitKeypressEvents } from \"node:readline\";\nimport { PassThrough } from \"node:stream\";\nimport type { HackshPromptErrorReason, PromptErrorDetails, PromptKind } from \"./errors.ts\";\nimport { HackshPromptError } from \"./errors.ts\";\nimport type {\n ConfirmPromptState,\n Printer,\n PromptState,\n PromptStatus,\n SelectPromptState,\n TerminalInput,\n TextPromptState,\n} from \"./printer.ts\";\nimport { TerminalLock } from \"./terminal.ts\";\n\nexport interface SelectOption<T extends string> {\n value: T;\n label?: string;\n hint?: string;\n}\n\nexport interface SelectOptions<T extends string> {\n message: string;\n options: readonly SelectOption<T>[];\n initialValue?: T;\n}\n\nexport interface ConfirmOptions {\n message: string;\n initialValue?: boolean;\n}\n\nexport interface TextOptions {\n message: string;\n placeholder?: string;\n validate?(value: string): string | undefined;\n}\n\nexport interface Prompter {\n select<const T extends string>(options: SelectOptions<T>): Promise<T>;\n confirm(options: ConfirmOptions): Promise<boolean>;\n text(options: TextOptions): Promise<string>;\n}\n\ninterface Key {\n name?: string;\n ctrl?: boolean;\n meta?: boolean;\n sequence?: string;\n}\n\ninterface PromptControllerOptions {\n interactive: boolean;\n input: TerminalInput;\n print(event: Parameters<Printer[\"print\"]>[0]): Promise<void>;\n terminal: TerminalLock;\n signal: AbortSignal;\n}\n\ninterface BufferedKeypress {\n character: string | undefined;\n key: Key;\n}\n\nfunction details(\n kind: PromptKind,\n message: unknown,\n choices?: readonly string[],\n): PromptErrorDetails {\n let normalizedMessage: string;\n try {\n normalizedMessage = typeof message === \"string\" ? message : String(message);\n } catch {\n normalizedMessage = \"[Unserializable prompt message]\";\n }\n return {\n kind,\n message: normalizedMessage,\n ...(choices === undefined ? {} : { choices }),\n };\n}\n\nfunction promptError(\n reason: HackshPromptErrorReason,\n prompt: PromptErrorDetails,\n message: string,\n cause?: unknown,\n): HackshPromptError {\n return new HackshPromptError(\n reason,\n prompt,\n message,\n cause === undefined ? undefined : { cause },\n );\n}\n\nfunction validateMessage(kind: PromptKind, message: unknown, choices?: readonly string[]): void {\n if (typeof message !== \"string\" || message.length === 0) {\n throw promptError(\n \"invalid-options\",\n details(kind, message, choices),\n `Invalid ${kind} prompt: message must be a non-empty string`,\n );\n }\n}\n\nfunction asInput(value: TerminalInput, prompt: PromptErrorDetails): TerminalInput {\n if (\n typeof value !== \"object\" ||\n value === null ||\n typeof Reflect.get(value, \"on\") !== \"function\" ||\n typeof Reflect.get(value, \"removeListener\") !== \"function\" ||\n typeof Reflect.get(value, \"resume\") !== \"function\" ||\n typeof Reflect.get(value, \"pause\") !== \"function\"\n ) {\n throw promptError(\"input-error\", prompt, \"Interactive input is not a readable stream\");\n }\n return value;\n}\n\nexport class PromptController implements Prompter {\n readonly #interactive: boolean;\n readonly #inputValue: TerminalInput;\n readonly #printEvent: PromptControllerOptions[\"print\"];\n readonly #bufferedKeys: BufferedKeypress[] = [];\n readonly #terminal: TerminalLock;\n readonly #signal: AbortSignal;\n\n constructor(options: PromptControllerOptions) {\n this.#interactive = options.interactive;\n this.#inputValue = options.input;\n this.#printEvent = (event) => options.print(event);\n this.#terminal = options.terminal;\n this.#signal = options.signal;\n }\n\n async #print(state: PromptState, prompt: PromptErrorDetails): Promise<void> {\n try {\n await this.#printEvent({ type: \"prompt\", prompt: state });\n } catch (cause) {\n throw promptError(\"printer-error\", prompt, \"The prompt could not be displayed\", cause);\n }\n }\n\n async #run<T>(\n prompt: PromptErrorDetails,\n initial: PromptState,\n accept: (character: string, key: Key) => T | undefined,\n update: (character: string, key: Key) => PromptState | undefined,\n submitted: (value: T) => PromptState,\n closed: () => PromptState,\n ): Promise<T> {\n if (!this.#interactive) {\n throw promptError(\n \"non-interactive\",\n prompt,\n `Cannot request ${prompt.kind} input in non-interactive mode: ${prompt.message}`,\n );\n }\n if (this.#signal.aborted) {\n throw promptError(\"aborted\", prompt, \"Prompt aborted\", this.#signal.reason);\n }\n const input = asInput(this.#inputValue, prompt);\n if (!this.#terminal.acquire(\"prompt\")) {\n throw promptError(\n \"overlapping\",\n prompt,\n this.#terminal.owner === \"exec\"\n ? \"A command is using the terminal\"\n : \"Another prompt is already active\",\n );\n }\n let originallyFlowing = false;\n let rawChanged = false;\n let outcome: { ok: true; value: T } | { ok: false; error: unknown };\n try {\n originallyFlowing = input.readableFlowing === true;\n if (input.setRawMode && input.isRaw !== true) {\n input.setRawMode(true);\n rawChanged = true;\n }\n await this.#print(initial, prompt);\n\n const value = await new Promise<T>((resolve, reject) => {\n const keypressInput = new PassThrough();\n emitKeypressEvents(keypressInput);\n let settled = false;\n let draining = false;\n let finalized = false;\n let completion: (() => void) | undefined;\n const queuedKeys = this.#bufferedKeys.splice(0);\n const finalize = (): void => {\n if (finalized || !settled || draining) return;\n finalized = true;\n cleanup();\n completion?.();\n };\n const finish = (action: () => void): void => {\n if (settled) return;\n settled = true;\n completion = action;\n finalize();\n };\n const fail = (reason: HackshPromptErrorReason, message: string, cause?: unknown): void => {\n finish(() => reject(promptError(reason, prompt, message, cause)));\n };\n const handleKeypress = async (\n character: string | undefined,\n key: Key = {},\n ): Promise<void> => {\n if (settled) return;\n if ((key.ctrl && key.name === \"c\") || key.name === \"escape\") {\n fail(\"cancelled\", \"Prompt cancelled\");\n return;\n }\n if (key.ctrl && key.name === \"d\") {\n fail(\"eof\", \"Prompt input ended before a value was submitted\");\n return;\n }\n try {\n const value = accept(character ?? \"\", key);\n if (value !== undefined) {\n finish(() => resolve(value));\n return;\n }\n const state = update(character ?? \"\", key);\n if (state) await this.#print(state, prompt);\n } catch (cause) {\n if (cause instanceof HackshPromptError) finish(() => reject(cause));\n else fail(\"input-error\", \"Prompt input could not be processed\", cause);\n }\n };\n const drainKeys = async (): Promise<void> => {\n if (draining || finalized) return;\n draining = true;\n try {\n while (queuedKeys.length > 0) {\n if (settled) {\n this.#bufferedKeys.push(...queuedKeys.splice(0));\n break;\n }\n const next = queuedKeys.shift()!;\n await handleKeypress(next.character, next.key);\n }\n } finally {\n draining = false;\n finalize();\n }\n };\n const onKeypress = (character: string | undefined, key: Key = {}): void => {\n queuedKeys.push({ character, key });\n void drainKeys().catch((cause: unknown) =>\n fail(\"input-error\", \"Prompt input could not be processed\", cause),\n );\n };\n const onEnd = (): void => fail(\"eof\", \"Prompt input ended before a value was submitted\");\n const onError = (cause: unknown): void => fail(\"input-error\", \"Prompt input failed\", cause);\n const onAbort = (): void => fail(\"aborted\", \"Prompt aborted\", this.#signal.reason);\n const onData = (chunk: unknown): void => {\n if (typeof chunk === \"string\" || chunk instanceof Uint8Array) keypressInput.write(chunk);\n else fail(\"input-error\", \"Prompt input produced a non-byte value\");\n };\n const cleanup = (): void => {\n keypressInput.removeListener(\"keypress\", onKeypress);\n keypressInput.destroy();\n input.removeListener(\"data\", onData as (...args: never[]) => void);\n input.removeListener(\"end\", onEnd as (...args: never[]) => void);\n input.removeListener(\"close\", onEnd as (...args: never[]) => void);\n input.removeListener(\"error\", onError as (...args: never[]) => void);\n this.#signal.removeEventListener(\"abort\", onAbort);\n };\n keypressInput.on(\"keypress\", onKeypress);\n input.on(\"data\", onData as (...args: never[]) => void);\n input.on(\"end\", onEnd as (...args: never[]) => void);\n input.on(\"close\", onEnd as (...args: never[]) => void);\n input.on(\"error\", onError as (...args: never[]) => void);\n this.#signal.addEventListener(\"abort\", onAbort, { once: true });\n if (this.#signal.aborted) onAbort();\n input.resume();\n void drainKeys().catch((cause: unknown) =>\n fail(\"input-error\", \"Prompt input could not be processed\", cause),\n );\n });\n outcome = { ok: true, value };\n } catch (cause) {\n outcome = {\n ok: false,\n error:\n cause instanceof HackshPromptError\n ? cause\n : promptError(\"input-error\", prompt, \"Prompt input could not be initialized\", cause),\n };\n }\n\n let restoreError: HackshPromptError | undefined;\n try {\n if (rawChanged) input.setRawMode?.(false);\n if (!originallyFlowing) input.pause();\n } catch (cause) {\n restoreError = promptError(\n \"input-error\",\n prompt,\n \"Prompt input could not be restored\",\n cause,\n );\n }\n const closeWithFailure = async (failure: unknown): Promise<never> => {\n try {\n await this.#print(closed(), prompt);\n } catch {\n // Preserve the error that terminated the prompt, including an earlier printer failure.\n } finally {\n this.#terminal.release();\n }\n throw failure;\n };\n if (restoreError) return closeWithFailure(restoreError);\n if (!outcome.ok) return closeWithFailure(outcome.error);\n try {\n await this.#print(submitted(outcome.value), prompt);\n return outcome.value;\n } catch (error) {\n try {\n await this.#print(closed(), prompt);\n } catch {\n // The submitted-state failure remains the primary error.\n }\n throw error;\n } finally {\n this.#terminal.release();\n }\n }\n\n async select<const T extends string>(options: SelectOptions<T>): Promise<T> {\n const choices = Array.isArray(options?.options)\n ? options.options.map((option) =>\n typeof option === \"object\" && option !== null && typeof option.value === \"string\"\n ? option.value\n : \"[Invalid choice]\",\n )\n : [];\n const prompt = details(\"select\", options?.message, choices);\n validateMessage(\"select\", options?.message, choices);\n if (!Array.isArray(options.options) || options.options.length === 0) {\n throw promptError(\"invalid-options\", prompt, \"A select prompt requires at least one choice\");\n }\n const seen = new Set<string>();\n for (const option of options.options) {\n if (\n typeof option !== \"object\" ||\n option === null ||\n typeof option.value !== \"string\" ||\n option.value.length === 0 ||\n (option.label !== undefined && typeof option.label !== \"string\") ||\n (option.hint !== undefined && typeof option.hint !== \"string\")\n ) {\n throw promptError(\n \"invalid-options\",\n prompt,\n \"Select choices must have valid string values\",\n );\n }\n if (seen.has(option.value)) {\n throw promptError(\"invalid-options\", prompt, `Duplicate select choice: ${option.value}`);\n }\n seen.add(option.value);\n }\n let selected = options.initialValue === undefined ? 0 : choices.indexOf(options.initialValue);\n if (selected < 0) {\n throw promptError(\n \"invalid-options\",\n prompt,\n `Unknown initial select value: ${String(options.initialValue)}`,\n );\n }\n const state = (status: PromptStatus = \"active\"): SelectPromptState => ({\n kind: \"select\",\n message: options.message,\n status,\n value: options.options[selected]!.value,\n choices: options.options.map(({ value, label, hint }, index) => ({\n value,\n label: label ?? value,\n ...(hint === undefined ? {} : { hint }),\n selected: index === selected,\n })),\n });\n const value = await this.#run<T>(\n prompt,\n state(),\n (_character, key) =>\n key.name === \"return\" || key.name === \"enter\"\n ? options.options[selected]!.value\n : undefined,\n (_character, key) => {\n if (key.name !== \"up\" && key.name !== \"down\") return undefined;\n selected =\n (selected + (key.name === \"up\" ? -1 : 1) + options.options.length) %\n options.options.length;\n return state();\n },\n () => state(\"submitted\"),\n () => state(\"closed\"),\n );\n return value;\n }\n\n async confirm(options: ConfirmOptions): Promise<boolean> {\n const prompt = details(\"confirm\", options?.message);\n validateMessage(\"confirm\", options?.message);\n if (options.initialValue !== undefined && typeof options.initialValue !== \"boolean\") {\n throw promptError(\"invalid-options\", prompt, \"Confirm initialValue must be a boolean\");\n }\n const value = options.initialValue ?? false;\n const state = (result: boolean, status: PromptStatus = \"active\"): ConfirmPromptState => ({\n kind: \"confirm\",\n message: options.message,\n status,\n value: result,\n ...(options.initialValue === undefined ? {} : { defaultValue: options.initialValue }),\n });\n const result = await this.#run<boolean>(\n prompt,\n state(value),\n (character, key) => {\n if (key.name === \"return\" || key.name === \"enter\") return value;\n if (character.toLowerCase() === \"y\") return true;\n if (character.toLowerCase() === \"n\") return false;\n return undefined;\n },\n () => undefined,\n (submitted) => state(submitted, \"submitted\"),\n () => state(value, \"closed\"),\n );\n return result;\n }\n\n async text(options: TextOptions): Promise<string> {\n const prompt = details(\"text\", options?.message);\n validateMessage(\"text\", options?.message);\n if (options.placeholder !== undefined && typeof options.placeholder !== \"string\") {\n throw promptError(\"invalid-options\", prompt, \"Text placeholder must be a string\");\n }\n if (options.validate !== undefined && typeof options.validate !== \"function\") {\n throw promptError(\"invalid-options\", prompt, \"Text validate must be a function\");\n }\n let value = \"\";\n let validationError: string | undefined;\n const state = (\n status: PromptStatus = validationError ? \"error\" : \"active\",\n ): TextPromptState => ({\n kind: \"text\",\n message: options.message,\n status,\n value,\n ...(options.placeholder === undefined ? {} : { placeholder: options.placeholder }),\n ...(validationError === undefined ? {} : { error: validationError }),\n });\n const result = await this.#run<string>(\n prompt,\n state(),\n (_character, key) => {\n if (key.name !== \"return\" && key.name !== \"enter\") return undefined;\n let error: string | undefined;\n try {\n error = options.validate?.(value);\n } catch (cause) {\n throw promptError(\"input-error\", prompt, \"Text validation failed\", cause);\n }\n if (error !== undefined && typeof error !== \"string\") {\n throw promptError(\n \"input-error\",\n prompt,\n \"Text validation must return a string or undefined\",\n );\n }\n validationError = error || undefined;\n return validationError === undefined ? value : undefined;\n },\n (character, key) => {\n if (key.name === \"return\" || key.name === \"enter\") return state();\n validationError = undefined;\n if (key.name === \"backspace\") value = Array.from(value).slice(0, -1).join(\"\");\n else if (!key.ctrl && !key.meta && character.length > 0) value += character;\n else return undefined;\n return state();\n },\n () => state(\"submitted\"),\n () => state(\"closed\"),\n );\n return result;\n }\n}\n","import { createPrettyPrinter } from \"./pretty.ts\";\nimport {\n createJsonPrinter,\n resolveOutputMode,\n type OutputMode,\n type OutputPreference,\n type Printer,\n type TerminalInput,\n type TerminalOutput,\n} from \"./printer.ts\";\n\nexport interface OutputOptions {\n output?: OutputPreference;\n /** Use Unicode presentation symbols in pretty output. Defaults to true. */\n unicode?: boolean;\n env?: Readonly<Record<string, string | undefined>>;\n stdin?: TerminalInput;\n stdout?: TerminalOutput;\n stderr?: TerminalOutput;\n}\n\nfunction consoleWriter(method: \"log\" | \"error\", stream: TerminalOutput): TerminalOutput {\n return {\n get isTTY() {\n return stream.isTTY;\n },\n get columns() {\n return stream.columns;\n },\n write(text) {\n if (!text.endsWith(\"\\n\")) return stream.write(text);\n console[method](text.slice(0, -1));\n },\n };\n}\n\n/** Resolve the automatic output policy and select its printer for one operation. */\nexport function selectOutputPrinter(\n options: OutputOptions,\n override?: Printer,\n resolvedMode?: OutputMode,\n): Printer {\n const stdin = options.stdin ?? process.stdin;\n const stdout = options.stdout ?? process.stdout;\n const stderr = options.stderr ?? process.stderr;\n const mode =\n resolvedMode ??\n resolveOutputMode({\n output: options.output,\n env: options.env,\n inputIsTTY: stdin.isTTY,\n outputIsTTY: stdout.isTTY,\n errorOutputIsTTY: stderr.isTTY,\n });\n if (override) return override;\n if (mode.format === \"json\") return createJsonPrinter({ stdout, stderr });\n\n const useConsole = options.stdout === undefined && options.stderr === undefined;\n return createPrettyPrinter({\n color: mode.color,\n unicode: options.unicode ?? true,\n stdout: options.stdout ?? (useConsole ? consoleWriter(\"log\", stdout) : stdout),\n stderr: options.stderr ?? (useConsole ? consoleWriter(\"error\", process.stderr) : stderr),\n });\n}\n","import type { AnyCommandDef } from \"./command.ts\";\nimport { commandEnvPath, optionEnvNames } from \"./environment.ts\";\nimport { summarizeErrors } from \"./errors.ts\";\nimport { aliasList, kebabCase } from \"./options.ts\";\nimport type { Printer, PrintStream } from \"./printer.ts\";\nimport { POSITIONALS_KEY, readArgInfo, readPositionals, schemaShape } from \"./schema.ts\";\n\nfunction details(\n description: string | undefined,\n required: boolean,\n defaultValue: unknown,\n choices: readonly string[] | undefined,\n envName?: string,\n): string {\n const parts = [description];\n if (choices) parts.push(`(Choices: ${choices.join(\", \")})`);\n if (required) parts.push(\"(Required)\");\n if (defaultValue !== undefined) parts.push(`(Default: ${formatDefault(defaultValue)})`);\n if (envName !== undefined) parts.push(`(Env: ${envName})`);\n return parts.filter(Boolean).join(\" \");\n}\n\nfunction formatDefault(value: unknown): string {\n if (typeof value === \"string\") return value;\n if (typeof value === \"number\" || typeof value === \"boolean\" || typeof value === \"bigint\") {\n return value.toString();\n }\n if (value === null) return \"null\";\n try {\n return JSON.stringify(value) ?? \"undefined\";\n } catch {\n return \"[Unserializable]\";\n }\n}\n\nexport interface UsageArgumentSummary {\n name: string;\n required: boolean;\n variadic: boolean;\n description?: string;\n choices?: readonly string[];\n defaultValue?: unknown;\n}\n\nexport interface UsageOptionSummary {\n name: string;\n flags: readonly string[];\n takesValue: boolean;\n /** Whether the long flag also accepts a `--no-` prefixed form. */\n negatable: boolean;\n valueName?: string;\n required: boolean;\n description?: string;\n choices?: readonly string[];\n defaultValue?: unknown;\n env?: string;\n}\n\nexport interface UsageCommandSummary {\n name: string;\n description?: string;\n}\n\n/** A schema-free description of the useful help metadata for a command. */\nexport interface UsageSummary {\n name: string;\n heading?: string;\n version?: string;\n description?: string;\n synopsis: string;\n arguments: readonly UsageArgumentSummary[];\n options: readonly UsageOptionSummary[];\n commands: readonly UsageCommandSummary[];\n}\n\nfunction heading(command: AnyCommandDef): string | undefined {\n const identity = command.name\n ? `${command.name}${command.version ? ` v${command.version}` : \"\"}`\n : command.version\n ? `v${command.version}`\n : undefined;\n if (command.description && identity) return `${command.description} (${identity})`;\n return command.description ?? identity;\n}\n\n/** Build a serializable help summary without retaining command or schema objects. */\nexport function summarizeUsage(command: AnyCommandDef): UsageSummary {\n const shape = command.args ? schemaShape(command.args) : {};\n const positionals = readPositionals(shape);\n const positionalItems = positionals?.items ?? [];\n const syntax = positionalItems.map(({ schema, label }) =>\n readArgInfo(schema).required ? `<${label}>` : `[${label}]`,\n );\n if (positionals?.rest) syntax.push(`[${positionals.rest.label}...]`);\n if (command.subCommands && Object.keys(command.subCommands).length > 0) syntax.push(\"<COMMAND>\");\n\n const args: UsageArgumentSummary[] = positionalItems.map(({ schema, label }) => {\n const info = readArgInfo(schema);\n return {\n name: label,\n required: info.required,\n variadic: false,\n ...(info.description === undefined ? {} : { description: info.description }),\n ...(info.choices === undefined ? {} : { choices: info.choices }),\n ...(info.defaultValue === undefined\n ? {}\n : { defaultValue: summarizeErrors(info.defaultValue) }),\n };\n });\n if (positionals?.rest) {\n const info = readArgInfo(positionals.rest.schema);\n args.push({\n name: positionals.rest.label,\n required: false,\n variadic: true,\n ...(info.description === undefined ? {} : { description: info.description }),\n ...(info.choices === undefined ? {} : { choices: info.choices }),\n });\n }\n\n const envNames = optionEnvNames(command, commandEnvPath(command));\n const options = Object.entries(shape)\n .filter(([key]) => key !== POSITIONALS_KEY)\n .map(([key, schema]): UsageOptionSummary => {\n const info = readArgInfo(schema);\n const aliases =\n info.alias === undefined ? [] : aliasList(info.alias).map((item) => `-${item}`);\n const name = kebabCase(key);\n const valueName = info.valueName ?? name;\n const envName = envNames.get(key);\n return {\n name,\n flags: [...aliases, `--${name}`],\n takesValue: info.takesValue,\n negatable: !info.takesValue,\n required: info.required,\n ...(info.takesValue ? { valueName } : {}),\n ...(info.description === undefined ? {} : { description: info.description }),\n ...(info.choices === undefined ? {} : { choices: info.choices }),\n ...(info.defaultValue === undefined\n ? {}\n : { defaultValue: summarizeErrors(info.defaultValue) }),\n ...(envName === undefined ? {} : { env: envName }),\n };\n });\n\n const commands = Object.entries(command.subCommands ?? {})\n .filter(([, child]) => !child.hidden)\n .map(([name, child]) => ({\n name,\n ...(child.description === undefined ? {} : { description: child.description }),\n }));\n const name = command.name ?? \"command\";\n const title = heading(command);\n return {\n name,\n ...(title === undefined ? {} : { heading: title }),\n ...(command.version === undefined ? {} : { version: command.version }),\n ...(command.description === undefined ? {} : { description: command.description }),\n synopsis: `${name} [OPTIONS]${syntax.length ? ` ${syntax.join(\" \")}` : \"\"}`,\n arguments: args,\n options,\n commands,\n };\n}\n\nfunction formatUsage(summary: UsageSummary): string {\n const lines: string[] = [];\n if (summary.heading) lines.push(summary.heading, \"\");\n lines.push(`USAGE ${summary.synopsis}`);\n\n if (summary.arguments.length > 0) {\n lines.push(\"\", \"ARGUMENTS\", \"\");\n for (const argument of summary.arguments) {\n lines.push(\n ` ${argument.name}${argument.variadic ? \"...\" : \"\"} ${details(argument.description, argument.required, argument.defaultValue, argument.choices)}`.trimEnd(),\n );\n }\n }\n\n if (summary.options.length > 0) {\n lines.push(\"\", \"OPTIONS\", \"\");\n for (const option of summary.options) {\n const flags = option.flags.map((flag) => {\n if (!flag.startsWith(\"--\")) return flag;\n if (option.takesValue) return `${flag}=<${option.valueName}>`;\n if (option.negatable) return `--[no-]${flag.slice(2)}`;\n return flag;\n });\n lines.push(\n ` ${flags.join(\", \")} ${details(option.description, option.required, option.defaultValue, option.choices, option.env)}`.trimEnd(),\n );\n }\n }\n\n if (summary.commands.length > 0) {\n lines.push(\"\", \"COMMANDS\", \"\");\n for (const command of summary.commands) {\n lines.push(` ${command.name} ${command.description ?? \"\"}`.trimEnd());\n }\n }\n return lines.join(\"\\n\");\n}\n\nexport interface ShowUsageOptions {\n printer: Printer;\n stream?: PrintStream;\n}\n\n/** Generate usage text without writing to stdout or stderr. */\nexport function renderUsage(command: AnyCommandDef): string {\n return formatUsage(summarizeUsage(command));\n}\n\n/** Generate a usage event and await its printer. */\nexport async function showUsage(command: AnyCommandDef, options: ShowUsageOptions): Promise<void> {\n const usage = summarizeUsage(command);\n const text = formatUsage(usage);\n return options.printer.print({\n type: \"usage\",\n usage,\n text,\n stream: options.stream ?? \"stdout\",\n });\n}\n","import type { ArgsSchema } from \"./schema.ts\";\nimport type { AnyCommandDef, CommandDef } from \"./command.ts\";\nimport { assertUniqueEnvNames, commandEnvPath, registerCommandPath } from \"./environment.ts\";\nimport {\n HackshError,\n HackshExitError,\n HackshPromptError,\n summarizeError,\n HackshUsageError,\n} from \"./errors.ts\";\nimport { createOutput } from \"./command-output.ts\";\nimport { createExec, type ExecContext } from \"./exec.ts\";\nimport { createLogger } from \"./logger.ts\";\nimport { findPackageVersion } from \"./package-version.ts\";\nimport {\n parseCommandArgs,\n tokenizedBefore,\n tokenizeCommandArgs,\n type TokenizedCommandArgs,\n} from \"./parser.ts\";\nimport {\n createPrintQueue,\n resolveOutputMode,\n type OutputFormat,\n type Printer,\n type PrintQueue,\n type TerminalInput,\n} from \"./printer.ts\";\nimport { PromptController } from \"./prompts.ts\";\nimport { TerminalLock } from \"./terminal.ts\";\nimport { selectOutputPrinter, type OutputOptions } from \"./output.ts\";\nimport { showUsage } from \"./usage.ts\";\n\nexport type { OutputOptions } from \"./output.ts\";\n\ninterface CommandSegment {\n command: AnyCommandDef;\n rawArgs: string[];\n tokenized: TokenizedCommandArgs;\n}\n\ninterface ResolvedCommand extends CommandSegment {\n parents: CommandSegment[];\n segments: CommandSegment[];\n}\n\nfunction resolveCommand(root: AnyCommandDef, rawArgs: string[]): ResolvedCommand {\n let command = root;\n let remaining = rawArgs;\n const parents: ResolvedCommand[\"parents\"] = [];\n const segments: ResolvedCommand[\"segments\"] = [];\n\n for (;;) {\n const tokenized = tokenizeCommandArgs(command, remaining);\n const index = command.subCommands\n ? tokenized.tokens.find((token) => token.kind === \"positional\")?.index\n : undefined;\n if (index === undefined) {\n const segment = { command, rawArgs: remaining, tokenized };\n segments.push(segment);\n assertUniqueEnvNames(\n segments.map(({ command }) => ({ command, path: commandEnvPath(command) })),\n );\n return { ...segment, parents, segments };\n }\n const key = remaining[index]!;\n const child = command.subCommands?.[key];\n if (!child) throw new HackshUsageError(`Unknown command \\`${key}\\``, command);\n const prefix = remaining.slice(0, index);\n const segment = { command, rawArgs: prefix, tokenized: tokenizedBefore(tokenized, index) };\n parents.push(segment);\n segments.push(segment);\n const parentPath = commandEnvPath(command);\n command = {\n ...child,\n name: child.name ?? key,\n allowUnknownArgs: child.allowUnknownArgs ?? command.allowUnknownArgs,\n };\n registerCommandPath(command, parentPath === undefined ? undefined : [...parentPath, key]);\n remaining = remaining.slice(index + 1);\n }\n}\n\nasync function executeCommand<S extends ArgsSchema>(\n root: CommandDef<S>,\n argv: string[],\n output: PreparedOutput,\n env: ExecContext[\"env\"],\n signal: AbortSignal,\n fallbackVersion: () => Promise<string | undefined> = async () => undefined,\n): Promise<unknown> {\n const { printer } = output;\n const argEnv = env ?? process.env;\n const resolved = resolveCommand(root, argv);\n if (resolved.segments[0]?.tokenized.version) {\n const version = root.version ?? (await fallbackVersion()) ?? \"\";\n await printer.print({ type: \"version\", version });\n return undefined;\n }\n if (resolved.segments.some(({ tokenized }) => tokenized.help)) {\n await showUsage(resolved.command, { printer });\n return undefined;\n }\n\n for (const parent of resolved.parents) {\n await parseCommandArgs(\n parent.command,\n parent.rawArgs,\n parent.tokenized,\n argEnv,\n commandEnvPath(parent.command),\n );\n }\n const parsed = await parseCommandArgs(\n resolved.command,\n resolved.rawArgs,\n resolved.tokenized,\n argEnv,\n commandEnvPath(resolved.command),\n );\n if (!resolved.command.run) {\n throw new HackshUsageError(\"No command specified\", resolved.command);\n }\n signal.throwIfAborted();\n const category = resolved.segments.flatMap(({ command }) =>\n command.name === undefined ? [] : [command.name],\n );\n return resolved.command.run({\n command: resolved.command,\n args: parsed.args,\n input: {\n argv: resolved.rawArgs,\n unknown: parsed.extraArgs,\n passthrough: parsed.passthrough,\n },\n output: createOutput(printer),\n logger: createLogger(printer, category),\n prompt: new PromptController({\n interactive: output.interactive,\n input: output.input,\n print: (event) => output.printChecked(event),\n terminal: output.terminal,\n signal,\n }),\n exec: createExec({\n env,\n mode: { format: output.format, interactive: output.interactive },\n print: (event) => printer.print(event),\n terminal: output.terminal,\n signal,\n }),\n signal,\n });\n}\n\nexport interface RunCommandOptions extends OutputOptions {\n printer?: Printer;\n signal?: AbortSignal;\n}\n\ninterface PreparedOutput extends PrintQueue {\n format: OutputFormat;\n interactive: boolean;\n input: TerminalInput;\n terminal: TerminalLock;\n}\n\nfunction prepareOutput(\n options: RunCommandOptions,\n env: Readonly<Record<string, string | undefined>>,\n): PreparedOutput {\n const input = options.stdin ?? process.stdin;\n const mode = resolveOutputMode({\n output: options.output,\n env,\n inputIsTTY: input.isTTY,\n outputIsTTY: (options.stdout ?? process.stdout).isTTY,\n errorOutputIsTTY: (options.stderr ?? process.stderr).isTTY,\n });\n return {\n ...createPrintQueue(selectOutputPrinter(options, options.printer, mode)),\n format: mode.format,\n interactive: mode.interactive,\n input,\n terminal: new TerminalLock(),\n };\n}\n\ntype HandlerResult<C> = C extends { run?: infer Handler }\n ? Handler extends (...args: never[]) => infer R\n ? Awaited<R>\n : never\n : never;\n\ntype CommandResult<C> =\n | HandlerResult<C>\n | (C extends { subCommands?: infer Children }\n ? Children extends Record<string, AnyCommandDef>\n ? string extends keyof Children\n ? unknown\n : CommandResult<Children[keyof Children]>\n : never\n : never);\n\nexport function runCommand<C extends AnyCommandDef>(\n root: C,\n argv: string[],\n options?: RunCommandOptions,\n): Promise<CommandResult<C> | undefined>;\nexport async function runCommand(\n root: AnyCommandDef,\n argv: string[],\n options: RunCommandOptions = {},\n): Promise<unknown> {\n const output = prepareOutput(options, options.env ?? process.env);\n try {\n return await executeCommand(\n root,\n argv,\n output,\n options.env,\n options.signal ?? new AbortController().signal,\n );\n } finally {\n await output.drain();\n }\n}\n\nexport interface RunMainOptions extends OutputOptions {\n onError?: (error: HackshError) => void | Promise<void>;\n argv?: string[];\n printer?: Printer;\n}\n\nfunction commandErrorExitCode(error: HackshError): number {\n if (error instanceof HackshExitError) return error.exitCode;\n return error instanceof HackshPromptError && error.reason === \"cancelled\" ? 130 : 1;\n}\n\nconst SIGNAL_EXIT_CODES = { SIGINT: 130, SIGTERM: 143 } as const;\n\nfunction listenForExitSignals() {\n const controller = new AbortController();\n let exitCode: number | undefined;\n const listeners = Object.entries(SIGNAL_EXIT_CODES).map(([signal, code]) => {\n const listener = (): void => {\n if (exitCode !== undefined) process.exit(code);\n exitCode = code;\n controller.abort(new DOMException(`Received ${signal}`, \"AbortError\"));\n };\n process.on(signal, listener);\n return [signal, listener] as const;\n });\n return {\n signal: controller.signal,\n exitCode: () => exitCode,\n release(): void {\n for (const [signal, listener] of listeners) process.removeListener(signal, listener);\n },\n };\n}\n\nasync function reportCommandError(error: HackshError, output: PrintQueue): Promise<void> {\n if (error instanceof HackshExitError && error.message === \"\") return;\n await output.printer.print({ type: \"error\", error: summarizeError(error) });\n if (error instanceof HackshUsageError) {\n await showUsage(error.command, { printer: output.printer, stream: \"stderr\" });\n }\n}\n\nexport async function runMain<S extends ArgsSchema>(\n command: CommandDef<S>,\n options: RunMainOptions = {},\n): Promise<void> {\n const output = prepareOutput(options, options.env ?? process.env);\n const signals = listenForExitSignals();\n let exitCode: number | undefined;\n try {\n try {\n await executeCommand(\n command,\n options.argv ?? process.argv.slice(2),\n output,\n options.env,\n signals.signal,\n () => findPackageVersion(process.argv[1]),\n );\n } catch (error) {\n const signalExitCode = signals.exitCode();\n if (signalExitCode !== undefined && error === signals.signal.reason) {\n exitCode = signalExitCode;\n } else {\n if (!(error instanceof HackshError)) throw error;\n if (options.onError) await options.onError(error);\n else await reportCommandError(error, output);\n exitCode = commandErrorExitCode(error);\n }\n }\n } finally {\n try {\n await output.drain();\n } finally {\n signals.release();\n }\n }\n const code = signals.exitCode() ?? exitCode;\n if (code !== undefined) process.exit(code);\n}\n"],"mappings":";;;;;;;;AAAA,SAAgB,UAAU,OAAuB;CAC/C,OAAO,MAAM,WAAW,sBAAsB,OAAO,CAAC,CAAC,YAAY;AACrE;AAEA,SAAgB,UAAU,OAAsD;CAC9E,OAAO,OAAO,UAAU,WAAW,CAAC,KAAK,IAAI;AAC/C;;;ACeA,MAAa,kBAAkB;AA0B/B,SAAS,WAAW,QAA0B;CAC5C,OAAO,OAAO,KAAK;AACrB;AAEA,SAAS,YAAY,KAAmC;CACtD,QAAQ,IAAI,MAAZ;EACE,KAAK;EACL,KAAK;EACL,KAAK;EACL,KAAK;EACL,KAAK;EACL,KAAK;EACL,KAAK,YACH,OAAO,IAAI;EACb,KAAK,QACH,OAAO,IAAI;EACb,SACE;CACJ;AACF;;AAGA,SAAgB,YAAY,QAA2B;CACrD,IAAI,UAAgC;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AAQ;EACrF;CACF;AACF;AAEA,eAAe,mBAAmB,OAAoB,QAAmC;CACvF,IAAI,iBAAiB,mBAAmB,MAAM,YAAY,IAAI;CAC9D,MAAM,OAAO,QAAQ,MAAM;EAAE,MAAM;EAAS,OAAO,eAAe,KAAK;CAAE,CAAC;CAC1E,IAAI,iBAAiB,kBACnB,MAAM,UAAU,MAAM,SAAS;EAAE,SAAS,OAAO;EAAS,QAAQ;CAAS,CAAC;AAEhF;AAEA,eAAsB,QACpB,SACA,UAA0B,CAAC,GACZ;CACf,MAAM,SAAS,cAAc,SAAS,QAAQ,OAAO,QAAQ,GAAG;CAChE,MAAM,UAAU,qBAAqB;CACrC,IAAI;CACJ,IAAI;EACF,IAAI;GACF,MAAM,eACJ,SACA,QAAQ,QAAQ,QAAQ,KAAK,MAAM,CAAC,GACpC,QACA,QAAQ,KACR,QAAQ,cACF,mBAAmB,QAAQ,KAAK,EAAE,CAC1C;EACF,SAAS,OAAO;GACd,MAAM,iBAAiB,QAAQ,SAAS;GACxC,IAAI,mBAAmB,KAAA,KAAa,UAAU,QAAQ,OAAO,QAC3D,WAAW;QACN;IACL,IAAI,EAAE,iBAAiB,cAAc,MAAM;IAC3C,IAAI,QAAQ,SAAS,MAAM,QAAQ,QAAQ,KAAK;SAC3C,MAAM,mBAAmB,OAAO,MAAM;IAC3C,WAAW,qBAAqB,KAAK;GACvC;EACF;CACF,UAAU;EACR,IAAI;GACF,MAAM,OAAO,MAAM;EACrB,UAAU;GACR,QAAQ,QAAQ;EAClB;CACF;CACA,MAAM,OAAO,QAAQ,SAAS,KAAK;CACnC,IAAI,SAAS,KAAA,GAAW,QAAQ,KAAK,IAAI;AAC3C"}
@@ -1,11 +1,17 @@
1
1
  import { inspect, stripVTControlCharacters, styleText } from "node:util";
2
2
  import { spawn } from "node:child_process";
3
3
  //#region src/errors.ts
4
- var HackshUsageError = class extends Error {
4
+ /** An expected CLI failure that runMain reports; application errors can extend this class. */
5
+ var HackshError = class extends Error {
6
+ constructor(message, options) {
7
+ super(message, options);
8
+ this.name = new.target.name;
9
+ }
10
+ };
11
+ var HackshUsageError = class extends HackshError {
5
12
  command;
6
13
  constructor(message, command, options) {
7
14
  super(message, options);
8
- this.name = "HackshUsageError";
9
15
  this.command = command;
10
16
  }
11
17
  };
@@ -13,27 +19,24 @@ var HackshValidationError = class extends HackshUsageError {
13
19
  issues;
14
20
  constructor(command, issues) {
15
21
  super(`Invalid arguments:\n${issues.map(({ arg, message }) => ` ${arg}: ${message}`).join("\n")}`, command);
16
- this.name = "HackshValidationError";
17
22
  this.issues = issues;
18
23
  }
19
24
  };
20
25
  /** An input request that could not be completed safely. */
21
- var HackshPromptError = class extends Error {
26
+ var HackshPromptError = class extends HackshError {
22
27
  reason;
23
28
  prompt;
24
29
  constructor(reason, prompt, message, options) {
25
30
  super(message, options);
26
- this.name = "HackshPromptError";
27
31
  this.reason = reason;
28
32
  this.prompt = prompt;
29
33
  }
30
34
  };
31
35
  /** An external command that did not succeed; `result` is not enumerable so error summaries omit child output. */
32
- var HackshExecError = class extends Error {
36
+ var HackshExecError = class extends HackshError {
33
37
  #result;
34
38
  constructor(message, result, options) {
35
39
  super(message, options);
36
- this.name = "HackshExecError";
37
40
  this.#result = result;
38
41
  }
39
42
  get result() {
@@ -41,12 +44,11 @@ var HackshExecError = class extends Error {
41
44
  }
42
45
  };
43
46
  /** A requested process exit status; `runMain` exits with it and reports only a non-empty message. */
44
- var HackshExitError = class extends Error {
47
+ var HackshExitError = class extends HackshError {
45
48
  exitCode;
46
49
  constructor(exitCode, message, options) {
47
50
  if (!Number.isInteger(exitCode) || exitCode < 0 || exitCode > 255) throw new TypeError("Exit code must be an integer from 0 to 255");
48
51
  super(message, options);
49
- this.name = "HackshExitError";
50
52
  this.exitCode = exitCode;
51
53
  }
52
54
  };
@@ -1023,6 +1025,6 @@ function createPrettyPrinter(options) {
1023
1025
  } };
1024
1026
  }
1025
1027
  //#endregion
1026
- export { createExec as a, HackshPromptError as c, summarizeError as d, summarizeErrors as f, resolveOutputMode as i, HackshUsageError as l, createJsonPrinter as n, HackshExecError as o, createPrintQueue as r, HackshExitError as s, createPrettyPrinter as t, HackshValidationError as u };
1028
+ export { createExec as a, HackshExitError as c, HackshValidationError as d, summarizeError as f, resolveOutputMode as i, HackshPromptError as l, createJsonPrinter as n, HackshError as o, summarizeErrors as p, createPrintQueue as r, HackshExecError as s, createPrettyPrinter as t, HackshUsageError as u };
1027
1029
 
1028
- //# sourceMappingURL=pretty-DJ2CE6TU.js.map
1030
+ //# sourceMappingURL=pretty-Db7-kATM.js.map