hacksh 0.12.0 → 0.13.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/README.md CHANGED
@@ -436,9 +436,9 @@ parse Git records or infer whether stdout is text, JSON, or a list.
436
436
  ### Execution options
437
437
 
438
438
  Options are `cwd`, `env`, `input`, `reject`, `timeout` (milliseconds), `signal` (an
439
- `AbortSignal`), `maxBuffer` (bytes per stream, default 100,000,000), and `forceKillAfterDelay`
440
- (milliseconds, default 5,000). Every call also stops with `aborted` when the invocation's `signal`
441
- aborts. `input` is written to stdin and closed; otherwise stdin is empty.
439
+ `AbortSignal`), `maxBuffer` (bytes per stream, default 100,000,000), `forceKillAfterDelay`
440
+ (milliseconds, default 5,000), and `dryRun`. Every call also stops with `aborted` when the
441
+ invocation's `signal` aborts. `input` is written to stdin and closed; otherwise stdin is empty.
442
442
  Output beyond `maxBuffer` is truncated to that many bytes. On timeout, abort, or output limit,
443
443
  hacksh sends `SIGTERM` to the child it started and `SIGKILL` after `forceKillAfterDelay`; it does
444
444
  not stop grandchildren, and it does not wait for them to close inherited pipes. Invalid arguments
@@ -458,6 +458,18 @@ JSON event has `phase: "start"`, `command` (`file`, `args`, and `cwd` when set),
458
458
  in the event, the result's `command`, the `HackshExecError` message, and a `spawn` failure's
459
459
  `error`. The child still receives the real values, and its captured output is returned unchanged.
460
460
 
461
+ `dryRun: true` does not start the child and does not write `input`. The result is
462
+ `{ status: "skipped", command }` with the redacted command and no `stdout`, `stderr`, or `exitCode`.
463
+ The `exec` event uses `phase: "skip"` and the same command, stdio, and `interactive` flag.
464
+ Pretty output marks that line with `#` instead of `$`. Omit `dryRun`, or pass `false`, to keep
465
+ today's success or failure result. A boolean `dryRun` returns the union of a skip and the executed
466
+ result, so narrow `status` before reading output. `reject` does not apply to a skip. An invocation
467
+ signal that is already aborted still fails as `aborted` before any skip event, and `reject` applies
468
+ to that failure. Option checks still run, including `input` together with `stdin: "inherit"`.
469
+ JSON mode, a non-interactive environment, and a busy terminal still show the plan and return
470
+ a skip. `display: false` hides the skip event. `dryRun` is not read from CLI flags or
471
+ `context.args`.
472
+
461
473
  ```ts
462
474
  await exec("git", ["worktree", "add", path, branch], { cwd: repository });
463
475
  await exec("gh", ["auth", "login", "--with-token"], { input: token, display: false });
package/dist/index.d.ts CHANGED
@@ -242,7 +242,7 @@ interface PromptPrintEvent {
242
242
  }
243
243
  interface ExecPrintEvent {
244
244
  type: "exec";
245
- phase: "start";
245
+ phase: "start" | "skip";
246
246
  command: Omit<ExecCommand, "cwd"> & {
247
247
  cwd?: string;
248
248
  };
@@ -308,6 +308,7 @@ interface ExecOptions {
308
308
  interactive?: boolean;
309
309
  display?: boolean;
310
310
  redact?: readonly string[];
311
+ dryRun?: boolean;
311
312
  }
312
313
  interface ExecCommand {
313
314
  file: string;
@@ -342,7 +343,22 @@ type ExecFailure = {
342
343
  });
343
344
  type ExecFailureReason = ExecFailure["reason"];
344
345
  type ExecResult = ExecSuccess | ExecFailure;
345
- type ExecReturn<O extends ExecOptions> = "reject" extends keyof O ? false extends O["reject"] ? ExecResult : ExecSuccess : ExecSuccess;
346
+ interface ExecSkipped {
347
+ status: "skipped";
348
+ command: ExecCommand;
349
+ }
350
+ type ExecOutcome<O extends ExecOptions> = "reject" extends keyof O ? false extends O["reject"] ? ExecResult : ExecSuccess : ExecSuccess;
351
+ type SpecifiedDryRun<O> = "dryRun" extends keyof O ? O["dryRun"] : false;
352
+ type ReturnsFailure<O extends ExecOptions> = "reject" extends keyof O ? false extends O["reject"] ? true : false : false;
353
+ type AbortedFailure = {
354
+ status: "failed";
355
+ command: ExecCommand;
356
+ stdout: string;
357
+ stderr: string;
358
+ reason: "aborted";
359
+ };
360
+ type DefiniteSkip<O extends ExecOptions> = ReturnsFailure<O> extends true ? ExecSkipped | AbortedFailure : ExecSkipped;
361
+ type ExecReturn<O extends ExecOptions> = true extends SpecifiedDryRun<O> ? false extends SpecifiedDryRun<O> ? ExecSkipped | ExecOutcome<O> : undefined extends SpecifiedDryRun<O> ? ExecSkipped | ExecOutcome<O> : DefiniteSkip<O> : ExecOutcome<O>;
346
362
  type RejectInheritedInput<O> = O extends {
347
363
  input: string;
348
364
  stdin: "inherit";
@@ -424,5 +440,5 @@ interface RunMainOptions extends OutputOptions {
424
440
  declare function runMain<S extends ArgsSchema>(command: CommandDef<S>, options?: RunMainOptions): Promise<void>;
425
441
  declare function createMain<S extends ArgsSchema>(command: CommandDef<S>, options?: RunMainOptions): (argv?: string[]) => Promise<void>;
426
442
  //#endregion
427
- export { type ArgOptions, type ArgOptionsMap, type CommandContext, type CommandDef, type ConfirmOptions, type ConfirmPromptState, type ErrorPrintEvent, type Exec, type ExecCommand, type ExecFailure, type ExecFailureReason, type ExecOptions, type ExecPrintEvent, type ExecResult, type ExecReturn, type ExecSuccess, type HackshErrorKind, type HackshErrorSummary, HackshExecError, HackshExitError, type HackshIssue, HackshPromptError, type HackshPromptErrorReason, HackshUsageError, HackshValidationError, type JsonPrinterOptions, type LogKind, type LogLevel, type LogPrintEvent, type LogProperties, type LogRecord, type Logger, type OutputFormat, type OutputMode, type OutputOptions, type OutputPreference, type OutputWriter, type PrettyPrinterOptions, type PrintEvent, type PrintStream, type Printer, type PromptChoiceState, type PromptErrorDetails, type PromptKind, type PromptPrintEvent, type PromptState, type PromptStatus, type Prompter, type ResolveOutputModeOptions, type RunCommandOptions, type RunMainOptions, type SelectOption, type SelectOptions, type SelectPromptState, type ShowUsageCallback, type ShowUsageOptions, type StreamPrinterOptions, type TerminalInput, type TerminalOutput, type TextOptions, type TextPromptState, type UsageArgumentSummary, type UsageCommandSummary, type UsageOptionSummary, type UsageOutput, type UsagePrintEvent, type UsageSummary, type UsageWriter, type ValidationIssueSummary, type VersionPrintEvent, consolePrinter, createJsonPrinter, createMain, createPrettyPrinter, createStreamPrinter, defineCommand, parseArgs, renderUsage, resolveOutputMode, runCommand, runMain, showUsage, summarizeUsage };
443
+ export { type ArgOptions, type ArgOptionsMap, type CommandContext, type CommandDef, type ConfirmOptions, type ConfirmPromptState, type ErrorPrintEvent, type Exec, type ExecCommand, type ExecFailure, type ExecFailureReason, type ExecOptions, type ExecPrintEvent, type ExecResult, type ExecReturn, type ExecSkipped, type ExecSuccess, type HackshErrorKind, type HackshErrorSummary, HackshExecError, HackshExitError, type HackshIssue, HackshPromptError, type HackshPromptErrorReason, HackshUsageError, HackshValidationError, type JsonPrinterOptions, type LogKind, type LogLevel, type LogPrintEvent, type LogProperties, type LogRecord, type Logger, type OutputFormat, type OutputMode, type OutputOptions, type OutputPreference, type OutputWriter, type PrettyPrinterOptions, type PrintEvent, type PrintStream, type Printer, type PromptChoiceState, type PromptErrorDetails, type PromptKind, type PromptPrintEvent, type PromptState, type PromptStatus, type Prompter, type ResolveOutputModeOptions, type RunCommandOptions, type RunMainOptions, type SelectOption, type SelectOptions, type SelectPromptState, type ShowUsageCallback, type ShowUsageOptions, type StreamPrinterOptions, type TerminalInput, type TerminalOutput, type TextOptions, type TextPromptState, type UsageArgumentSummary, type UsageCommandSummary, type UsageOptionSummary, type UsageOutput, type UsagePrintEvent, type UsageSummary, type UsageWriter, type ValidationIssueSummary, type VersionPrintEvent, consolePrinter, createJsonPrinter, createMain, createPrettyPrinter, createStreamPrinter, defineCommand, parseArgs, renderUsage, resolveOutputMode, runCommand, runMain, showUsage, summarizeUsage };
428
444
  //# sourceMappingURL=index.d.ts.map
package/dist/index.js CHANGED
@@ -694,7 +694,8 @@ const OPTION_KEYS = /* @__PURE__ */ new Set([
694
694
  "stderr",
695
695
  "interactive",
696
696
  "display",
697
- "redact"
697
+ "redact",
698
+ "dryRun"
698
699
  ]);
699
700
  const MAX_DELAY = 2147483647;
700
701
  const REFUSAL_MESSAGE = {
@@ -814,7 +815,8 @@ function parsePlan(file, args, options, context) {
814
815
  stderr,
815
816
  interactive: raw.interactive === void 0 ? false : readBoolean(raw.interactive, "interactive"),
816
817
  display: raw.display === void 0 ? true : readBoolean(raw.display, "display"),
817
- redact
818
+ redact,
819
+ dryRun: raw.dryRun === void 0 ? false : readBoolean(raw.dryRun, "dryRun")
818
820
  };
819
821
  }
820
822
  function stripFinalNewline(text) {
@@ -882,6 +884,23 @@ function toResult(command, outcome, stdout, stderr) {
882
884
  function isSpawnErrno(error) {
883
885
  return error instanceof Error && "syscall" in error;
884
886
  }
887
+ function execEvent(plan, phase) {
888
+ const { file, args, cwd } = plan.reported;
889
+ return {
890
+ type: "exec",
891
+ phase,
892
+ command: cwd === void 0 ? {
893
+ file,
894
+ args
895
+ } : {
896
+ file,
897
+ args,
898
+ cwd
899
+ },
900
+ stdio: commandStdio(plan),
901
+ interactive: plan.interactive
902
+ };
903
+ }
885
904
  function commandStdio(plan) {
886
905
  return {
887
906
  stdin: plan.stdin === "inherit" ? "inherit" : plan.input === void 0 ? "ignore" : "input",
@@ -1020,29 +1039,20 @@ function blockedReason(plan, context, stdio) {
1020
1039
  async function execute(file, args, options, context) {
1021
1040
  const plan = parsePlan(file, args, options, context);
1022
1041
  if (plan.signal.aborted) return complete(plan, emptyFailure(plan, "aborted"));
1042
+ if (plan.dryRun) {
1043
+ if (plan.display) await context.print(execEvent(plan, "skip"));
1044
+ return {
1045
+ status: "skipped",
1046
+ command: plan.reported
1047
+ };
1048
+ }
1023
1049
  const stdio = commandStdio(plan);
1024
1050
  const blocked = blockedReason(plan, context, stdio);
1025
1051
  if (blocked) return complete(plan, emptyFailure(plan, blocked));
1026
1052
  const holdTerminal = usesTerminal(plan, stdio);
1027
1053
  if (holdTerminal && !context.terminal.acquire("exec")) return complete(plan, emptyFailure(plan, "overlapping"));
1028
1054
  try {
1029
- if (plan.display) {
1030
- const { file, args, cwd } = plan.reported;
1031
- await context.print({
1032
- type: "exec",
1033
- phase: "start",
1034
- command: cwd === void 0 ? {
1035
- file,
1036
- args
1037
- } : {
1038
- file,
1039
- args,
1040
- cwd
1041
- },
1042
- stdio,
1043
- interactive: plan.interactive
1044
- });
1045
- }
1055
+ if (plan.display) await context.print(execEvent(plan, "start"));
1046
1056
  return complete(plan, await runPlan(plan));
1047
1057
  } finally {
1048
1058
  if (holdTerminal) context.terminal.release();
@@ -1192,7 +1202,7 @@ function formatTextEvent(event) {
1192
1202
  case "error": return event.error.kind === "usage" || event.error.kind === "validation" ? event.error.message : `Error: ${event.error.message}`;
1193
1203
  case "log": return event.record.message;
1194
1204
  case "prompt": return event.prompt.message;
1195
- case "exec": return `$ ${formatExecCommand(event.command)}`;
1205
+ case "exec": return `${event.phase === "skip" ? "#" : "$"} ${formatExecCommand(event.command)}`;
1196
1206
  }
1197
1207
  }
1198
1208
  /** Undecorated console compatibility adapter; automatic output uses the selected format printer. */
@@ -1283,7 +1293,8 @@ const unicodeSymbols = {
1283
1293
  version: "●",
1284
1294
  errorEvent: "■",
1285
1295
  prompt: "?",
1286
- exec: "$"
1296
+ exec: "$",
1297
+ execSkip: "#"
1287
1298
  }
1288
1299
  };
1289
1300
  const asciiSymbols = {
@@ -1301,7 +1312,8 @@ const asciiSymbols = {
1301
1312
  version: "i",
1302
1313
  errorEvent: "x",
1303
1314
  prompt: "?",
1304
- exec: "$"
1315
+ exec: "$",
1316
+ execSkip: "#"
1305
1317
  }
1306
1318
  };
1307
1319
  const markStyles = {
@@ -1321,7 +1333,8 @@ const markStyles = {
1321
1333
  version: "blue",
1322
1334
  errorEvent: "red",
1323
1335
  prompt: "cyan",
1324
- exec: "gray"
1336
+ exec: "gray",
1337
+ execSkip: "gray"
1325
1338
  };
1326
1339
  function safelyInspect(value) {
1327
1340
  if (typeof value === "string") return value;
@@ -1368,7 +1381,7 @@ function eventMark(event) {
1368
1381
  if (event.type === "version") return "version";
1369
1382
  if (event.type === "error") return "errorEvent";
1370
1383
  if (event.type === "prompt") return event.prompt.status === "submitted" ? "success" : "prompt";
1371
- if (event.type === "exec") return "exec";
1384
+ if (event.type === "exec") return event.phase === "skip" ? "execSkip" : "exec";
1372
1385
  return event.record.kind === "message" ? event.record.level : event.record.kind;
1373
1386
  }
1374
1387
  function eventLines(event) {
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["#result","safeString","parseNodeArgs","#owner","details","#interactive","#inputValue","#printEvent","#bufferedKeys","#terminal","#signal","#print","#run"],"sources":["../src/options.ts","../src/schema.ts","../src/command.ts","../src/errors.ts","../src/environment.ts","../src/parser.ts","../src/terminal.ts","../src/exec.ts","../src/serialization.ts","../src/printer.ts","../src/pretty.ts","../src/prompts.ts","../src/logger.ts","../src/package-version.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 } from \"zod/v4/core\";\n\nexport type ArgsSchema = $ZodObject;\nexport type EmptyArgs = $ZodObject<{}>;\nexport type ShapeOf<S extends ArgsSchema> = S[\"_zod\"][\"def\"][\"shape\"];\nexport type ArgKey<S extends ArgsSchema> = Extract<keyof ShapeOf<S>, string>;\nexport type OptionKey<S extends ArgsSchema> = Exclude<ArgKey<S>, typeof POSITIONALS_KEY>;\n\nexport const POSITIONALS_KEY = \"_\";\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 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\n while (current) {\n const metadata = globalRegistry.get(current);\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 choices: enumChoices(base),\n };\n}\n\n/** Read the `_` 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 `_` 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 { Exec } from \"./exec.ts\";\nimport type { Logger } from \"./logger.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 type OptionKey,\n} from \"./schema.ts\";\n\nexport interface ArgOptions {\n alias?: string | readonly string[];\n valueName?: string;\n env?: string | false;\n}\n\nexport type ArgOptionsMap<S extends ArgsSchema> = Partial<Record<OptionKey<S>, ArgOptions>>;\n\nexport interface CommandContext<S extends ArgsSchema> {\n cmd: CommandDef<S>;\n args: output<S>;\n rawArgs: string[];\n passthrough: string[];\n extraArgs: string[];\n logger: Logger;\n exec: Exec;\n signal: AbortSignal;\n}\n\nexport interface CommandDef<S extends ArgsSchema = EmptyArgs> {\n name?: string;\n version?: string;\n description?: string;\n hidden?: boolean;\n /** Keep unknown options and excess positionals in extraArgs. Inherits from the parent; defaults to false. */\n allowUnknownArgs?: boolean;\n args?: S;\n argOptions?: ArgOptionsMap<S>;\n subCommands?: Record<string, CommandDef<ArgsSchema>>;\n run?(context: CommandContext<S>): unknown;\n}\n\nexport type AnyCommandDef = CommandDef<ArgsSchema>;\n\nexport function defineCommand<S extends ArgsSchema = EmptyArgs>(def: CommandDef<S>): CommandDef<S> {\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 (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 (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, options] of Object.entries(def.argOptions ?? {})) {\n if (key === POSITIONALS_KEY) {\n throw new TypeError(\"Positional arguments cannot have argument options\");\n }\n const schema = shape[key];\n if (!schema) throw new TypeError(`Unknown argument options key \\`${key}\\``);\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\") throw new TypeError(\"Option `help` conflicts with the builtin --help\");\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 { $ZodIssue } from \"zod/v4/core\";\nimport type { AnyCommandDef } from \"./command.ts\";\nimport type { ExecFailure } from \"./exec.ts\";\n\nexport interface HackshIssue {\n arg: string;\n message: string;\n issue?: $ZodIssue;\n}\n\nexport class HackshUsageError extends Error {\n readonly command: AnyCommandDef;\n\n constructor(message: string, command: AnyCommandDef, options?: ErrorOptions) {\n super(message, options);\n this.name = \"HackshUsageError\";\n this.command = command;\n }\n}\n\nexport class HackshValidationError extends HackshUsageError {\n readonly issues: ReadonlyArray<HackshIssue>;\n\n constructor(command: AnyCommandDef, issues: ReadonlyArray<HackshIssue>) {\n super(\n `Invalid arguments:\\n${issues.map(({ arg, message }) => ` ${arg}: ${message}`).join(\"\\n\")}`,\n command,\n );\n this.name = \"HackshValidationError\";\n this.issues = issues;\n }\n}\n\nexport type PromptKind = \"select\" | \"confirm\" | \"text\";\n\nexport type HackshPromptErrorReason =\n | \"non-interactive\"\n | \"cancelled\"\n | \"aborted\"\n | \"eof\"\n | \"overlapping\"\n | \"invalid-options\"\n | \"input-error\"\n | \"printer-error\";\n\nexport interface PromptErrorDetails {\n kind: PromptKind;\n message: string;\n choices?: readonly string[];\n}\n\n/** An input request that could not be completed safely. */\nexport class HackshPromptError extends Error {\n readonly reason: HackshPromptErrorReason;\n readonly prompt: PromptErrorDetails;\n\n constructor(\n reason: HackshPromptErrorReason,\n prompt: PromptErrorDetails,\n message: string,\n options?: ErrorOptions,\n ) {\n super(message, options);\n this.name = \"HackshPromptError\";\n this.reason = reason;\n this.prompt = prompt;\n }\n}\n\n/** An external command that did not succeed; `result` is not enumerable so error summaries omit child output. */\nexport class HackshExecError extends Error {\n readonly #result: ExecFailure;\n\n constructor(message: string, result: ExecFailure, options?: ErrorOptions) {\n super(message, options);\n this.name = \"HackshExecError\";\n this.#result = result;\n }\n\n get result(): ExecFailure {\n return this.#result;\n }\n}\n\n/** A requested process exit status; `runMain` exits with it and reports only a non-empty message. */\nexport class HackshExitError extends Error {\n readonly exitCode: number;\n\n constructor(exitCode: number, message?: string, options?: ErrorOptions) {\n if (!Number.isInteger(exitCode) || exitCode < 0 || exitCode > 255) {\n throw new TypeError(\"Exit code must be an integer from 0 to 255\");\n }\n super(message, options);\n this.name = \"HackshExitError\";\n this.exitCode = exitCode;\n }\n}\n\nexport type HackshErrorKind = \"error\" | \"prompt\" | \"usage\" | \"validation\" | \"thrown\";\n\nexport interface ValidationIssueSummary {\n arg: string;\n message: string;\n code?: string;\n path?: readonly PropertyKey[];\n details?: Readonly<Record<string, unknown>>;\n}\n\nexport interface HackshErrorSummary {\n kind: HackshErrorKind;\n name: string;\n message: string;\n stack?: string;\n cause?: unknown;\n issues?: readonly ValidationIssueSummary[];\n properties?: Readonly<Record<string, unknown>>;\n value?: unknown;\n}\n\nfunction safeString(value: unknown, fallback: string): string {\n try {\n return String(value);\n } catch {\n return fallback;\n }\n}\n\nfunction readProperty(value: object, key: PropertyKey): unknown {\n try {\n return Reflect.get(value, key);\n } catch {\n return \"[Unserializable]\";\n }\n}\n\nfunction enumerableKeys(value: object): string[] {\n try {\n return Object.keys(value);\n } catch {\n return [];\n }\n}\n\nfunction hasToJSON(value: object): boolean {\n try {\n return typeof Reflect.get(value, \"toJSON\") === \"function\";\n } catch {\n return false;\n }\n}\n\nfunction isPlainObject(value: object): boolean {\n try {\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n } catch {\n return false;\n }\n}\n\nfunction summarizeIssue(\n { arg, message, issue }: HackshIssue,\n seen: WeakMap<object, unknown>,\n): ValidationIssueSummary {\n if (!issue) return { arg, message };\n const details: Record<string, unknown> = {};\n for (const key of enumerableKeys(issue)) {\n if ([\"code\", \"path\", \"message\", \"inst\"].includes(key)) continue;\n details[key] = summarizeErrors(readProperty(issue, key), seen);\n }\n const code = readProperty(issue, \"code\");\n const path = readProperty(issue, \"path\");\n return {\n arg,\n message,\n ...(typeof code === \"string\" ? { code } : {}),\n ...(Array.isArray(path) ? { path } : {}),\n ...(Object.keys(details).length === 0 ? {} : { details }),\n };\n}\n\nfunction errorKind(error: Error): HackshErrorKind {\n if (error instanceof HackshPromptError) return \"prompt\";\n if (error instanceof HackshValidationError) return \"validation\";\n if (error instanceof HackshUsageError) return \"usage\";\n return \"error\";\n}\n\nfunction summarizeErrorWithSeen(error: Error, seen: WeakMap<object, unknown>): HackshErrorSummary {\n const summary: HackshErrorSummary = {\n kind: errorKind(error),\n name: safeString(readProperty(error, \"name\"), \"Error\"),\n message: safeString(readProperty(error, \"message\"), \"[Unserializable error message]\"),\n };\n seen.set(error, summary);\n\n const stack = readProperty(error, \"stack\");\n const cause = readProperty(error, \"cause\");\n if (typeof stack === \"string\") summary.stack = stack;\n if (cause !== undefined) summary.cause = summarizeErrors(cause, seen);\n if (error instanceof HackshValidationError) {\n summary.issues = error.issues.map((issue) => summarizeIssue(issue, seen));\n }\n\n const reserved = new Set([\"name\", \"message\", \"stack\", \"cause\", \"command\", \"issues\"]);\n const properties: Record<string, unknown> = {};\n for (const key of enumerableKeys(error)) {\n if (reserved.has(key)) continue;\n properties[key] = summarizeErrors(readProperty(error, key), seen);\n }\n if (Object.keys(properties).length > 0) summary.properties = properties;\n return summary;\n}\n\n/** Recursively replace Error values with command- and schema-free summaries. */\nexport function summarizeErrors(\n value: unknown,\n seen: WeakMap<object, unknown> = new WeakMap(),\n): unknown {\n if (typeof value !== \"object\" || value === null) return value;\n const existing = seen.get(value);\n if (existing !== undefined) return existing;\n if (value instanceof Error) return summarizeErrorWithSeen(value, seen);\n\n if (Array.isArray(value)) {\n const result: unknown[] = [];\n seen.set(value, result);\n let changed = false;\n for (const item of value) {\n const summarized = summarizeErrors(item, seen);\n result.push(summarized);\n changed ||= summarized !== item;\n }\n if (changed) return result;\n seen.set(value, value);\n return value;\n }\n if (value instanceof Map) {\n const result = new Map<unknown, unknown>();\n seen.set(value, result);\n let changed = false;\n for (const [key, item] of value) {\n const summarizedKey = summarizeErrors(key, seen);\n const summarizedItem = summarizeErrors(item, seen);\n result.set(summarizedKey, summarizedItem);\n changed ||= summarizedKey !== key || summarizedItem !== item;\n }\n if (changed) return result;\n seen.set(value, value);\n return value;\n }\n if (value instanceof Set) {\n const result = new Set<unknown>();\n seen.set(value, result);\n let changed = false;\n for (const item of value) {\n const summarized = summarizeErrors(item, seen);\n result.add(summarized);\n changed ||= summarized !== item;\n }\n if (changed) return result;\n seen.set(value, value);\n return value;\n }\n if (ArrayBuffer.isView(value) || hasToJSON(value) || !isPlainObject(value)) return value;\n\n const result: Record<string, unknown> = {};\n seen.set(value, result);\n let changed = false;\n for (const key of enumerableKeys(value)) {\n const original = readProperty(value, key);\n const summarized = summarizeErrors(original, seen);\n result[key] = summarized;\n changed ||= summarized !== original;\n }\n if (changed) return result;\n seen.set(value, value);\n return value;\n}\n\n/** Convert any thrown value into a canonical error description. */\nexport function summarizeError(error: unknown): HackshErrorSummary {\n if (error instanceof Error) return summarizeErrorWithSeen(error, new WeakMap());\n return {\n kind: \"thrown\",\n name: \"NonErrorThrown\",\n message: safeString(error, \"[Unserializable thrown value]\"),\n value: summarizeErrors(error),\n };\n}\n","import type { AnyCommandDef } from \"./command.ts\";\nimport { kebabCase } from \"./options.ts\";\nimport { isArrayInput, isObjectInput, POSITIONALS_KEY, schemaShape } 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 = command.argOptions?.[key]?.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 alias = command.argOptions?.[key]?.alias;\n const aliases = alias ? aliasList(alias) : [];\n const definition: OptionDefinition = {\n key,\n kebabName: kebabCase(key),\n takesValue: readArgInfo(schema).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","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 { spawn, type ChildProcess } from \"node:child_process\";\nimport type { Readable } from \"node:stream\";\nimport { HackshExecError } from \"./errors.ts\";\nimport type { ExecPrintEvent, OutputFormat } from \"./printer.ts\";\nimport { TerminalLock } from \"./terminal.ts\";\n\ntype Environment = Readonly<Record<string, string | undefined>>;\n\nexport interface ExecOptions {\n cwd?: string;\n env?: Environment;\n input?: string;\n reject?: boolean;\n timeout?: number;\n signal?: AbortSignal;\n maxBuffer?: number;\n forceKillAfterDelay?: number;\n stdin?: \"pipe\" | \"inherit\";\n stdout?: \"pipe\" | \"inherit\";\n stderr?: \"pipe\" | \"inherit\";\n interactive?: boolean;\n display?: boolean;\n redact?: readonly string[];\n}\n\nexport interface ExecCommand {\n file: string;\n args: readonly string[];\n cwd: string | undefined;\n}\n\nexport interface ExecSuccess {\n status: \"succeeded\";\n command: ExecCommand;\n stdout: string;\n stderr: string;\n exitCode: 0;\n}\n\nexport type ExecFailure = {\n status: \"failed\";\n command: ExecCommand;\n stdout: string;\n stderr: string;\n} & (\n | { reason: \"exit-code\"; exitCode: number }\n | { reason: \"signal\"; signal: string }\n | { reason: \"spawn\"; error: Error }\n | { reason: \"timeout\" | \"aborted\" | \"output-limit\" }\n | { reason: \"json-output\" | \"non-interactive\" | \"overlapping\" }\n);\n\nexport type ExecFailureReason = ExecFailure[\"reason\"];\n\nexport type ExecResult = ExecSuccess | ExecFailure;\n\nexport type ExecReturn<O extends ExecOptions> = \"reject\" extends keyof O\n ? false extends O[\"reject\"]\n ? ExecResult\n : ExecSuccess\n : ExecSuccess;\n\ntype RejectInheritedInput<O> = O extends { input: string; stdin: \"inherit\" } ? never : unknown;\n\nexport type Exec = <const O extends ExecOptions = {}>(\n file: string,\n args?: readonly string[],\n options?: O & { [K in Exclude<keyof O, keyof ExecOptions>]: never } & RejectInheritedInput<O>,\n) => Promise<ExecReturn<O>>;\n\nexport interface ExecContext {\n env: Environment | undefined;\n mode: { format: OutputFormat; interactive: boolean };\n print(event: ExecPrintEvent): void | Promise<void>;\n terminal: TerminalLock;\n signal: AbortSignal;\n}\n\nconst OPTION_KEYS: ReadonlySet<string> = new Set([\n \"cwd\",\n \"env\",\n \"input\",\n \"reject\",\n \"timeout\",\n \"signal\",\n \"maxBuffer\",\n \"forceKillAfterDelay\",\n \"stdin\",\n \"stdout\",\n \"stderr\",\n \"interactive\",\n \"display\",\n \"redact\",\n] satisfies (keyof ExecOptions)[]);\n\ntype TerminationCause = \"timeout\" | \"aborted\" | \"output-limit\";\ntype StreamMode = \"pipe\" | \"inherit\";\ntype ExecStdio = ExecPrintEvent[\"stdio\"];\ntype RefusalReason = \"aborted\" | \"json-output\" | \"non-interactive\" | \"overlapping\";\n\ninterface SpawnError extends NodeJS.ErrnoException {\n spawnargs?: readonly string[];\n}\n\ninterface ExecPlan {\n command: ExecCommand;\n reported: ExecCommand;\n env: NodeJS.ProcessEnv | undefined;\n input: string | undefined;\n reject: boolean;\n timeout: number | undefined;\n signal: AbortSignal;\n maxBuffer: number;\n forceKillAfterDelay: number;\n stdin: StreamMode;\n stdout: StreamMode;\n stderr: StreamMode;\n interactive: boolean;\n display: boolean;\n redact: readonly string[];\n}\n\ninterface Outcome {\n cause: TerminationCause | undefined;\n spawnError: Error | undefined;\n exit: { code: number | null; signal: string | null } | undefined;\n}\n\nconst MAX_DELAY = 2_147_483_647;\nconst REFUSAL_MESSAGE = {\n \"json-output\": \"Command cannot use the terminal in JSON output mode\",\n \"non-interactive\": \"Command requires an interactive terminal\",\n overlapping: \"Command cannot use the terminal while it is in use\",\n} as const;\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction assertNoNul(value: string, label: string): void {\n if (value.includes(\"\\0\")) throw new TypeError(`${label} must not contain NUL characters`);\n}\n\nfunction readInteger(value: unknown, label: string, minimum: number, maximum: number): number {\n if (typeof value !== \"number\" || !Number.isInteger(value) || value < minimum || value > maximum) {\n throw new TypeError(`${label} must be an integer from ${minimum} to ${maximum}`);\n }\n return value;\n}\n\nfunction readEnum<const T extends string>(value: unknown, label: string, allowed: readonly T[]): T {\n if (typeof value === \"string\" && (allowed as readonly string[]).includes(value))\n return value as T;\n throw new TypeError(\n `Exec option \\`${label}\\` must be ${allowed.map((item) => JSON.stringify(item)).join(\" or \")}`,\n );\n}\n\nfunction readBoolean(value: unknown, label: string): boolean {\n if (typeof value !== \"boolean\") throw new TypeError(`Exec option \\`${label}\\` must be a boolean`);\n return value;\n}\n\nfunction readRedact(value: unknown): readonly string[] {\n if (!Array.isArray(value)) throw new TypeError(\"Exec option `redact` must be an array\");\n for (const item of value) {\n if (typeof item !== \"string\" || item === \"\") {\n throw new TypeError(\"Exec option `redact` must contain only non-empty strings\");\n }\n assertNoNul(item, \"Exec option `redact`\");\n }\n return value as readonly string[];\n}\n\nfunction mergeEnvironment(\n base: Environment | undefined,\n overrides: unknown,\n): NodeJS.ProcessEnv | undefined {\n if (overrides === undefined && base === undefined) return undefined;\n if (overrides !== undefined && !isRecord(overrides)) {\n throw new TypeError(\"Exec option `env` must be an object\");\n }\n const merged: NodeJS.ProcessEnv = {};\n for (const [key, value] of Object.entries(base ?? process.env)) {\n if (value !== undefined) merged[key] = value;\n }\n for (const [key, value] of Object.entries(overrides ?? {})) {\n if (key === \"\" || key.includes(\"=\") || key.includes(\"\\0\")) {\n throw new TypeError(`Invalid environment variable name ${JSON.stringify(key)}`);\n }\n if (value === undefined) {\n delete merged[key];\n continue;\n }\n if (typeof value !== \"string\") {\n throw new TypeError(`Environment variable ${key} must be a string or undefined`);\n }\n assertNoNul(value, `Environment variable ${key}`);\n merged[key] = value;\n }\n return merged;\n}\n\nfunction redactValue(value: string, secrets: readonly string[]): string {\n let redacted = value;\n for (const secret of [...secrets].sort((left, right) => right.length - left.length)) {\n redacted = redacted.split(secret).join(\"***\");\n }\n return redacted;\n}\n\nfunction redactCommand(command: ExecCommand, secrets: readonly string[]): ExecCommand {\n if (secrets.length === 0) return command;\n return {\n file: redactValue(command.file, secrets),\n args: command.args.map((arg) => redactValue(arg, secrets)),\n cwd: command.cwd === undefined ? undefined : redactValue(command.cwd, secrets),\n };\n}\n\nfunction redactError(error: Error, secrets: readonly string[]): Error {\n const source = error as SpawnError;\n const redacted = new Error(redactValue(error.message, secrets)) as SpawnError;\n if (typeof error.stack === \"string\") redacted.stack = redactValue(error.stack, secrets);\n if (source.code !== undefined) redacted.code = source.code;\n if (source.errno !== undefined) redacted.errno = source.errno;\n if (typeof source.syscall === \"string\") redacted.syscall = redactValue(source.syscall, secrets);\n if (typeof source.path === \"string\") redacted.path = redactValue(source.path, secrets);\n if (Array.isArray(source.spawnargs)) {\n redacted.spawnargs = source.spawnargs.map((arg) =>\n typeof arg === \"string\" ? redactValue(arg, secrets) : arg,\n );\n }\n return redacted;\n}\n\nfunction observedError(plan: ExecPlan, error: Error): Error {\n return plan.redact.length === 0 ? error : redactError(error, plan.redact);\n}\n\nfunction parsePlan(file: unknown, args: unknown, options: unknown, context: ExecContext): ExecPlan {\n if (typeof file !== \"string\" || file === \"\") {\n throw new TypeError(\"Exec file must be a non-empty string\");\n }\n assertNoNul(file, \"Exec file\");\n const argv = args === undefined ? [] : args;\n if (!Array.isArray(argv) || !argv.every((arg) => typeof arg === \"string\")) {\n throw new TypeError(\"Exec args must be an array of strings\");\n }\n for (const arg of argv) assertNoNul(arg, \"Exec args\");\n const raw = options === undefined ? {} : options;\n if (!isRecord(raw)) throw new TypeError(\"Exec options must be an object\");\n for (const key of Object.keys(raw)) {\n if (!OPTION_KEYS.has(key)) throw new TypeError(`Unknown exec option \\`${key}\\``);\n }\n\n const { cwd, input, reject, timeout, signal, maxBuffer, forceKillAfterDelay } = raw;\n if (cwd !== undefined) {\n if (typeof cwd !== \"string\" || cwd === \"\") {\n throw new TypeError(\"Exec option `cwd` must be a non-empty string\");\n }\n assertNoNul(cwd, \"Exec option `cwd`\");\n }\n if (input !== undefined && typeof input !== \"string\") {\n throw new TypeError(\"Exec option `input` must be a string\");\n }\n if (reject !== undefined && typeof reject !== \"boolean\") {\n throw new TypeError(\"Exec option `reject` must be a boolean\");\n }\n if (signal !== undefined && !(signal instanceof AbortSignal)) {\n throw new TypeError(\"Exec option `signal` must be an AbortSignal\");\n }\n const stdin =\n raw.stdin === undefined ? \"pipe\" : readEnum(raw.stdin, \"stdin\", [\"pipe\", \"inherit\"]);\n const stdout =\n raw.stdout === undefined ? \"pipe\" : readEnum(raw.stdout, \"stdout\", [\"pipe\", \"inherit\"]);\n const stderr =\n raw.stderr === undefined ? \"pipe\" : readEnum(raw.stderr, \"stderr\", [\"pipe\", \"inherit\"]);\n if (input !== undefined && stdin === \"inherit\") {\n throw new TypeError(\"Exec option `input` cannot be combined with stdin inherit\");\n }\n const command = { file, args: [...argv], cwd };\n const redact = raw.redact === undefined ? [] : readRedact(raw.redact);\n return {\n command,\n reported: redactCommand(command, redact),\n env: mergeEnvironment(context.env, raw.env),\n input,\n reject: reject ?? true,\n timeout:\n timeout === undefined\n ? undefined\n : readInteger(timeout, \"Exec option `timeout`\", 1, MAX_DELAY),\n signal: signal === undefined ? context.signal : AbortSignal.any([context.signal, signal]),\n maxBuffer:\n maxBuffer === undefined\n ? 100_000_000\n : readInteger(maxBuffer, \"Exec option `maxBuffer`\", 1, Number.MAX_SAFE_INTEGER),\n forceKillAfterDelay:\n forceKillAfterDelay === undefined\n ? 5_000\n : readInteger(forceKillAfterDelay, \"Exec option `forceKillAfterDelay`\", 0, MAX_DELAY),\n stdin,\n stdout,\n stderr,\n interactive:\n raw.interactive === undefined ? false : readBoolean(raw.interactive, \"interactive\"),\n display: raw.display === undefined ? true : readBoolean(raw.display, \"display\"),\n redact,\n };\n}\n\nfunction stripFinalNewline(text: string): string {\n if (text.endsWith(\"\\r\\n\")) return text.slice(0, -2);\n if (text.endsWith(\"\\n\")) return text.slice(0, -1);\n return text;\n}\n\nfunction collect(stream: Readable, limit: number, onLimit: () => void): () => string {\n const chunks: Buffer[] = [];\n let length = 0;\n let exceeded = false;\n stream.on(\"data\", (chunk: Buffer) => {\n if (exceeded) return;\n const remaining = limit - length;\n if (chunk.length <= remaining) {\n chunks.push(chunk);\n length += chunk.length;\n return;\n }\n chunks.push(chunk.subarray(0, remaining));\n length = limit;\n exceeded = true;\n onLimit();\n });\n return () => stripFinalNewline(Buffer.concat(chunks).toString(\"utf8\"));\n}\n\nfunction toResult(\n command: ExecCommand,\n outcome: Outcome,\n stdout: string,\n stderr: string,\n): ExecResult {\n const failed = { status: \"failed\", command, stdout, stderr } as const;\n if (outcome.cause) return { ...failed, reason: outcome.cause };\n if (outcome.spawnError) return { ...failed, reason: \"spawn\", error: outcome.spawnError };\n const { code, signal } = outcome.exit ?? { code: null, signal: null };\n if (signal !== null) return { ...failed, reason: \"signal\", signal };\n if (code !== 0) return { ...failed, reason: \"exit-code\", exitCode: code ?? 1 };\n return { status: \"succeeded\", command, stdout, stderr, exitCode: 0 };\n}\n\nfunction isSpawnErrno(error: unknown): error is NodeJS.ErrnoException {\n return error instanceof Error && \"syscall\" in error;\n}\n\nfunction commandStdio(plan: ExecPlan): ExecStdio {\n return {\n stdin: plan.stdin === \"inherit\" ? \"inherit\" : plan.input === undefined ? \"ignore\" : \"input\",\n stdout: plan.stdout,\n stderr: plan.stderr,\n };\n}\n\nfunction usesTerminal(plan: ExecPlan, stdio: ExecStdio): boolean {\n return (\n plan.interactive ||\n stdio.stdin === \"inherit\" ||\n stdio.stdout === \"inherit\" ||\n stdio.stderr === \"inherit\"\n );\n}\n\nfunction startChild(plan: ExecPlan): ChildProcess | Error {\n const stdio = commandStdio(plan);\n try {\n return spawn(plan.command.file, plan.command.args, {\n cwd: plan.command.cwd,\n env: plan.env,\n shell: false,\n windowsHide: true,\n stdio: [\n stdio.stdin === \"inherit\" ? \"inherit\" : stdio.stdin === \"input\" ? \"pipe\" : \"ignore\",\n stdio.stdout,\n stdio.stderr,\n ],\n });\n } catch (error) {\n if (isSpawnErrno(error)) return error;\n throw error;\n }\n}\n\nfunction runPlan(plan: ExecPlan): Promise<ExecResult> {\n const outcome: Outcome = { cause: undefined, spawnError: undefined, exit: undefined };\n if (plan.signal.aborted) {\n outcome.cause = \"aborted\";\n return Promise.resolve(toResult(plan.reported, outcome, \"\", \"\"));\n }\n const child = startChild(plan);\n if (child instanceof Error) {\n outcome.spawnError = observedError(plan, child);\n return Promise.resolve(toResult(plan.reported, outcome, \"\", \"\"));\n }\n\n return new Promise((resolve) => {\n const stdout = child.stdout;\n const stderr = child.stderr;\n let settled = false;\n let killTimer: NodeJS.Timeout | undefined;\n\n const settle = () => {\n if (settled) return;\n settled = true;\n clearTimeout(timeoutTimer);\n clearTimeout(killTimer);\n plan.signal.removeEventListener(\"abort\", onAbort);\n resolve(toResult(plan.reported, outcome, readStdout(), readStderr()));\n };\n const release = () => {\n stdout?.destroy();\n stderr?.destroy();\n settle();\n };\n const terminate = (cause: TerminationCause) => {\n if (settled || outcome.cause) return;\n outcome.cause = cause;\n if (outcome.exit) {\n release();\n return;\n }\n child.kill(\"SIGTERM\");\n killTimer = setTimeout(() => child.kill(\"SIGKILL\"), plan.forceKillAfterDelay);\n };\n const onAbort = () => terminate(\"aborted\");\n\n const readStdout = stdout\n ? collect(stdout, plan.maxBuffer, () => terminate(\"output-limit\"))\n : () => \"\";\n const readStderr = stderr\n ? collect(stderr, plan.maxBuffer, () => terminate(\"output-limit\"))\n : () => \"\";\n const timeoutTimer =\n plan.timeout === undefined ? undefined : setTimeout(() => terminate(\"timeout\"), plan.timeout);\n plan.signal.addEventListener(\"abort\", onAbort, { once: true });\n\n child.on(\"error\", (error) => {\n if (child.pid !== undefined) return;\n outcome.spawnError = observedError(plan, error);\n release();\n });\n child.on(\"exit\", (code, signal) => {\n outcome.exit = { code, signal };\n clearTimeout(killTimer);\n // A grandchild may keep the pipes open after hacksh terminates the direct child.\n if (outcome.cause) release();\n });\n child.on(\"close\", settle);\n\n if (child.stdin) {\n child.stdin.on(\"error\", () => undefined);\n child.stdin.end(plan.input);\n }\n });\n}\n\nfunction formatArgument(value: string): string {\n return value === \"\" || /[\\s\"'\\\\$`;|&<>*?()[\\]{}~#!]/.test(value) ? JSON.stringify(value) : value;\n}\n\nexport function formatExecCommand(command: Pick<ExecCommand, \"file\" | \"args\">): string {\n return [command.file, ...command.args].map(formatArgument).join(\" \");\n}\n\nfunction failureMessage(plan: ExecPlan, result: ExecFailure): string {\n const display = formatExecCommand(plan.reported);\n switch (result.reason) {\n case \"exit-code\":\n return `Command failed with exit code ${result.exitCode}: ${display}`;\n case \"signal\":\n return `Command was terminated by ${result.signal}: ${display}`;\n case \"spawn\": {\n const code = (result.error as NodeJS.ErrnoException).code;\n return `Command could not be started (${code ?? result.error.message}): ${display}`;\n }\n case \"timeout\":\n return `Command timed out after ${plan.timeout} ms: ${display}`;\n case \"aborted\":\n return `Command was aborted: ${display}`;\n case \"output-limit\":\n return `Command output exceeded ${plan.maxBuffer} bytes: ${display}`;\n case \"json-output\":\n case \"non-interactive\":\n case \"overlapping\":\n return `${REFUSAL_MESSAGE[result.reason]}: ${display}`;\n }\n}\n\nfunction emptyFailure(plan: ExecPlan, reason: RefusalReason): ExecFailure {\n return { status: \"failed\", command: plan.reported, stdout: \"\", stderr: \"\", reason };\n}\n\nfunction complete(plan: ExecPlan, result: ExecResult): ExecResult {\n if (result.status === \"failed\" && plan.reject) {\n throw new HackshExecError(\n failureMessage(plan, result),\n result,\n result.reason === \"spawn\" ? { cause: result.error } : undefined,\n );\n }\n return result;\n}\n\nfunction blockedReason(\n plan: ExecPlan,\n context: ExecContext,\n stdio: ExecStdio,\n): \"json-output\" | \"non-interactive\" | undefined {\n const inherited =\n stdio.stdin === \"inherit\" || stdio.stdout === \"inherit\" || stdio.stderr === \"inherit\";\n if (context.mode.format === \"json\" && inherited) return \"json-output\";\n if (plan.interactive && !context.mode.interactive) return \"non-interactive\";\n return undefined;\n}\n\nasync function execute(\n file: unknown,\n args: unknown,\n options: unknown,\n context: ExecContext,\n): Promise<ExecResult> {\n const plan = parsePlan(file, args, options, context);\n if (plan.signal.aborted) return complete(plan, emptyFailure(plan, \"aborted\"));\n\n const stdio = commandStdio(plan);\n const blocked = blockedReason(plan, context, stdio);\n if (blocked) return complete(plan, emptyFailure(plan, blocked));\n\n const holdTerminal = usesTerminal(plan, stdio);\n if (holdTerminal && !context.terminal.acquire(\"exec\")) {\n return complete(plan, emptyFailure(plan, \"overlapping\"));\n }\n try {\n if (plan.display) {\n const { file, args, cwd } = plan.reported;\n await context.print({\n type: \"exec\",\n phase: \"start\",\n command: cwd === undefined ? { file, args } : { file, args, cwd },\n stdio,\n interactive: plan.interactive,\n });\n }\n return complete(plan, await runPlan(plan));\n } finally {\n if (holdTerminal) context.terminal.release();\n }\n}\n\nexport function createExec(context: ExecContext): Exec {\n return ((file, args, options) => execute(file, args, options, context)) as Exec;\n}\n","import { stripVTControlCharacters } from \"node:util\";\nimport { summarizeError } from \"./errors.ts\";\n\nfunction safeString(value: unknown): string {\n try {\n return String(value);\n } catch {\n return \"[Unserializable]\";\n }\n}\n\nfunction normalizeProperty(value: object, key: PropertyKey, ancestors: Set<object>): unknown {\n try {\n return normalizeJson(Reflect.get(value, key), ancestors);\n } catch {\n return \"[Unserializable]\";\n }\n}\n\nfunction normalizedKeys(value: object): string[] | undefined {\n try {\n return Object.keys(value);\n } catch {\n return undefined;\n }\n}\n\nconst noToJson = Symbol(\"noToJson\");\n\nfunction normalizedToJson(value: object, ancestors: Set<object>): unknown {\n let toJSON: unknown;\n try {\n toJSON = Reflect.get(value, \"toJSON\");\n } catch {\n return noToJson;\n }\n if (typeof toJSON !== \"function\") return noToJson;\n try {\n const result = Reflect.apply(toJSON, value, []);\n return result === value ? noToJson : normalizeJson(result, ancestors);\n } catch {\n return noToJson;\n }\n}\n\nfunction isArrayBufferView(value: object): value is ArrayBufferView {\n try {\n return ArrayBuffer.isView(value);\n } catch {\n return false;\n }\n}\n\n/** Normalize arbitrary event data into values accepted by JSON.stringify. */\nexport function normalizeJson(value: unknown, ancestors = new Set<object>()): unknown {\n switch (typeof value) {\n case \"string\":\n return stripVTControlCharacters(value);\n case \"boolean\":\n return value;\n case \"number\":\n return Number.isFinite(value) ? value : null;\n case \"bigint\":\n return value.toString();\n case \"undefined\":\n return \"[undefined]\";\n case \"symbol\":\n return `[symbol:${stripVTControlCharacters(value.description ?? \"\")}]`;\n case \"function\":\n return `[function:${stripVTControlCharacters(value.name || \"anonymous\")}]`;\n case \"object\":\n break;\n }\n if (value === null) return null;\n if (ancestors.has(value)) return \"[Circular]\";\n\n const nextAncestors = new Set(ancestors).add(value);\n if (value instanceof Error) return normalizeJson(summarizeError(value), nextAncestors);\n\n const jsonValue = normalizedToJson(value, nextAncestors);\n if (jsonValue !== noToJson) return jsonValue;\n\n if (isArrayBufferView(value)) {\n if (value instanceof DataView) {\n return Array.from(new Uint8Array(value.buffer, value.byteOffset, value.byteLength));\n }\n try {\n return Array.from(value as unknown as Iterable<unknown>, (item) =>\n normalizeJson(item, nextAncestors),\n );\n } catch {\n return \"[Unserializable]\";\n }\n }\n if (value instanceof ArrayBuffer) return Array.from(new Uint8Array(value));\n if (Array.isArray(value)) {\n return Array.from({ length: value.length }, (_, index) =>\n normalizeProperty(value, index, nextAncestors),\n );\n }\n if (value instanceof Map) {\n try {\n return [...value].map(([key, item]) => [\n normalizeJson(key, nextAncestors),\n normalizeJson(item, nextAncestors),\n ]);\n } catch {\n return \"[Unserializable]\";\n }\n }\n if (value instanceof Set) {\n try {\n return [...value].map((item) => normalizeJson(item, nextAncestors));\n } catch {\n return \"[Unserializable]\";\n }\n }\n\n const keys = normalizedKeys(value);\n if (!keys) return safeString(value);\n const result: Record<string, unknown> = {};\n for (const key of keys) {\n result[stripVTControlCharacters(key)] = normalizeProperty(value, key, nextAncestors);\n }\n return result;\n}\n","import type { HackshErrorSummary } from \"./errors.ts\";\nimport { formatExecCommand, type ExecCommand } from \"./exec.ts\";\nimport type { LogRecord } from \"./logger.ts\";\nimport { normalizeJson } from \"./serialization.ts\";\nimport type { UsageSummary } from \"./usage.ts\";\n\nexport type PrintStream = \"stdout\" | \"stderr\";\nexport type OutputPreference = \"auto\" | \"pretty\" | \"json\";\nexport type OutputFormat = Exclude<OutputPreference, \"auto\">;\n\nexport interface OutputMode {\n format: OutputFormat;\n interactive: boolean;\n color: boolean;\n}\n\nexport interface ResolveOutputModeOptions {\n output?: OutputPreference;\n env?: Readonly<Record<string, string | undefined>>;\n inputIsTTY?: boolean;\n outputIsTTY?: boolean;\n}\n\nfunction fallbackValue(value: unknown): string {\n try {\n return String(value);\n } catch {\n return \"[Unserializable]\";\n }\n}\n\nfunction validatePreference(value: unknown, source: string): OutputPreference | undefined {\n if (value === undefined) return undefined;\n if (value === \"auto\" || value === \"pretty\" || value === \"json\") return value;\n throw new TypeError(\n `Invalid ${source} value ${fallbackValue(value)}; expected auto, pretty, or json`,\n );\n}\n\nfunction readEnvironment(\n env: Readonly<Record<string, string | undefined>>,\n key: string,\n): string | undefined {\n try {\n return env[key];\n } catch {\n return undefined;\n }\n}\n\n/** Resolve output behavior once, before command routing or argument parsing. */\nexport function resolveOutputMode(options: ResolveOutputModeOptions = {}): OutputMode {\n const env = options.env ?? process.env;\n const configured = validatePreference(options.output, \"output\");\n const overridden = validatePreference(readEnvironment(env, \"HACKSH_OUTPUT\"), \"HACKSH_OUTPUT\");\n const requested = overridden ?? configured ?? \"auto\";\n const ci = Boolean(readEnvironment(env, \"CI\"));\n const format = requested === \"auto\" ? (ci ? \"json\" : \"pretty\") : requested;\n const inputIsTTY = options.inputIsTTY ?? process.stdin.isTTY === true;\n const outputIsTTY = options.outputIsTTY ?? process.stdout.isTTY === true;\n return {\n format,\n interactive: format === \"pretty\" && !ci && inputIsTTY && outputIsTTY,\n color: format === \"pretty\" && outputIsTTY && !readEnvironment(env, \"NO_COLOR\"),\n };\n}\n\nexport interface UsagePrintEvent {\n type: \"usage\";\n usage: UsageSummary;\n text: string;\n stream: PrintStream;\n}\n\nexport interface VersionPrintEvent {\n type: \"version\";\n version: string;\n}\n\nexport interface ErrorPrintEvent {\n type: \"error\";\n error: HackshErrorSummary;\n}\n\nexport interface LogPrintEvent {\n type: \"log\";\n record: LogRecord;\n}\n\nexport interface PromptChoiceState {\n value: string;\n label: string;\n hint?: string;\n selected: boolean;\n}\n\nexport type PromptStatus = \"active\" | \"error\" | \"submitted\" | \"closed\";\n\ninterface PromptStateBase {\n message: string;\n status: PromptStatus;\n error?: string;\n}\n\nexport interface SelectPromptState extends PromptStateBase {\n kind: \"select\";\n choices: readonly PromptChoiceState[];\n value: string;\n}\n\nexport interface ConfirmPromptState extends PromptStateBase {\n kind: \"confirm\";\n value: boolean;\n defaultValue?: boolean;\n}\n\nexport interface TextPromptState extends PromptStateBase {\n kind: \"text\";\n value: string;\n placeholder?: string;\n}\n\nexport type PromptState = SelectPromptState | ConfirmPromptState | TextPromptState;\n\nexport interface PromptPrintEvent {\n type: \"prompt\";\n prompt: PromptState;\n}\n\nexport interface ExecPrintEvent {\n type: \"exec\";\n phase: \"start\";\n command: Omit<ExecCommand, \"cwd\"> & { cwd?: string };\n stdio: {\n stdin: \"ignore\" | \"input\" | \"inherit\";\n stdout: \"pipe\" | \"inherit\";\n stderr: \"pipe\" | \"inherit\";\n };\n interactive: boolean;\n}\n\n/** A semantic, command- and schema-free output value emitted by hacksh. */\nexport type PrintEvent =\n | UsagePrintEvent\n | VersionPrintEvent\n | ErrorPrintEvent\n | LogPrintEvent\n | PromptPrintEvent\n | ExecPrintEvent;\n\n/** Receives every output event produced by one command invocation. */\nexport interface Printer {\n print(event: PrintEvent): void | Promise<void>;\n}\n\nfunction isErrorLevel(level: LogRecord[\"level\"]): boolean {\n return level === \"warning\" || level === \"error\" || level === \"fatal\";\n}\n\nexport function eventStream(event: PrintEvent): PrintStream {\n if (event.type === \"error\" || event.type === \"exec\") return \"stderr\";\n if (event.type === \"usage\") return event.stream;\n if (event.type === \"log\" && isErrorLevel(event.record.level)) return \"stderr\";\n return \"stdout\";\n}\n\nfunction formatTextEvent(event: PrintEvent): string {\n switch (event.type) {\n case \"usage\":\n return event.text;\n case \"version\":\n return event.version;\n case \"error\":\n return event.error.kind === \"usage\" || event.error.kind === \"validation\"\n ? event.error.message\n : `Error: ${event.error.message}`;\n case \"log\":\n return event.record.message;\n case \"prompt\":\n return event.prompt.message;\n case \"exec\":\n return `$ ${formatExecCommand(event.command)}`;\n }\n}\n\n/** Undecorated console compatibility adapter; automatic output uses the selected format printer. */\nexport const consolePrinter: Printer = {\n print(event) {\n const text = formatTextEvent(event);\n return eventStream(event) === \"stdout\" ? console.log(text) : console.error(text);\n },\n};\n\nexport interface OutputWriter {\n write(text: string): unknown;\n}\n\nexport interface TerminalInput {\n readonly isTTY?: boolean;\n readonly isRaw?: boolean;\n readonly readableFlowing?: boolean | null;\n setRawMode?(mode: boolean): unknown;\n resume(): unknown;\n pause(): unknown;\n on(event: string, listener: (...args: never[]) => void): unknown;\n removeListener(event: string, listener: (...args: never[]) => void): unknown;\n}\n\nexport interface TerminalOutput extends OutputWriter {\n readonly isTTY?: boolean;\n readonly columns?: number;\n}\n\nexport interface JsonPrinterOptions {\n stdout?: OutputWriter;\n stderr?: OutputWriter;\n}\n\nexport interface StreamPrinterOptions {\n stdout: OutputWriter;\n stderr: OutputWriter;\n}\n\n/** Create an undecorated stream-backed compatibility adapter. */\nexport function createStreamPrinter(options: StreamPrinterOptions): Printer {\n return {\n print(event) {\n const writer = eventStream(event) === \"stdout\" ? options.stdout : options.stderr;\n writer.write(`${formatTextEvent(event)}\\n`);\n },\n };\n}\n\n/** Create a one-semantic-event-per-line JSON printer. */\nexport function createJsonPrinter(options: JsonPrinterOptions = {}): Printer {\n const stdout = options.stdout ?? process.stdout;\n const stderr = options.stderr ?? process.stderr;\n return {\n print(event) {\n let serialized: string;\n try {\n serialized = JSON.stringify(normalizeJson(event));\n } catch {\n serialized = JSON.stringify({\n type: event.type,\n serializationError: \"Event data could not be serialized\",\n });\n }\n const line = `${serialized}\\n`;\n (eventStream(event) === \"stdout\" ? stdout : stderr).write(line);\n },\n };\n}\n\nexport interface PrintQueue {\n printer: Printer;\n printChecked(event: PrintEvent): Promise<void>;\n drain(): Promise<void>;\n}\n\n/** Serialize printer calls and retain failures until the invocation drains its output. */\nexport function createPrintQueue(target: Printer): PrintQueue {\n let pending: Promise<void> | undefined;\n let failure: unknown;\n let failed = false;\n\n function recordFailure(error: unknown): void {\n if (!failed) failure = error;\n failed = true;\n }\n\n function track(execution: Promise<void>, retainFailure: boolean): Promise<void> {\n const barrier = execution.catch((error: unknown) => {\n if (retainFailure) recordFailure(error);\n });\n pending = barrier;\n void barrier.then(() => {\n if (pending === barrier) pending = undefined;\n });\n return retainFailure ? barrier : execution;\n }\n\n function enqueue(event: PrintEvent, retainFailure: boolean): void | Promise<void> {\n if (pending)\n return track(\n pending.then(() => target.print(event)),\n retainFailure,\n );\n try {\n const result = target.print(event);\n if (result) return track(Promise.resolve(result), retainFailure);\n } catch (error) {\n if (retainFailure) recordFailure(error);\n else return Promise.reject(error);\n }\n }\n\n const printer: Printer = {\n print(event) {\n return enqueue(event, true);\n },\n };\n\n return {\n printer,\n async printChecked(event) {\n await enqueue(event, false);\n },\n async drain() {\n await pending;\n if (failed) throw failure;\n },\n };\n}\n","import { inspect, stripVTControlCharacters, styleText } from \"node:util\";\nimport type { HackshErrorSummary } from \"./errors.ts\";\nimport { formatExecCommand } from \"./exec.ts\";\nimport type { LogLevel, LogRecord } from \"./logger.ts\";\nimport {\n eventStream,\n type OutputWriter,\n type Printer,\n type PrintEvent,\n type TerminalOutput,\n} from \"./printer.ts\";\n\ntype PrettyMark =\n | LogLevel\n | \"step\"\n | \"success\"\n | \"usage\"\n | \"version\"\n | \"errorEvent\"\n | \"prompt\"\n | \"exec\";\ntype TextStyle = Parameters<typeof styleText>[0];\n\ninterface PrettySymbols {\n bar: string;\n marks: Record<PrettyMark, string>;\n}\n\nconst unicodeSymbols: PrettySymbols = {\n bar: \"│\",\n marks: {\n trace: \"·\",\n debug: \"◆\",\n info: \"●\",\n warning: \"▲\",\n error: \"■\",\n fatal: \"✖\",\n step: \"◇\",\n success: \"✔\",\n usage: \"◆\",\n version: \"●\",\n errorEvent: \"■\",\n prompt: \"?\",\n exec: \"$\",\n },\n};\n\nconst asciiSymbols: PrettySymbols = {\n bar: \"|\",\n marks: {\n trace: \".\",\n debug: \":\",\n info: \"i\",\n warning: \"!\",\n error: \"x\",\n fatal: \"X\",\n step: \">\",\n success: \"+\",\n usage: \"?\",\n version: \"i\",\n errorEvent: \"x\",\n prompt: \"?\",\n exec: \"$\",\n },\n};\n\nconst markStyles: Record<PrettyMark, TextStyle> = {\n trace: \"gray\",\n debug: \"magenta\",\n info: \"blue\",\n warning: \"yellow\",\n error: \"red\",\n fatal: [\"bgRed\", \"white\", \"bold\"],\n step: \"cyan\",\n success: \"green\",\n usage: \"cyan\",\n version: \"blue\",\n errorEvent: \"red\",\n prompt: \"cyan\",\n exec: \"gray\",\n};\n\nexport interface PrettyPrinterOptions {\n color: boolean;\n unicode: boolean;\n stdout?: TerminalOutput;\n stderr?: OutputWriter;\n}\n\nfunction safelyInspect(value: unknown): string {\n if (typeof value === \"string\") return value;\n try {\n return inspect(value, {\n breakLength: 80,\n colors: false,\n compact: false,\n depth: null,\n sorted: true,\n });\n } catch {\n return \"[Unserializable]\";\n }\n}\n\nfunction propertyLines(properties: Readonly<Record<string, unknown>>): string[] {\n const lines: string[] = [];\n for (const key of Object.keys(properties).sort()) {\n const rendered = ` ${key}: ${safelyInspect(properties[key])}`.split(\"\\n\");\n lines.push(rendered[0] ?? \"\");\n for (const continuation of rendered.slice(1)) lines.push(` ${continuation}`);\n }\n return lines;\n}\n\nfunction logLines(record: LogRecord): string[] {\n const category = record.category.length > 0 ? `[${record.category.join(\":\")}] ` : \"\";\n const message = record.message.split(\"\\n\");\n return [\n `${category}${message[0] ?? \"\"}`,\n ...message.slice(1),\n ...propertyLines(record.properties),\n ];\n}\n\nfunction errorLines(error: HackshErrorSummary): string[] {\n const lines = error.message.split(\"\\n\");\n const details: Record<string, unknown> = {};\n if (error.cause !== undefined) details.cause = error.cause;\n if (error.properties !== undefined) Object.assign(details, error.properties);\n if (error.value !== undefined) details.value = error.value;\n return [...lines, ...propertyLines(details)];\n}\n\nfunction eventMark(event: PrintEvent): PrettyMark {\n if (event.type === \"usage\") return \"usage\";\n if (event.type === \"version\") return \"version\";\n if (event.type === \"error\") return \"errorEvent\";\n if (event.type === \"prompt\") return event.prompt.status === \"submitted\" ? \"success\" : \"prompt\";\n if (event.type === \"exec\") return \"exec\";\n return event.record.kind === \"message\" ? event.record.level : event.record.kind;\n}\n\nfunction eventLines(event: PrintEvent): string[] {\n switch (event.type) {\n case \"usage\":\n return event.text.split(\"\\n\");\n case \"version\":\n return event.version.split(\"\\n\");\n case \"error\":\n return errorLines(event.error);\n case \"log\":\n return logLines(event.record);\n case \"prompt\": {\n const { prompt } = event;\n if (prompt.status === \"submitted\") {\n const result =\n prompt.kind === \"select\"\n ? (prompt.choices.find(({ value }) => value === prompt.value)?.label ?? prompt.value)\n : prompt.kind === \"confirm\"\n ? prompt.value\n ? \"Yes\"\n : \"No\"\n : prompt.value;\n return [`${prompt.message}: ${result}`];\n }\n const lines = [prompt.message];\n if (prompt.kind === \"select\") {\n for (const choice of prompt.choices) {\n lines.push(\n `${choice.selected ? \">\" : \" \"} ${choice.label}${choice.hint ? ` — ${choice.hint}` : \"\"}`,\n );\n }\n } else if (prompt.kind === \"confirm\") {\n lines.push(\n `${prompt.value ? \"Yes\" : \"No\"}${prompt.defaultValue === undefined ? \"\" : ` (default: ${prompt.defaultValue ? \"yes\" : \"no\"})`}`,\n );\n } else {\n lines.push(prompt.value || (prompt.placeholder ? `(${prompt.placeholder})` : \"\"));\n }\n if (prompt.error) lines.push(prompt.error);\n return lines;\n }\n case \"exec\": {\n const lines = [formatExecCommand(event.command)];\n if (event.command.cwd !== undefined) lines.push(...propertyLines({ cwd: event.command.cwd }));\n return lines;\n }\n }\n}\n\nfunction colorize(enabled: boolean, style: TextStyle, text: string): string {\n return enabled ? styleText(style, text, { validateStream: false }) : text;\n}\n\nconst graphemeSegmenter = new Intl.Segmenter(undefined, { granularity: \"grapheme\" });\nconst combiningMark = /\\p{Mark}/u;\nconst pictograph = /\\p{Extended_Pictographic}/u;\n\nfunction isWideCodePoint(codePoint: number): boolean {\n return (\n codePoint >= 0x1100 &&\n (codePoint <= 0x115f ||\n codePoint === 0x2329 ||\n codePoint === 0x232a ||\n (codePoint >= 0x2e80 && codePoint <= 0xa4cf && codePoint !== 0x303f) ||\n (codePoint >= 0xac00 && codePoint <= 0xd7a3) ||\n (codePoint >= 0xf900 && codePoint <= 0xfaff) ||\n (codePoint >= 0xfe10 && codePoint <= 0xfe19) ||\n (codePoint >= 0xfe30 && codePoint <= 0xfe6f) ||\n (codePoint >= 0xff00 && codePoint <= 0xff60) ||\n (codePoint >= 0xffe0 && codePoint <= 0xffe6) ||\n (codePoint >= 0x20000 && codePoint <= 0x3fffd))\n );\n}\n\nfunction displayWidth(text: string): number {\n let width = 0;\n for (const { segment } of graphemeSegmenter.segment(stripVTControlCharacters(text))) {\n if (segment === \"\\t\") {\n width += 8 - (width % 8);\n continue;\n }\n if (\n pictograph.test(segment) ||\n Array.from(segment).some((value) => isWideCodePoint(value.codePointAt(0)!))\n ) {\n width += 2;\n continue;\n }\n for (const value of segment) {\n const codePoint = value.codePointAt(0)!;\n if (codePoint < 0x20 || (codePoint >= 0x7f && codePoint < 0xa0)) continue;\n if (codePoint === 0x200d || (codePoint >= 0xfe00 && codePoint <= 0xfe0f)) continue;\n if (!combiningMark.test(value)) width += 1;\n }\n }\n return width;\n}\n\nfunction renderedRows(rendered: string, columns: number | undefined): number {\n const width =\n Number.isInteger(columns) && columns !== undefined && columns > 0 ? columns : undefined;\n return rendered.split(\"\\n\").reduce((rows, line) => {\n if (!width) return rows + 1;\n return rows + Math.max(1, Math.ceil(displayWidth(line) / width));\n }, 0);\n}\n\n/** Create the fixed human-readable renderer used for pretty output. */\nexport function createPrettyPrinter(options: PrettyPrinterOptions): Printer {\n const stdout = options.stdout ?? process.stdout;\n const stderr = options.stderr ?? process.stderr;\n const symbols = options.unicode ? unicodeSymbols : asciiSymbols;\n let activePrompt: { rendered: string; lines: number } | undefined;\n\n function render(event: PrintEvent): string {\n const mark = eventMark(event);\n const lines = eventLines(event);\n const firstPrefix = colorize(options.color, markStyles[mark], symbols.marks[mark]);\n const barPrefix = colorize(options.color, \"gray\", symbols.bar);\n return lines\n .map((line, index) => `${index === 0 ? firstPrefix : barPrefix}${line ? ` ${line}` : \"\"}`)\n .join(\"\\n\");\n }\n\n function eraseActivePrompt(): string {\n return activePrompt ? \"\\u001b[1A\\u001b[2K\".repeat(activePrompt.lines) : \"\";\n }\n\n return {\n print(event) {\n const rendered = render(event);\n if (event.type === \"prompt\") {\n const erase = eraseActivePrompt();\n if (event.prompt.status === \"closed\") {\n activePrompt = undefined;\n if (erase) stdout.write(erase);\n return;\n }\n if (event.prompt.status === \"submitted\") activePrompt = undefined;\n else activePrompt = { rendered, lines: renderedRows(rendered, stdout.columns) };\n stdout.write(`${erase}${rendered}\\n`);\n return;\n }\n\n const erase = eraseActivePrompt();\n if (!activePrompt) {\n (eventStream(event) === \"stdout\" ? stdout : stderr).write(`${rendered}\\n`);\n return;\n }\n\n stdout.write(erase);\n if (event.type === \"error\") activePrompt = undefined;\n (eventStream(event) === \"stdout\" ? stdout : stderr).write(`${rendered}\\n`);\n if (activePrompt) stdout.write(`${activePrompt.rendered}\\n`);\n },\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 type { Printer, TerminalInput } from \"./printer.ts\";\nimport { summarizeErrors } from \"./errors.ts\";\nimport type { Prompter } from \"./prompts.ts\";\nimport { PromptController } from \"./prompts.ts\";\nimport type { TerminalLock } from \"./terminal.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 extends Prompter {\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 prompts: PromptController,\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 select: (options) => prompts.select(options),\n confirm: (options) => prompts.confirm(options),\n text: (options) => prompts.text(options),\n with: (properties) =>\n createBoundLogger(printer, category, { ...boundProperties, ...properties }, prompts),\n getChild: (child) => createBoundLogger(printer, [...category, child], boundProperties, prompts),\n };\n}\n\nexport interface CreateLoggerOptions {\n interactive: boolean;\n input: TerminalInput;\n printPrompt(event: Parameters<Printer[\"print\"]>[0]): Promise<void>;\n terminal: TerminalLock;\n signal: AbortSignal;\n}\n\n/** Create the logger for one command invocation. */\nexport function createLogger(\n printer: Printer,\n category: readonly string[],\n options: CreateLoggerOptions,\n): Logger {\n const prompts = new PromptController({\n interactive: options.interactive,\n input: options.input,\n print: (event) => options.printPrompt(event),\n terminal: options.terminal,\n signal: options.signal,\n });\n return createBoundLogger(printer, [...category], {}, prompts);\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 { createPrettyPrinter } from \"./pretty.ts\";\nimport {\n createJsonPrinter,\n resolveOutputMode,\n type OutputMode,\n type OutputPreference,\n type OutputWriter,\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?: OutputWriter;\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 });\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 { selectOutputPrinter, type OutputOptions } from \"./output.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 argOptions = command.argOptions?.[key];\n const aliases = argOptions?.alias\n ? aliasList(argOptions.alias).map((item) => `-${item}`)\n : [];\n const name = kebabCase(key);\n const valueName = argOptions?.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 type UsageWriter = (text: string) => void | Promise<void>;\n\nexport interface ShowUsageOptions extends OutputOptions {\n write?: UsageWriter;\n printer?: Printer;\n stream?: PrintStream;\n}\n\nexport type UsageOutput = Required<Pick<ShowUsageOptions, \"write\">>;\n\nexport type ShowUsageCallback = (\n command: AnyCommandDef,\n output: UsageOutput,\n) => void | Promise<void>;\n\n/** Generate usage text without writing to stdout or stderr. */\nexport async function renderUsage(command: AnyCommandDef): Promise<string> {\n return formatUsage(summarizeUsage(command));\n}\n\n/** Generate and write usage text, awaiting asynchronous writers. */\nexport async function showUsage(\n command: AnyCommandDef,\n options: ShowUsageOptions = {},\n): Promise<void> {\n const usage = summarizeUsage(command);\n const text = formatUsage(usage);\n if (options.write) return options.write(text);\n const printer = options.printer ?? selectOutputPrinter(options);\n return printer.print({\n type: \"usage\",\n usage,\n text,\n stream: options.stream ?? \"stdout\",\n });\n}\n","import { schemaShape, 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 { 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 PrintStream,\n type TerminalInput,\n} from \"./printer.ts\";\nimport { TerminalLock } from \"./terminal.ts\";\nimport { selectOutputPrinter, type OutputOptions } from \"./output.ts\";\nimport { showUsage, summarizeUsage, type ShowUsageCallback } 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 displayUsage: ShowUsageCallback,\n output: PreparedOutput,\n env: ExecContext[\"env\"],\n signal: AbortSignal,\n fallbackVersion: () => Promise<string | undefined> = async () => undefined,\n): Promise<unknown> {\n if (root.args && \"version\" in schemaShape(root.args)) {\n throw new TypeError(\"Root option `version` conflicts with the builtin --version\");\n }\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 printUsage(displayUsage, resolved.command, printer, \"stdout\");\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 ...parsed,\n cmd: resolved.command,\n rawArgs: resolved.rawArgs,\n logger: createLogger(printer, category, {\n interactive: output.interactive,\n input: output.input,\n printPrompt: (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\nfunction printUsage(\n displayUsage: ShowUsageCallback,\n command: AnyCommandDef,\n printer: Printer,\n stream: PrintStream,\n): void | Promise<void> {\n return displayUsage(command, {\n write: (text) => printer.print({ type: \"usage\", usage: summarizeUsage(command), text, stream }),\n });\n}\n\nexport interface RunCommandOptions extends OutputOptions {\n printer?: Printer;\n signal?: AbortSignal;\n showUsage?: ShowUsageCallback;\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 });\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\nexport async function runCommand<S extends ArgsSchema>(\n root: CommandDef<S>,\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 options.showUsage ?? showUsage,\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 showUsage?: ShowUsageCallback;\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(\n error: unknown,\n output: PrintQueue,\n displayUsage: ShowUsageCallback,\n): 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 printUsage(displayUsage, error.command, output.printer, \"stderr\");\n }\n}\n\nexport async function runMain<S extends ArgsSchema>(\n command: CommandDef<S>,\n options: RunMainOptions = {},\n): Promise<void> {\n const displayUsage = options.showUsage ?? showUsage;\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 displayUsage,\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, displayUsage);\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\nexport function createMain<S extends ArgsSchema>(\n command: CommandDef<S>,\n options: RunMainOptions = {},\n): (argv?: string[]) => Promise<void> {\n return (argv) => runMain(command, argv === undefined ? options : { ...options, argv });\n}\n"],"mappings":";;;;;;;;AAAA,SAAgB,UA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AAK,MAAM,CAAC,GACpC,cACA,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,QAAQ,YAAY;EACtD,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;AAEA,SAAgB,WACd,SACA,UAA0B,CAAC,GACS;CACpC,QAAQ,SAAS,QAAQ,SAAS,SAAS,KAAA,IAAY,UAAU;EAAE,GAAG;EAAS;CAAK,CAAC;AACvF"}
1
+ {"version":3,"file":"index.js","names":["#result","safeString","parseNodeArgs","#owner","details","#interactive","#inputValue","#printEvent","#bufferedKeys","#terminal","#signal","#print","#run"],"sources":["../src/options.ts","../src/schema.ts","../src/command.ts","../src/errors.ts","../src/environment.ts","../src/parser.ts","../src/terminal.ts","../src/exec.ts","../src/serialization.ts","../src/printer.ts","../src/pretty.ts","../src/prompts.ts","../src/logger.ts","../src/package-version.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 } from \"zod/v4/core\";\n\nexport type ArgsSchema = $ZodObject;\nexport type EmptyArgs = $ZodObject<{}>;\nexport type ShapeOf<S extends ArgsSchema> = S[\"_zod\"][\"def\"][\"shape\"];\nexport type ArgKey<S extends ArgsSchema> = Extract<keyof ShapeOf<S>, string>;\nexport type OptionKey<S extends ArgsSchema> = Exclude<ArgKey<S>, typeof POSITIONALS_KEY>;\n\nexport const POSITIONALS_KEY = \"_\";\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 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\n while (current) {\n const metadata = globalRegistry.get(current);\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 choices: enumChoices(base),\n };\n}\n\n/** Read the `_` 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 `_` 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 { Exec } from \"./exec.ts\";\nimport type { Logger } from \"./logger.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 type OptionKey,\n} from \"./schema.ts\";\n\nexport interface ArgOptions {\n alias?: string | readonly string[];\n valueName?: string;\n env?: string | false;\n}\n\nexport type ArgOptionsMap<S extends ArgsSchema> = Partial<Record<OptionKey<S>, ArgOptions>>;\n\nexport interface CommandContext<S extends ArgsSchema> {\n cmd: CommandDef<S>;\n args: output<S>;\n rawArgs: string[];\n passthrough: string[];\n extraArgs: string[];\n logger: Logger;\n exec: Exec;\n signal: AbortSignal;\n}\n\nexport interface CommandDef<S extends ArgsSchema = EmptyArgs> {\n name?: string;\n version?: string;\n description?: string;\n hidden?: boolean;\n /** Keep unknown options and excess positionals in extraArgs. Inherits from the parent; defaults to false. */\n allowUnknownArgs?: boolean;\n args?: S;\n argOptions?: ArgOptionsMap<S>;\n subCommands?: Record<string, CommandDef<ArgsSchema>>;\n run?(context: CommandContext<S>): unknown;\n}\n\nexport type AnyCommandDef = CommandDef<ArgsSchema>;\n\nexport function defineCommand<S extends ArgsSchema = EmptyArgs>(def: CommandDef<S>): CommandDef<S> {\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 (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 (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, options] of Object.entries(def.argOptions ?? {})) {\n if (key === POSITIONALS_KEY) {\n throw new TypeError(\"Positional arguments cannot have argument options\");\n }\n const schema = shape[key];\n if (!schema) throw new TypeError(`Unknown argument options key \\`${key}\\``);\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\") throw new TypeError(\"Option `help` conflicts with the builtin --help\");\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 { $ZodIssue } from \"zod/v4/core\";\nimport type { AnyCommandDef } from \"./command.ts\";\nimport type { ExecFailure } from \"./exec.ts\";\n\nexport interface HackshIssue {\n arg: string;\n message: string;\n issue?: $ZodIssue;\n}\n\nexport class HackshUsageError extends Error {\n readonly command: AnyCommandDef;\n\n constructor(message: string, command: AnyCommandDef, options?: ErrorOptions) {\n super(message, options);\n this.name = \"HackshUsageError\";\n this.command = command;\n }\n}\n\nexport class HackshValidationError extends HackshUsageError {\n readonly issues: ReadonlyArray<HackshIssue>;\n\n constructor(command: AnyCommandDef, issues: ReadonlyArray<HackshIssue>) {\n super(\n `Invalid arguments:\\n${issues.map(({ arg, message }) => ` ${arg}: ${message}`).join(\"\\n\")}`,\n command,\n );\n this.name = \"HackshValidationError\";\n this.issues = issues;\n }\n}\n\nexport type PromptKind = \"select\" | \"confirm\" | \"text\";\n\nexport type HackshPromptErrorReason =\n | \"non-interactive\"\n | \"cancelled\"\n | \"aborted\"\n | \"eof\"\n | \"overlapping\"\n | \"invalid-options\"\n | \"input-error\"\n | \"printer-error\";\n\nexport interface PromptErrorDetails {\n kind: PromptKind;\n message: string;\n choices?: readonly string[];\n}\n\n/** An input request that could not be completed safely. */\nexport class HackshPromptError extends Error {\n readonly reason: HackshPromptErrorReason;\n readonly prompt: PromptErrorDetails;\n\n constructor(\n reason: HackshPromptErrorReason,\n prompt: PromptErrorDetails,\n message: string,\n options?: ErrorOptions,\n ) {\n super(message, options);\n this.name = \"HackshPromptError\";\n this.reason = reason;\n this.prompt = prompt;\n }\n}\n\n/** An external command that did not succeed; `result` is not enumerable so error summaries omit child output. */\nexport class HackshExecError extends Error {\n readonly #result: ExecFailure;\n\n constructor(message: string, result: ExecFailure, options?: ErrorOptions) {\n super(message, options);\n this.name = \"HackshExecError\";\n this.#result = result;\n }\n\n get result(): ExecFailure {\n return this.#result;\n }\n}\n\n/** A requested process exit status; `runMain` exits with it and reports only a non-empty message. */\nexport class HackshExitError extends Error {\n readonly exitCode: number;\n\n constructor(exitCode: number, message?: string, options?: ErrorOptions) {\n if (!Number.isInteger(exitCode) || exitCode < 0 || exitCode > 255) {\n throw new TypeError(\"Exit code must be an integer from 0 to 255\");\n }\n super(message, options);\n this.name = \"HackshExitError\";\n this.exitCode = exitCode;\n }\n}\n\nexport type HackshErrorKind = \"error\" | \"prompt\" | \"usage\" | \"validation\" | \"thrown\";\n\nexport interface ValidationIssueSummary {\n arg: string;\n message: string;\n code?: string;\n path?: readonly PropertyKey[];\n details?: Readonly<Record<string, unknown>>;\n}\n\nexport interface HackshErrorSummary {\n kind: HackshErrorKind;\n name: string;\n message: string;\n stack?: string;\n cause?: unknown;\n issues?: readonly ValidationIssueSummary[];\n properties?: Readonly<Record<string, unknown>>;\n value?: unknown;\n}\n\nfunction safeString(value: unknown, fallback: string): string {\n try {\n return String(value);\n } catch {\n return fallback;\n }\n}\n\nfunction readProperty(value: object, key: PropertyKey): unknown {\n try {\n return Reflect.get(value, key);\n } catch {\n return \"[Unserializable]\";\n }\n}\n\nfunction enumerableKeys(value: object): string[] {\n try {\n return Object.keys(value);\n } catch {\n return [];\n }\n}\n\nfunction hasToJSON(value: object): boolean {\n try {\n return typeof Reflect.get(value, \"toJSON\") === \"function\";\n } catch {\n return false;\n }\n}\n\nfunction isPlainObject(value: object): boolean {\n try {\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n } catch {\n return false;\n }\n}\n\nfunction summarizeIssue(\n { arg, message, issue }: HackshIssue,\n seen: WeakMap<object, unknown>,\n): ValidationIssueSummary {\n if (!issue) return { arg, message };\n const details: Record<string, unknown> = {};\n for (const key of enumerableKeys(issue)) {\n if ([\"code\", \"path\", \"message\", \"inst\"].includes(key)) continue;\n details[key] = summarizeErrors(readProperty(issue, key), seen);\n }\n const code = readProperty(issue, \"code\");\n const path = readProperty(issue, \"path\");\n return {\n arg,\n message,\n ...(typeof code === \"string\" ? { code } : {}),\n ...(Array.isArray(path) ? { path } : {}),\n ...(Object.keys(details).length === 0 ? {} : { details }),\n };\n}\n\nfunction errorKind(error: Error): HackshErrorKind {\n if (error instanceof HackshPromptError) return \"prompt\";\n if (error instanceof HackshValidationError) return \"validation\";\n if (error instanceof HackshUsageError) return \"usage\";\n return \"error\";\n}\n\nfunction summarizeErrorWithSeen(error: Error, seen: WeakMap<object, unknown>): HackshErrorSummary {\n const summary: HackshErrorSummary = {\n kind: errorKind(error),\n name: safeString(readProperty(error, \"name\"), \"Error\"),\n message: safeString(readProperty(error, \"message\"), \"[Unserializable error message]\"),\n };\n seen.set(error, summary);\n\n const stack = readProperty(error, \"stack\");\n const cause = readProperty(error, \"cause\");\n if (typeof stack === \"string\") summary.stack = stack;\n if (cause !== undefined) summary.cause = summarizeErrors(cause, seen);\n if (error instanceof HackshValidationError) {\n summary.issues = error.issues.map((issue) => summarizeIssue(issue, seen));\n }\n\n const reserved = new Set([\"name\", \"message\", \"stack\", \"cause\", \"command\", \"issues\"]);\n const properties: Record<string, unknown> = {};\n for (const key of enumerableKeys(error)) {\n if (reserved.has(key)) continue;\n properties[key] = summarizeErrors(readProperty(error, key), seen);\n }\n if (Object.keys(properties).length > 0) summary.properties = properties;\n return summary;\n}\n\n/** Recursively replace Error values with command- and schema-free summaries. */\nexport function summarizeErrors(\n value: unknown,\n seen: WeakMap<object, unknown> = new WeakMap(),\n): unknown {\n if (typeof value !== \"object\" || value === null) return value;\n const existing = seen.get(value);\n if (existing !== undefined) return existing;\n if (value instanceof Error) return summarizeErrorWithSeen(value, seen);\n\n if (Array.isArray(value)) {\n const result: unknown[] = [];\n seen.set(value, result);\n let changed = false;\n for (const item of value) {\n const summarized = summarizeErrors(item, seen);\n result.push(summarized);\n changed ||= summarized !== item;\n }\n if (changed) return result;\n seen.set(value, value);\n return value;\n }\n if (value instanceof Map) {\n const result = new Map<unknown, unknown>();\n seen.set(value, result);\n let changed = false;\n for (const [key, item] of value) {\n const summarizedKey = summarizeErrors(key, seen);\n const summarizedItem = summarizeErrors(item, seen);\n result.set(summarizedKey, summarizedItem);\n changed ||= summarizedKey !== key || summarizedItem !== item;\n }\n if (changed) return result;\n seen.set(value, value);\n return value;\n }\n if (value instanceof Set) {\n const result = new Set<unknown>();\n seen.set(value, result);\n let changed = false;\n for (const item of value) {\n const summarized = summarizeErrors(item, seen);\n result.add(summarized);\n changed ||= summarized !== item;\n }\n if (changed) return result;\n seen.set(value, value);\n return value;\n }\n if (ArrayBuffer.isView(value) || hasToJSON(value) || !isPlainObject(value)) return value;\n\n const result: Record<string, unknown> = {};\n seen.set(value, result);\n let changed = false;\n for (const key of enumerableKeys(value)) {\n const original = readProperty(value, key);\n const summarized = summarizeErrors(original, seen);\n result[key] = summarized;\n changed ||= summarized !== original;\n }\n if (changed) return result;\n seen.set(value, value);\n return value;\n}\n\n/** Convert any thrown value into a canonical error description. */\nexport function summarizeError(error: unknown): HackshErrorSummary {\n if (error instanceof Error) return summarizeErrorWithSeen(error, new WeakMap());\n return {\n kind: \"thrown\",\n name: \"NonErrorThrown\",\n message: safeString(error, \"[Unserializable thrown value]\"),\n value: summarizeErrors(error),\n };\n}\n","import type { AnyCommandDef } from \"./command.ts\";\nimport { kebabCase } from \"./options.ts\";\nimport { isArrayInput, isObjectInput, POSITIONALS_KEY, schemaShape } 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 = command.argOptions?.[key]?.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 alias = command.argOptions?.[key]?.alias;\n const aliases = alias ? aliasList(alias) : [];\n const definition: OptionDefinition = {\n key,\n kebabName: kebabCase(key),\n takesValue: readArgInfo(schema).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","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 { spawn, type ChildProcess } from \"node:child_process\";\nimport type { Readable } from \"node:stream\";\nimport { HackshExecError } from \"./errors.ts\";\nimport type { ExecPrintEvent, OutputFormat } from \"./printer.ts\";\nimport { TerminalLock } from \"./terminal.ts\";\n\ntype Environment = Readonly<Record<string, string | undefined>>;\n\nexport interface ExecOptions {\n cwd?: string;\n env?: Environment;\n input?: string;\n reject?: boolean;\n timeout?: number;\n signal?: AbortSignal;\n maxBuffer?: number;\n forceKillAfterDelay?: number;\n stdin?: \"pipe\" | \"inherit\";\n stdout?: \"pipe\" | \"inherit\";\n stderr?: \"pipe\" | \"inherit\";\n interactive?: boolean;\n display?: boolean;\n redact?: readonly string[];\n dryRun?: boolean;\n}\n\nexport interface ExecCommand {\n file: string;\n args: readonly string[];\n cwd: string | undefined;\n}\n\nexport interface ExecSuccess {\n status: \"succeeded\";\n command: ExecCommand;\n stdout: string;\n stderr: string;\n exitCode: 0;\n}\n\nexport type ExecFailure = {\n status: \"failed\";\n command: ExecCommand;\n stdout: string;\n stderr: string;\n} & (\n | { reason: \"exit-code\"; exitCode: number }\n | { reason: \"signal\"; signal: string }\n | { reason: \"spawn\"; error: Error }\n | { reason: \"timeout\" | \"aborted\" | \"output-limit\" }\n | { reason: \"json-output\" | \"non-interactive\" | \"overlapping\" }\n);\n\nexport type ExecFailureReason = ExecFailure[\"reason\"];\n\nexport type ExecResult = ExecSuccess | ExecFailure;\n\nexport interface ExecSkipped {\n status: \"skipped\";\n command: ExecCommand;\n}\n\ntype ExecOutcome<O extends ExecOptions> = \"reject\" extends keyof O\n ? false extends O[\"reject\"]\n ? ExecResult\n : ExecSuccess\n : ExecSuccess;\n\ntype SpecifiedDryRun<O> = \"dryRun\" extends keyof O ? O[\"dryRun\"] : false;\n\ntype ReturnsFailure<O extends ExecOptions> = \"reject\" extends keyof O\n ? false extends O[\"reject\"]\n ? true\n : false\n : false;\n\ntype AbortedFailure = {\n status: \"failed\";\n command: ExecCommand;\n stdout: string;\n stderr: string;\n reason: \"aborted\";\n};\n\ntype DefiniteSkip<O extends ExecOptions> =\n ReturnsFailure<O> extends true ? ExecSkipped | AbortedFailure : ExecSkipped;\n\nexport type ExecReturn<O extends ExecOptions> =\n true extends SpecifiedDryRun<O>\n ? false extends SpecifiedDryRun<O>\n ? ExecSkipped | ExecOutcome<O>\n : undefined extends SpecifiedDryRun<O>\n ? ExecSkipped | ExecOutcome<O>\n : DefiniteSkip<O>\n : ExecOutcome<O>;\n\ntype RejectInheritedInput<O> = O extends { input: string; stdin: \"inherit\" } ? never : unknown;\n\nexport type Exec = <const O extends ExecOptions = {}>(\n file: string,\n args?: readonly string[],\n options?: O & { [K in Exclude<keyof O, keyof ExecOptions>]: never } & RejectInheritedInput<O>,\n) => Promise<ExecReturn<O>>;\n\nexport interface ExecContext {\n env: Environment | undefined;\n mode: { format: OutputFormat; interactive: boolean };\n print(event: ExecPrintEvent): void | Promise<void>;\n terminal: TerminalLock;\n signal: AbortSignal;\n}\n\nconst OPTION_KEYS: ReadonlySet<string> = new Set([\n \"cwd\",\n \"env\",\n \"input\",\n \"reject\",\n \"timeout\",\n \"signal\",\n \"maxBuffer\",\n \"forceKillAfterDelay\",\n \"stdin\",\n \"stdout\",\n \"stderr\",\n \"interactive\",\n \"display\",\n \"redact\",\n \"dryRun\",\n] satisfies (keyof ExecOptions)[]);\n\ntype TerminationCause = \"timeout\" | \"aborted\" | \"output-limit\";\ntype StreamMode = \"pipe\" | \"inherit\";\ntype ExecStdio = ExecPrintEvent[\"stdio\"];\ntype RefusalReason = \"aborted\" | \"json-output\" | \"non-interactive\" | \"overlapping\";\n\ninterface SpawnError extends NodeJS.ErrnoException {\n spawnargs?: readonly string[];\n}\n\ninterface ExecPlan {\n command: ExecCommand;\n reported: ExecCommand;\n env: NodeJS.ProcessEnv | undefined;\n input: string | undefined;\n reject: boolean;\n timeout: number | undefined;\n signal: AbortSignal;\n maxBuffer: number;\n forceKillAfterDelay: number;\n stdin: StreamMode;\n stdout: StreamMode;\n stderr: StreamMode;\n interactive: boolean;\n display: boolean;\n redact: readonly string[];\n dryRun: boolean;\n}\n\ninterface Outcome {\n cause: TerminationCause | undefined;\n spawnError: Error | undefined;\n exit: { code: number | null; signal: string | null } | undefined;\n}\n\nconst MAX_DELAY = 2_147_483_647;\nconst REFUSAL_MESSAGE = {\n \"json-output\": \"Command cannot use the terminal in JSON output mode\",\n \"non-interactive\": \"Command requires an interactive terminal\",\n overlapping: \"Command cannot use the terminal while it is in use\",\n} as const;\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction assertNoNul(value: string, label: string): void {\n if (value.includes(\"\\0\")) throw new TypeError(`${label} must not contain NUL characters`);\n}\n\nfunction readInteger(value: unknown, label: string, minimum: number, maximum: number): number {\n if (typeof value !== \"number\" || !Number.isInteger(value) || value < minimum || value > maximum) {\n throw new TypeError(`${label} must be an integer from ${minimum} to ${maximum}`);\n }\n return value;\n}\n\nfunction readEnum<const T extends string>(value: unknown, label: string, allowed: readonly T[]): T {\n if (typeof value === \"string\" && (allowed as readonly string[]).includes(value))\n return value as T;\n throw new TypeError(\n `Exec option \\`${label}\\` must be ${allowed.map((item) => JSON.stringify(item)).join(\" or \")}`,\n );\n}\n\nfunction readBoolean(value: unknown, label: string): boolean {\n if (typeof value !== \"boolean\") throw new TypeError(`Exec option \\`${label}\\` must be a boolean`);\n return value;\n}\n\nfunction readRedact(value: unknown): readonly string[] {\n if (!Array.isArray(value)) throw new TypeError(\"Exec option `redact` must be an array\");\n for (const item of value) {\n if (typeof item !== \"string\" || item === \"\") {\n throw new TypeError(\"Exec option `redact` must contain only non-empty strings\");\n }\n assertNoNul(item, \"Exec option `redact`\");\n }\n return value as readonly string[];\n}\n\nfunction mergeEnvironment(\n base: Environment | undefined,\n overrides: unknown,\n): NodeJS.ProcessEnv | undefined {\n if (overrides === undefined && base === undefined) return undefined;\n if (overrides !== undefined && !isRecord(overrides)) {\n throw new TypeError(\"Exec option `env` must be an object\");\n }\n const merged: NodeJS.ProcessEnv = {};\n for (const [key, value] of Object.entries(base ?? process.env)) {\n if (value !== undefined) merged[key] = value;\n }\n for (const [key, value] of Object.entries(overrides ?? {})) {\n if (key === \"\" || key.includes(\"=\") || key.includes(\"\\0\")) {\n throw new TypeError(`Invalid environment variable name ${JSON.stringify(key)}`);\n }\n if (value === undefined) {\n delete merged[key];\n continue;\n }\n if (typeof value !== \"string\") {\n throw new TypeError(`Environment variable ${key} must be a string or undefined`);\n }\n assertNoNul(value, `Environment variable ${key}`);\n merged[key] = value;\n }\n return merged;\n}\n\nfunction redactValue(value: string, secrets: readonly string[]): string {\n let redacted = value;\n for (const secret of [...secrets].sort((left, right) => right.length - left.length)) {\n redacted = redacted.split(secret).join(\"***\");\n }\n return redacted;\n}\n\nfunction redactCommand(command: ExecCommand, secrets: readonly string[]): ExecCommand {\n if (secrets.length === 0) return command;\n return {\n file: redactValue(command.file, secrets),\n args: command.args.map((arg) => redactValue(arg, secrets)),\n cwd: command.cwd === undefined ? undefined : redactValue(command.cwd, secrets),\n };\n}\n\nfunction redactError(error: Error, secrets: readonly string[]): Error {\n const source = error as SpawnError;\n const redacted = new Error(redactValue(error.message, secrets)) as SpawnError;\n if (typeof error.stack === \"string\") redacted.stack = redactValue(error.stack, secrets);\n if (source.code !== undefined) redacted.code = source.code;\n if (source.errno !== undefined) redacted.errno = source.errno;\n if (typeof source.syscall === \"string\") redacted.syscall = redactValue(source.syscall, secrets);\n if (typeof source.path === \"string\") redacted.path = redactValue(source.path, secrets);\n if (Array.isArray(source.spawnargs)) {\n redacted.spawnargs = source.spawnargs.map((arg) =>\n typeof arg === \"string\" ? redactValue(arg, secrets) : arg,\n );\n }\n return redacted;\n}\n\nfunction observedError(plan: ExecPlan, error: Error): Error {\n return plan.redact.length === 0 ? error : redactError(error, plan.redact);\n}\n\nfunction parsePlan(file: unknown, args: unknown, options: unknown, context: ExecContext): ExecPlan {\n if (typeof file !== \"string\" || file === \"\") {\n throw new TypeError(\"Exec file must be a non-empty string\");\n }\n assertNoNul(file, \"Exec file\");\n const argv = args === undefined ? [] : args;\n if (!Array.isArray(argv) || !argv.every((arg) => typeof arg === \"string\")) {\n throw new TypeError(\"Exec args must be an array of strings\");\n }\n for (const arg of argv) assertNoNul(arg, \"Exec args\");\n const raw = options === undefined ? {} : options;\n if (!isRecord(raw)) throw new TypeError(\"Exec options must be an object\");\n for (const key of Object.keys(raw)) {\n if (!OPTION_KEYS.has(key)) throw new TypeError(`Unknown exec option \\`${key}\\``);\n }\n\n const { cwd, input, reject, timeout, signal, maxBuffer, forceKillAfterDelay } = raw;\n if (cwd !== undefined) {\n if (typeof cwd !== \"string\" || cwd === \"\") {\n throw new TypeError(\"Exec option `cwd` must be a non-empty string\");\n }\n assertNoNul(cwd, \"Exec option `cwd`\");\n }\n if (input !== undefined && typeof input !== \"string\") {\n throw new TypeError(\"Exec option `input` must be a string\");\n }\n if (reject !== undefined && typeof reject !== \"boolean\") {\n throw new TypeError(\"Exec option `reject` must be a boolean\");\n }\n if (signal !== undefined && !(signal instanceof AbortSignal)) {\n throw new TypeError(\"Exec option `signal` must be an AbortSignal\");\n }\n const stdin =\n raw.stdin === undefined ? \"pipe\" : readEnum(raw.stdin, \"stdin\", [\"pipe\", \"inherit\"]);\n const stdout =\n raw.stdout === undefined ? \"pipe\" : readEnum(raw.stdout, \"stdout\", [\"pipe\", \"inherit\"]);\n const stderr =\n raw.stderr === undefined ? \"pipe\" : readEnum(raw.stderr, \"stderr\", [\"pipe\", \"inherit\"]);\n if (input !== undefined && stdin === \"inherit\") {\n throw new TypeError(\"Exec option `input` cannot be combined with stdin inherit\");\n }\n const command = { file, args: [...argv], cwd };\n const redact = raw.redact === undefined ? [] : readRedact(raw.redact);\n return {\n command,\n reported: redactCommand(command, redact),\n env: mergeEnvironment(context.env, raw.env),\n input,\n reject: reject ?? true,\n timeout:\n timeout === undefined\n ? undefined\n : readInteger(timeout, \"Exec option `timeout`\", 1, MAX_DELAY),\n signal: signal === undefined ? context.signal : AbortSignal.any([context.signal, signal]),\n maxBuffer:\n maxBuffer === undefined\n ? 100_000_000\n : readInteger(maxBuffer, \"Exec option `maxBuffer`\", 1, Number.MAX_SAFE_INTEGER),\n forceKillAfterDelay:\n forceKillAfterDelay === undefined\n ? 5_000\n : readInteger(forceKillAfterDelay, \"Exec option `forceKillAfterDelay`\", 0, MAX_DELAY),\n stdin,\n stdout,\n stderr,\n interactive:\n raw.interactive === undefined ? false : readBoolean(raw.interactive, \"interactive\"),\n display: raw.display === undefined ? true : readBoolean(raw.display, \"display\"),\n redact,\n dryRun: raw.dryRun === undefined ? false : readBoolean(raw.dryRun, \"dryRun\"),\n };\n}\n\nfunction stripFinalNewline(text: string): string {\n if (text.endsWith(\"\\r\\n\")) return text.slice(0, -2);\n if (text.endsWith(\"\\n\")) return text.slice(0, -1);\n return text;\n}\n\nfunction collect(stream: Readable, limit: number, onLimit: () => void): () => string {\n const chunks: Buffer[] = [];\n let length = 0;\n let exceeded = false;\n stream.on(\"data\", (chunk: Buffer) => {\n if (exceeded) return;\n const remaining = limit - length;\n if (chunk.length <= remaining) {\n chunks.push(chunk);\n length += chunk.length;\n return;\n }\n chunks.push(chunk.subarray(0, remaining));\n length = limit;\n exceeded = true;\n onLimit();\n });\n return () => stripFinalNewline(Buffer.concat(chunks).toString(\"utf8\"));\n}\n\nfunction toResult(\n command: ExecCommand,\n outcome: Outcome,\n stdout: string,\n stderr: string,\n): ExecResult {\n const failed = { status: \"failed\", command, stdout, stderr } as const;\n if (outcome.cause) return { ...failed, reason: outcome.cause };\n if (outcome.spawnError) return { ...failed, reason: \"spawn\", error: outcome.spawnError };\n const { code, signal } = outcome.exit ?? { code: null, signal: null };\n if (signal !== null) return { ...failed, reason: \"signal\", signal };\n if (code !== 0) return { ...failed, reason: \"exit-code\", exitCode: code ?? 1 };\n return { status: \"succeeded\", command, stdout, stderr, exitCode: 0 };\n}\n\nfunction isSpawnErrno(error: unknown): error is NodeJS.ErrnoException {\n return error instanceof Error && \"syscall\" in error;\n}\n\nfunction execEvent(plan: ExecPlan, phase: \"start\" | \"skip\"): ExecPrintEvent {\n const { file, args, cwd } = plan.reported;\n return {\n type: \"exec\",\n phase,\n command: cwd === undefined ? { file, args } : { file, args, cwd },\n stdio: commandStdio(plan),\n interactive: plan.interactive,\n };\n}\n\nfunction commandStdio(plan: ExecPlan): ExecStdio {\n return {\n stdin: plan.stdin === \"inherit\" ? \"inherit\" : plan.input === undefined ? \"ignore\" : \"input\",\n stdout: plan.stdout,\n stderr: plan.stderr,\n };\n}\n\nfunction usesTerminal(plan: ExecPlan, stdio: ExecStdio): boolean {\n return (\n plan.interactive ||\n stdio.stdin === \"inherit\" ||\n stdio.stdout === \"inherit\" ||\n stdio.stderr === \"inherit\"\n );\n}\n\nfunction startChild(plan: ExecPlan): ChildProcess | Error {\n const stdio = commandStdio(plan);\n try {\n return spawn(plan.command.file, plan.command.args, {\n cwd: plan.command.cwd,\n env: plan.env,\n shell: false,\n windowsHide: true,\n stdio: [\n stdio.stdin === \"inherit\" ? \"inherit\" : stdio.stdin === \"input\" ? \"pipe\" : \"ignore\",\n stdio.stdout,\n stdio.stderr,\n ],\n });\n } catch (error) {\n if (isSpawnErrno(error)) return error;\n throw error;\n }\n}\n\nfunction runPlan(plan: ExecPlan): Promise<ExecResult> {\n const outcome: Outcome = { cause: undefined, spawnError: undefined, exit: undefined };\n if (plan.signal.aborted) {\n outcome.cause = \"aborted\";\n return Promise.resolve(toResult(plan.reported, outcome, \"\", \"\"));\n }\n const child = startChild(plan);\n if (child instanceof Error) {\n outcome.spawnError = observedError(plan, child);\n return Promise.resolve(toResult(plan.reported, outcome, \"\", \"\"));\n }\n\n return new Promise((resolve) => {\n const stdout = child.stdout;\n const stderr = child.stderr;\n let settled = false;\n let killTimer: NodeJS.Timeout | undefined;\n\n const settle = () => {\n if (settled) return;\n settled = true;\n clearTimeout(timeoutTimer);\n clearTimeout(killTimer);\n plan.signal.removeEventListener(\"abort\", onAbort);\n resolve(toResult(plan.reported, outcome, readStdout(), readStderr()));\n };\n const release = () => {\n stdout?.destroy();\n stderr?.destroy();\n settle();\n };\n const terminate = (cause: TerminationCause) => {\n if (settled || outcome.cause) return;\n outcome.cause = cause;\n if (outcome.exit) {\n release();\n return;\n }\n child.kill(\"SIGTERM\");\n killTimer = setTimeout(() => child.kill(\"SIGKILL\"), plan.forceKillAfterDelay);\n };\n const onAbort = () => terminate(\"aborted\");\n\n const readStdout = stdout\n ? collect(stdout, plan.maxBuffer, () => terminate(\"output-limit\"))\n : () => \"\";\n const readStderr = stderr\n ? collect(stderr, plan.maxBuffer, () => terminate(\"output-limit\"))\n : () => \"\";\n const timeoutTimer =\n plan.timeout === undefined ? undefined : setTimeout(() => terminate(\"timeout\"), plan.timeout);\n plan.signal.addEventListener(\"abort\", onAbort, { once: true });\n\n child.on(\"error\", (error) => {\n if (child.pid !== undefined) return;\n outcome.spawnError = observedError(plan, error);\n release();\n });\n child.on(\"exit\", (code, signal) => {\n outcome.exit = { code, signal };\n clearTimeout(killTimer);\n // A grandchild may keep the pipes open after hacksh terminates the direct child.\n if (outcome.cause) release();\n });\n child.on(\"close\", settle);\n\n if (child.stdin) {\n child.stdin.on(\"error\", () => undefined);\n child.stdin.end(plan.input);\n }\n });\n}\n\nfunction formatArgument(value: string): string {\n return value === \"\" || /[\\s\"'\\\\$`;|&<>*?()[\\]{}~#!]/.test(value) ? JSON.stringify(value) : value;\n}\n\nexport function formatExecCommand(command: Pick<ExecCommand, \"file\" | \"args\">): string {\n return [command.file, ...command.args].map(formatArgument).join(\" \");\n}\n\nfunction failureMessage(plan: ExecPlan, result: ExecFailure): string {\n const display = formatExecCommand(plan.reported);\n switch (result.reason) {\n case \"exit-code\":\n return `Command failed with exit code ${result.exitCode}: ${display}`;\n case \"signal\":\n return `Command was terminated by ${result.signal}: ${display}`;\n case \"spawn\": {\n const code = (result.error as NodeJS.ErrnoException).code;\n return `Command could not be started (${code ?? result.error.message}): ${display}`;\n }\n case \"timeout\":\n return `Command timed out after ${plan.timeout} ms: ${display}`;\n case \"aborted\":\n return `Command was aborted: ${display}`;\n case \"output-limit\":\n return `Command output exceeded ${plan.maxBuffer} bytes: ${display}`;\n case \"json-output\":\n case \"non-interactive\":\n case \"overlapping\":\n return `${REFUSAL_MESSAGE[result.reason]}: ${display}`;\n }\n}\n\nfunction emptyFailure(plan: ExecPlan, reason: RefusalReason): ExecFailure {\n return { status: \"failed\", command: plan.reported, stdout: \"\", stderr: \"\", reason };\n}\n\nfunction complete(plan: ExecPlan, result: ExecResult): ExecResult {\n if (result.status === \"failed\" && plan.reject) {\n throw new HackshExecError(\n failureMessage(plan, result),\n result,\n result.reason === \"spawn\" ? { cause: result.error } : undefined,\n );\n }\n return result;\n}\n\nfunction blockedReason(\n plan: ExecPlan,\n context: ExecContext,\n stdio: ExecStdio,\n): \"json-output\" | \"non-interactive\" | undefined {\n const inherited =\n stdio.stdin === \"inherit\" || stdio.stdout === \"inherit\" || stdio.stderr === \"inherit\";\n if (context.mode.format === \"json\" && inherited) return \"json-output\";\n if (plan.interactive && !context.mode.interactive) return \"non-interactive\";\n return undefined;\n}\n\nasync function execute(\n file: unknown,\n args: unknown,\n options: unknown,\n context: ExecContext,\n): Promise<ExecResult | ExecSkipped> {\n const plan = parsePlan(file, args, options, context);\n if (plan.signal.aborted) return complete(plan, emptyFailure(plan, \"aborted\"));\n if (plan.dryRun) {\n if (plan.display) await context.print(execEvent(plan, \"skip\"));\n return { status: \"skipped\", command: plan.reported };\n }\n\n const stdio = commandStdio(plan);\n const blocked = blockedReason(plan, context, stdio);\n if (blocked) return complete(plan, emptyFailure(plan, blocked));\n\n const holdTerminal = usesTerminal(plan, stdio);\n if (holdTerminal && !context.terminal.acquire(\"exec\")) {\n return complete(plan, emptyFailure(plan, \"overlapping\"));\n }\n try {\n if (plan.display) await context.print(execEvent(plan, \"start\"));\n return complete(plan, await runPlan(plan));\n } finally {\n if (holdTerminal) context.terminal.release();\n }\n}\n\nexport function createExec(context: ExecContext): Exec {\n return ((file, args, options) => execute(file, args, options, context)) as Exec;\n}\n","import { stripVTControlCharacters } from \"node:util\";\nimport { summarizeError } from \"./errors.ts\";\n\nfunction safeString(value: unknown): string {\n try {\n return String(value);\n } catch {\n return \"[Unserializable]\";\n }\n}\n\nfunction normalizeProperty(value: object, key: PropertyKey, ancestors: Set<object>): unknown {\n try {\n return normalizeJson(Reflect.get(value, key), ancestors);\n } catch {\n return \"[Unserializable]\";\n }\n}\n\nfunction normalizedKeys(value: object): string[] | undefined {\n try {\n return Object.keys(value);\n } catch {\n return undefined;\n }\n}\n\nconst noToJson = Symbol(\"noToJson\");\n\nfunction normalizedToJson(value: object, ancestors: Set<object>): unknown {\n let toJSON: unknown;\n try {\n toJSON = Reflect.get(value, \"toJSON\");\n } catch {\n return noToJson;\n }\n if (typeof toJSON !== \"function\") return noToJson;\n try {\n const result = Reflect.apply(toJSON, value, []);\n return result === value ? noToJson : normalizeJson(result, ancestors);\n } catch {\n return noToJson;\n }\n}\n\nfunction isArrayBufferView(value: object): value is ArrayBufferView {\n try {\n return ArrayBuffer.isView(value);\n } catch {\n return false;\n }\n}\n\n/** Normalize arbitrary event data into values accepted by JSON.stringify. */\nexport function normalizeJson(value: unknown, ancestors = new Set<object>()): unknown {\n switch (typeof value) {\n case \"string\":\n return stripVTControlCharacters(value);\n case \"boolean\":\n return value;\n case \"number\":\n return Number.isFinite(value) ? value : null;\n case \"bigint\":\n return value.toString();\n case \"undefined\":\n return \"[undefined]\";\n case \"symbol\":\n return `[symbol:${stripVTControlCharacters(value.description ?? \"\")}]`;\n case \"function\":\n return `[function:${stripVTControlCharacters(value.name || \"anonymous\")}]`;\n case \"object\":\n break;\n }\n if (value === null) return null;\n if (ancestors.has(value)) return \"[Circular]\";\n\n const nextAncestors = new Set(ancestors).add(value);\n if (value instanceof Error) return normalizeJson(summarizeError(value), nextAncestors);\n\n const jsonValue = normalizedToJson(value, nextAncestors);\n if (jsonValue !== noToJson) return jsonValue;\n\n if (isArrayBufferView(value)) {\n if (value instanceof DataView) {\n return Array.from(new Uint8Array(value.buffer, value.byteOffset, value.byteLength));\n }\n try {\n return Array.from(value as unknown as Iterable<unknown>, (item) =>\n normalizeJson(item, nextAncestors),\n );\n } catch {\n return \"[Unserializable]\";\n }\n }\n if (value instanceof ArrayBuffer) return Array.from(new Uint8Array(value));\n if (Array.isArray(value)) {\n return Array.from({ length: value.length }, (_, index) =>\n normalizeProperty(value, index, nextAncestors),\n );\n }\n if (value instanceof Map) {\n try {\n return [...value].map(([key, item]) => [\n normalizeJson(key, nextAncestors),\n normalizeJson(item, nextAncestors),\n ]);\n } catch {\n return \"[Unserializable]\";\n }\n }\n if (value instanceof Set) {\n try {\n return [...value].map((item) => normalizeJson(item, nextAncestors));\n } catch {\n return \"[Unserializable]\";\n }\n }\n\n const keys = normalizedKeys(value);\n if (!keys) return safeString(value);\n const result: Record<string, unknown> = {};\n for (const key of keys) {\n result[stripVTControlCharacters(key)] = normalizeProperty(value, key, nextAncestors);\n }\n return result;\n}\n","import type { HackshErrorSummary } from \"./errors.ts\";\nimport { formatExecCommand, type ExecCommand } from \"./exec.ts\";\nimport type { LogRecord } from \"./logger.ts\";\nimport { normalizeJson } from \"./serialization.ts\";\nimport type { UsageSummary } from \"./usage.ts\";\n\nexport type PrintStream = \"stdout\" | \"stderr\";\nexport type OutputPreference = \"auto\" | \"pretty\" | \"json\";\nexport type OutputFormat = Exclude<OutputPreference, \"auto\">;\n\nexport interface OutputMode {\n format: OutputFormat;\n interactive: boolean;\n color: boolean;\n}\n\nexport interface ResolveOutputModeOptions {\n output?: OutputPreference;\n env?: Readonly<Record<string, string | undefined>>;\n inputIsTTY?: boolean;\n outputIsTTY?: boolean;\n}\n\nfunction fallbackValue(value: unknown): string {\n try {\n return String(value);\n } catch {\n return \"[Unserializable]\";\n }\n}\n\nfunction validatePreference(value: unknown, source: string): OutputPreference | undefined {\n if (value === undefined) return undefined;\n if (value === \"auto\" || value === \"pretty\" || value === \"json\") return value;\n throw new TypeError(\n `Invalid ${source} value ${fallbackValue(value)}; expected auto, pretty, or json`,\n );\n}\n\nfunction readEnvironment(\n env: Readonly<Record<string, string | undefined>>,\n key: string,\n): string | undefined {\n try {\n return env[key];\n } catch {\n return undefined;\n }\n}\n\n/** Resolve output behavior once, before command routing or argument parsing. */\nexport function resolveOutputMode(options: ResolveOutputModeOptions = {}): OutputMode {\n const env = options.env ?? process.env;\n const configured = validatePreference(options.output, \"output\");\n const overridden = validatePreference(readEnvironment(env, \"HACKSH_OUTPUT\"), \"HACKSH_OUTPUT\");\n const requested = overridden ?? configured ?? \"auto\";\n const ci = Boolean(readEnvironment(env, \"CI\"));\n const format = requested === \"auto\" ? (ci ? \"json\" : \"pretty\") : requested;\n const inputIsTTY = options.inputIsTTY ?? process.stdin.isTTY === true;\n const outputIsTTY = options.outputIsTTY ?? process.stdout.isTTY === true;\n return {\n format,\n interactive: format === \"pretty\" && !ci && inputIsTTY && outputIsTTY,\n color: format === \"pretty\" && outputIsTTY && !readEnvironment(env, \"NO_COLOR\"),\n };\n}\n\nexport interface UsagePrintEvent {\n type: \"usage\";\n usage: UsageSummary;\n text: string;\n stream: PrintStream;\n}\n\nexport interface VersionPrintEvent {\n type: \"version\";\n version: string;\n}\n\nexport interface ErrorPrintEvent {\n type: \"error\";\n error: HackshErrorSummary;\n}\n\nexport interface LogPrintEvent {\n type: \"log\";\n record: LogRecord;\n}\n\nexport interface PromptChoiceState {\n value: string;\n label: string;\n hint?: string;\n selected: boolean;\n}\n\nexport type PromptStatus = \"active\" | \"error\" | \"submitted\" | \"closed\";\n\ninterface PromptStateBase {\n message: string;\n status: PromptStatus;\n error?: string;\n}\n\nexport interface SelectPromptState extends PromptStateBase {\n kind: \"select\";\n choices: readonly PromptChoiceState[];\n value: string;\n}\n\nexport interface ConfirmPromptState extends PromptStateBase {\n kind: \"confirm\";\n value: boolean;\n defaultValue?: boolean;\n}\n\nexport interface TextPromptState extends PromptStateBase {\n kind: \"text\";\n value: string;\n placeholder?: string;\n}\n\nexport type PromptState = SelectPromptState | ConfirmPromptState | TextPromptState;\n\nexport interface PromptPrintEvent {\n type: \"prompt\";\n prompt: PromptState;\n}\n\nexport interface ExecPrintEvent {\n type: \"exec\";\n phase: \"start\" | \"skip\";\n command: Omit<ExecCommand, \"cwd\"> & { cwd?: string };\n stdio: {\n stdin: \"ignore\" | \"input\" | \"inherit\";\n stdout: \"pipe\" | \"inherit\";\n stderr: \"pipe\" | \"inherit\";\n };\n interactive: boolean;\n}\n\n/** A semantic, command- and schema-free output value emitted by hacksh. */\nexport type PrintEvent =\n | UsagePrintEvent\n | VersionPrintEvent\n | ErrorPrintEvent\n | LogPrintEvent\n | PromptPrintEvent\n | ExecPrintEvent;\n\n/** Receives every output event produced by one command invocation. */\nexport interface Printer {\n print(event: PrintEvent): void | Promise<void>;\n}\n\nfunction isErrorLevel(level: LogRecord[\"level\"]): boolean {\n return level === \"warning\" || level === \"error\" || level === \"fatal\";\n}\n\nexport function eventStream(event: PrintEvent): PrintStream {\n if (event.type === \"error\" || event.type === \"exec\") return \"stderr\";\n if (event.type === \"usage\") return event.stream;\n if (event.type === \"log\" && isErrorLevel(event.record.level)) return \"stderr\";\n return \"stdout\";\n}\n\nfunction formatTextEvent(event: PrintEvent): string {\n switch (event.type) {\n case \"usage\":\n return event.text;\n case \"version\":\n return event.version;\n case \"error\":\n return event.error.kind === \"usage\" || event.error.kind === \"validation\"\n ? event.error.message\n : `Error: ${event.error.message}`;\n case \"log\":\n return event.record.message;\n case \"prompt\":\n return event.prompt.message;\n case \"exec\":\n return `${event.phase === \"skip\" ? \"#\" : \"$\"} ${formatExecCommand(event.command)}`;\n }\n}\n\n/** Undecorated console compatibility adapter; automatic output uses the selected format printer. */\nexport const consolePrinter: Printer = {\n print(event) {\n const text = formatTextEvent(event);\n return eventStream(event) === \"stdout\" ? console.log(text) : console.error(text);\n },\n};\n\nexport interface OutputWriter {\n write(text: string): unknown;\n}\n\nexport interface TerminalInput {\n readonly isTTY?: boolean;\n readonly isRaw?: boolean;\n readonly readableFlowing?: boolean | null;\n setRawMode?(mode: boolean): unknown;\n resume(): unknown;\n pause(): unknown;\n on(event: string, listener: (...args: never[]) => void): unknown;\n removeListener(event: string, listener: (...args: never[]) => void): unknown;\n}\n\nexport interface TerminalOutput extends OutputWriter {\n readonly isTTY?: boolean;\n readonly columns?: number;\n}\n\nexport interface JsonPrinterOptions {\n stdout?: OutputWriter;\n stderr?: OutputWriter;\n}\n\nexport interface StreamPrinterOptions {\n stdout: OutputWriter;\n stderr: OutputWriter;\n}\n\n/** Create an undecorated stream-backed compatibility adapter. */\nexport function createStreamPrinter(options: StreamPrinterOptions): Printer {\n return {\n print(event) {\n const writer = eventStream(event) === \"stdout\" ? options.stdout : options.stderr;\n writer.write(`${formatTextEvent(event)}\\n`);\n },\n };\n}\n\n/** Create a one-semantic-event-per-line JSON printer. */\nexport function createJsonPrinter(options: JsonPrinterOptions = {}): Printer {\n const stdout = options.stdout ?? process.stdout;\n const stderr = options.stderr ?? process.stderr;\n return {\n print(event) {\n let serialized: string;\n try {\n serialized = JSON.stringify(normalizeJson(event));\n } catch {\n serialized = JSON.stringify({\n type: event.type,\n serializationError: \"Event data could not be serialized\",\n });\n }\n const line = `${serialized}\\n`;\n (eventStream(event) === \"stdout\" ? stdout : stderr).write(line);\n },\n };\n}\n\nexport interface PrintQueue {\n printer: Printer;\n printChecked(event: PrintEvent): Promise<void>;\n drain(): Promise<void>;\n}\n\n/** Serialize printer calls and retain failures until the invocation drains its output. */\nexport function createPrintQueue(target: Printer): PrintQueue {\n let pending: Promise<void> | undefined;\n let failure: unknown;\n let failed = false;\n\n function recordFailure(error: unknown): void {\n if (!failed) failure = error;\n failed = true;\n }\n\n function track(execution: Promise<void>, retainFailure: boolean): Promise<void> {\n const barrier = execution.catch((error: unknown) => {\n if (retainFailure) recordFailure(error);\n });\n pending = barrier;\n void barrier.then(() => {\n if (pending === barrier) pending = undefined;\n });\n return retainFailure ? barrier : execution;\n }\n\n function enqueue(event: PrintEvent, retainFailure: boolean): void | Promise<void> {\n if (pending)\n return track(\n pending.then(() => target.print(event)),\n retainFailure,\n );\n try {\n const result = target.print(event);\n if (result) return track(Promise.resolve(result), retainFailure);\n } catch (error) {\n if (retainFailure) recordFailure(error);\n else return Promise.reject(error);\n }\n }\n\n const printer: Printer = {\n print(event) {\n return enqueue(event, true);\n },\n };\n\n return {\n printer,\n async printChecked(event) {\n await enqueue(event, false);\n },\n async drain() {\n await pending;\n if (failed) throw failure;\n },\n };\n}\n","import { inspect, stripVTControlCharacters, styleText } from \"node:util\";\nimport type { HackshErrorSummary } from \"./errors.ts\";\nimport { formatExecCommand } from \"./exec.ts\";\nimport type { LogLevel, LogRecord } from \"./logger.ts\";\nimport {\n eventStream,\n type OutputWriter,\n type Printer,\n type PrintEvent,\n type TerminalOutput,\n} from \"./printer.ts\";\n\ntype PrettyMark =\n | LogLevel\n | \"step\"\n | \"success\"\n | \"usage\"\n | \"version\"\n | \"errorEvent\"\n | \"prompt\"\n | \"exec\"\n | \"execSkip\";\ntype TextStyle = Parameters<typeof styleText>[0];\n\ninterface PrettySymbols {\n bar: string;\n marks: Record<PrettyMark, string>;\n}\n\nconst unicodeSymbols: PrettySymbols = {\n bar: \"│\",\n marks: {\n trace: \"·\",\n debug: \"◆\",\n info: \"●\",\n warning: \"▲\",\n error: \"■\",\n fatal: \"✖\",\n step: \"◇\",\n success: \"✔\",\n usage: \"◆\",\n version: \"●\",\n errorEvent: \"■\",\n prompt: \"?\",\n exec: \"$\",\n execSkip: \"#\",\n },\n};\n\nconst asciiSymbols: PrettySymbols = {\n bar: \"|\",\n marks: {\n trace: \".\",\n debug: \":\",\n info: \"i\",\n warning: \"!\",\n error: \"x\",\n fatal: \"X\",\n step: \">\",\n success: \"+\",\n usage: \"?\",\n version: \"i\",\n errorEvent: \"x\",\n prompt: \"?\",\n exec: \"$\",\n execSkip: \"#\",\n },\n};\n\nconst markStyles: Record<PrettyMark, TextStyle> = {\n trace: \"gray\",\n debug: \"magenta\",\n info: \"blue\",\n warning: \"yellow\",\n error: \"red\",\n fatal: [\"bgRed\", \"white\", \"bold\"],\n step: \"cyan\",\n success: \"green\",\n usage: \"cyan\",\n version: \"blue\",\n errorEvent: \"red\",\n prompt: \"cyan\",\n exec: \"gray\",\n execSkip: \"gray\",\n};\n\nexport interface PrettyPrinterOptions {\n color: boolean;\n unicode: boolean;\n stdout?: TerminalOutput;\n stderr?: OutputWriter;\n}\n\nfunction safelyInspect(value: unknown): string {\n if (typeof value === \"string\") return value;\n try {\n return inspect(value, {\n breakLength: 80,\n colors: false,\n compact: false,\n depth: null,\n sorted: true,\n });\n } catch {\n return \"[Unserializable]\";\n }\n}\n\nfunction propertyLines(properties: Readonly<Record<string, unknown>>): string[] {\n const lines: string[] = [];\n for (const key of Object.keys(properties).sort()) {\n const rendered = ` ${key}: ${safelyInspect(properties[key])}`.split(\"\\n\");\n lines.push(rendered[0] ?? \"\");\n for (const continuation of rendered.slice(1)) lines.push(` ${continuation}`);\n }\n return lines;\n}\n\nfunction logLines(record: LogRecord): string[] {\n const category = record.category.length > 0 ? `[${record.category.join(\":\")}] ` : \"\";\n const message = record.message.split(\"\\n\");\n return [\n `${category}${message[0] ?? \"\"}`,\n ...message.slice(1),\n ...propertyLines(record.properties),\n ];\n}\n\nfunction errorLines(error: HackshErrorSummary): string[] {\n const lines = error.message.split(\"\\n\");\n const details: Record<string, unknown> = {};\n if (error.cause !== undefined) details.cause = error.cause;\n if (error.properties !== undefined) Object.assign(details, error.properties);\n if (error.value !== undefined) details.value = error.value;\n return [...lines, ...propertyLines(details)];\n}\n\nfunction eventMark(event: PrintEvent): PrettyMark {\n if (event.type === \"usage\") return \"usage\";\n if (event.type === \"version\") return \"version\";\n if (event.type === \"error\") return \"errorEvent\";\n if (event.type === \"prompt\") return event.prompt.status === \"submitted\" ? \"success\" : \"prompt\";\n if (event.type === \"exec\") return event.phase === \"skip\" ? \"execSkip\" : \"exec\";\n return event.record.kind === \"message\" ? event.record.level : event.record.kind;\n}\n\nfunction eventLines(event: PrintEvent): string[] {\n switch (event.type) {\n case \"usage\":\n return event.text.split(\"\\n\");\n case \"version\":\n return event.version.split(\"\\n\");\n case \"error\":\n return errorLines(event.error);\n case \"log\":\n return logLines(event.record);\n case \"prompt\": {\n const { prompt } = event;\n if (prompt.status === \"submitted\") {\n const result =\n prompt.kind === \"select\"\n ? (prompt.choices.find(({ value }) => value === prompt.value)?.label ?? prompt.value)\n : prompt.kind === \"confirm\"\n ? prompt.value\n ? \"Yes\"\n : \"No\"\n : prompt.value;\n return [`${prompt.message}: ${result}`];\n }\n const lines = [prompt.message];\n if (prompt.kind === \"select\") {\n for (const choice of prompt.choices) {\n lines.push(\n `${choice.selected ? \">\" : \" \"} ${choice.label}${choice.hint ? ` — ${choice.hint}` : \"\"}`,\n );\n }\n } else if (prompt.kind === \"confirm\") {\n lines.push(\n `${prompt.value ? \"Yes\" : \"No\"}${prompt.defaultValue === undefined ? \"\" : ` (default: ${prompt.defaultValue ? \"yes\" : \"no\"})`}`,\n );\n } else {\n lines.push(prompt.value || (prompt.placeholder ? `(${prompt.placeholder})` : \"\"));\n }\n if (prompt.error) lines.push(prompt.error);\n return lines;\n }\n case \"exec\": {\n const lines = [formatExecCommand(event.command)];\n if (event.command.cwd !== undefined) lines.push(...propertyLines({ cwd: event.command.cwd }));\n return lines;\n }\n }\n}\n\nfunction colorize(enabled: boolean, style: TextStyle, text: string): string {\n return enabled ? styleText(style, text, { validateStream: false }) : text;\n}\n\nconst graphemeSegmenter = new Intl.Segmenter(undefined, { granularity: \"grapheme\" });\nconst combiningMark = /\\p{Mark}/u;\nconst pictograph = /\\p{Extended_Pictographic}/u;\n\nfunction isWideCodePoint(codePoint: number): boolean {\n return (\n codePoint >= 0x1100 &&\n (codePoint <= 0x115f ||\n codePoint === 0x2329 ||\n codePoint === 0x232a ||\n (codePoint >= 0x2e80 && codePoint <= 0xa4cf && codePoint !== 0x303f) ||\n (codePoint >= 0xac00 && codePoint <= 0xd7a3) ||\n (codePoint >= 0xf900 && codePoint <= 0xfaff) ||\n (codePoint >= 0xfe10 && codePoint <= 0xfe19) ||\n (codePoint >= 0xfe30 && codePoint <= 0xfe6f) ||\n (codePoint >= 0xff00 && codePoint <= 0xff60) ||\n (codePoint >= 0xffe0 && codePoint <= 0xffe6) ||\n (codePoint >= 0x20000 && codePoint <= 0x3fffd))\n );\n}\n\nfunction displayWidth(text: string): number {\n let width = 0;\n for (const { segment } of graphemeSegmenter.segment(stripVTControlCharacters(text))) {\n if (segment === \"\\t\") {\n width += 8 - (width % 8);\n continue;\n }\n if (\n pictograph.test(segment) ||\n Array.from(segment).some((value) => isWideCodePoint(value.codePointAt(0)!))\n ) {\n width += 2;\n continue;\n }\n for (const value of segment) {\n const codePoint = value.codePointAt(0)!;\n if (codePoint < 0x20 || (codePoint >= 0x7f && codePoint < 0xa0)) continue;\n if (codePoint === 0x200d || (codePoint >= 0xfe00 && codePoint <= 0xfe0f)) continue;\n if (!combiningMark.test(value)) width += 1;\n }\n }\n return width;\n}\n\nfunction renderedRows(rendered: string, columns: number | undefined): number {\n const width =\n Number.isInteger(columns) && columns !== undefined && columns > 0 ? columns : undefined;\n return rendered.split(\"\\n\").reduce((rows, line) => {\n if (!width) return rows + 1;\n return rows + Math.max(1, Math.ceil(displayWidth(line) / width));\n }, 0);\n}\n\n/** Create the fixed human-readable renderer used for pretty output. */\nexport function createPrettyPrinter(options: PrettyPrinterOptions): Printer {\n const stdout = options.stdout ?? process.stdout;\n const stderr = options.stderr ?? process.stderr;\n const symbols = options.unicode ? unicodeSymbols : asciiSymbols;\n let activePrompt: { rendered: string; lines: number } | undefined;\n\n function render(event: PrintEvent): string {\n const mark = eventMark(event);\n const lines = eventLines(event);\n const firstPrefix = colorize(options.color, markStyles[mark], symbols.marks[mark]);\n const barPrefix = colorize(options.color, \"gray\", symbols.bar);\n return lines\n .map((line, index) => `${index === 0 ? firstPrefix : barPrefix}${line ? ` ${line}` : \"\"}`)\n .join(\"\\n\");\n }\n\n function eraseActivePrompt(): string {\n return activePrompt ? \"\\u001b[1A\\u001b[2K\".repeat(activePrompt.lines) : \"\";\n }\n\n return {\n print(event) {\n const rendered = render(event);\n if (event.type === \"prompt\") {\n const erase = eraseActivePrompt();\n if (event.prompt.status === \"closed\") {\n activePrompt = undefined;\n if (erase) stdout.write(erase);\n return;\n }\n if (event.prompt.status === \"submitted\") activePrompt = undefined;\n else activePrompt = { rendered, lines: renderedRows(rendered, stdout.columns) };\n stdout.write(`${erase}${rendered}\\n`);\n return;\n }\n\n const erase = eraseActivePrompt();\n if (!activePrompt) {\n (eventStream(event) === \"stdout\" ? stdout : stderr).write(`${rendered}\\n`);\n return;\n }\n\n stdout.write(erase);\n if (event.type === \"error\") activePrompt = undefined;\n (eventStream(event) === \"stdout\" ? stdout : stderr).write(`${rendered}\\n`);\n if (activePrompt) stdout.write(`${activePrompt.rendered}\\n`);\n },\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 type { Printer, TerminalInput } from \"./printer.ts\";\nimport { summarizeErrors } from \"./errors.ts\";\nimport type { Prompter } from \"./prompts.ts\";\nimport { PromptController } from \"./prompts.ts\";\nimport type { TerminalLock } from \"./terminal.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 extends Prompter {\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 prompts: PromptController,\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 select: (options) => prompts.select(options),\n confirm: (options) => prompts.confirm(options),\n text: (options) => prompts.text(options),\n with: (properties) =>\n createBoundLogger(printer, category, { ...boundProperties, ...properties }, prompts),\n getChild: (child) => createBoundLogger(printer, [...category, child], boundProperties, prompts),\n };\n}\n\nexport interface CreateLoggerOptions {\n interactive: boolean;\n input: TerminalInput;\n printPrompt(event: Parameters<Printer[\"print\"]>[0]): Promise<void>;\n terminal: TerminalLock;\n signal: AbortSignal;\n}\n\n/** Create the logger for one command invocation. */\nexport function createLogger(\n printer: Printer,\n category: readonly string[],\n options: CreateLoggerOptions,\n): Logger {\n const prompts = new PromptController({\n interactive: options.interactive,\n input: options.input,\n print: (event) => options.printPrompt(event),\n terminal: options.terminal,\n signal: options.signal,\n });\n return createBoundLogger(printer, [...category], {}, prompts);\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 { createPrettyPrinter } from \"./pretty.ts\";\nimport {\n createJsonPrinter,\n resolveOutputMode,\n type OutputMode,\n type OutputPreference,\n type OutputWriter,\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?: OutputWriter;\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 });\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 { selectOutputPrinter, type OutputOptions } from \"./output.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 argOptions = command.argOptions?.[key];\n const aliases = argOptions?.alias\n ? aliasList(argOptions.alias).map((item) => `-${item}`)\n : [];\n const name = kebabCase(key);\n const valueName = argOptions?.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 type UsageWriter = (text: string) => void | Promise<void>;\n\nexport interface ShowUsageOptions extends OutputOptions {\n write?: UsageWriter;\n printer?: Printer;\n stream?: PrintStream;\n}\n\nexport type UsageOutput = Required<Pick<ShowUsageOptions, \"write\">>;\n\nexport type ShowUsageCallback = (\n command: AnyCommandDef,\n output: UsageOutput,\n) => void | Promise<void>;\n\n/** Generate usage text without writing to stdout or stderr. */\nexport async function renderUsage(command: AnyCommandDef): Promise<string> {\n return formatUsage(summarizeUsage(command));\n}\n\n/** Generate and write usage text, awaiting asynchronous writers. */\nexport async function showUsage(\n command: AnyCommandDef,\n options: ShowUsageOptions = {},\n): Promise<void> {\n const usage = summarizeUsage(command);\n const text = formatUsage(usage);\n if (options.write) return options.write(text);\n const printer = options.printer ?? selectOutputPrinter(options);\n return printer.print({\n type: \"usage\",\n usage,\n text,\n stream: options.stream ?? \"stdout\",\n });\n}\n","import { schemaShape, 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 { 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 PrintStream,\n type TerminalInput,\n} from \"./printer.ts\";\nimport { TerminalLock } from \"./terminal.ts\";\nimport { selectOutputPrinter, type OutputOptions } from \"./output.ts\";\nimport { showUsage, summarizeUsage, type ShowUsageCallback } 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 displayUsage: ShowUsageCallback,\n output: PreparedOutput,\n env: ExecContext[\"env\"],\n signal: AbortSignal,\n fallbackVersion: () => Promise<string | undefined> = async () => undefined,\n): Promise<unknown> {\n if (root.args && \"version\" in schemaShape(root.args)) {\n throw new TypeError(\"Root option `version` conflicts with the builtin --version\");\n }\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 printUsage(displayUsage, resolved.command, printer, \"stdout\");\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 ...parsed,\n cmd: resolved.command,\n rawArgs: resolved.rawArgs,\n logger: createLogger(printer, category, {\n interactive: output.interactive,\n input: output.input,\n printPrompt: (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\nfunction printUsage(\n displayUsage: ShowUsageCallback,\n command: AnyCommandDef,\n printer: Printer,\n stream: PrintStream,\n): void | Promise<void> {\n return displayUsage(command, {\n write: (text) => printer.print({ type: \"usage\", usage: summarizeUsage(command), text, stream }),\n });\n}\n\nexport interface RunCommandOptions extends OutputOptions {\n printer?: Printer;\n signal?: AbortSignal;\n showUsage?: ShowUsageCallback;\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 });\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\nexport async function runCommand<S extends ArgsSchema>(\n root: CommandDef<S>,\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 options.showUsage ?? showUsage,\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 showUsage?: ShowUsageCallback;\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(\n error: unknown,\n output: PrintQueue,\n displayUsage: ShowUsageCallback,\n): 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 printUsage(displayUsage, error.command, output.printer, \"stderr\");\n }\n}\n\nexport async function runMain<S extends ArgsSchema>(\n command: CommandDef<S>,\n options: RunMainOptions = {},\n): Promise<void> {\n const displayUsage = options.showUsage ?? showUsage;\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 displayUsage,\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, displayUsage);\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\nexport function createMain<S extends ArgsSchema>(\n command: CommandDef<S>,\n options: RunMainOptions = {},\n): (argv?: string[]) => Promise<void> {\n return (argv) => runMain(command, argv === undefined ? options : { ...options, argv });\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;ACyBA,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;CAEJ,OAAO,SAAS;EACd,MAAM,WAAW,eAAe,IAAI,OAAO;EAC3C,gBAAgB,UAAU;EAC1B,UAAU,UAAU;EAEpB,MAAM,MAAM,WAAW,OAAO;EAC9B,IAAI,IAAI,SAAS,cAAc,IAAI,SAAS,aAAa,IAAI,SAAS,YACpE,WAAW;EAEb,IAAI,IAAI,SAAS,aAAa,iBAAiB,KAAA,GAAW,eAAe,IAAI;EAC7E,UAAU,YAAY,GAAG;CAC3B;CAEA,MAAM,OAAO,YAAY,MAAM;CAC/B,OAAO;EACL,YAAY,WAAW,IAAI,CAAC,CAAC,SAAS;EACtC;EACA;EACA;EACA;EACA,SAAS,YAAY,IAAI;CAC3B;AACF;;AAGA,SAAgB,gBA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U;EAAE,GAAG;EAAS;CAAK,CAAC;AACvF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "hacksh",
3
- "version": "0.12.0",
3
+ "version": "0.13.0",
4
4
  "description": "Type-safe command-line interfaces powered by Zod 4 schemas.",
5
5
  "keywords": [
6
6
  "cli",