cli-kiss 0.2.8 → 0.2.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/lib/Typo.ts","../src/lib/Suggest.ts","../src/lib/Command.ts","../src/lib/Operation.ts","../src/lib/Type.ts","../src/lib/Option.ts","../src/lib/Positional.ts","../src/lib/Reader.ts","../src/lib/Usage.ts","../src/lib/Run.ts"],"sourcesContent":["export * from \"./lib/Command\";\nexport * from \"./lib/Operation\";\nexport * from \"./lib/Option\";\nexport * from \"./lib/Positional\";\nexport * from \"./lib/Reader\";\nexport * from \"./lib/Run\";\nexport * from \"./lib/Suggest\";\nexport * from \"./lib/Type\";\nexport * from \"./lib/Typo\";\nexport * from \"./lib/Usage\";\n","/**\n * Color names for terminal styling, used by {@link TypoStyle}.\n * `dark*` = standard ANSI (30–37); `bright*` = high-intensity (90–97).\n */\nexport type TypoColor =\n | \"darkBlack\"\n | \"darkRed\"\n | \"darkGreen\"\n | \"darkYellow\"\n | \"darkBlue\"\n | \"darkMagenta\"\n | \"darkCyan\"\n | \"darkWhite\"\n | \"brightBlack\"\n | \"brightRed\"\n | \"brightGreen\"\n | \"brightYellow\"\n | \"brightBlue\"\n | \"brightMagenta\"\n | \"brightCyan\"\n | \"brightWhite\";\n\n/**\n * Visual styling applied by a {@link TypoSupport} instance.\n * All fields are optional; ignored entirely in `\"none\"` mode.\n */\nexport type TypoStyle = {\n /**\n * Letter case.\n */\n case?: \"upper\" | \"lower\";\n /**\n * Foreground (text) color.\n */\n fgColor?: TypoColor;\n /**\n * Background color.\n */\n bgColor?: TypoColor;\n /**\n * Reduced intensity.\n */\n dim?: boolean;\n /**\n * Bold.\n */\n bold?: boolean;\n /**\n * Italic.\n */\n italic?: boolean;\n /**\n * Underline.\n */\n underline?: boolean;\n /**\n * Strikethrough.\n */\n strikethrough?: boolean;\n};\n\n/**\n * Section title style. Bold dark-green.\n */\nexport const typoStyleTitle: TypoStyle = {\n fgColor: \"darkGreen\",\n bold: true,\n};\n/**\n * Logic/type identifier style. Bold dark-magenta.\n */\nexport const typoStyleLogic: TypoStyle = {\n fgColor: \"darkMagenta\",\n bold: true,\n};\n/**\n * Quoted user-input style. Bold dark-yellow.\n */\nexport const typoStyleQuote: TypoStyle = {\n fgColor: \"darkYellow\",\n bold: true,\n};\n\n/**\n * Error label style. Bold dark-red.\n */\nexport const typoStyleFailure: TypoStyle = {\n fgColor: \"darkRed\",\n bold: true,\n};\n\n/**\n * Option/command name style. Bold dark-cyan.\n */\nexport const typoStyleConstants: TypoStyle = {\n fgColor: \"darkCyan\",\n bold: true,\n};\n/**\n * Positional/user-input label style. Bold dark-blue.\n */\nexport const typoStyleUserInput: TypoStyle = {\n fgColor: \"darkBlue\",\n bold: true,\n};\n\n/**\n * Strong text style. Bold.\n */\nexport const typoStyleRegularStrong: TypoStyle = {\n bold: true,\n};\n/**\n * Subtle text style. Italic and dim.\n */\nexport const typoStyleRegularWeaker: TypoStyle = {\n italic: true,\n dim: true,\n};\n\n/**\n * Immutable styled string segment. Compose into a {@link TypoText}.\n */\nexport class TypoString {\n #value: string;\n #style: TypoStyle | undefined;\n /**\n * @param value - Raw text content.\n * @param style - Style to apply when rendering.\n */\n constructor(value: string, style?: TypoStyle) {\n this.#value = value;\n this.#style = style;\n }\n /**\n * Returns the text styled by `typoSupport`.\n *\n * @param typoSupport - Rendering mode.\n */\n computeStyledString(typoSupport: TypoSupport): string {\n return typoSupport.computeStyledString(this.#value, this.#style);\n }\n /**\n * Returns the raw text.\n */\n getRawString(): string {\n // TODO - should there be a global config or smthg instead of passing support everywhere?\n return this.#value;\n }\n /**\n * Predefined ellipsis segment with subtle styling.\n */\n static elipsis = new TypoString(\"...\", typoStyleRegularWeaker);\n}\n\n/**\n * A segment of styled text, a string, or an array of segments.\n */\nexport type TypoSegment = TypoText | TypoString | Array<TypoSegment>;\n\n/**\n * Mutable sequence of {@link TypoString} segments.\n */\nexport class TypoText {\n #strings: Array<TypoString>;\n /**\n * @param segments - Initial text segments\n */\n constructor(...segments: Array<TypoSegment>) {\n this.#strings = [];\n for (const segment of segments) {\n this.push(segment);\n }\n }\n /**\n * Appends new text segment(s).\n */\n push(...segments: Array<TypoSegment>): void {\n for (const segment of segments) {\n if (typeof segment === \"string\") {\n this.#strings.push(new TypoString(segment));\n } else if (segment instanceof TypoString) {\n this.#strings.push(segment);\n } else if (segment instanceof TypoText) {\n this.#strings.push(...segment.#strings);\n } else if (Array.isArray(segment)) {\n for (const part of segment) {\n this.push(part);\n }\n }\n }\n }\n /**\n * Appends separated segments, optionally truncating with an ellipsis.\n */\n pushJoined(\n segments: Array<TypoSegment>,\n separator: TypoSegment,\n ellipsisLimit: number,\n ): void {\n for (let index = 0; index < segments.length; index++) {\n if (index > 0) {\n this.push(separator);\n }\n if (ellipsisLimit !== undefined && index >= ellipsisLimit) {\n this.push(TypoString.elipsis);\n break;\n }\n this.push(segments[index]!);\n }\n }\n /**\n * Renders all segments into a single styled string.\n *\n * @param typoSupport - Rendering mode.\n * @returns Concatenated styled string.\n */\n computeStyledString(typoSupport: TypoSupport): string {\n return this.#strings\n .map((t) => t.computeStyledString(typoSupport))\n .join(\"\");\n }\n /**\n * Returns the concatenated raw text.\n */\n computeRawString(): string {\n return this.#strings.map((t) => t.getRawString()).join(\"\");\n }\n /**\n * Returns the total raw character count.\n */\n computeRawLength(): number {\n let length = 0;\n for (const typoString of this.#strings) {\n length += typoString.getRawString().length;\n }\n return length;\n }\n}\n\n/**\n * Column-aligned grid of {@link TypoText} cells.\n * Each column is padded to the widest cell (raw chars); the last column is not padded.\n */\nexport class TypoGrid {\n #typoRows: Array<Array<TypoText>>;\n constructor() {\n this.#typoRows = [];\n }\n /**\n * Appends a row. All rows should have the same cell count.\n *\n * @param cells - Ordered {@link TypoText} cells.\n */\n pushRow(cells: Array<TypoText>) {\n this.#typoRows.push(cells);\n }\n /**\n * Renders as an array of styled, column-padded strings.\n *\n * @param typoSupport - Rendering mode.\n * @returns Array of styled strings.\n */\n computeStyledLines(typoSupport: TypoSupport): Array<string> {\n const widths = new Array<number>();\n const styledLines = new Array<string>();\n for (const typoGridRow of this.#typoRows) {\n for (\n let typoGridColumnIndex = 0;\n typoGridColumnIndex < typoGridRow.length;\n typoGridColumnIndex++\n ) {\n const typoGridCell = typoGridRow[typoGridColumnIndex]!;\n const width = typoGridCell.computeRawLength();\n if (\n widths[typoGridColumnIndex] === undefined ||\n width > widths[typoGridColumnIndex]!\n ) {\n widths[typoGridColumnIndex] = width;\n }\n }\n }\n for (const typoGridRow of this.#typoRows) {\n const styledGridRow = new Array<string>();\n for (\n let typoGridColumnIndex = 0;\n typoGridColumnIndex < typoGridRow.length;\n typoGridColumnIndex++\n ) {\n const typoGridCell = typoGridRow[typoGridColumnIndex]!;\n styledGridRow.push(typoGridCell.computeStyledString(typoSupport));\n if (typoGridColumnIndex < typoGridRow.length - 1) {\n const width = typoGridCell.computeRawLength();\n const padding = \" \".repeat(widths[typoGridColumnIndex]! - width);\n styledGridRow.push(padding);\n }\n }\n styledLines.push(styledGridRow.join(\"\"));\n }\n return styledLines;\n }\n}\n\n/**\n * `Error` subclass with a {@link TypoText} styled message for rich terminal output.\n * Chains `TypoError` sources after `\": \"`.\n */\nexport class TypoError extends Error {\n #typoText: TypoText;\n /**\n * @param currentTypoText - Styled message for this error.\n * @param source - Optional cause; `TypoError` chains styled text, `Error` appends `.message`, else `String()`.\n */\n constructor(currentTypoText: TypoText, source?: unknown) {\n const typoText = new TypoText();\n typoText.push(currentTypoText);\n if (source instanceof TypoError) {\n typoText.push(new TypoString(\": \"));\n typoText.push(source.#typoText);\n } else if (source instanceof Error) {\n typoText.push(new TypoString(`: ${source.message}`));\n } else if (source !== undefined) {\n typoText.push(new TypoString(`: ${String(source)}`));\n }\n super(typoText.computeRawString());\n this.#typoText = typoText;\n }\n /**\n * Renders the styled message (without `\"Error:\"` prefix).\n *\n * @param typoSupport - Rendering mode.\n * @returns Styled error string.\n */\n computeStyledString(typoSupport: TypoSupport): string {\n return this.#typoText.computeStyledString(typoSupport);\n }\n /**\n * Runs `thrower`; wraps any thrown error as a `TypoError` with `context()` prepended.\n *\n * @typeParam Value - Return type of `thrower`.\n * @param thrower - Function to execute; result passed through on success.\n * @param context - Produces the {@link TypoText} prepended to the caught error.\n * @returns Value from `thrower`.\n * @throws `TypoError` wrapping the original error with context prepended.\n */\n static tryWithContext<Value>(\n thrower: () => Value,\n context: () => TypoText,\n ): Value {\n try {\n return thrower();\n } catch (error) {\n throw new TypoError(context(), error);\n }\n }\n}\n\n/**\n * Controls ANSI terminal styling. Create via the static factory methods.\n */\nexport class TypoSupport {\n #kind: TypoSupportKind;\n private constructor(kind: TypoSupportKind) {\n this.#kind = kind;\n }\n /**\n * Plain text — no ANSI codes.\n */\n static none(): TypoSupport {\n return new TypoSupport(\"none\");\n }\n /**\n * ANSI escape codes for color terminals.\n */\n static tty(): TypoSupport {\n return new TypoSupport(\"tty\");\n }\n /**\n * Deterministic textual styling for snapshot tests.\n */\n static mock(): TypoSupport {\n return new TypoSupport(\"mock\");\n }\n /**\n * Auto-detects styling mode from the process environment on best-effort basis.\n */\n static inferFromEnv(): TypoSupport {\n if (!process || !process.env || !process.stdout) {\n return TypoSupport.none();\n }\n if (readEnvVar(\"NO_COLOR\")) {\n return TypoSupport.none();\n }\n const envForceColor = readEnvVar(\"FORCE_COLOR\");\n if (envForceColor === \"0\") {\n return TypoSupport.none();\n }\n if (envForceColor === \"1\") {\n return TypoSupport.tty();\n }\n if (envForceColor === \"2\") {\n return TypoSupport.tty();\n }\n if (envForceColor === \"3\") {\n return TypoSupport.tty(); // TODO - should there be fancy colors possible?\n }\n if (envForceColor) {\n return TypoSupport.tty();\n }\n if (!process.stdout.isTTY) {\n return TypoSupport.none();\n }\n if (readEnvVar(\"TERM\")?.toLowerCase() === \"dumb\") {\n return TypoSupport.none();\n }\n return TypoSupport.tty();\n }\n /**\n * Applies `typoStyle` to `value` according to the current mode.\n *\n * @param value - Raw text.\n * @param typoStyle - Style to apply.\n * @returns Styled string.\n */\n computeStyledString(value: string, typoStyle: TypoStyle | undefined): string {\n if (typoStyle === undefined) {\n return value;\n }\n let styledValue = value;\n if (typoStyle.case === \"upper\") {\n styledValue = styledValue.toUpperCase();\n }\n if (typoStyle.case === \"lower\") {\n styledValue = styledValue.toLowerCase();\n }\n if (this.#kind === \"none\") {\n return styledValue;\n }\n if (this.#kind === \"tty\") {\n const fgColorCode = typoStyle.fgColor\n ? ttyCodeFgColors[typoStyle.fgColor]\n : \"\";\n const bgColorCode = typoStyle.bgColor\n ? ttyCodeBgColors[typoStyle.bgColor]\n : \"\";\n const boldCode = typoStyle.bold ? ttyCodeBold : \"\";\n const dimCode = typoStyle.dim ? ttyCodeDim : \"\";\n const italicCode = typoStyle.italic ? ttyCodeItalic : \"\";\n const underlineCode = typoStyle.underline ? ttyCodeUnderline : \"\";\n const strikethroughCode = typoStyle.strikethrough\n ? ttyCodeStrikethrough\n : \"\";\n return `${fgColorCode}${bgColorCode}${boldCode}${dimCode}${italicCode}${underlineCode}${strikethroughCode}${styledValue}${ttyCodeReset}`;\n }\n if (this.#kind === \"mock\") {\n const fgColorPart = typoStyle.fgColor\n ? `{${styledValue}}@${typoStyle.fgColor}`\n : styledValue;\n const bgColorPart = typoStyle.bgColor\n ? `{${fgColorPart}}#${typoStyle.bgColor}`\n : fgColorPart;\n const boldPart = typoStyle.bold ? `{${bgColorPart}}+` : bgColorPart;\n const dimPart = typoStyle.dim ? `{${boldPart}}-` : boldPart;\n const italicPart = typoStyle.italic ? `{${dimPart}}*` : dimPart;\n const underlinePart = typoStyle.underline\n ? `{${italicPart}}_`\n : italicPart;\n const strikethroughPart = typoStyle.strikethrough\n ? `{${underlinePart}}~`\n : underlinePart;\n return strikethroughPart;\n }\n throw new Error(`Unknown TypoSupport kind: ${this.#kind}`);\n }\n /**\n * Formats any thrown value as `\"Error: <message>\"` with {@link typoStyleFailure} on the prefix.\n *\n * @param error - Any thrown value.\n * @returns Styled error string.\n */\n computeStyledErrorMessage(error: unknown): string {\n return [\n this.computeStyledString(\"Error:\", typoStyleFailure),\n error instanceof TypoError\n ? error.computeStyledString(this)\n : error instanceof Error\n ? error.message\n : String(error),\n ].join(\" \");\n }\n}\n\nconst ttyCodeReset = \"\\x1b[0m\";\nconst ttyCodeBold = \"\\x1b[1m\";\nconst ttyCodeDim = \"\\x1b[2m\";\nconst ttyCodeItalic = \"\\x1b[3m\";\nconst ttyCodeUnderline = \"\\x1b[4m\";\nconst ttyCodeStrikethrough = \"\\x1b[9m\";\nconst ttyCodeFgColors: Record<TypoColor, string> = {\n darkBlack: \"\\x1b[30m\",\n darkRed: \"\\x1b[31m\",\n darkGreen: \"\\x1b[32m\",\n darkYellow: \"\\x1b[33m\",\n darkBlue: \"\\x1b[34m\",\n darkMagenta: \"\\x1b[35m\",\n darkCyan: \"\\x1b[36m\",\n darkWhite: \"\\x1b[37m\",\n brightBlack: \"\\x1b[90m\",\n brightRed: \"\\x1b[91m\",\n brightGreen: \"\\x1b[92m\",\n brightYellow: \"\\x1b[93m\",\n brightBlue: \"\\x1b[94m\",\n brightMagenta: \"\\x1b[95m\",\n brightCyan: \"\\x1b[96m\",\n brightWhite: \"\\x1b[97m\",\n};\nconst ttyCodeBgColors: Record<TypoColor, string> = {\n darkBlack: \"\\x1b[40m\",\n darkRed: \"\\x1b[41m\",\n darkGreen: \"\\x1b[42m\",\n darkYellow: \"\\x1b[43m\",\n darkBlue: \"\\x1b[44m\",\n darkMagenta: \"\\x1b[45m\",\n darkCyan: \"\\x1b[46m\",\n darkWhite: \"\\x1b[47m\",\n brightBlack: \"\\x1b[100m\",\n brightRed: \"\\x1b[101m\",\n brightGreen: \"\\x1b[102m\",\n brightYellow: \"\\x1b[103m\",\n brightBlue: \"\\x1b[104m\",\n brightMagenta: \"\\x1b[105m\",\n brightCyan: \"\\x1b[106m\",\n brightWhite: \"\\x1b[107m\",\n};\n\nfunction readEnvVar(name: string) {\n if (!(name in process.env)) {\n return undefined;\n }\n return process.env[name];\n}\n\ntype TypoSupportKind = \"none\" | \"tty\" | \"mock\";\n","import { TypoSegment, TypoString, TypoText } from \"./Typo\";\n\nexport function suggestTextPushMessage(\n text: TypoText,\n query: string,\n candidates: Array<{ reference: string; hint: TypoSegment }>,\n) {\n const reasonableHints = suggestReasonablePayloads(\n query,\n candidates.map(({ reference, hint }) => ({ reference, payload: hint })),\n );\n if (reasonableHints.length === 0) {\n return;\n }\n text.push(new TypoString(\" Did you mean: \"));\n text.pushJoined(reasonableHints, new TypoString(\", \"), 3);\n text.push(new TypoString(` ?`));\n}\n\nfunction suggestReasonablePayloads<Payload>(\n query: string,\n candidates: Array<{ reference: string; payload: Payload }>,\n): Array<Payload> {\n if (candidates.length === 0) {\n return [];\n }\n const sortedAlternatives = computeAndSortByDivergences(query, candidates);\n const divergenceThreshold = sortedAlternatives[0]!.divergence + 0.25;\n const acceptablePayloads = new Array<Payload>();\n for (const { divergence, payload } of sortedAlternatives) {\n if (divergence > divergenceThreshold) {\n break;\n }\n acceptablePayloads.push(payload);\n }\n return acceptablePayloads;\n}\n\nfunction computeAndSortByDivergences<Payload>(\n query: string,\n candidates: Array<{ reference: string; payload: Payload }>,\n): Array<{ divergence: number; payload: Payload }> {\n const queryNormalized = query.toLowerCase().slice(0, 100);\n const scored = candidates.map(({ reference, payload }) => {\n const referenceNormalized = reference.toLowerCase().slice(0, 100);\n const divergence =\n distanceDamerauLevenshtein(queryNormalized, referenceNormalized) /\n Math.max(queryNormalized.length, referenceNormalized.length);\n return { divergence, reference, payload };\n });\n return scored.sort((a, b) => a.divergence - b.divergence);\n}\n\nfunction distanceDamerauLevenshtein(a: string, b: string): number {\n const m = a.length;\n const n = b.length;\n const dp = Array.from({ length: m + 1 }, () => Array<number>(n + 1).fill(0));\n for (let i = 0; i <= m; i++) {\n dp[i]![0] = i;\n }\n for (let j = 0; j <= n; j++) {\n dp[0]![j] = j;\n }\n for (let i = 1; i <= m; i++) {\n for (let j = 1; j <= n; j++) {\n const cost = a[i - 1] === b[j - 1] ? 0 : 1;\n dp[i]![j] = Math.min(\n dp[i - 1]![j]! + 1,\n dp[i]![j - 1]! + 1,\n dp[i - 1]![j - 1]! + cost,\n );\n if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {\n dp[i]![j] = Math.min(dp[i]![j]!, dp[i - 2]![j - 2]! + cost);\n }\n }\n }\n return dp[m]![n]!;\n}\n","import { Operation } from \"./Operation\";\nimport { ReaderArgs } from \"./Reader\";\nimport { suggestTextPushMessage } from \"./Suggest\";\nimport {\n TypoError,\n TypoString,\n typoStyleConstants,\n typoStyleQuote,\n typoStyleUserInput,\n TypoText,\n} from \"./Typo\";\nimport { UsageCommand } from \"./Usage\";\n\n/**\n * A CLI command. Created with {@link command}, {@link commandWithSubcommands}, or {@link commandChained}.\n *\n * @typeParam Context - Injected at execution; forwarded to handlers.\n * @typeParam Result - Produced on execution; typically `void`.\n */\nexport type Command<Context, Result> = {\n /**\n * Returns static metadata.\n */\n getInformation(): CommandInformation;\n /**\n * Registers options/positionals on `readerArgs`; returns a {@link CommandDecoder}.\n */\n consumeAndMakeDecoder(\n readerArgs: ReaderArgs,\n ): CommandDecoder<Context, Result>;\n};\n\n/**\n * Produced by {@link Command.consumeAndMakeDecoder}.\n *\n * @typeParam Context - See {@link Command}.\n * @typeParam Result - See {@link Command}.\n */\nexport type CommandDecoder<Context, Result> = {\n /**\n * Returns {@link UsageCommand} for the current command path.\n */\n generateUsage(): UsageCommand;\n /**\n * Creates a ready-to-execute {@link CommandInterpreter}.\n *\n * @throws if parsing or decoding failed.\n */\n decodeAndMakeInterpreter(): CommandInterpreter<Context, Result>;\n};\n\n/**\n * A fully parsed, decoded and ready-to-execute command.\n *\n * @typeParam Context - Context passed to the handler.\n * @typeParam Result - Value produced on success.\n */\nexport type CommandInterpreter<Context, Result> = {\n /**\n * Executes with the provided context.\n */\n executeWithContext(context: Context): Promise<Result>;\n};\n\n/**\n * Command metadata shown in `--help` output.\n */\nexport type CommandInformation = {\n /**\n * Shown in the usage header.\n */\n description: string;\n /**\n * Shown in parentheses, e.g. `\"deprecated\"`, `\"experimental\"`.\n */\n hint?: string;\n /**\n * Extra lines printed below the description.\n */\n details?: Array<string>;\n /**\n * Shown in the `Examples:` section.\n */\n examples?: Array<{\n // TODO - a nicer example system, maybe with --help=example support\n /**\n * Explanation shown above the example.\n */\n explanation: string;\n /**\n * Example command args.\n */\n commandArgs: Array<\n | string\n | { positional: string }\n | { subcommand: string }\n | {\n option:\n | { long: string; inlined?: string; separated?: Array<string> }\n | { short: string; inlined?: string; separated?: Array<string> };\n }\n >;\n }>;\n};\n\n/**\n * Creates a leaf command that directly executes an {@link Operation}.\n *\n * @typeParam Context - Context forwarded to the handler.\n * @typeParam Result - Value returned by the handler.\n *\n * @param information - Command metadata.\n * @param operation - Options, positionals, and handler.\n * @returns A {@link Command}.\n *\n * @example\n * ```ts\n * const greet = command(\n * { description: \"Greet a user\" },\n * operation(\n * { positionals: [positionalRequired({ type: type(\"name\") })] },\n * async (_ctx, { positionals: [name] }) => console.log(`Hello, ${name}!`),\n * ),\n * );\n * ```\n */\nexport function command<Context, Result = void>(\n information: CommandInformation,\n operation: Operation<Context, Result>,\n): Command<Context, Result> {\n return {\n getInformation() {\n return information;\n },\n consumeAndMakeDecoder(readerArgs: ReaderArgs) {\n try {\n const operationDecoder = operation.consumeAndMakeDecoder(readerArgs);\n const endPositional = readerArgs.consumePositional();\n if (endPositional !== undefined) {\n const errorText = new TypoText();\n errorText.push(new TypoString(`Unexpected argument: `));\n errorText.push(new TypoString(`\"${endPositional}\"`, typoStyleQuote));\n errorText.push(new TypoString(`.`));\n throw new TypoError(errorText);\n }\n return {\n generateUsage: () => generateUsageLeaf(information, operation),\n decodeAndMakeInterpreter() {\n const operationInterpreter =\n operationDecoder.decodeAndMakeInterpreter();\n return {\n async executeWithContext(context: Context) {\n return await operationInterpreter.executeWithContext(context);\n },\n };\n },\n };\n } catch (error) {\n return {\n generateUsage: () => generateUsageLeaf(information, operation),\n decodeAndMakeInterpreter() {\n throw error;\n },\n };\n }\n },\n };\n}\n\n/**\n * Creates a command that runs `operation` first,\n * then dispatches result to a named subcommand.\n *\n * @typeParam Context - Context accepted by `operation`.\n * @typeParam Payload - Output of `operation`; becomes the subcommand's context.\n * @typeParam Result - Value produced by the selected subcommand.\n *\n * @param information - Command metadata.\n * @param operation - Runs first; output becomes the subcommand's context.\n * @param subcommands - Map of subcommand names to their {@link Command}s.\n * @returns A dispatching {@link Command}.\n *\n * @example\n * ```ts\n * const rootCmd = commandWithSubcommands(\n * { description: \"My CLI\" },\n * operation({ options: {}, positionals: [] }, async (ctx) => ctx),\n * {\n * deploy: command({ description: \"Deploy\" }, deployOperation),\n * rollback: command({ description: \"Rollback\" }, rollbackOperation),\n * },\n * );\n * ```\n */\nexport function commandWithSubcommands<Context, Payload, Result = void>(\n information: CommandInformation,\n operation: Operation<Context, Payload>,\n subcommands: { [subcommand: string]: Command<Payload, Result> },\n): Command<Context, Result> {\n // TODO - forbid subcommands that start with a \"-\" ?\n const subcommandNames = Object.keys(subcommands);\n if (subcommandNames.length === 0) {\n throw new Error(\"At least one subcommand is required\");\n }\n return {\n getInformation() {\n return information;\n },\n consumeAndMakeDecoder(readerArgs: ReaderArgs) {\n try {\n const operationDecoder = operation.consumeAndMakeDecoder(readerArgs);\n const subcommandName = readerArgs.consumePositional();\n if (subcommandName === undefined) {\n const errorText = new TypoText();\n errorText.push(new TypoString(`<subcommand>`, typoStyleUserInput));\n errorText.push(new TypoString(`: Missing argument.`));\n suggestSubcommandNames(errorText, \"\", subcommandNames);\n throw new TypoError(errorText);\n }\n const subcommandInput = subcommands[subcommandName];\n if (subcommandInput === undefined) {\n const errorText = new TypoText();\n errorText.push(new TypoString(`<subcommand>`, typoStyleUserInput));\n errorText.push(new TypoString(`: Unknown name: `));\n errorText.push(new TypoString(`\"${subcommandName}\"`, typoStyleQuote));\n errorText.push(new TypoString(`.`));\n suggestSubcommandNames(errorText, subcommandName, subcommandNames);\n throw new TypoError(errorText);\n }\n const subcommandDecoder =\n subcommandInput.consumeAndMakeDecoder(readerArgs);\n return {\n generateUsage() {\n const subcommandUsage = subcommandDecoder.generateUsage();\n const currentUsage = generateUsageLeaf(information, operation);\n currentUsage.segments.push({ subcommand: subcommandName });\n currentUsage.segments.push(...subcommandUsage.segments);\n currentUsage.information = subcommandUsage.information;\n currentUsage.positionals.push(...subcommandUsage.positionals);\n currentUsage.subcommands = subcommandUsage.subcommands;\n currentUsage.options.push(...subcommandUsage.options);\n return currentUsage;\n },\n decodeAndMakeInterpreter() {\n const operationInterpreter =\n operationDecoder.decodeAndMakeInterpreter();\n const subcommandInterpreter =\n subcommandDecoder.decodeAndMakeInterpreter();\n return {\n async executeWithContext(context: Context) {\n return await subcommandInterpreter.executeWithContext(\n await operationInterpreter.executeWithContext(context),\n );\n },\n };\n },\n };\n } catch (error) {\n return {\n generateUsage() {\n const currentUsage = generateUsageLeaf(information, operation);\n currentUsage.segments.push({ positional: \"<subcommand>\" });\n for (const [name, subcommand] of Object.entries(subcommands)) {\n const { description, hint } = subcommand.getInformation();\n currentUsage.subcommands.push({ name, description, hint });\n }\n return currentUsage;\n },\n decodeAndMakeInterpreter() {\n throw error;\n },\n };\n }\n },\n };\n}\n\n/**\n * Chains an {@link Operation} and a {@link Command}: `operation` runs first,\n * its output becomes `subcommand`'s context. No token is consumed for routing.\n *\n * @typeParam Context - Context accepted by `operation`.\n * @typeParam Payload - Output of `operation`; becomes `subcommand`'s context.\n * @typeParam Result - Value produced by `subcommand`.\n *\n * @param information - Command metadata.\n * @param operation - Runs first; output becomes `subcommand`'s context.\n * @param subcommand - Runs after `operation`.\n * @returns A {@link Command} composing both stages.\n */\nexport function commandChained<Context, Payload, Result = void>(\n information: CommandInformation,\n operation: Operation<Context, Payload>,\n subcommand: Command<Payload, Result>,\n): Command<Context, Result> {\n return {\n getInformation() {\n return information;\n },\n consumeAndMakeDecoder(readerArgs: ReaderArgs) {\n try {\n const operationDecoder = operation.consumeAndMakeDecoder(readerArgs);\n const subcommandDecoder = subcommand.consumeAndMakeDecoder(readerArgs);\n return {\n generateUsage() {\n const subcommandUsage = subcommandDecoder.generateUsage();\n const currentUsage = generateUsageLeaf(information, operation);\n currentUsage.segments.push(...subcommandUsage.segments);\n currentUsage.information = subcommandUsage.information;\n currentUsage.positionals.push(...subcommandUsage.positionals);\n currentUsage.subcommands = subcommandUsage.subcommands;\n currentUsage.options.push(...subcommandUsage.options);\n return currentUsage;\n },\n decodeAndMakeInterpreter() {\n const operationInterpreter =\n operationDecoder.decodeAndMakeInterpreter();\n const subcommandInterpreter =\n subcommandDecoder.decodeAndMakeInterpreter();\n return {\n async executeWithContext(context: Context) {\n return await subcommandInterpreter.executeWithContext(\n await operationInterpreter.executeWithContext(context),\n );\n },\n };\n },\n };\n } catch (error) {\n return {\n generateUsage() {\n const currentUsage = generateUsageLeaf(information, operation);\n currentUsage.segments.push({ positional: \"[REST]...\" });\n return currentUsage;\n },\n decodeAndMakeInterpreter() {\n throw error;\n },\n };\n }\n },\n };\n}\n\nfunction generateUsageLeaf(\n information: CommandInformation,\n operation: Operation<any, any>,\n): UsageCommand {\n const { positionals, options } = operation.generateUsage();\n return {\n segments: positionals.map((p) => ({ positional: p.label })),\n information,\n positionals,\n subcommands: [],\n options,\n };\n}\n\nfunction suggestSubcommandNames(\n errorText: TypoText,\n input: string,\n subcommandNames: Array<string> = [],\n) {\n suggestTextPushMessage(\n errorText,\n input,\n subcommandNames.map((subcommandName) => ({\n reference: subcommandName,\n hint: new TypoString(subcommandName, typoStyleConstants),\n })),\n );\n}\n","import { Option, OptionDecoder } from \"./Option\";\nimport { Positional, PositionalDecoder } from \"./Positional\";\nimport { ReaderArgs } from \"./Reader\";\nimport { UsageOption, UsagePositional } from \"./Usage\";\n\n/**\n * Options, positionals, and an async handler that together form the logic of a CLI command.\n *\n * Created with {@link operation} and passed to {@link command},\n * {@link commandWithSubcommands}, or {@link commandChained}.\n *\n * @typeParam Context - Injected at execution; forwarded to handlers.\n * @typeParam Result - Value produced on execution; typically `void`.\n */\nexport type Operation<Context, Result> = {\n /**\n * Returns usage metadata without consuming any arguments.\n */\n generateUsage(): {\n /**\n * Registered options.\n */\n options: Array<UsageOption>;\n /**\n * Declared positionals, in order.\n */\n positionals: Array<UsagePositional>;\n };\n /**\n * Consumes args from `readerArgs` and returns an {@link OperationDecoder}.\n */\n consumeAndMakeDecoder(\n readerArgs: ReaderArgs,\n ): OperationDecoder<Context, Result>;\n};\n\n/**\n * Produced by {@link Operation.consumeAndMakeDecoder}.\n *\n * @typeParam Context - See {@link Operation}.\n * @typeParam Result - See {@link Operation}.\n */\nexport type OperationDecoder<Context, Result> = {\n /**\n * Creates a ready-to-execute {@link OperationInterpreter}.\n *\n * @throws if parsing or decoding failed.\n */\n decodeAndMakeInterpreter(): OperationInterpreter<Context, Result>;\n};\n\n/**\n * A fully parsed, decoded and ready-to-execute operation.\n *\n * @typeParam Context - Caller-supplied context.\n * @typeParam Result - Value produced on success.\n */\nexport type OperationInterpreter<Context, Result> = {\n /**\n * Executes with the provided context.\n */\n executeWithContext(context: Context): Promise<Result>;\n};\n\n/**\n * Creates an {@link Operation} from options, positionals, and an async handler.\n *\n * The `handler` receives `context` and `inputs` with decoded `options` and `positionals`.\n *\n * @typeParam Context - Context type accepted by the handler.\n * @typeParam Result - Return type of the handler.\n * @typeParam Options - Map of option keys to parsed value types.\n * @typeParam Positionals - Tuple of parsed positional value types, in order.\n *\n * @param inputs - Options and positionals this operation accepts.\n * @param inputs.options - Map of keys to {@link Option} descriptors.\n * @param inputs.positionals - Ordered array of {@link Positional} descriptors.\n * @param handler - Async function implementing the command logic.\n * @returns An {@link Operation}.\n *\n * @example\n * ```ts\n * const greetOperation = operation(\n * {\n * options: {\n * loud: optionFlag({ long: \"loud\", description: \"Print in uppercase\" }),\n * },\n * positionals: [\n * positionalRequired({ type: type(\"name\"), description: \"Name to greet\" }),\n * ],\n * },\n * async function (_ctx, { options: { loud }, positionals: [name] }) {\n * const message = `Hello, ${name}!`;\n * console.log(loud ? message.toUpperCase() : message);\n * },\n * );\n * ```\n */\nexport function operation<\n Context,\n Result,\n const Options extends { [option: string]: any } = {},\n const Positionals extends Array<any> = [],\n>(\n inputs: {\n options?: { [K in keyof Options]: Option<Options[K]> };\n positionals?: { [K in keyof Positionals]: Positional<Positionals[K]> };\n },\n handler: (\n context: Context,\n inputs: {\n options: { [K in keyof Options]: Options[K] };\n positionals: { [K in keyof Positionals]: Positionals[K] };\n },\n ) => Promise<Result>,\n): Operation<Context, Result> {\n return {\n generateUsage() {\n const optionsUsage = new Array<UsageOption>();\n if (inputs.options !== undefined) {\n for (const optionKey in inputs.options) {\n const optionInput = inputs.options[optionKey]!;\n optionsUsage.push(optionInput.generateUsage());\n }\n }\n const positionalsUsage = new Array<UsagePositional>();\n if (inputs.positionals !== undefined) {\n for (const positionalInput of inputs.positionals) {\n positionalsUsage.push(positionalInput.generateUsage());\n }\n }\n return { options: optionsUsage, positionals: positionalsUsage };\n },\n consumeAndMakeDecoder(readerArgs: ReaderArgs) {\n const optionsDecoders: Record<string, OptionDecoder<any>> = {};\n if (inputs.options !== undefined) {\n for (const optionKey in inputs.options) {\n const optionInput = inputs.options[optionKey]!;\n optionsDecoders[optionKey] =\n optionInput.registerAndMakeDecoder(readerArgs);\n }\n }\n const positionalsDecoders: Array<PositionalDecoder<any>> = [];\n if (inputs.positionals !== undefined) {\n for (const positionalInput of inputs.positionals) {\n positionalsDecoders.push(\n positionalInput.consumeAndMakeDecoder(readerArgs),\n );\n }\n }\n return {\n decodeAndMakeInterpreter() {\n const optionsValues: any = {};\n for (const optionKey in optionsDecoders) {\n optionsValues[optionKey] =\n optionsDecoders[optionKey]!.getAndDecodeValue();\n }\n const positionalsValues: any = [];\n for (const positionalDecoder of positionalsDecoders) {\n positionalsValues.push(positionalDecoder.decodeValue());\n }\n return {\n executeWithContext(context: Context) {\n return handler(context, {\n options: optionsValues,\n positionals: positionalsValues,\n });\n },\n };\n },\n };\n },\n };\n}\n","import { statSync } from \"fs\";\nimport { suggestTextPushMessage } from \"./Suggest\";\nimport {\n TypoError,\n TypoString,\n typoStyleLogic,\n typoStyleQuote,\n TypoText,\n} from \"./Typo\";\n\n/**\n * Decodes a raw CLI string into a typed value.\n * A pair of a human-readable `content` name and a `decoder` function.\n *\n * Built-in: {@link type}, {@link typeBoolean}, {@link typeNumber},\n * {@link typeInteger}, {@link typeDatetime}, {@link typeUrl}.\n * Composite: {@link typeChoice}, {@link typeConverted}, {@link typeTuple}, {@link typeList}.\n *\n * @typeParam Value - Type produced by the decoder.\n */\nexport type Type<Value> = {\n /**\n * Human-readable name shown in help and errors (e.g. `\"name\"`, `\"context\"`).\n */\n content: string; // TODO - add an enforcement mechanism for casing ?\n /**\n * Decodes a raw CLI string into `Value`.\n *\n * @param input - Raw string from the command line.\n * @returns The decoded value.\n * @throws on invalid input.\n */\n decoder(input: string): Value;\n};\n\n/**\n * Decodes a string to `boolean` (case-insensitive).\n * Used by {@link optionFlag} for `--flag=<value>`.\n *\n * @example\n * ```ts\n * typeBoolean(\"flag\").decoder(\"true\") // → true\n * typeBoolean(\"flag\").decoder(\"yes\") // → true\n * typeBoolean(\"flag\").decoder(\"y\") // → true\n * typeBoolean(\"flag\").decoder(\"false\") // → false\n * typeBoolean(\"flag\").decoder(\"no\") // → false\n * typeBoolean(\"flag\").decoder(\"n\") // → false\n * ```\n */\nexport function typeBoolean(name?: string): Type<boolean> {\n return {\n content: name ?? \"boolean\",\n decoder(input: string) {\n const lowerInput = input.toLowerCase();\n if (typeBooleanValuesTrue.has(lowerInput)) {\n return true;\n }\n if (typeBooleanValuesFalse.has(lowerInput)) {\n return false;\n }\n throwInvalidValue(\"a boolean\", input);\n },\n };\n}\nconst typeBooleanValuesTrue = new Set([\"true\", \"yes\", \"on\", \"y\"]);\nconst typeBooleanValuesFalse = new Set([\"false\", \"no\", \"off\", \"n\"]);\n\n/**\n * Parses a date/time string via `Date.parse`.\n * Accepts any format supported by `Date.parse`, including ISO 8601.\n *\n * @example\n * ```ts\n * typeDatetime(\"my-datetime\").decoder(\"2024-01-15\") // → Date object for 2024-01-15\n * typeDatetime(\"my-datetime\").decoder(\"2024-01-15T13:45:30Z\") // → Date object for 2024-01-15 13:45:30 UTC\n * typeDatetime(\"my-datetime\").decoder(\"not a date\") // throws TypoError\n * ```\n */\nexport function typeDatetime(name?: string): Type<Date> {\n return {\n content: name ?? \"datetime\",\n decoder(input: string) {\n try {\n const timestampMs = Date.parse(input);\n if (isNaN(timestampMs)) {\n throw new Error();\n }\n return new Date(timestampMs);\n } catch {\n throwInvalidValue(\"a valid ISO_8601 datetime\", input);\n }\n },\n };\n}\n\n/**\n * Parses a string to `number` via `Number()`; `NaN` throws.\n *\n * @example\n * ```ts\n * typeNumber(\"my-number\").decoder(\"3.14\") // → 3.14\n * typeNumber(\"my-number\").decoder(\"-1\") // → -1\n * typeNumber(\"my-number\").decoder(\"hello\") // throws\n * ```\n */\nexport function typeNumber(name?: string): Type<number> {\n return {\n content: name ?? \"number\",\n decoder(input: string) {\n try {\n const parsed = Number(input);\n if (isNaN(parsed)) {\n throw new Error();\n }\n return parsed;\n } catch {\n throwInvalidValue(\"a number\", input);\n }\n },\n };\n}\n\n/**\n * Parses an integer string to `bigint` via `BigInt()`.\n * Floats and non-numeric strings throws.\n *\n * @example\n * ```ts\n * typeInteger(\"my-integer\").decoder(\"42\") // → 42n\n * typeInteger(\"my-integer\").decoder(\"3.14\") // throws\n * typeInteger(\"my-integer\").decoder(\"abc\") // throws\n * ```\n */\nexport function typeInteger(name?: string): Type<bigint> {\n return {\n content: name ?? \"integer\",\n decoder(input: string) {\n try {\n return BigInt(input);\n } catch {\n throwInvalidValue(\"an integer\", input);\n }\n },\n };\n}\n\n/**\n * Parses an absolute URL string to a `URL` object.\n * Relative or malformed URLs throws.\n *\n * @example\n * ```ts\n * typeUrl(\"my-url\").decoder(\"https://example.com\") // → URL { href: \"https://example.com/\", ... }\n * typeUrl(\"my-url\").decoder(\"not-a-url\") // throws\n * ```\n */\nexport function typeUrl(name?: string): Type<URL> {\n return {\n content: name ?? \"url\",\n decoder(input: string) {\n try {\n return new URL(input);\n } catch {\n throwInvalidValue(\"an URL\", input);\n }\n },\n };\n}\n\n/**\n * A named type that accepts any string as input.\n * @param name - Name shown in help and errors (e.g. `\"my-value\"`).\n * @example\n * ```ts\n * type(\"greeting\").decoder(\"hello\") // → \"hello\"\n * type(\"greeting\").decoder(\"\") // → \"\"\n * ```\n */\nexport function type(name?: string): Type<string> {\n return {\n content: name ?? \"string\",\n decoder: (input: string) => input,\n };\n}\n\n/**\n * Chains `before`'s decoder with an `after` transformation.\n * `before` errors are prefixed with `\"from: <content>\"` for traceability.\n *\n * @typeParam Before - Intermediate type from `before.decoder`.\n * @typeParam After - Final type from `after.decoder`.\n *\n * @param name - Name shown in help and errors (e.g. `\"my-value\"`).\n * @param before - Base type to decode the raw string.\n * @param mapper - Transforms `before`'s output to the final value; errors are wrapped with context.\n * @returns A {@link Type}`<After>`.\n *\n * @example\n * ```ts\n * const typePort = typeConverted(\"port\", typeNumber(), (n) => {\n * if (n < 1 || n > 65535) throw new Error(\"Out of range\");\n * return n;\n * });\n * // \"--port 8080\" → 8080\n * // \"--port 99999\" → TypoError: --port: <PORT>: Port: Out of range\n * ```\n */\nexport function typeConverted<Before, After>(\n name: string,\n before: Type<Before>,\n mapper: (value: Before) => After,\n): Type<After> {\n return {\n content: name,\n decoder: (input: string) => {\n return mapper(\n TypoError.tryWithContext(\n () => before.decoder(input),\n () =>\n new TypoText(\n new TypoString(\"from: \"),\n new TypoString(before.content, typoStyleLogic),\n ),\n ),\n );\n },\n };\n}\n\n/**\n * Adds a name to a {@link Type} for clearer error messages and help text.\n *\n * @param name - Name to use for the type.\n * @param type - Base type to name.\n * @returns A {@link Type} with the given name.\n */\nexport function typeRenamed<Value>(\n type: Type<Value>,\n name: string,\n): Type<Value> {\n return {\n content: name,\n decoder: (input: string) => {\n return TypoError.tryWithContext(\n () => type.decoder(input),\n () =>\n new TypoText(\n new TypoString(\"from: \"),\n new TypoString(type.content, typoStyleLogic),\n ),\n );\n },\n };\n}\n\n/**\n * Creates a {@link Type} for filesystem paths with optional existence checks.\n * @param checks - Optional checks for path existence and type (file/directory).\n * @returns A {@link Type}`<string>` representing the path.\n */\nexport function typePath(\n name?: string,\n checks?: { checkSyncExistAs?: \"file\" | \"directory\" | \"anything\" },\n): Type<string> {\n return {\n content: name ?? \"path\",\n decoder(input: string) {\n if (input.length === 0) {\n throw new Error(`Path cannot be empty`);\n }\n if (input.includes(\"\\0\")) {\n throw new Error(`Path cannot contain null characters`);\n }\n if (checks?.checkSyncExistAs !== undefined) {\n function safeStatSync(path: string) {\n try {\n return statSync(path);\n } catch (error) {\n throw new TypoError(\n new TypoText(\n new TypoString(`Path does not exist: `),\n new TypoString(`\"${path}\"`, typoStyleQuote),\n ),\n error,\n );\n }\n }\n const stats = safeStatSync(input);\n const preview = stats.isDirectory()\n ? \"directory\"\n : stats.isFile()\n ? \"file\"\n : \"unknown\";\n if (checks.checkSyncExistAs === \"file\" && !stats.isFile()) {\n throw new TypoError(\n new TypoText(\n new TypoString(`Expected a file but found: ${preview}: `),\n new TypoString(`\"${input}\"`, typoStyleQuote),\n ),\n );\n }\n if (checks.checkSyncExistAs === \"directory\" && !stats.isDirectory()) {\n throw new TypoError(\n new TypoText(\n new TypoString(`Expected a directory but found: ${preview}: `),\n new TypoString(`\"${input}\"`, typoStyleQuote),\n ),\n );\n }\n }\n return input;\n },\n };\n}\n\n/**\n * Creates a {@link Type}`<string>` that only accepts a fixed set of values.\n *\n * @param name - Name shown in help and errors.\n * @param values - Ordered list of accepted values.\n * @returns A {@link Type}`<string>`.\n *\n * @example\n * ```ts\n * const typeEnv = typeChoice(\"environment\", [\"dev\", \"staging\", \"prod\"]);\n * typeEnv.decoder(\"prod\") // → \"prod\"\n * typeEnv.decoder(\"unknown\") // throws\n * ```\n */\nexport function typeChoice<const Value extends string>(\n name: string,\n values: Array<Value>,\n caseSensitive: boolean = true,\n): Type<Value> {\n if (values.length === 0) {\n throw new Error(\"At least one value is required\");\n }\n const normalize = caseSensitive\n ? (input: string) => input\n : (input: string) => input.toLowerCase();\n const valueByNormalized = new Map(\n values.map((value) => [normalize(value), value]),\n );\n return {\n content: name,\n decoder(input: string) {\n const value = valueByNormalized.get(normalize(input));\n if (value !== undefined) {\n return value;\n }\n const errorText = new TypoText();\n errorText.push(new TypoString(`Unknown value: `));\n errorText.push(new TypoString(`\"${input}\"`, typoStyleQuote));\n errorText.push(new TypoString(`.`));\n suggestTextPushMessage(\n errorText,\n input,\n values.map((value) => ({\n reference: value,\n hint: new TypoString(`\"${value}\"`, typoStyleQuote),\n })),\n );\n throw new TypoError(errorText);\n },\n };\n}\n\n/**\n * Splits a delimited string into a typed tuple.\n * Each part is decoded by the corresponding element type; wrong count or decode failure throws.\n *\n * @typeParam Elements - Tuple of decoded value types (inferred from `elementTypes`).\n *\n * @param elementTypes - One {@link Type} per tuple element, in order.\n * @param separator - Delimiter (default `\",\"`).\n * @returns A {@link Type}`<Elements>`.\n *\n * @example\n * ```ts\n * const typePoint = typeTuple([typeNumber(\"x\"), typeNumber(\"y\")]);\n * typePoint.decoder(\"3.14,2.71\") // → [3.14, 2.71]\n * typePoint.decoder(\"1\") // throws\n * typePoint.decoder(\"1,2,3\") // throws\n * typePoint.decoder(\"x,2\") // throws\n * ```\n */\nexport function typeTuple<const Elements extends Array<any>>(\n elementTypes: { [K in keyof Elements]: Type<Elements[K]> },\n separator: string = \",\",\n): Type<Elements> {\n return {\n content: elementTypes\n .map((elementType) => elementType.content)\n .join(separator),\n decoder(input: string) {\n const splits = input.split(separator, elementTypes.length);\n if (splits.length !== elementTypes.length) {\n throw new TypoError(\n new TypoText(\n new TypoString(`Found ${splits.length} splits: `),\n new TypoString(`Expected ${elementTypes.length} splits from: `),\n new TypoString(`\"${input}\"`, typoStyleQuote),\n new TypoString(`.`),\n ),\n );\n }\n return splits.map((split, index) => {\n const elementType = elementTypes[index]!;\n return TypoError.tryWithContext(\n () => elementType.decoder(split),\n () =>\n new TypoText(\n new TypoString(`at ${index}: `),\n new TypoString(elementType.content, typoStyleLogic),\n ),\n );\n }) as Elements;\n },\n };\n}\n\n/**\n * Splits a delimited string into a typed array.\n * Each part is decoded by `elementType`; failed decodes throws.\n * Note: splitting an empty string yields one empty element — prefer {@link optionRepeatable} for a zero-default.\n *\n * @typeParam Value - Element type produced by `elementType.decoder`.\n *\n * @param elementType - Decoder applied to each element.\n * @param separator - Delimiter (default `\",\"`).\n * @returns A {@link Type}`<Array<Value>>`.\n *\n * @example\n * ```ts\n * const typeNumbers = typeList(typeNumber(\"v\"));\n * typeNumbers.decoder(\"1,2,3\") // → [1, 2, 3]\n * typeNumbers.decoder(\"1,x,3\") // throws\n * const typePaths = typeList(typePath(), \":\");\n * typePaths.decoder(\"/usr/bin:/usr/local/bin\") // → [\"/usr/bin\", \"/usr/local/bin\"]\n * ```\n */\nexport function typeList<Value>(\n elementType: Type<Value>,\n separator: string = \",\",\n): Type<Array<Value>> {\n return {\n content: `${elementType.content}[${separator}${elementType.content}]...`,\n decoder(input: string) {\n const splits = input.split(separator);\n return splits.map((split, index) =>\n TypoError.tryWithContext(\n () => elementType.decoder(split),\n () =>\n new TypoText(\n new TypoString(`at ${index}: `),\n new TypoString(elementType.content, typoStyleLogic),\n ),\n ),\n );\n },\n };\n}\n\nfunction throwInvalidValue(kind: string, input: string): never {\n throw new TypoError(\n new TypoText(\n new TypoString(`Not ${kind}: `),\n new TypoString(`\"${input}\"`, typoStyleQuote),\n new TypoString(`.`),\n ),\n );\n}\n","import {\n ReaderOptionGetter,\n ReaderOptionNextGuard,\n ReaderOptionRestGuard,\n ReaderOptions,\n ReaderOptionValue,\n} from \"./Reader\";\nimport { Type, typeBoolean } from \"./Type\";\nimport {\n TypoError,\n TypoString,\n typoStyleConstants,\n typoStyleLogic,\n typoStyleUserInput,\n TypoText,\n} from \"./Typo\";\nimport { UsageOption } from \"./Usage\";\n\n/**\n * A CLI option. Created with {@link optionFlag}, {@link optionSingleValue},\n * or {@link optionRepeatable}.\n *\n * @typeParam Value - Decoded value type.\n */\nexport type Option<Value> = {\n /**\n * Returns metadata for the `Options:` section.\n */\n generateUsage(): UsageOption;\n /**\n * Registers the option on `readerOptions` and returns an {@link OptionDecoder}.\n */\n registerAndMakeDecoder(readerOptions: ReaderOptions): OptionDecoder<Value>;\n};\n\n/**\n * Produced by {@link Option.registerAndMakeDecoder}.\n *\n * @typeParam Value - Decoded value type.\n */\nexport type OptionDecoder<Value> = {\n /**\n * Returns the decoded option value.\n *\n * @throws if decoding failed.\n */\n getAndDecodeValue(): Value;\n};\n\n/**\n * Creates a boolean flag option (`--verbose`, optionally `--flag=no`).\n *\n * Syntax: `--long`, `--long=no`, `-s`, `-s=no`.\n * Parsing logic:\n * - absent → default value\n * - `--flag` / `--flag=yes` → `true`\n * - `--flag=no` → `false`\n * - specified more than once → throws.\n *\n * @param definition.long - Long-form name (without `--`).\n * @param definition.short - Short-form name (without `-`).\n * @param definition.description - Help text.\n * @param definition.hint - Short note shown in parentheses.\n * @param definition.aliases - Additional names.\n * @param definition.default - Default value when absent.\n * @returns An {@link Option}`<boolean>`.\n *\n * @example\n * ```ts\n * const verboseFlag = optionFlag({\n * long: \"verbose\",\n * short: \"v\",\n * description: \"Enable verbose output\",\n * });\n * ```\n */\nexport function optionFlag(definition: {\n long: string;\n short?: string;\n description?: string;\n hint?: string;\n aliases?: { longs?: Array<string>; shorts?: Array<string> };\n default?: boolean;\n}): Option<boolean> {\n const type = typeBoolean(\"value\");\n const { long, short, description, hint, aliases } = definition;\n return {\n generateUsage() {\n return { short, long, annotation: \"[=no]\", description, hint };\n },\n registerAndMakeDecoder(readerOptions: ReaderOptions) {\n const resultsGetter = setupOptionAliased(readerOptions, {\n longKey: long,\n shortKey: short,\n aliasLongKeys: aliases?.longs,\n aliasShortKeys: aliases?.shorts,\n restGuard: () => false,\n nextGuard: () => false,\n });\n return {\n getAndDecodeValue() {\n const results = resultsGetter();\n if (results.length > 1) {\n throwSetMultipleTimesError(results.map((r) => r.identifier));\n }\n if (results.length === 0) {\n return definition.default === undefined\n ? false\n : definition.default;\n }\n const input = results[0]!.value.inlined;\n if (input === null) {\n return true;\n }\n return decodeValue({ long, label: undefined, type, input });\n },\n };\n },\n };\n}\n\n/**\n * Creates an option that accepts exactly one value (e.g. `--output dist/`).\n *\n * Syntax: `--long value`, `--long=value`, `-s value`, `-s=value`, `-svalue`.\n * Parsing logic:\n * - absent → `fallbackValueIfAbsent()`\n * - `--long value` → decoded with `type.decoder(\"value\")`\n * - more than once → throws\n * - if `impliedValueIfNotInlined` is not provided, then: `--long` / `-s` without a value → throws\n * - if `impliedValueIfNotInlined` is provided, then: `--long` / `-s` without an inline value → `impliedValueIfNotInlined()`\n *\n * @typeParam Value - Type produced by the decoder.\n *\n * @param definition.long - Long-form name (without `--`).\n * @param definition.short - Short-form name (without `-`).\n * @param definition.description - Help text.\n * @param definition.hint - Short note shown in parentheses.\n * @param definition.aliases - Additional names.\n * @param definition.type - Decoder for the raw string value.\n * @param definition.fallbackValueIfAbsent - Default value when the option is not specified at all.\n * @param definition.impliedValueIfNotInlined - Default value when the option is specified without an inline value (e.g. `--option` or `-o`).\n * @returns An {@link Option}`<Value>`.\n *\n * @example\n * ```ts\n * const outputOption = optionSingleValue({\n * long: \"output\",\n * short: \"o\",\n * type: typePath(),\n * description: \"Output directory\",\n * fallbackValueIfAbsent: () => \"dist\",\n * });\n * ```\n */\nexport function optionSingleValue<Value>(definition: {\n long: string;\n short?: string;\n description?: string;\n hint?: string;\n aliases?: { longs?: Array<string>; shorts?: Array<string> };\n type: Type<Value>;\n fallbackValueIfAbsent?: () => Value;\n impliedValueIfNotInlined?: () => Value;\n}): Option<Value> {\n const { long, short, description, hint, aliases, type } = definition;\n const label = definition.impliedValueIfNotInlined\n ? undefined\n : `<${type.content}>`;\n const annotation = definition.impliedValueIfNotInlined\n ? `[=${type.content}]`\n : undefined; // TODO - handle implied value and default better in usage and errors\n return {\n generateUsage() {\n return { short, long, label, annotation, description, hint };\n },\n registerAndMakeDecoder(readerOptions: ReaderOptions) {\n const resultsGetter = setupOptionAliased(readerOptions, {\n longKey: long,\n shortKey: short,\n aliasLongKeys: aliases?.longs,\n aliasShortKeys: aliases?.shorts,\n restGuard: () => {\n if (definition.impliedValueIfNotInlined !== undefined) {\n return false;\n }\n return true;\n },\n nextGuard: (value) => {\n if (definition.impliedValueIfNotInlined !== undefined) {\n return false;\n }\n if (value.inlined !== null) {\n return false;\n }\n if (value.separated.length !== 0) {\n return false;\n }\n return true;\n },\n });\n return {\n getAndDecodeValue() {\n const results = resultsGetter();\n if (results.length > 1) {\n throwSetMultipleTimesError(\n results.map((result) => result.identifier),\n );\n }\n const result = results[0];\n if (result === undefined) {\n if (definition.fallbackValueIfAbsent === undefined) {\n const errorText = makeErrorText({ long, label, type });\n errorText.push(new TypoString(`: Is required, but was not set.`));\n throw new TypoError(errorText);\n }\n try {\n return definition.fallbackValueIfAbsent();\n } catch (error) {\n const errorText = makeErrorText({ long, label, type });\n errorText.push(new TypoString(`: Failed to get fallback value.`));\n throw new TypoError(errorText, error);\n }\n }\n const inlined = result.value.inlined;\n if (inlined !== null) {\n return decodeValue({ long, label, type, input: inlined });\n }\n if (definition.impliedValueIfNotInlined !== undefined) {\n try {\n return definition.impliedValueIfNotInlined();\n } catch (error) {\n const errorText = makeErrorText({ long, label, type });\n errorText.push(new TypoString(`: Failed to get implied value.`));\n throw new TypoError(errorText, error);\n }\n }\n const separated = result.value.separated[0]!;\n return decodeValue({ long, label, type, input: separated });\n },\n };\n },\n };\n}\n\n/**\n * Creates an option that collects every occurrence into an array (e.g. `--file a.ts --file b.ts`).\n *\n * Syntax: `--long value`, `--long=value`, `-s value`, `-s=value`, `-svalue`.\n * Parsing logic:\n * - absent → `[]`\n * - N occurrences → array of N decoded values in order.\n *\n * @typeParam Value - Type produced by the decoder for each occurrence.\n *\n * @param definition.long - Long-form name (without `--`).\n * @param definition.short - Short-form name (without `-`).\n * @param definition.description - Help text.\n * @param definition.hint - Short note shown in parentheses.\n * @param definition.aliases - Additional names.\n * @param definition.type - Decoder applied to each raw string value.\n * @returns An {@link Option}`<Array<Value>>`.\n *\n * @example\n * ```ts\n * const filesOption = optionRepeatable({\n * long: \"file\",\n * short: \"f\",\n * type: typeString,\n * label: \"PATH\",\n * description: \"Input file (may be repeated)\",\n * });\n * ```\n */\nexport function optionRepeatable<Value>(definition: {\n long: string;\n short?: string;\n description?: string;\n hint?: string;\n aliases?: { longs?: Array<string>; shorts?: Array<string> };\n type: Type<Value>;\n}): Option<Array<Value>> {\n const { long, short, description, hint, aliases, type } = definition;\n const label = `<${type.content}>`;\n return {\n generateUsage() {\n return { short, long, label, annotation: \" [*]\", description, hint };\n },\n registerAndMakeDecoder(readerOptions: ReaderOptions) {\n const resultsGetter = setupOptionAliased(readerOptions, {\n longKey: long,\n shortKey: short,\n aliasLongKeys: aliases?.longs,\n aliasShortKeys: aliases?.shorts,\n restGuard: () => true,\n nextGuard: (value) => {\n if (value.inlined !== null) {\n return false;\n }\n if (value.separated.length !== 0) {\n return false;\n }\n return true;\n },\n });\n return {\n getAndDecodeValue() {\n return resultsGetter().map((result) => {\n const value = result.value;\n const input = value.inlined ?? value.separated[0]!;\n return decodeValue({ long, label, type, input });\n });\n },\n };\n },\n };\n}\n\nfunction decodeValue<Value>(params: {\n long: string;\n label: string | undefined;\n type: Type<Value>;\n input: string;\n}): Value {\n const { long, label, type, input } = params;\n return TypoError.tryWithContext(\n () => type.decoder(input),\n () => makeErrorText({ long, label, type }),\n );\n}\n\nfunction makeErrorText(params: {\n long: string;\n label: string | undefined;\n type: Type<any>;\n}): TypoText {\n const errorText = new TypoText();\n errorText.push(new TypoString(`--${params.long}`, typoStyleConstants));\n if (params.label !== undefined) {\n errorText.push(new TypoString(`: `));\n errorText.push(new TypoString(params.label, typoStyleUserInput));\n } else {\n errorText.push(new TypoString(`: `));\n errorText.push(new TypoString(params.type.content, typoStyleLogic));\n }\n return errorText;\n}\n\nfunction setupOptionAliased(\n readerOptions: ReaderOptions,\n params: {\n longKey: string;\n shortKey: string | undefined;\n aliasLongKeys: Array<string> | undefined;\n aliasShortKeys: Array<string> | undefined;\n restGuard: ReaderOptionRestGuard;\n nextGuard: ReaderOptionNextGuard;\n },\n): () => Array<{ identifier: string; value: ReaderOptionValue }> {\n const { longKey, shortKey, aliasLongKeys, aliasShortKeys } = params;\n const longKeys = [longKey];\n if (aliasLongKeys !== undefined) {\n longKeys.push(...aliasLongKeys);\n }\n const shortKeys = shortKey ? [shortKey] : [];\n if (aliasShortKeys !== undefined) {\n shortKeys.push(...aliasShortKeys);\n }\n return setupOptionMany(readerOptions, {\n longKeys,\n shortKeys,\n restGuard: params.restGuard,\n nextGuard: params.nextGuard,\n });\n}\n\nfunction setupOptionMany(\n readerOptions: ReaderOptions,\n params: {\n longKeys: Array<string>;\n shortKeys: Array<string>;\n restGuard: ReaderOptionRestGuard;\n nextGuard: ReaderOptionNextGuard;\n },\n): () => Array<{ identifier: string; value: ReaderOptionValue }> {\n const { longKeys, shortKeys, restGuard, nextGuard } = params;\n const getters = new Array<ReaderOptionGetter>();\n for (const key of longKeys) {\n getters.push(readerOptions.registerOptionLong({ key, nextGuard }));\n }\n for (const key of shortKeys) {\n getters.push(\n readerOptions.registerOptionShort({ key, restGuard, nextGuard }),\n );\n }\n return () => {\n const results = new Array();\n for (const getter of getters) {\n const { identifier, values } = getter();\n for (const value of values) {\n results.push({ identifier, value });\n }\n }\n return results;\n };\n}\n\nfunction throwSetMultipleTimesError(identifiers: Array<string>): never {\n const identifiersTexts = Array.from(new Set(identifiers)).map(\n (identifier) => new TypoString(identifier, typoStyleConstants),\n );\n const errorText = new TypoText();\n errorText.pushJoined(identifiersTexts, new TypoString(\", \"), 3);\n errorText.push(new TypoString(`: Must not be set multiple times.`));\n throw new TypoError(errorText);\n}\n","import { ReaderPositionals } from \"./Reader\";\nimport { Type } from \"./Type\";\nimport {\n TypoError,\n TypoString,\n typoStyleRegularWeaker,\n typoStyleUserInput,\n TypoText,\n} from \"./Typo\";\nimport { UsagePositional } from \"./Usage\";\n\n/**\n * A positional argument. Created with {@link positionalRequired}, {@link positionalOptional},\n * or {@link positionalVariadics}.\n *\n * @typeParam Value - Decoded value type.\n */\nexport type Positional<Value> = {\n /**\n * Returns metadata for the `Positionals:` section.\n */\n generateUsage(): UsagePositional;\n /**\n * Consumes the next positional token from `readerPositionals`.\n * Returns a decoder that produces the final value.\n */\n consumeAndMakeDecoder(\n readerPositionals: ReaderPositionals,\n ): PositionalDecoder<Value>;\n};\n\n/**\n * Produced by {@link Positional.consumeAndMakeDecoder}.\n *\n * @typeParam Value - Decoded value type.\n */\nexport type PositionalDecoder<Value> = {\n /**\n * Returns the decoded positional value.\n *\n * @throws if decoding failed.\n */\n decodeValue(): Value;\n};\n\n/**\n * Creates a required positional — missing token throws.\n *\n * Syntax: `<type>`, e.g. `<NAME>`.\n * Parsing logic:\n * - \"token\" → decoded with `type.decoder(\"token\")`\n * - token missing → throws\n *\n * @typeParam Value - Type produced by the decoder.\n *\n * @param definition.description - Help text.\n * @param definition.hint - Short note shown in parentheses.\n * @param definition.type - Decoder for the raw token.\n * @param definition.missing - Message shown when the token is missing.\n * @returns A {@link Positional}`<Value>`.\n *\n * @example\n * ```ts\n * const namePositional = positionalRequired({\n * type: type(\"name\"),\n * description: \"The name to greet\",\n * });\n * ```\n */\nexport function positionalRequired<Value>(definition: {\n description?: string;\n hint?: string;\n type: Type<Value>;\n}): Positional<Value> {\n const { description, hint, type } = definition;\n const label = `<${type.content}>`;\n return {\n generateUsage() {\n return { description, hint, label };\n },\n consumeAndMakeDecoder(readerPositionals: ReaderPositionals) {\n const positional = readerPositionals.consumePositional();\n if (positional === undefined) {\n const errorText = makeErrorText(label);\n errorText.push(new TypoString(`: Is required, but was not provided.`));\n if (description !== undefined) {\n // TODO - should there be a dedicated hint here ?\n errorText.push(\n new TypoString(` (${description})`, typoStyleRegularWeaker),\n );\n }\n throw new TypoError(errorText);\n }\n return {\n decodeValue() {\n return decodeValue(label, definition.type, positional);\n },\n };\n },\n };\n}\n\n/**\n * Creates an optional positional — absent token falls back to `default()`.\n *\n * Syntax: `[type]`, e.g. `[NAME]`.\n * Parsing logic:\n * - \"token\" → decoded with `type.decoder(\"token\")`\n * - token missing → `default()`\n *\n * @typeParam Value - Type produced by the decoder (or the default).\n *\n * @param definition.description - Help text.\n * @param definition.hint - Short note shown in parentheses.\n * @param definition.type - Decoder for the raw token.\n * @param definition.default - Value when absent. Throw to make it required.\n * @returns A {@link Positional}`<Value>`.\n *\n * @example\n * ```ts\n * const greeteePositional = positionalOptional({\n * type: type(\"name\"),\n * description: \"Name to greet\",\n * hint: \"Defaults to \\\"world\\\"\",\n * default: () => \"world\",\n * });\n * ```\n */\nexport function positionalOptional<Value>(definition: {\n description?: string;\n hint?: string;\n type: Type<Value>;\n default: () => Value;\n}): Positional<Value> {\n const { description, hint, type } = definition;\n const label = `[${type.content}]`;\n return {\n generateUsage() {\n return { description, hint, label };\n },\n consumeAndMakeDecoder(readerPositionals: ReaderPositionals) {\n const positional = readerPositionals.consumePositional();\n return {\n decodeValue() {\n if (positional === undefined) {\n try {\n return definition.default();\n } catch (error) {\n throwsWhenFailedToGetDefault(label);\n }\n }\n return decodeValue(label, definition.type, positional);\n },\n };\n },\n };\n}\n\n/**\n * Creates a variadic positional that collects zero or more remaining tokens into an array.\n * Optionally stops at `endDelimiter` (consumed, not included).\n *\n * Syntax: `[type]...`, e.g. `[NAME]...`.\n * Parsing logic:\n * - \"a b ...\" → decoded with `[type.decoder(\"a\")`, `type.decoder(\"b\"), ...]``\n * - token missing → stops collection\n * - endDelimiter encountered → stops collection\n *\n * @typeParam Value - Type produced by the decoder for each token.\n *\n * @param definition.endDelimiter - Sentinel token that stops collection (consumed, not included).\n * @param definition.description - Help text.\n * @param definition.hint - Short note shown in parentheses.\n * @param definition.type - Decoder applied to each token.\n * @returns A {@link Positional}`<Array<Value>>`.\n *\n * @example\n * ```ts\n * const filesPositional = positionalVariadics({\n * type: typePath(),\n * description: \"Files to process\",\n * });\n * ```\n */\nexport function positionalVariadics<Value>(definition: {\n endDelimiter?: string;\n description?: string;\n hint?: string;\n type: Type<Value>;\n}): Positional<Array<Value>> {\n const { description, hint, type } = definition;\n const labelSingle = `[${type.content}]`;\n const labelMultiple =\n `${labelSingle}...` +\n (definition.endDelimiter ? ` [\"${definition.endDelimiter}\"]` : \"\");\n return {\n generateUsage() {\n return { description, hint, label: labelMultiple };\n },\n consumeAndMakeDecoder(readerPositionals: ReaderPositionals) {\n const positionals = new Array<string>();\n while (true) {\n const positional = readerPositionals.consumePositional();\n if (\n positional === undefined ||\n positional === definition.endDelimiter\n ) {\n break;\n }\n positionals.push(positional);\n }\n return {\n decodeValue() {\n return positionals.map((positional) =>\n decodeValue(labelSingle, definition.type, positional),\n );\n },\n };\n },\n };\n}\n\nfunction decodeValue<Value>(\n label: string,\n type: Type<Value>,\n input: string,\n): Value {\n return TypoError.tryWithContext(\n () => type.decoder(input),\n () => new TypoText(new TypoString(label, typoStyleUserInput)),\n );\n}\n\nfunction makeErrorText(label: string): TypoText {\n const errorText = new TypoText();\n errorText.push(new TypoString(label, typoStyleUserInput));\n return errorText;\n}\n\nfunction throwsWhenFailedToGetDefault(label: string): never {\n const errorText = makeErrorText(label);\n errorText.push(new TypoString(`: Failed to get default value.`));\n throw new TypoError(errorText);\n}\n","import { suggestTextPushMessage } from \"./Suggest\";\nimport {\n TypoError,\n TypoString,\n typoStyleConstants,\n typoStyleQuote,\n TypoText,\n} from \"./Typo\";\n\n/**\n */\nexport type ReaderOptionLongSpec = {\n key: string;\n nextGuard: ReaderOptionNextGuard;\n};\n\n/**\n */\nexport type ReaderOptionShortSpec = {\n key: string;\n restGuard: ReaderOptionRestGuard;\n nextGuard: ReaderOptionNextGuard;\n};\n\n/**\n */\nexport type ReaderOptionRestGuard = (rest: string) => boolean;\n\n/**\n */\nexport type ReaderOptionNextGuard = (\n value: ReaderOptionValue,\n next: string | undefined,\n) => boolean;\n\n/**\n */\nexport type ReaderOptionResult = {\n identifier: string;\n values: ReadonlyArray<ReaderOptionValue>;\n};\n\n/**\n */\nexport type ReaderOptionValue = {\n inlined: string | null;\n separated: ReadonlyArray<string>;\n};\n\n/**\n */\nexport type ReaderOptionGetter = () => ReaderOptionResult;\n\n/**\n * Option registration/query interface. Subset of {@link ReaderArgs}.\n */\nexport type ReaderOptions = {\n registerOptionLong(longSpec: ReaderOptionLongSpec): ReaderOptionGetter;\n registerOptionShort(shortSpec: ReaderOptionShortSpec): ReaderOptionGetter;\n};\n\n/**\n * Positional consumption interface. Subset of {@link ReaderArgs}.\n */\nexport type ReaderPositionals = {\n /**\n * Returns the next positional token, parsing intervening options as side-effects.\n *\n * @returns The next positional, or `undefined` when exhausted.\n * @throws on an unrecognised option.\n */\n consumePositional(): string | undefined;\n};\n\n/**\n * Core argument parser: converts raw CLI tokens into named options and positionals.\n * Options must be registered before {@link ReaderArgs.consumePositional} is called.\n *\n * Supported syntax: `--name`, `--name value`, `--name=value`,\n * `-n`, `-n value`, `-nvalue`, `-abc` (stacked), `--` (end-of-options).\n *\n * Created internally by {@link runAndExit}; exposed for advanced / custom runners.\n */\nexport class ReaderArgs {\n #tokens: ReadonlyArray<string>;\n #parsedIndex: number;\n #parsedDouble: boolean;\n #optionLongContextByIdentifier: Map<string, Context<ReaderOptionLongSpec>>;\n #optionShortContextByIdentifier: Map<string, Context<ReaderOptionShortSpec>>;\n\n /**\n * @param tokens - Raw CLI tokens (e.g. `process.argv.slice(2)`).\n */\n constructor(tokens: ReadonlyArray<string>) {\n this.#tokens = tokens;\n this.#parsedIndex = 0;\n this.#parsedDouble = false;\n this.#optionLongContextByIdentifier = new Map();\n this.#optionShortContextByIdentifier = new Map();\n }\n\n /**\n */\n registerOptionLong(longSpec: ReaderOptionLongSpec): ReaderOptionGetter {\n const identifier = `--${longSpec.key}`;\n if (!isValidOptionKey(longSpec.key)) {\n throw new Error(`Option identifier is invalid: ${identifier}.`);\n }\n if (this.#optionLongContextByIdentifier.has(identifier)) {\n throw new Error(`Option already registered: ${identifier}.`);\n }\n const values = new Array<ReaderOptionValue>();\n this.#optionLongContextByIdentifier.set(identifier, {\n identifier,\n spec: longSpec,\n values,\n });\n return () => ({ identifier, values });\n }\n\n /**\n */\n registerOptionShort(shortSpec: ReaderOptionShortSpec): ReaderOptionGetter {\n const identifier = `-${shortSpec.key}`;\n if (!isValidOptionKey(shortSpec.key)) {\n throw new Error(`Option identifier is invalid: ${identifier}.`);\n }\n if (this.#optionShortContextByIdentifier.has(identifier)) {\n throw new Error(`Option already registered: ${identifier}.`);\n }\n for (let i = 0; i < identifier.length; i++) {\n const slicedIdentifier = identifier.slice(0, 1 + i);\n if (this.#optionShortContextByIdentifier.has(slicedIdentifier)) {\n throw new Error(\n `Option ${identifier} overlap with shorter option: ${slicedIdentifier}.`,\n );\n }\n }\n for (const otherIdentifier of this.#optionShortContextByIdentifier.keys()) {\n if (otherIdentifier.startsWith(identifier)) {\n throw new Error(\n `Option ${identifier} overlap with longer option: ${otherIdentifier}.`,\n );\n }\n }\n const values = new Array<ReaderOptionValue>();\n this.#optionShortContextByIdentifier.set(identifier, {\n identifier,\n spec: shortSpec,\n values,\n });\n return () => ({ identifier, values });\n }\n\n /**\n * Returns the next positional token; parses intervening options as a side-effect.\n * All tokens after `--` are treated as positionals.\n *\n * @returns The next positional, or `undefined` when exhausted.\n * @throws on an unrecognised option.\n */\n consumePositional(): string | undefined {\n while (true) {\n const token = this.#consumeToken();\n if (token === undefined) {\n return undefined;\n }\n if (!this.#tryConsumeAsOption(token)) {\n return token;\n }\n }\n }\n\n #consumeToken(): string | undefined {\n const token = this.#tokens[this.#parsedIndex];\n if (token === undefined) {\n return undefined;\n }\n this.#parsedIndex++;\n if (!this.#parsedDouble) {\n if (token === \"--\") {\n this.#parsedDouble = true;\n return this.#consumeToken();\n }\n }\n return token;\n }\n\n #tryConsumeAsOption(token: string): boolean {\n if (this.#parsedDouble) {\n return false;\n }\n if (token.startsWith(\"--\")) {\n const valueIndexStart = token.indexOf(\"=\");\n if (valueIndexStart === -1) {\n this.#consumeOptionLong(token, null);\n } else {\n this.#consumeOptionLong(\n token.slice(0, valueIndexStart),\n token.slice(valueIndexStart + 1),\n );\n }\n return true;\n }\n if (token.startsWith(\"-\")) {\n let shortIndexStart = 1;\n let shortIndexEnd = 2;\n while (shortIndexEnd <= token.length) {\n const identifier = `-${token.slice(shortIndexStart, shortIndexEnd)}`;\n const shortContext =\n this.#optionShortContextByIdentifier.get(identifier);\n if (shortContext !== undefined) {\n const tokenRest = token.slice(shortIndexEnd);\n if (this.#tryConsumeOptionShort(shortContext, tokenRest)) {\n return true;\n }\n shortIndexStart = shortIndexEnd;\n }\n shortIndexEnd++;\n }\n this.#throwUnknownOptionError(`-${token.slice(shortIndexStart)}`);\n }\n return false;\n }\n\n #consumeOptionLong(identifier: string, valueInlined: string | null): void {\n const longContext = this.#optionLongContextByIdentifier.get(identifier);\n if (longContext !== undefined) {\n return this.#consumeOptionValues(longContext, valueInlined);\n }\n this.#throwUnknownOptionError(identifier);\n }\n\n #tryConsumeOptionShort(\n shortContext: Context<ReaderOptionShortSpec>,\n tokenRest: string,\n ): boolean {\n if (tokenRest.startsWith(\"=\")) {\n this.#consumeOptionValues(shortContext, tokenRest.slice(1));\n return true;\n }\n if (tokenRest.length === 0) {\n this.#consumeOptionValues(shortContext, null);\n return true;\n }\n if (shortContext.spec.restGuard(tokenRest)) {\n this.#consumeOptionValues(shortContext, tokenRest);\n return true;\n }\n this.#consumeOptionValues(shortContext, null);\n return false;\n }\n\n #consumeOptionValues(\n context: Context<{ nextGuard: ReaderOptionNextGuard }>,\n valueInlined: string | null,\n ) {\n const value = { inlined: valueInlined, separated: new Array<string>() };\n const { identifier, values, spec } = context;\n values.push(value);\n while (true) {\n const nextToken = this.#tokens[this.#parsedIndex];\n if (!spec.nextGuard(value, nextToken)) {\n return;\n }\n const token = this.#consumeToken();\n if (this.#parsedDouble) {\n throw new TypoError(\n new TypoText(\n new TypoString(identifier, typoStyleConstants),\n new TypoString(`: Requires a value but got: `),\n new TypoString(`\"--\"`, typoStyleQuote),\n new TypoString(`.`),\n ),\n );\n }\n // TODO - should we allow consuming the EOF token ?\n if (token === undefined) {\n throw new TypoError(\n new TypoText(\n new TypoString(identifier, typoStyleConstants),\n new TypoString(`: Requires a value, but got end of input.`), // TODO - hint at option value syntax ?\n ),\n );\n }\n // TODO - is that weird, could a valid value start with dash ?\n if (token.startsWith(\"-\")) {\n throw new TypoError(\n new TypoText(\n new TypoString(identifier, typoStyleConstants),\n new TypoString(`: Requires a value, but got: `),\n new TypoString(`\"${token}\"`, typoStyleQuote),\n new TypoString(`.`),\n ),\n );\n }\n value.separated.push(token);\n }\n }\n\n #throwUnknownOptionError(inputIdentifier: string): never {\n const candidatesIdentifiers = [];\n for (const identifier of this.#optionLongContextByIdentifier.keys()) {\n candidatesIdentifiers.push(identifier);\n }\n for (const identifier of this.#optionShortContextByIdentifier.keys()) {\n candidatesIdentifiers.push(identifier);\n }\n const errorText = new TypoText();\n errorText.push(new TypoString(`Unknown option: `));\n errorText.push(new TypoString(`\"${inputIdentifier}\"`, typoStyleQuote));\n if (candidatesIdentifiers.length === 0) {\n errorText.push(new TypoString(`, no options are registered.`));\n } else {\n errorText.push(new TypoString(`.`));\n suggestTextPushMessage(\n errorText,\n inputIdentifier,\n candidatesIdentifiers.map((candidateIdentifier) => ({\n reference: candidateIdentifier,\n hint: new TypoString(candidateIdentifier, typoStyleConstants),\n })),\n );\n }\n throw new TypoError(errorText);\n }\n}\n\nfunction isValidOptionKey(name: string): boolean {\n return name.length > 0 && !name.includes(\"=\") && !name.includes(\"\\0\");\n}\n\ntype Context<Spec> = {\n identifier: string;\n spec: Spec;\n values: Array<ReaderOptionValue>;\n};\n","import { CommandInformation } from \"./Command\";\nimport {\n TypoGrid,\n TypoString,\n typoStyleConstants,\n typoStyleLogic,\n typoStyleRegularStrong,\n typoStyleRegularWeaker,\n typoStyleTitle,\n typoStyleUserInput,\n TypoSupport,\n TypoText,\n} from \"./Typo\";\n\n/**\n * Usage model. Produced by {@link CommandDecoder.generateUsage}, consumed by {@link usageToStyledLines}.\n */\nexport type UsageCommand = {\n /**\n * Segments of the usage line\n */\n segments: Array<{ positional: string } | { subcommand: string }>;\n /**\n * Command metadata.\n */\n information: CommandInformation;\n /**\n * Positionals in declaration order.\n */\n positionals: Array<UsagePositional>;\n /**\n * Subcommands, populated when none was selected.\n */\n subcommands: Array<UsageSubcommand>;\n /**\n * Options in registration order.\n */\n options: Array<UsageOption>;\n};\n\n/**\n * Positional metadata for the `Positionals:` section of help.\n */\nexport type UsagePositional = {\n /**\n * Help text.\n */\n description?: string | undefined;\n /**\n * Short note shown in parentheses.\n */\n hint?: string | undefined;\n /**\n * Placeholder label shown in the usage line and the `Positionals:` section.\n */\n label: string;\n};\n\n/**\n * Entry in the `Subcommands:` section.\n */\nexport type UsageSubcommand = {\n /**\n * Token the user types (e.g. `\"deploy\"`).\n */\n name: string;\n /**\n * From {@link CommandInformation.description}.\n */\n description?: string | undefined;\n /**\n * From {@link CommandInformation.hint}.\n */\n hint?: string | undefined;\n};\n\n/**\n * Option metadata for the `Options:` section of help.\n */\nexport type UsageOption = {\n /**\n * Short-form name without `-` (e.g. `\"v\"`).\n */\n short?: string | undefined;\n /**\n * Long-form name without `--` (e.g. `\"verbose\"`).\n */\n long: string;\n /**\n * Value placeholder in help (e.g. `\"<FILE>\"`).\n */\n label?: string | undefined;\n /**\n * Extra annotation appended to the option label in help.\n */\n annotation?: string | undefined; // TODO - maybe prefix/postfix would be more useful\n /**\n * Help text.\n */\n description?: string | undefined;\n /**\n * Short note shown in parentheses.\n */\n hint?: string | undefined;\n};\n\n/**\n * Converts a {@link UsageCommand} model into an array of styled lines ready to be\n * joined with `\"\\n\"` and printed to the terminal.\n *\n * The output format is:\n * ```\n * Usage: <cliName> [segments...]\n *\n * <description> (<hint>)\n * <detail lines...>\n *\n * Positionals:\n * <label> <description> (<hint>)\n *\n * Subcommands:\n * <name> <description> (<hint>)\n *\n * Options:\n * -s, --long <label><annotation> <description> (<hint>)\n *\n * Examples:\n * <explanation>\n * <command line>\n *\n * ```\n * Sections that have no entries are omitted. The trailing empty line is always included.\n *\n * Column alignment per section via {@link TypoGrid}.\n *\n * @param params.cliName - Program name for the usage line.\n * @param params.usage - From {@link CommandDecoder.generateUsage}.\n * @param params.typoSupport - Rendering mode.\n * @returns Styled lines; includes a trailing empty string.\n *\n * @example\n * ```ts\n * const lines = usageToStyledLines({\n * cliName: \"my-cli\",\n * usage: commandDecoder.generateUsage(),\n * typoSupport: TypoSupport.tty(),\n * });\n * process.stdout.write(lines.join(\"\\n\"));\n * ```\n */\nexport function usageToStyledLines(params: {\n cliName: string;\n usage: UsageCommand;\n typoSupport: TypoSupport;\n}) {\n const { cliName, usage, typoSupport } = params;\n\n const lines = new Array<string>();\n\n const segmentsText = new TypoText();\n segmentsText.push(textUsageHero(\"Usage:\"));\n segmentsText.push(textDelimiter(\" \"));\n segmentsText.push(textConstants(cliName));\n for (const segment of usage.segments) {\n segmentsText.push(textDelimiter(\" \"));\n if (\"positional\" in segment) {\n segmentsText.push(textUserInput(segment.positional));\n }\n if (\"subcommand\" in segment) {\n segmentsText.push(textConstants(segment.subcommand));\n }\n }\n lines.push(segmentsText.computeStyledString(typoSupport));\n\n lines.push(\"\");\n const introText = new TypoText();\n introText.push(textUsageText(usage.information.description));\n if (usage.information.hint !== undefined) {\n introText.push(textDelimiter(\" \"));\n introText.push(textSubtleInfo(`(${usage.information.hint})`));\n }\n lines.push(introText.computeStyledString(typoSupport));\n for (const detail of usage.information.details ?? []) {\n const detailText = new TypoText();\n detailText.push(textSubtleInfo(detail));\n lines.push(detailText.computeStyledString(typoSupport));\n }\n\n if (usage.positionals.length > 0) {\n lines.push(\"\");\n lines.push(textBlockTitle(\"Positionals:\").computeStyledString(typoSupport));\n const typoGrid = new TypoGrid();\n for (const positionalUsage of usage.positionals) {\n const typoGridRow = new Array<TypoText>();\n typoGridRow.push(new TypoText(textDelimiter(\" \")));\n typoGridRow.push(new TypoText(textUserInput(positionalUsage.label)));\n typoGridRow.push(...createInformationals(positionalUsage));\n typoGrid.pushRow(typoGridRow);\n }\n lines.push(...typoGrid.computeStyledLines(typoSupport));\n }\n\n if (usage.subcommands.length > 0) {\n lines.push(\"\");\n lines.push(textBlockTitle(\"Subcommands:\").computeStyledString(typoSupport));\n const typoGrid = new TypoGrid();\n for (const subcommandUsage of usage.subcommands) {\n const typoGridRow = new Array<TypoText>();\n typoGridRow.push(new TypoText(textDelimiter(\" \")));\n typoGridRow.push(new TypoText(textConstants(subcommandUsage.name)));\n typoGridRow.push(...createInformationals(subcommandUsage));\n typoGrid.pushRow(typoGridRow);\n }\n lines.push(...typoGrid.computeStyledLines(typoSupport));\n }\n\n if (usage.options.length > 0) {\n lines.push(\"\");\n lines.push(textBlockTitle(\"Options:\").computeStyledString(typoSupport));\n const typoGrid = new TypoGrid();\n for (const optionUsage of usage.options) {\n const typoGridRow = new Array<TypoText>();\n typoGridRow.push(new TypoText(textDelimiter(\" \")));\n if (optionUsage.short !== undefined) {\n typoGridRow.push(\n new TypoText(\n textConstants(`-${optionUsage.short}`),\n textDelimiter(\", \"),\n ),\n );\n } else {\n typoGridRow.push(new TypoText());\n }\n const longOptionText = new TypoText(\n textConstants(`--${optionUsage.long}`),\n );\n if (optionUsage.label !== undefined) {\n longOptionText.push(textDelimiter(\" \"));\n longOptionText.push(textUserInput(optionUsage.label));\n }\n if (optionUsage.annotation !== undefined) {\n longOptionText.push(textSubtleInfo(optionUsage.annotation));\n }\n typoGridRow.push(longOptionText);\n typoGridRow.push(...createInformationals(optionUsage));\n typoGrid.pushRow(typoGridRow);\n }\n lines.push(...typoGrid.computeStyledLines(typoSupport));\n }\n\n if (usage.information.examples !== undefined) {\n lines.push(\"\");\n lines.push(textBlockTitle(\"Examples:\").computeStyledString(typoSupport));\n for (const example of usage.information.examples) {\n const explanationText = new TypoText();\n explanationText.push(textDelimiter(\" \"));\n explanationText.push(textSubtleInfo(`# ${example.explanation}`));\n lines.push(explanationText.computeStyledString(typoSupport));\n const commandLineText = new TypoText();\n commandLineText.push(textDelimiter(\" \"));\n commandLineText.push(textConstants(cliName));\n for (const commandArg of example.commandArgs) {\n commandLineText.push(textDelimiter(\" \"));\n if (typeof commandArg === \"string\") {\n commandLineText.push(new TypoString(commandArg));\n } else if (\"positional\" in commandArg) {\n commandLineText.push(textUserInput(commandArg.positional));\n } else if (\"subcommand\" in commandArg) {\n commandLineText.push(textConstants(commandArg.subcommand));\n } else if (\"option\" in commandArg) {\n const option = commandArg.option;\n if (\"short\" in option) {\n commandLineText.push(textConstants(`-${option.short}`));\n } else {\n commandLineText.push(textConstants(`--${option.long}`));\n }\n if (option.inlined !== undefined) {\n commandLineText.push(textSubtleInfo(\"=\"));\n commandLineText.push(textUserInput(option.inlined));\n }\n if (option.separated !== undefined) {\n for (const separatedValue of option.separated) {\n commandLineText.push(textDelimiter(\" \"));\n commandLineText.push(textUserInput(separatedValue));\n }\n }\n }\n }\n lines.push(commandLineText.computeStyledString(typoSupport));\n }\n }\n\n lines.push(\"\");\n return lines;\n}\n\nfunction createInformationals(usage: {\n description?: string | undefined;\n hint?: string | undefined;\n}): Array<TypoText> {\n const informationals = [];\n if (usage.description !== undefined) {\n informationals.push(textDelimiter(\" \"));\n informationals.push(textUsefulInfo(usage.description));\n }\n if (usage.hint !== undefined) {\n informationals.push(textDelimiter(\" \"));\n informationals.push(textSubtleInfo(`(${usage.hint})`));\n }\n if (informationals.length > 0) {\n return [new TypoText(textDelimiter(\" \"), ...informationals)];\n }\n return [];\n}\n\nfunction textUsageHero(value: string): TypoString {\n return new TypoString(value, typoStyleLogic);\n}\n\nfunction textUsageText(value: string): TypoString {\n return new TypoString(value, typoStyleRegularStrong);\n}\n\nfunction textUsefulInfo(value: string): TypoString {\n return new TypoString(value);\n}\n\nfunction textBlockTitle(value: string): TypoString {\n return new TypoString(value, typoStyleTitle);\n}\n\nfunction textSubtleInfo(value: string): TypoString {\n return new TypoString(value, typoStyleRegularWeaker);\n}\n\nfunction textConstants(value: string): TypoString {\n return new TypoString(value, typoStyleConstants);\n}\n\nfunction textUserInput(value: string): TypoString {\n return new TypoString(value, typoStyleUserInput);\n}\n\nfunction textDelimiter(value: string): TypoString {\n return new TypoString(value);\n}\n","import { Command, CommandDecoder } from \"./Command\";\nimport { optionFlag, optionSingleValue } from \"./Option\";\nimport { ReaderArgs } from \"./Reader\";\nimport { typeChoice } from \"./Type\";\nimport { TypoSupport } from \"./Typo\";\nimport { usageToStyledLines } from \"./Usage\";\n\n/**\n * Color selection modes availables\n */\nexport type RunColorMode = \"env\" | \"always\" | \"never\" | \"mock\";\n\n/**\n * Main entry point: parses CLI arguments, executes the matched command, and exits.\n * Handles `--help`, `--version`, usage-on-error, and exit codes.\n *\n * Exit codes:\n * - `0` on success / `--help` / `--version`\n * - `1` on parse error or execution error.\n *\n * @typeParam Context - Forwarded unchanged to the handler.\n *\n * @param cliName - Program name used in usage and `--version` output.\n * @param cliArgs - Raw arguments, typically `process.argv.slice(2)`.\n * @param context - Forwarded to the handler.\n * @param command - Root {@link Command}.\n * @param options.colorSetup - Configures color support; enables `--color` flag if set to `\"flag\"`.\n * @param options.usageOnHelp - Enables `--help` flag (default `true`).\n * @param options.usageOnError - Prints usage to stderr on parse error (default `true`).\n * @param options.buildVersion - Enables `--version`; prints `<cliName> <buildVersion>`.\n * @param options.onError - Custom handler for errors.\n * @param options.onExit - Overrides `process.exit`; useful for testing.\n *\n * @returns `Promise<never>` — always calls `onExit`.\n *\n * @example\n * ```ts\n * import { runAndExit, command, operation, positionalRequired, type } from \"cli-kiss\";\n *\n * const greetCommand = command(\n * { description: \"Greet someone\" },\n * operation(\n * { options: {}, positionals: [positionalRequired({ type: type(\"name\") })] },\n * async function (_ctx, { positionals: [name] }) {\n * console.log(`Hello, ${name}!`);\n * },\n * ),\n * );\n *\n * await runAndExit(\"greet\", process.argv.slice(2), undefined, greetCommand, {\n * buildVersion: \"1.0.0\",\n * });\n * ```\n */\nexport async function runAndExit<Context>(\n cliName: string,\n cliArgs: ReadonlyArray<string>,\n context: Context,\n command: Command<Context, void>,\n options?: {\n colorSetup?: \"flag\" | RunColorMode | undefined;\n usageOnHelp?: boolean | undefined;\n usageOnError?: boolean | undefined;\n buildVersion?: string | undefined;\n onError?: ((error: unknown) => void) | undefined;\n onExit?: ((code: number) => never) | undefined;\n },\n): Promise<never> {\n const readerArgs = new ReaderArgs(cliArgs);\n const preprocessors = new Array<\n (commandDecoder: CommandDecoder<Context, void>) => undefined | number\n >();\n let typoSupport = TypoSupport.none();\n const colorSetup = options?.colorSetup ?? \"flag\";\n if (colorSetup === \"flag\") {\n const colorOption = optionSingleValue<\"auto\" | RunColorMode>({\n long: \"color\",\n type: typeChoice(\"color-mode\", [\"auto\", \"always\", \"never\"]),\n fallbackValueIfAbsent: () => \"auto\",\n impliedValueIfNotInlined: () => \"always\",\n }).registerAndMakeDecoder(readerArgs);\n preprocessors.push(() => {\n try {\n typoSupport = computeTypoSupport(colorOption.getAndDecodeValue());\n } catch (error) {\n typoSupport = TypoSupport.inferFromEnv();\n throw error;\n }\n return undefined;\n });\n } else {\n typoSupport = computeTypoSupport(colorSetup);\n }\n if (options?.usageOnHelp ?? true) {\n const helpOption = optionFlag({ long: \"help\" }).registerAndMakeDecoder(\n readerArgs,\n );\n preprocessors.push((commandDecoder) => {\n if (!helpOption.getAndDecodeValue()) {\n return undefined;\n }\n console.log(computeUsageString(cliName, commandDecoder, typoSupport));\n return 0;\n });\n }\n if (options?.buildVersion !== undefined) {\n const versionOption = optionFlag({\n long: \"version\",\n }).registerAndMakeDecoder(readerArgs);\n preprocessors.push(() => {\n if (!versionOption.getAndDecodeValue()) {\n return undefined;\n }\n console.log([cliName, options.buildVersion].join(\" \"));\n return 0;\n });\n }\n // TODO - the lifecycle of this function should be improved\n // TODO - how to pass the color information to the command logic ?\n /*\n // TODO - handle completions ?\n readerArgs.registerFlag({\n key: \"completion\",\n shorts: [],\n longs: [\"completion\"],\n });\n */\n const commandDecoder = command.consumeAndMakeDecoder(readerArgs);\n while (true) {\n try {\n const positional = readerArgs.consumePositional();\n if (positional === undefined) {\n break;\n }\n } catch (_) {}\n }\n const onExit = options?.onExit ?? process.exit;\n try {\n for (const preprocessor of preprocessors) {\n const preprocessorResult = preprocessor(commandDecoder);\n if (preprocessorResult !== undefined) {\n return onExit(preprocessorResult);\n }\n }\n const commandInterpreter = commandDecoder.decodeAndMakeInterpreter();\n try {\n await commandInterpreter.executeWithContext(context);\n return onExit(0);\n } catch (executionError) {\n handleError(cliName, options?.onError, executionError, typoSupport);\n return onExit(1);\n }\n } catch (parsingError) {\n if (options?.usageOnError ?? true) {\n console.error(computeUsageString(cliName, commandDecoder, typoSupport));\n }\n handleError(cliName, options?.onError, parsingError, typoSupport);\n return onExit(1);\n }\n}\n\nfunction handleError(\n _cliName: string,\n onError: ((error: unknown) => void) | undefined,\n error: unknown,\n typoSupport: TypoSupport,\n) {\n // TODO - should the cliName be part of the error message for logs ?\n const finalError = error;\n /*\n const finalError = new TypoError(\n new TypoText(new TypoString(cliName, typoStyleConstants)),\n error,\n );\n */\n if (onError !== undefined) {\n onError(finalError);\n } else {\n console.error(typoSupport.computeStyledErrorMessage(finalError));\n }\n}\n\nfunction computeUsageString<Context, Result>(\n cliName: string,\n commandDecoder: CommandDecoder<Context, Result>,\n typoSupport: TypoSupport,\n) {\n return usageToStyledLines({\n cliName,\n usage: commandDecoder.generateUsage(),\n typoSupport,\n }).join(\"\\n\");\n}\n\nfunction computeTypoSupport(colorMode: \"auto\" | RunColorMode): TypoSupport {\n switch (colorMode) {\n case \"auto\":\n return TypoSupport.inferFromEnv();\n case \"env\":\n return TypoSupport.inferFromEnv();\n case \"always\":\n return TypoSupport.tty();\n case \"never\":\n return Typ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OAASM,EAAc,CACrB,OAAIvB,GAAS,cAAgB,KAC3B,QAAQ,MAAMe,GAAmBnB,EAASkB,EAAgBV,CAAW,CAAC,EAExEkB,GAAY1B,EAASI,GAAS,QAASuB,EAAcnB,CAAW,EACzDa,EAAO,CAAC,CACjB,CACF,CAEA,SAASK,GACPE,EACAC,EACAd,EACAP,EACA,CAEA,IAAMsB,EAAaf,EAOfc,IAAY,OACdA,EAAQC,CAAU,EAElB,QAAQ,MAAMtB,EAAY,0BAA0BsB,CAAU,CAAC,CAEnE,CAEA,SAASX,GACPnB,EACAkB,EACAV,EACA,CACA,OAAOuB,GAAmB,CACxB,QAAA/B,EACA,MAAOkB,EAAe,cAAc,EACpC,YAAAV,CACF,CAAC,EAAE,KAAK;AAAA,CAAI,CACd,CAEA,SAASM,GAAmBkB,EAA+C,CACzE,OAAQA,EAAW,CACjB,IAAK,OACH,OAAOvB,EAAY,aAAa,EAClC,IAAK,MACH,OAAOA,EAAY,aAAa,EAClC,IAAK,SACH,OAAOA,EAAY,IAAI,EACzB,IAAK,QACH,OAAOA,EAAY,KAAK,EAC1B,IAAK,OACH,OAAOA,EAAY,KAAK,CAC5B,CACF","names":["index_exports","__export","ReaderArgs","TypoError","TypoGrid","TypoString","TypoSupport","TypoText","command","commandChained","commandWithSubcommands","operation","optionFlag","optionRepeatable","optionSingleValue","positionalOptional","positionalRequired","positionalVariadics","runAndExit","suggestTextPushMessage","type","typeBoolean","typeChoice","typeConverted","typeDatetime","typeInteger","typeList","typeNumber","typePath","typeRenamed","typeTuple","typeUrl","typoStyleConstants","typoStyleFailure","typoStyleLogic","typoStyleQuote","typoStyleRegularStrong","typoStyleRegularWeaker","typoStyleTitle","typoStyleUserInput","usageToStyledLines","__toCommonJS","typoStyleTitle","typoStyleLogic","typoStyleQuote","typoStyleFailure","typoStyleConstants","typoStyleUserInput","typoStyleRegularStrong","typoStyleRegularWeaker","_value","_style","_TypoString","value","style","__privateAdd","__privateSet","typoSupport","__privateGet","TypoString","_strings","_TypoText","segments","segment","part","separator","ellipsisLimit","index","t","length","typoString","TypoText","_typoRows","TypoGrid","cells","widths","styledLines","typoGridRow","typoGridColumnIndex","width","styledGridRow","typoGridCell","padding","_typoText","_TypoError","currentTypoText","source","typoText","thrower","context","error","TypoError","_kind","_TypoSupport","kind","readEnvVar","envForceColor","typoStyle","styledValue","fgColorCode","ttyCodeFgColors","bgColorCode","ttyCodeBgColors","boldCode","ttyCodeBold","dimCode","ttyCodeDim","italicCode","ttyCodeItalic","underlineCode","ttyCodeUnderline","strikethroughCode","ttyCodeStrikethrough","ttyCodeReset","fgColorPart","bgColorPart","boldPart","dimPart","italicPart","underlinePart","TypoSupport","name","suggestTextPushMessage","text","query","candidates","reasonableHints","suggestReasonablePayloads","reference","hint","TypoString","sortedAlternatives","computeAndSortByDivergences","divergenceThreshold","acceptablePayloads","divergence","payload","queryNormalized","referenceNormalized","distanceDamerauLevenshtein","a","b","m","n","dp","i","j","cost","command","information","operation","readerArgs","operationDecoder","endPositional","errorText","TypoText","TypoString","typoStyleQuote","TypoError","generateUsageLeaf","operationInterpreter","context","error","commandWithSubcommands","subcommands","subcommandNames","subcommandName","typoStyleUserInput","suggestSubcommandNames","subcommandInput","subcommandDecoder","subcommandUsage","currentUsage","subcommandInterpreter","name","subcommand","description","hint","commandChained","positionals","options","p","input","suggestTextPushMessage","typoStyleConstants","operation","inputs","handler","optionsUsage","optionKey","optionInput","positionalsUsage","positionalInput","readerArgs","optionsDecoders","positionalsDecoders","optionsValues","positionalsValues","positionalDecoder","context","import_fs","typeBoolean","name","input","lowerInput","typeBooleanValuesTrue","typeBooleanValuesFalse","throwInvalidValue","typeDatetime","timestampMs","typeNumber","parsed","typeInteger","typeUrl","type","typeConverted","before","mapper","TypoError","TypoText","TypoString","typoStyleLogic","typeRenamed","typePath","checks","safeStatSync","path","error","typoStyleQuote","stats","preview","typeChoice","values","caseSensitive","normalize","valueByNormalized","value","errorText","suggestTextPushMessage","typeTuple","elementTypes","separator","elementType","splits","split","index","typeList","kind","optionFlag","definition","type","typeBoolean","long","short","description","hint","aliases","readerOptions","resultsGetter","setupOptionAliased","results","throwSetMultipleTimesError","r","input","decodeValue","optionSingleValue","label","annotation","value","result","errorText","makeErrorText","TypoString","TypoError","error","inlined","separated","optionRepeatable","params","TypoText","typoStyleConstants","typoStyleUserInput","typoStyleLogic","longKey","shortKey","aliasLongKeys","aliasShortKeys","longKeys","shortKeys","setupOptionMany","restGuard","nextGuard","getters","key","getter","identifier","values","identifiers","identifiersTexts","positionalRequired","definition","description","hint","type","label","readerPositionals","positional","errorText","makeErrorText","TypoString","typoStyleRegularWeaker","TypoError","decodeValue","positionalOptional","throwsWhenFailedToGetDefault","positionalVariadics","labelSingle","labelMultiple","positionals","input","TypoText","typoStyleUserInput","_tokens","_parsedIndex","_parsedDouble","_optionLongContextByIdentifier","_optionShortContextByIdentifier","_ReaderArgs_instances","consumeToken_fn","tryConsumeAsOption_fn","consumeOptionLong_fn","tryConsumeOptionShort_fn","consumeOptionValues_fn","throwUnknownOptionError_fn","ReaderArgs","tokens","__privateAdd","__privateSet","longSpec","identifier","isValidOptionKey","__privateGet","values","shortSpec","i","slicedIdentifier","otherIdentifier","token","__privateMethod","__privateWrapper","valueIndexStart","shortIndexStart","shortIndexEnd","shortContext","tokenRest","valueInlined","longContext","context","value","spec","nextToken","TypoError","TypoText","TypoString","typoStyleConstants","typoStyleQuote","inputIdentifier","candidatesIdentifiers","errorText","suggestTextPushMessage","candidateIdentifier","name","usageToStyledLines","params","cliName","usage","typoSupport","lines","segmentsText","TypoText","textUsageHero","textDelimiter","textConstants","segment","textUserInput","introText","textUsageText","textSubtleInfo","detail","detailText","textBlockTitle","typoGrid","TypoGrid","positionalUsage","typoGridRow","createInformationals","subcommandUsage","optionUsage","longOptionText","example","explanationText","commandLineText","commandArg","TypoString","option","separatedValue","informationals","textUsefulInfo","value","typoStyleLogic","typoStyleRegularStrong","typoStyleTitle","typoStyleRegularWeaker","typoStyleConstants","typoStyleUserInput","runAndExit","cliName","cliArgs","context","command","options","readerArgs","ReaderArgs","preprocessors","typoSupport","TypoSupport","colorSetup","colorOption","optionSingleValue","typeChoice","computeTypoSupport","error","helpOption","optionFlag","commandDecoder","computeUsageString","versionOption","onExit","preprocessor","preprocessorResult","commandInterpreter","executionError","handleError","parsingError","_cliName","onError","finalError","usageToStyledLines","colorMode"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/lib/Typo.ts","../src/lib/Suggest.ts","../src/lib/Command.ts","../src/lib/Operation.ts","../src/lib/Type.ts","../src/lib/Option.ts","../src/lib/Positional.ts","../src/lib/Reader.ts","../src/lib/Usage.ts","../src/lib/Run.ts"],"sourcesContent":["export * from \"./lib/Command\";\nexport * from \"./lib/Operation\";\nexport * from \"./lib/Option\";\nexport * from \"./lib/Positional\";\nexport * from \"./lib/Reader\";\nexport * from \"./lib/Run\";\nexport * from \"./lib/Suggest\";\nexport * from \"./lib/Type\";\nexport * from \"./lib/Typo\";\nexport * from \"./lib/Usage\";\n","/**\n * Color names for terminal styling, used by {@link TypoStyle}.\n * `dark*` = standard ANSI (30–37); `bright*` = high-intensity (90–97).\n */\nexport type TypoColor =\n | \"darkBlack\"\n | \"darkRed\"\n | \"darkGreen\"\n | \"darkYellow\"\n | \"darkBlue\"\n | \"darkMagenta\"\n | \"darkCyan\"\n | \"darkWhite\"\n | \"brightBlack\"\n | \"brightRed\"\n | \"brightGreen\"\n | \"brightYellow\"\n | \"brightBlue\"\n | \"brightMagenta\"\n | \"brightCyan\"\n | \"brightWhite\";\n\n/**\n * Visual styling applied by a {@link TypoSupport} instance.\n * All fields are optional; ignored entirely in `\"none\"` mode.\n */\nexport type TypoStyle = {\n /**\n * Letter case.\n */\n case?: \"upper\" | \"lower\";\n /**\n * Foreground (text) color.\n */\n fgColor?: TypoColor;\n /**\n * Background color.\n */\n bgColor?: TypoColor;\n /**\n * Reduced intensity.\n */\n dim?: boolean;\n /**\n * Bold.\n */\n bold?: boolean;\n /**\n * Italic.\n */\n italic?: boolean;\n /**\n * Underline.\n */\n underline?: boolean;\n /**\n * Strikethrough.\n */\n strikethrough?: boolean;\n};\n\n/**\n * Section title style. Bold dark-green.\n */\nexport const typoStyleTitle: TypoStyle = {\n fgColor: \"darkGreen\",\n bold: true,\n};\n/**\n * Logic/type identifier style. Bold dark-magenta.\n */\nexport const typoStyleLogic: TypoStyle = {\n fgColor: \"darkMagenta\",\n bold: true,\n};\n/**\n * Quoted user-input style. Bold dark-yellow.\n */\nexport const typoStyleQuote: TypoStyle = {\n fgColor: \"darkYellow\",\n bold: true,\n};\n\n/**\n * Error label style. Bold dark-red.\n */\nexport const typoStyleFailure: TypoStyle = {\n fgColor: \"darkRed\",\n bold: true,\n};\n\n/**\n * Option/command name style. Bold dark-cyan.\n */\nexport const typoStyleConstants: TypoStyle = {\n fgColor: \"darkCyan\",\n bold: true,\n};\n/**\n * Positional/user-input label style. Bold dark-blue.\n */\nexport const typoStyleUserInput: TypoStyle = {\n fgColor: \"darkBlue\",\n bold: true,\n};\n\n/**\n * Strong text style. Bold.\n */\nexport const typoStyleRegularStrong: TypoStyle = {\n bold: true,\n};\n/**\n * Subtle text style. Italic and dim.\n */\nexport const typoStyleRegularWeaker: TypoStyle = {\n italic: true,\n dim: true,\n};\n\n/**\n * Immutable styled string segment. Compose into a {@link TypoText}.\n */\nexport class TypoString {\n #value: string;\n #style: TypoStyle | undefined;\n /**\n * @param value - Raw text content.\n * @param style - Style to apply when rendering.\n */\n constructor(value: string, style?: TypoStyle) {\n this.#value = value;\n this.#style = style;\n }\n /**\n * Returns the text styled by `typoSupport`.\n *\n * @param typoSupport - Rendering mode.\n */\n computeStyledString(typoSupport: TypoSupport): string {\n return typoSupport.computeStyledString(this.#value, this.#style);\n }\n /**\n * Returns the raw text.\n */\n getRawString(): string {\n // TODO - should there be a global config or smthg instead of passing support everywhere?\n return this.#value;\n }\n /**\n * Predefined ellipsis segment with subtle styling.\n */\n static elipsis = new TypoString(\"...\", typoStyleRegularWeaker);\n}\n\n/**\n * A segment of styled text, a string, or an array of segments.\n */\nexport type TypoSegment = TypoText | TypoString | Array<TypoSegment>;\n\n/**\n * Mutable sequence of {@link TypoString} segments.\n */\nexport class TypoText {\n #strings: Array<TypoString>;\n /**\n * @param segments - Initial text segments\n */\n constructor(...segments: Array<TypoSegment>) {\n this.#strings = [];\n for (const segment of segments) {\n this.push(segment);\n }\n }\n /**\n * Appends new text segment(s).\n */\n push(...segments: Array<TypoSegment>): void {\n for (const segment of segments) {\n if (typeof segment === \"string\") {\n this.#strings.push(new TypoString(segment));\n } else if (segment instanceof TypoString) {\n this.#strings.push(segment);\n } else if (segment instanceof TypoText) {\n this.#strings.push(...segment.#strings);\n } else if (Array.isArray(segment)) {\n for (const part of segment) {\n this.push(part);\n }\n }\n }\n }\n /**\n * Appends separated segments, optionally truncating with an ellipsis.\n */\n pushJoined(\n segments: Array<TypoSegment>,\n separator: TypoSegment,\n ellipsisLimit: number,\n ): void {\n for (let index = 0; index < segments.length; index++) {\n if (index > 0) {\n this.push(separator);\n }\n if (ellipsisLimit !== undefined && index >= ellipsisLimit) {\n this.push(TypoString.elipsis);\n break;\n }\n this.push(segments[index]!);\n }\n }\n /**\n * Renders all segments into a single styled string.\n *\n * @param typoSupport - Rendering mode.\n * @returns Concatenated styled string.\n */\n computeStyledString(typoSupport: TypoSupport): string {\n return this.#strings\n .map((t) => t.computeStyledString(typoSupport))\n .join(\"\");\n }\n /**\n * Returns the concatenated raw text.\n */\n computeRawString(): string {\n return this.#strings.map((t) => t.getRawString()).join(\"\");\n }\n /**\n * Returns the total raw character count.\n */\n computeRawLength(): number {\n let length = 0;\n for (const typoString of this.#strings) {\n length += typoString.getRawString().length;\n }\n return length;\n }\n}\n\n/**\n * Column-aligned grid of {@link TypoText} cells.\n * Each column is padded to the widest cell (raw chars); the last column is not padded.\n */\nexport class TypoGrid {\n #typoRows: Array<Array<TypoText>>;\n constructor() {\n this.#typoRows = [];\n }\n /**\n * Appends a row. All rows should have the same cell count.\n *\n * @param cells - Ordered {@link TypoText} cells.\n */\n pushRow(cells: Array<TypoText>) {\n this.#typoRows.push(cells);\n }\n /**\n * Renders as an array of styled, column-padded strings.\n *\n * @param typoSupport - Rendering mode.\n * @returns Array of styled strings.\n */\n computeStyledLines(typoSupport: TypoSupport): Array<string> {\n const widths = new Array<number>();\n const styledLines = new Array<string>();\n for (const typoGridRow of this.#typoRows) {\n for (\n let typoGridColumnIndex = 0;\n typoGridColumnIndex < typoGridRow.length;\n typoGridColumnIndex++\n ) {\n const typoGridCell = typoGridRow[typoGridColumnIndex]!;\n const width = typoGridCell.computeRawLength();\n if (\n widths[typoGridColumnIndex] === undefined ||\n width > widths[typoGridColumnIndex]!\n ) {\n widths[typoGridColumnIndex] = width;\n }\n }\n }\n for (const typoGridRow of this.#typoRows) {\n const styledGridRow = new Array<string>();\n for (\n let typoGridColumnIndex = 0;\n typoGridColumnIndex < typoGridRow.length;\n typoGridColumnIndex++\n ) {\n const typoGridCell = typoGridRow[typoGridColumnIndex]!;\n styledGridRow.push(typoGridCell.computeStyledString(typoSupport));\n if (typoGridColumnIndex < typoGridRow.length - 1) {\n const width = typoGridCell.computeRawLength();\n const padding = \" \".repeat(widths[typoGridColumnIndex]! - width);\n styledGridRow.push(padding);\n }\n }\n styledLines.push(styledGridRow.join(\"\"));\n }\n return styledLines;\n }\n}\n\n/**\n * `Error` subclass with a {@link TypoText} styled message for rich terminal output.\n * Chains `TypoError` sources after `\": \"`.\n */\nexport class TypoError extends Error {\n #typoText: TypoText;\n /**\n * @param currentTypoText - Styled message for this error.\n * @param source - Optional cause; `TypoError` chains styled text, `Error` appends `.message`, else `String()`.\n */\n constructor(currentTypoText: TypoText, source?: unknown) {\n const typoText = new TypoText();\n typoText.push(currentTypoText);\n if (source instanceof TypoError) {\n typoText.push(new TypoString(\": \"));\n typoText.push(source.#typoText);\n } else if (source instanceof Error) {\n typoText.push(new TypoString(`: ${source.message}`));\n } else if (source !== undefined) {\n typoText.push(new TypoString(`: ${String(source)}`));\n }\n super(typoText.computeRawString());\n this.#typoText = typoText;\n }\n /**\n * Renders the styled message (without `\"Error:\"` prefix).\n *\n * @param typoSupport - Rendering mode.\n * @returns Styled error string.\n */\n computeStyledString(typoSupport: TypoSupport): string {\n return this.#typoText.computeStyledString(typoSupport);\n }\n /**\n * Runs `thrower`; wraps any thrown error as a `TypoError` with `context()` prepended.\n *\n * @typeParam Value - Return type of `thrower`.\n * @param thrower - Function to execute; result passed through on success.\n * @param context - Produces the {@link TypoText} prepended to the caught error.\n * @returns Value from `thrower`.\n * @throws `TypoError` wrapping the original error with context prepended.\n */\n static tryWithContext<Value>(\n thrower: () => Value,\n context: () => TypoText,\n ): Value {\n try {\n return thrower();\n } catch (error) {\n throw new TypoError(context(), error);\n }\n }\n}\n\n/**\n * Controls ANSI terminal styling. Create via the static factory methods.\n */\nexport class TypoSupport {\n #kind: TypoSupportKind;\n private constructor(kind: TypoSupportKind) {\n this.#kind = kind;\n }\n /**\n * Plain text — no ANSI codes.\n */\n static none(): TypoSupport {\n return new TypoSupport(\"none\");\n }\n /**\n * ANSI escape codes for color terminals.\n */\n static tty(): TypoSupport {\n return new TypoSupport(\"tty\");\n }\n /**\n * Deterministic textual styling for snapshot tests.\n */\n static mock(): TypoSupport {\n return new TypoSupport(\"mock\");\n }\n /**\n * Auto-detects styling mode from the process environment on best-effort basis.\n */\n static inferFromEnv(): TypoSupport {\n if (!process || !process.env || !process.stdout) {\n return TypoSupport.none();\n }\n if (readEnvVar(\"NO_COLOR\")) {\n return TypoSupport.none();\n }\n const envForceColor = readEnvVar(\"FORCE_COLOR\");\n if (envForceColor === \"0\") {\n return TypoSupport.none();\n }\n if (envForceColor === \"1\") {\n return TypoSupport.tty();\n }\n if (envForceColor === \"2\") {\n return TypoSupport.tty();\n }\n if (envForceColor === \"3\") {\n return TypoSupport.tty();\n }\n if (envForceColor) {\n return TypoSupport.tty();\n }\n if (!process.stdout.isTTY) {\n return TypoSupport.none();\n }\n if (readEnvVar(\"TERM\")?.toLowerCase() === \"dumb\") {\n return TypoSupport.none();\n }\n return TypoSupport.tty();\n }\n /**\n * Applies `typoStyle` to `value` according to the current mode.\n *\n * @param value - Raw text.\n * @param typoStyle - Style to apply.\n * @returns Styled string.\n */\n computeStyledString(value: string, typoStyle: TypoStyle | undefined): string {\n if (typoStyle === undefined) {\n return value;\n }\n let styledValue = value;\n if (typoStyle.case === \"upper\") {\n styledValue = styledValue.toUpperCase();\n }\n if (typoStyle.case === \"lower\") {\n styledValue = styledValue.toLowerCase();\n }\n if (this.#kind === \"none\") {\n return styledValue;\n }\n if (this.#kind === \"tty\") {\n const fgColorCode = typoStyle.fgColor\n ? ttyCodeFgColors[typoStyle.fgColor]\n : \"\";\n const bgColorCode = typoStyle.bgColor\n ? ttyCodeBgColors[typoStyle.bgColor]\n : \"\";\n const boldCode = typoStyle.bold ? ttyCodeBold : \"\";\n const dimCode = typoStyle.dim ? ttyCodeDim : \"\";\n const italicCode = typoStyle.italic ? ttyCodeItalic : \"\";\n const underlineCode = typoStyle.underline ? ttyCodeUnderline : \"\";\n const strikethroughCode = typoStyle.strikethrough\n ? ttyCodeStrikethrough\n : \"\";\n return `${fgColorCode}${bgColorCode}${boldCode}${dimCode}${italicCode}${underlineCode}${strikethroughCode}${styledValue}${ttyCodeReset}`;\n }\n if (this.#kind === \"mock\") {\n const fgColorPart = typoStyle.fgColor\n ? `{${styledValue}}@${typoStyle.fgColor}`\n : styledValue;\n const bgColorPart = typoStyle.bgColor\n ? `{${fgColorPart}}#${typoStyle.bgColor}`\n : fgColorPart;\n const boldPart = typoStyle.bold ? `{${bgColorPart}}+` : bgColorPart;\n const dimPart = typoStyle.dim ? `{${boldPart}}-` : boldPart;\n const italicPart = typoStyle.italic ? `{${dimPart}}*` : dimPart;\n const underlinePart = typoStyle.underline\n ? `{${italicPart}}_`\n : italicPart;\n const strikethroughPart = typoStyle.strikethrough\n ? `{${underlinePart}}~`\n : underlinePart;\n return strikethroughPart;\n }\n throw new Error(`Unknown TypoSupport kind: ${this.#kind}`);\n }\n /**\n * Formats any thrown value as `\"Error: <message>\"` with {@link typoStyleFailure} on the prefix.\n *\n * @param error - Any thrown value.\n * @returns Styled error string.\n */\n computeStyledErrorMessage(error: unknown): string {\n return [\n this.computeStyledString(\"Error:\", typoStyleFailure),\n error instanceof TypoError\n ? error.computeStyledString(this)\n : error instanceof Error\n ? error.message\n : String(error),\n ].join(\" \");\n }\n}\n\nconst ttyCodeReset = \"\\x1b[0m\";\nconst ttyCodeBold = \"\\x1b[1m\";\nconst ttyCodeDim = \"\\x1b[2m\";\nconst ttyCodeItalic = \"\\x1b[3m\";\nconst ttyCodeUnderline = \"\\x1b[4m\";\nconst ttyCodeStrikethrough = \"\\x1b[9m\";\nconst ttyCodeFgColors: Record<TypoColor, string> = {\n darkBlack: \"\\x1b[30m\",\n darkRed: \"\\x1b[31m\",\n darkGreen: \"\\x1b[32m\",\n darkYellow: \"\\x1b[33m\",\n darkBlue: \"\\x1b[34m\",\n darkMagenta: \"\\x1b[35m\",\n darkCyan: \"\\x1b[36m\",\n darkWhite: \"\\x1b[37m\",\n brightBlack: \"\\x1b[90m\",\n brightRed: \"\\x1b[91m\",\n brightGreen: \"\\x1b[92m\",\n brightYellow: \"\\x1b[93m\",\n brightBlue: \"\\x1b[94m\",\n brightMagenta: \"\\x1b[95m\",\n brightCyan: \"\\x1b[96m\",\n brightWhite: \"\\x1b[97m\",\n};\nconst ttyCodeBgColors: Record<TypoColor, string> = {\n darkBlack: \"\\x1b[40m\",\n darkRed: \"\\x1b[41m\",\n darkGreen: \"\\x1b[42m\",\n darkYellow: \"\\x1b[43m\",\n darkBlue: \"\\x1b[44m\",\n darkMagenta: \"\\x1b[45m\",\n darkCyan: \"\\x1b[46m\",\n darkWhite: \"\\x1b[47m\",\n brightBlack: \"\\x1b[100m\",\n brightRed: \"\\x1b[101m\",\n brightGreen: \"\\x1b[102m\",\n brightYellow: \"\\x1b[103m\",\n brightBlue: \"\\x1b[104m\",\n brightMagenta: \"\\x1b[105m\",\n brightCyan: \"\\x1b[106m\",\n brightWhite: \"\\x1b[107m\",\n};\n\nfunction readEnvVar(name: string) {\n if (!(name in process.env)) {\n return undefined;\n }\n return process.env[name];\n}\n\ntype TypoSupportKind = \"none\" | \"tty\" | \"mock\";\n","import { TypoSegment, TypoString, TypoText } from \"./Typo\";\n\nexport function suggestTextPushMessage(\n text: TypoText,\n query: string,\n candidates: Array<{ reference: string; hint: TypoSegment }>,\n) {\n const reasonableHints = suggestReasonablePayloads(\n query,\n candidates.map(({ reference, hint }) => ({ reference, payload: hint })),\n );\n if (reasonableHints.length === 0) {\n return;\n }\n text.push(new TypoString(\" Did you mean: \"));\n text.pushJoined(reasonableHints, new TypoString(\", \"), 3);\n text.push(new TypoString(` ?`));\n}\n\nfunction suggestReasonablePayloads<Payload>(\n query: string,\n candidates: Array<{ reference: string; payload: Payload }>,\n): Array<Payload> {\n if (candidates.length === 0) {\n return [];\n }\n const sortedAlternatives = computeAndSortByDivergences(query, candidates);\n const divergenceThreshold = sortedAlternatives[0]!.divergence + 0.25;\n const acceptablePayloads = new Array<Payload>();\n for (const { divergence, payload } of sortedAlternatives) {\n if (divergence > divergenceThreshold) {\n break;\n }\n acceptablePayloads.push(payload);\n }\n return acceptablePayloads;\n}\n\nfunction computeAndSortByDivergences<Payload>(\n query: string,\n candidates: Array<{ reference: string; payload: Payload }>,\n): Array<{ divergence: number; payload: Payload }> {\n const queryNormalized = query.toLowerCase().slice(0, 100);\n const scored = candidates.map(({ reference, payload }) => {\n const referenceNormalized = reference.toLowerCase().slice(0, 100);\n const divergence =\n distanceDamerauLevenshtein(queryNormalized, referenceNormalized) /\n Math.max(queryNormalized.length, referenceNormalized.length);\n return { divergence, reference, payload };\n });\n return scored.sort((a, b) => a.divergence - b.divergence);\n}\n\nfunction distanceDamerauLevenshtein(a: string, b: string): number {\n const m = a.length;\n const n = b.length;\n const dp = Array.from({ length: m + 1 }, () => Array<number>(n + 1).fill(0));\n for (let i = 0; i <= m; i++) {\n dp[i]![0] = i;\n }\n for (let j = 0; j <= n; j++) {\n dp[0]![j] = j;\n }\n for (let i = 1; i <= m; i++) {\n for (let j = 1; j <= n; j++) {\n const cost = a[i - 1] === b[j - 1] ? 0 : 1;\n dp[i]![j] = Math.min(\n dp[i - 1]![j]! + 1,\n dp[i]![j - 1]! + 1,\n dp[i - 1]![j - 1]! + cost,\n );\n if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {\n dp[i]![j] = Math.min(dp[i]![j]!, dp[i - 2]![j - 2]! + cost);\n }\n }\n }\n return dp[m]![n]!;\n}\n","import { Operation } from \"./Operation\";\nimport { ReaderArgs } from \"./Reader\";\nimport { suggestTextPushMessage } from \"./Suggest\";\nimport {\n TypoError,\n TypoString,\n typoStyleConstants,\n typoStyleQuote,\n typoStyleUserInput,\n TypoText,\n} from \"./Typo\";\nimport { UsageCommand } from \"./Usage\";\n\n/**\n * A CLI command. Created with {@link command}, {@link commandWithSubcommands}, or {@link commandChained}.\n *\n * @typeParam Context - Injected at execution; forwarded to handlers.\n * @typeParam Result - Produced on execution; typically `void`.\n */\nexport type Command<Context, Result = void> = {\n /**\n * Returns static metadata.\n */\n getInformation(): CommandInformation;\n /**\n * Registers options/positionals on `readerArgs`; returns a {@link CommandDecoder}.\n */\n consumeAndMakeDecoder(\n readerArgs: ReaderArgs,\n ): CommandDecoder<Context, Result>;\n};\n\n/**\n * Produced by {@link Command.consumeAndMakeDecoder}.\n *\n * @typeParam Context - See {@link Command}.\n * @typeParam Result - See {@link Command}.\n */\nexport type CommandDecoder<Context, Result> = {\n /**\n * Returns {@link UsageCommand} for the current command path.\n */\n generateUsage(): UsageCommand;\n /**\n * Creates a ready-to-execute {@link CommandInterpreter}.\n *\n * @throws if parsing or decoding failed.\n */\n decodeAndMakeInterpreter(): CommandInterpreter<Context, Result>;\n};\n\n/**\n * A fully parsed, decoded and ready-to-execute command.\n *\n * @typeParam Context - Context passed to the handler.\n * @typeParam Result - Value produced on success.\n */\nexport type CommandInterpreter<Context, Result> = {\n /**\n * Executes with the provided context.\n */\n executeWithContext(context: Context): Promise<Result>;\n};\n\n/**\n * Command metadata shown in `--help` output.\n */\nexport type CommandInformation = {\n /**\n * Shown in the usage header.\n */\n description: string;\n /**\n * Shown in parentheses, e.g. `\"deprecated\"`, `\"experimental\"`.\n */\n hint?: string;\n /**\n * Extra lines printed below the description.\n */\n details?: Array<string>;\n /**\n * Shown in the `Examples:` section.\n */\n examples?: Array<{\n // TODO - a nicer example system, maybe with --help=example support\n /**\n * Explanation shown above the example.\n */\n explanation: string;\n /**\n * Example command args.\n */\n commandArgs: Array<\n | string\n | { positional: string }\n | { subcommand: string }\n | {\n option:\n | { long: string; inlined?: string; separated?: Array<string> }\n | { short: string; inlined?: string; separated?: Array<string> };\n }\n >;\n }>;\n};\n\n/**\n * Creates a leaf command that directly executes an {@link Operation}.\n *\n * @typeParam Context - Context forwarded to the handler.\n * @typeParam Result - Value returned by the handler.\n *\n * @param information - Command metadata.\n * @param operation - Options, positionals, and handler.\n * @returns A {@link Command}.\n *\n * @example\n * ```ts\n * const greet = command(\n * { description: \"Greet a user\" },\n * operation(\n * { positionals: [positionalRequired({ type: type(\"name\") })] },\n * async (_ctx, { positionals: [name] }) => console.log(`Hello, ${name}!`),\n * ),\n * );\n * ```\n */\nexport function command<Context, Result = void>(\n information: CommandInformation,\n operation: Operation<Context, Result>,\n): Command<Context, Result> {\n return {\n getInformation() {\n return information;\n },\n consumeAndMakeDecoder(readerArgs: ReaderArgs) {\n try {\n const operationDecoder = operation.consumeAndMakeDecoder(readerArgs);\n const endPositional = readerArgs.consumePositional();\n if (endPositional !== undefined) {\n const errorText = new TypoText();\n errorText.push(new TypoString(`Unexpected argument: `));\n errorText.push(new TypoString(`\"${endPositional}\"`, typoStyleQuote));\n errorText.push(new TypoString(`.`));\n throw new TypoError(errorText);\n }\n return {\n generateUsage: () => generateUsageLeaf(information, operation),\n decodeAndMakeInterpreter() {\n const operationInterpreter =\n operationDecoder.decodeAndMakeInterpreter();\n return {\n async executeWithContext(context: Context) {\n return await operationInterpreter.executeWithContext(context);\n },\n };\n },\n };\n } catch (error) {\n return {\n generateUsage: () => generateUsageLeaf(information, operation),\n decodeAndMakeInterpreter() {\n throw error;\n },\n };\n }\n },\n };\n}\n\n/**\n * Creates a command that runs `operation` first,\n * then dispatches result to a named subcommand.\n *\n * @typeParam Context - Context accepted by `operation`.\n * @typeParam Payload - Output of `operation`; becomes the subcommand's context.\n * @typeParam Result - Value produced by the selected subcommand.\n *\n * @param information - Command metadata.\n * @param operation - Runs first; output becomes the subcommand's context.\n * @param subcommands - Map of subcommand names to their {@link Command}s.\n * @returns A dispatching {@link Command}.\n *\n * @example\n * ```ts\n * const rootCmd = commandWithSubcommands(\n * { description: \"My CLI\" },\n * operation({ options: {}, positionals: [] }, async (ctx) => ctx),\n * {\n * deploy: command({ description: \"Deploy\" }, deployOperation),\n * rollback: command({ description: \"Rollback\" }, rollbackOperation),\n * },\n * );\n * ```\n */\nexport function commandWithSubcommands<Context, Payload, Result = void>(\n information: CommandInformation,\n operation: Operation<Context, Payload>,\n subcommands: { [subcommand: string]: Command<Payload, Result> },\n): Command<Context, Result> {\n const subcommandNames = Object.keys(subcommands);\n if (subcommandNames.length === 0) {\n throw new Error(\"At least one subcommand is required\");\n }\n for (const name of subcommandNames) {\n if (name.startsWith(\"-\")) {\n throw new Error(`Subcommand name \"${name}\" cannot start with \"-\".`);\n }\n }\n return {\n getInformation() {\n return information;\n },\n consumeAndMakeDecoder(readerArgs: ReaderArgs) {\n try {\n const operationDecoder = operation.consumeAndMakeDecoder(readerArgs);\n const subcommandName = readerArgs.consumePositional();\n if (subcommandName === undefined) {\n const errorText = new TypoText();\n errorText.push(new TypoString(`Missing argument: `));\n errorText.push(new TypoString(`<subcommand>`, typoStyleUserInput));\n errorText.push(new TypoString(`.`));\n suggestSubcommandNames(errorText, \"\", subcommandNames);\n throw new TypoError(errorText);\n }\n const subcommandInput = subcommands[subcommandName];\n if (subcommandInput === undefined) {\n const errorText = new TypoText();\n errorText.push(new TypoString(`<subcommand>`, typoStyleUserInput));\n errorText.push(new TypoString(`: Unknown name: `));\n errorText.push(new TypoString(`\"${subcommandName}\"`, typoStyleQuote));\n errorText.push(new TypoString(`.`));\n suggestSubcommandNames(errorText, subcommandName, subcommandNames);\n throw new TypoError(errorText);\n }\n const subcommandDecoder =\n subcommandInput.consumeAndMakeDecoder(readerArgs);\n return {\n generateUsage() {\n const subcommandUsage = subcommandDecoder.generateUsage();\n const currentUsage = generateUsageLeaf(information, operation);\n currentUsage.segments.push({ subcommand: subcommandName });\n currentUsage.segments.push(...subcommandUsage.segments);\n currentUsage.information = subcommandUsage.information;\n currentUsage.positionals.push(...subcommandUsage.positionals);\n currentUsage.subcommands = subcommandUsage.subcommands;\n currentUsage.options.push(...subcommandUsage.options);\n return currentUsage;\n },\n decodeAndMakeInterpreter() {\n const operationInterpreter =\n operationDecoder.decodeAndMakeInterpreter();\n const subcommandInterpreter =\n subcommandDecoder.decodeAndMakeInterpreter();\n return {\n async executeWithContext(context: Context) {\n return await subcommandInterpreter.executeWithContext(\n await operationInterpreter.executeWithContext(context),\n );\n },\n };\n },\n };\n } catch (error) {\n return {\n generateUsage() {\n const currentUsage = generateUsageLeaf(information, operation);\n currentUsage.segments.push({ positional: \"<subcommand>\" });\n for (const [name, subcommand] of Object.entries(subcommands)) {\n const { description, hint } = subcommand.getInformation();\n currentUsage.subcommands.push({ name, description, hint });\n }\n return currentUsage;\n },\n decodeAndMakeInterpreter() {\n throw error;\n },\n };\n }\n },\n };\n}\n\n/**\n * Chains an {@link Operation} and a {@link Command}: `operation` runs first,\n * its output becomes `subcommand`'s context. No token is consumed for routing.\n *\n * @typeParam Context - Context accepted by `operation`.\n * @typeParam Payload - Output of `operation`; becomes `subcommand`'s context.\n * @typeParam Result - Value produced by `subcommand`.\n *\n * @param information - Command metadata.\n * @param operation - Runs first; output becomes `subcommand`'s context.\n * @param subcommand - Runs after `operation`.\n * @returns A {@link Command} composing both stages.\n */\nexport function commandChained<Context, Payload, Result = void>(\n information: CommandInformation,\n operation: Operation<Context, Payload>,\n subcommand: Command<Payload, Result>,\n): Command<Context, Result> {\n return {\n getInformation() {\n return information;\n },\n consumeAndMakeDecoder(readerArgs: ReaderArgs) {\n try {\n const operationDecoder = operation.consumeAndMakeDecoder(readerArgs);\n const subcommandDecoder = subcommand.consumeAndMakeDecoder(readerArgs);\n return {\n generateUsage() {\n const subcommandUsage = subcommandDecoder.generateUsage();\n const currentUsage = generateUsageLeaf(information, operation);\n currentUsage.segments.push(...subcommandUsage.segments);\n currentUsage.information = subcommandUsage.information;\n currentUsage.positionals.push(...subcommandUsage.positionals);\n currentUsage.subcommands = subcommandUsage.subcommands;\n currentUsage.options.push(...subcommandUsage.options);\n return currentUsage;\n },\n decodeAndMakeInterpreter() {\n const operationInterpreter =\n operationDecoder.decodeAndMakeInterpreter();\n const subcommandInterpreter =\n subcommandDecoder.decodeAndMakeInterpreter();\n return {\n async executeWithContext(context: Context) {\n return await subcommandInterpreter.executeWithContext(\n await operationInterpreter.executeWithContext(context),\n );\n },\n };\n },\n };\n } catch (error) {\n return {\n generateUsage() {\n const currentUsage = generateUsageLeaf(information, operation);\n currentUsage.segments.push({ positional: \"[REST]...\" });\n return currentUsage;\n },\n decodeAndMakeInterpreter() {\n throw error;\n },\n };\n }\n },\n };\n}\n\nfunction generateUsageLeaf(\n information: CommandInformation,\n operation: Operation<any, any>,\n): UsageCommand {\n const { positionals, options } = operation.generateUsage();\n return {\n segments: positionals.map((p) => ({ positional: p.label })),\n information,\n positionals,\n subcommands: [],\n options,\n };\n}\n\nfunction suggestSubcommandNames(\n errorText: TypoText,\n input: string,\n subcommandNames: Array<string> = [],\n) {\n suggestTextPushMessage(\n errorText,\n input,\n subcommandNames.map((subcommandName) => ({\n reference: subcommandName,\n hint: new TypoString(subcommandName, typoStyleConstants),\n })),\n );\n}\n","import { Option, OptionDecoder } from \"./Option\";\nimport { Positional, PositionalDecoder } from \"./Positional\";\nimport { ReaderArgs } from \"./Reader\";\nimport { UsageOption, UsagePositional } from \"./Usage\";\n\n/**\n * Options, positionals, and an async handler that together form the logic of a CLI command.\n *\n * Created with {@link operation} and passed to {@link command},\n * {@link commandWithSubcommands}, or {@link commandChained}.\n *\n * @typeParam Context - Injected at execution; forwarded to handlers.\n * @typeParam Result - Value produced on execution; typically `void`.\n */\nexport type Operation<Context, Result = void> = {\n /**\n * Returns usage metadata without consuming any arguments.\n */\n generateUsage(): {\n /**\n * Registered options.\n */\n options: Array<UsageOption>;\n /**\n * Declared positionals, in order.\n */\n positionals: Array<UsagePositional>;\n };\n /**\n * Consumes args from `readerArgs` and returns an {@link OperationDecoder}.\n */\n consumeAndMakeDecoder(\n readerArgs: ReaderArgs,\n ): OperationDecoder<Context, Result>;\n};\n\n/**\n * Produced by {@link Operation.consumeAndMakeDecoder}.\n *\n * @typeParam Context - See {@link Operation}.\n * @typeParam Result - See {@link Operation}.\n */\nexport type OperationDecoder<Context, Result> = {\n /**\n * Creates a ready-to-execute {@link OperationInterpreter}.\n *\n * @throws if parsing or decoding failed.\n */\n decodeAndMakeInterpreter(): OperationInterpreter<Context, Result>;\n};\n\n/**\n * A fully parsed, decoded and ready-to-execute operation.\n *\n * @typeParam Context - Caller-supplied context.\n * @typeParam Result - Value produced on success.\n */\nexport type OperationInterpreter<Context, Result> = {\n /**\n * Executes with the provided context.\n */\n executeWithContext(context: Context): Promise<Result>;\n};\n\n/**\n * Creates an {@link Operation} from options, positionals, and an async handler.\n *\n * The `handler` receives `context` and `inputs` with decoded `options` and `positionals`.\n *\n * @typeParam Context - Context type accepted by the handler.\n * @typeParam Result - Return type of the handler.\n * @typeParam Options - Map of option keys to parsed value types.\n * @typeParam Positionals - Tuple of parsed positional value types, in order.\n *\n * @param inputs - Options and positionals this operation accepts.\n * @param inputs.options - Map of keys to {@link Option} descriptors.\n * @param inputs.positionals - Ordered array of {@link Positional} descriptors.\n * @param handler - Async function implementing the command logic.\n * @returns An {@link Operation}.\n *\n * @example\n * ```ts\n * const greetOperation = operation(\n * {\n * options: {\n * loud: optionFlag({ long: \"loud\", description: \"Print in uppercase\" }),\n * },\n * positionals: [\n * positionalRequired({ type: type(\"name\"), description: \"Name to greet\" }),\n * ],\n * },\n * async function (_ctx, { options: { loud }, positionals: [name] }) {\n * const message = `Hello, ${name}!`;\n * console.log(loud ? message.toUpperCase() : message);\n * },\n * );\n * ```\n */\nexport function operation<\n Context,\n Result,\n const Options extends { [option: string]: any } = {},\n const Positionals extends Array<any> = [],\n>(\n inputs: {\n options?: { [K in keyof Options]: Option<Options[K]> };\n positionals?: { [K in keyof Positionals]: Positional<Positionals[K]> };\n },\n handler: (\n context: Context,\n inputs: {\n options: { [K in keyof Options]: Options[K] };\n positionals: { [K in keyof Positionals]: Positionals[K] };\n },\n ) => Promise<Result>,\n): Operation<Context, Result> {\n return {\n generateUsage() {\n const optionsUsage = new Array<UsageOption>();\n if (inputs.options !== undefined) {\n for (const optionKey in inputs.options) {\n const optionInput = inputs.options[optionKey]!;\n optionsUsage.push(optionInput.generateUsage());\n }\n }\n const positionalsUsage = new Array<UsagePositional>();\n if (inputs.positionals !== undefined) {\n for (const positionalInput of inputs.positionals) {\n positionalsUsage.push(positionalInput.generateUsage());\n }\n }\n return { options: optionsUsage, positionals: positionalsUsage };\n },\n consumeAndMakeDecoder(readerArgs: ReaderArgs) {\n const optionsDecoders = {} as {\n [K in keyof Options]: OptionDecoder<Options[K]>;\n };\n if (inputs.options !== undefined) {\n for (const optionKey in inputs.options) {\n const optionInput = inputs.options[optionKey]!;\n optionsDecoders[optionKey] =\n optionInput.registerAndMakeDecoder(readerArgs);\n }\n }\n const positionalsDecoders = [] as {\n [K in keyof Positionals]: PositionalDecoder<Positionals[K]>;\n };\n if (inputs.positionals !== undefined) {\n for (const positionalInput of inputs.positionals) {\n positionalsDecoders.push(\n positionalInput.consumeAndMakeDecoder(readerArgs),\n );\n }\n }\n return {\n decodeAndMakeInterpreter() {\n const optionsValues = {} as {\n [K in keyof Options]: Options[K];\n };\n for (const optionKey in optionsDecoders) {\n optionsValues[optionKey] =\n optionsDecoders[optionKey]!.getAndDecodeValue();\n }\n const positionalsValues = [] as {\n [K in keyof Positionals]: Positionals[K];\n };\n for (const positionalDecoder of positionalsDecoders) {\n positionalsValues.push(positionalDecoder.decodeValue());\n }\n return {\n executeWithContext(context: Context) {\n return handler(context, {\n options: optionsValues,\n positionals: positionalsValues,\n });\n },\n };\n },\n };\n },\n };\n}\n","import { statSync } from \"fs\";\nimport { suggestTextPushMessage } from \"./Suggest\";\nimport {\n TypoError,\n TypoString,\n typoStyleLogic,\n typoStyleQuote,\n TypoText,\n} from \"./Typo\";\n\n/**\n * Decodes a raw CLI string into a typed value.\n * A pair of a human-readable `content` name and a `decoder` function.\n *\n * Primitive Types:\n * - {@link typeString}\n * - {@link typeBoolean}\n * - {@link typeNumber},\n * - {@link typeInteger}\n * - {@link typeDatetime}\n * - {@link typeUrl}\n * - {@link typePath}\n * - {@link typeChoice}\n *\n * Composed Types:\n * - {@link typeMapped}\n * - {@link typeTuple}\n * - {@link typeList}\n *\n * @typeParam Value - Type produced by the decoder.\n */\nexport type Type<Value> = {\n /**\n * Human-readable name shown in help and errors (e.g. `\"name\"`, `\"context\"`).\n */\n content: string; // TODO - add an enforcement mechanism for casing ?\n /**\n * Decodes a raw CLI string into `Value`.\n *\n * @param input - Raw string from the command line.\n * @returns The decoded value.\n * @throws on invalid input.\n */\n decoder(input: string): Value;\n};\n\n/**\n * A named type that accepts any string as input.\n * @param name - Name shown in help and errors (e.g. `\"my-value\"`).\n * @example\n * ```ts\n * typeString(\"greeting\").decoder(\"hello\") // → \"hello\"\n * typeString(\"greeting\").decoder(\"\") // → \"\"\n * ```\n */\nexport function typeString(name?: string): Type<string> {\n return {\n content: name ?? \"string\",\n decoder: (input: string) => input,\n };\n}\n\n/**\n * Decodes a string to `boolean` (case-insensitive).\n * Used by {@link optionFlag} for `--flag=<value>`.\n *\n * @example\n * ```ts\n * typeBoolean(\"flag\").decoder(\"true\") // → true\n * typeBoolean(\"flag\").decoder(\"yes\") // → true\n * typeBoolean(\"flag\").decoder(\"Y\") // → true\n * typeBoolean(\"flag\").decoder(\"FALSE\") // → false\n * typeBoolean(\"flag\").decoder(\"NO\") // → false\n * typeBoolean(\"flag\").decoder(\"n\") // → false\n * typeBoolean(\"flag\").decoder(\"maybe\") // throws\n * ```\n */\nexport function typeBoolean(name?: string): Type<boolean> {\n return {\n content: name ?? \"boolean\",\n decoder(input: string) {\n const lowerInput = input.toLowerCase();\n if (typeBooleanValuesTrue.has(lowerInput)) {\n return true;\n }\n if (typeBooleanValuesFalse.has(lowerInput)) {\n return false;\n }\n throwInvalidValue(\"a boolean\", input);\n },\n };\n}\n\n/**\n * Parses a string to `number` via `Number()`; `NaN` throws.\n *\n * @example\n * ```ts\n * typeNumber(\"my-number\").decoder(\"3.14\") // → 3.14\n * typeNumber(\"my-number\").decoder(\"-1\") // → -1\n * typeNumber(\"my-number\").decoder(\"hello\") // throws\n * ```\n */\nexport function typeNumber(name?: string): Type<number> {\n return {\n content: name ?? \"number\",\n decoder(input: string) {\n try {\n const parsed = Number(input);\n if (isNaN(parsed)) {\n throw new Error();\n }\n return parsed;\n } catch {\n throwInvalidValue(\"a number\", input);\n }\n },\n };\n}\n\n/**\n * Parses an integer string to `bigint` via `BigInt()`.\n * Floats and non-numeric strings throws.\n *\n * @example\n * ```ts\n * typeInteger(\"my-integer\").decoder(\"42\") // → 42n\n * typeInteger(\"my-integer\").decoder(\"3.14\") // throws\n * typeInteger(\"my-integer\").decoder(\"abc\") // throws\n * ```\n */\nexport function typeInteger(name?: string): Type<bigint> {\n return {\n content: name ?? \"integer\",\n decoder(input: string) {\n try {\n return BigInt(input);\n } catch {\n throwInvalidValue(\"an integer\", input);\n }\n },\n };\n}\n\n/**\n * Parses a date/time string via `Date.parse`.\n * Accepts any format supported by `Date.parse`, including ISO 8601.\n *\n * @example\n * ```ts\n * typeDatetime(\"start\").decoder(\"2024-01-15\") // → Date object for 2024-01-15\n * typeDatetime(\"start\").decoder(\"2024-01-15T13:45:30Z\") // → Date object for 2024-01-15 13:45:30 UTC\n * typeDatetime(\"start\").decoder(\"not a date\") // throws\n * ```\n */\nexport function typeDatetime(name?: string): Type<Date> {\n return {\n content: name ?? \"datetime\",\n decoder(input: string) {\n try {\n const timestampMs = Date.parse(input);\n if (isNaN(timestampMs)) {\n throw new Error();\n }\n return new Date(timestampMs);\n } catch {\n throwInvalidValue(\"a valid ISO_8601 datetime\", input);\n }\n },\n };\n}\n\n/**\n * Parses an absolute URL string to a `URL` object.\n * Relative or malformed URLs throws.\n *\n * @example\n * ```ts\n * typeUrl(\"my-url\").decoder(\"https://example.com\") // → URL { href: \"https://example.com/\", ... }\n * typeUrl(\"my-url\").decoder(\"not-a-url\") // throws\n * ```\n */\nexport function typeUrl(name?: string): Type<URL> {\n return {\n content: name ?? \"url\",\n decoder(input: string) {\n try {\n return new URL(input);\n } catch {\n throwInvalidValue(\"an URL\", input);\n }\n },\n };\n}\n\n/**\n * Creates a {@link Type} for filesystem paths with optional existence checks.\n *\n * @param checks - Optional checks for path existence and type (file/directory).\n * @returns A {@link Type}`<string>` representing the path.\n *\n * @example\n * ```ts\n * const typeInputFile = typePath(\"input-file\", { checkSyncExistAs: \"file\" });\n * typeInputFile.decoder(\"data.txt\"); // → \"data.txt\" if it exists and is a file, otherwise throws\n * typeInputFile.decoder(\"somedir\"); // throws if \"somedir\" exists and is a directory\n * ```\n */\nexport function typePath(\n name?: string,\n checks?: { checkSyncExistAs?: \"file\" | \"directory\" | \"anything\" },\n): Type<string> {\n return {\n content: name ?? \"path\",\n decoder(input: string) {\n if (input.length === 0) {\n throw new Error(`Path cannot be empty`);\n }\n if (input.includes(\"\\0\")) {\n throw new Error(`Path cannot contain null characters`);\n }\n if (checks?.checkSyncExistAs !== undefined) {\n function safeStatSync(path: string) {\n try {\n return statSync(path);\n } catch (error) {\n throw new TypoError(\n new TypoText(\n new TypoString(`Path does not exist: `),\n new TypoString(`\"${path}\"`, typoStyleQuote),\n ),\n error,\n );\n }\n }\n const stats = safeStatSync(input);\n const preview = stats.isDirectory()\n ? \"directory\"\n : stats.isFile()\n ? \"file\"\n : \"unknown\";\n if (checks.checkSyncExistAs === \"file\" && !stats.isFile()) {\n throw new TypoError(\n new TypoText(\n new TypoString(`Expected a file but found: ${preview}: `),\n new TypoString(`\"${input}\"`, typoStyleQuote),\n ),\n );\n }\n if (checks.checkSyncExistAs === \"directory\" && !stats.isDirectory()) {\n throw new TypoError(\n new TypoText(\n new TypoString(`Expected a directory but found: ${preview}: `),\n new TypoString(`\"${input}\"`, typoStyleQuote),\n ),\n );\n }\n }\n return input;\n },\n };\n}\n\n/**\n * Creates a {@link Type}`<string>` that only accepts a fixed set of values.\n *\n * @param name - Name shown in help and errors.\n * @param values - Ordered list of accepted values.\n * @returns A {@link Type}`<string>`.\n *\n * @example\n * ```ts\n * const typeEnv = typeChoice(\"environment\", [\"dev\", \"staging\", \"prod\"]);\n * typeEnv.decoder(\"prod\") // → \"prod\"\n * typeEnv.decoder(\"unknown\") // throws\n * ```\n */\nexport function typeChoice<const Value extends string>(\n name: string,\n values: Array<Value>,\n caseSensitive: boolean = true,\n): Type<Value> {\n if (values.length === 0) {\n throw new Error(\"At least one value is required\");\n }\n const normalize = caseSensitive\n ? (input: string) => input\n : (input: string) => input.toLowerCase();\n const valueByNormalized = new Map(\n values.map((value) => [normalize(value), value]),\n );\n return {\n content: name,\n decoder(input: string) {\n const value = valueByNormalized.get(normalize(input));\n if (value !== undefined) {\n return value;\n }\n const errorText = new TypoText();\n errorText.push(new TypoString(`Unknown value: `));\n errorText.push(new TypoString(`\"${input}\"`, typoStyleQuote));\n errorText.push(new TypoString(`.`));\n suggestTextPushMessage(\n errorText,\n input,\n values.map((value) => ({\n reference: value,\n hint: new TypoString(`\"${value}\"`, typoStyleQuote),\n })),\n );\n throw new TypoError(errorText);\n },\n };\n}\n\n/**\n * Chains `before`'s decoder with an `after` transformation.\n * `before` errors are prefixed with `\"from: <content>\"` for traceability.\n *\n * @typeParam Before - Intermediate type from `before.decoder`.\n * @typeParam After - Final type from `after.decoder`.\n *\n * @param name - Name shown in help and errors (e.g. `\"my-value\"`).\n * @param before - Base type to decode the raw string.\n * @param mapper - Transforms `before`'s output to the final value; errors are wrapped with context.\n * @returns A {@link Type}`<After>`.\n *\n * @example\n * ```ts\n * const typePort = typeMapped(\"port\", typeNumber(), (n) => {\n * if (n < 1 || n > 65535) {\n * throw new Error(\"Out of range\");\n * }\n * return n;\n * });\n * typePort.decoder(\"8080\"); // → 8080\n * typePort.decoder(\"70000\"); // throws\n * ```\n */\nexport function typeMapped<Before, After>(\n name: string,\n before: Type<Before>,\n mapper: (value: Before) => After,\n): Type<After> {\n return {\n content: name,\n decoder: (input: string) => {\n return mapper(\n TypoError.tryWithContext(\n () => before.decoder(input),\n () =>\n new TypoText(\n new TypoString(\"from: \"),\n new TypoString(before.content, typoStyleLogic),\n ),\n ),\n );\n },\n };\n}\n\n/**\n * Adds a name to a {@link Type} for clearer error messages and help text.\n *\n * @param name - Name to use for the type.\n * @param type - Base type to name.\n * @returns A {@link Type} with the given name.\n */\nexport function typeRenamed<Value>(\n type: Type<Value>,\n name: string,\n): Type<Value> {\n return {\n content: name,\n decoder: (input: string) => {\n return TypoError.tryWithContext(\n () => type.decoder(input),\n () =>\n new TypoText(\n new TypoString(\"from: \"),\n new TypoString(type.content, typoStyleLogic),\n ),\n );\n },\n };\n}\n\n/**\n * Splits a delimited string into a typed tuple.\n * Each part is decoded by the corresponding element type; wrong count or decode failure throws.\n *\n * @typeParam Elements - Tuple of decoded value types (inferred from `elementTypes`).\n *\n * @param elementTypes - One {@link Type} per tuple element, in order.\n * @param separator - Delimiter (default `\",\"`).\n * @returns A {@link Type}`<Elements>`.\n *\n * @example\n * ```ts\n * const typePoint = typeTuple([typeNumber(\"x\"), typeNumber(\"y\")]);\n * typePoint.decoder(\"3.14,2.71\") // → [3.14, 2.71]\n * typePoint.decoder(\"1\") // throws\n * typePoint.decoder(\"1,2,3\") // throws\n * typePoint.decoder(\"x,2\") // throws\n * ```\n */\nexport function typeTuple<const Elements extends Array<any>>(\n elementTypes: { [K in keyof Elements]: Type<Elements[K]> },\n separator: string = \",\",\n): Type<Elements> {\n return {\n content: elementTypes\n .map((elementType) => elementType.content)\n .join(separator),\n decoder(input: string) {\n const splits = input.split(separator, elementTypes.length);\n if (splits.length !== elementTypes.length) {\n throw new TypoError(\n new TypoText(\n new TypoString(`Found ${splits.length} splits: `),\n new TypoString(`Expected ${elementTypes.length} splits from: `),\n new TypoString(`\"${input}\"`, typoStyleQuote),\n new TypoString(`.`),\n ),\n );\n }\n return splits.map((split, index) => {\n const elementType = elementTypes[index]!;\n return TypoError.tryWithContext(\n () => elementType.decoder(split),\n () =>\n new TypoText(\n new TypoString(`at ${index}: `),\n new TypoString(elementType.content, typoStyleLogic),\n ),\n );\n }) as Elements;\n },\n };\n}\n\n/**\n * Splits a delimited string into a typed array.\n * Each part is decoded by `elementType`; failed decodes throws.\n * Note: splitting an empty string yields one empty element — prefer {@link optionRepeatable} for a zero-default.\n *\n * @typeParam Value - Element type produced by `elementType.decoder`.\n *\n * @param elementType - Decoder applied to each element.\n * @param separator - Delimiter (default `\",\"`).\n * @returns A {@link Type}`<Array<Value>>`.\n *\n * @example\n * ```ts\n * const typeNumbers = typeList(typeNumber(\"v\"));\n * typeNumbers.decoder(\"1,2,3\") // → [1, 2, 3]\n * typeNumbers.decoder(\"1,x,3\") // throws\n * const typePaths = typeList(typePath(), \":\");\n * typePaths.decoder(\"/bin:/usr\") // → [\"/bin\", \"/usr\"]\n * typePaths.decoder(\"/usr/bin\") // → [\"/usr/bin\"]\n * typePaths.decoder(\"\") // → throws\n * ```\n */\nexport function typeList<Value>(\n elementType: Type<Value>,\n separator: string = \",\",\n): Type<Array<Value>> {\n return {\n content: `${elementType.content}[${separator}${elementType.content}]...`,\n decoder(input: string) {\n const splits = input.split(separator);\n return splits.map((split, index) =>\n TypoError.tryWithContext(\n () => elementType.decoder(split),\n () =>\n new TypoText(\n new TypoString(`at ${index}: `),\n new TypoString(elementType.content, typoStyleLogic),\n ),\n ),\n );\n },\n };\n}\n\nfunction throwInvalidValue(kind: string, input: string): never {\n throw new TypoError(\n new TypoText(\n new TypoString(`Not ${kind}: `),\n new TypoString(`\"${input}\"`, typoStyleQuote),\n new TypoString(`.`),\n ),\n );\n}\n\nconst typeBooleanValuesTrue = new Set([\"true\", \"yes\", \"on\", \"y\"]);\nconst typeBooleanValuesFalse = new Set([\"false\", \"no\", \"off\", \"n\"]);\n","import {\n ReaderOptionGetter,\n ReaderOptionNextGuard,\n ReaderOptions,\n ReaderOptionValue,\n} from \"./Reader\";\nimport { Type, typeBoolean } from \"./Type\";\nimport {\n TypoError,\n TypoString,\n typoStyleConstants,\n typoStyleLogic,\n typoStyleUserInput,\n TypoText,\n} from \"./Typo\";\nimport { UsageOption } from \"./Usage\";\n\n/**\n * A CLI option. Created with {@link optionFlag}, {@link optionSingleValue},\n * or {@link optionRepeatable}.\n *\n * @typeParam Value - Decoded value type.\n */\nexport type Option<Value> = {\n /**\n * Returns metadata for the `Options:` section.\n */\n generateUsage(): UsageOption;\n /**\n * Registers the option on `readerOptions` and returns an {@link OptionDecoder}.\n */\n registerAndMakeDecoder(readerOptions: ReaderOptions): OptionDecoder<Value>;\n};\n\n/**\n * Produced by {@link Option.registerAndMakeDecoder}.\n *\n * @typeParam Value - Decoded value type.\n */\nexport type OptionDecoder<Value> = {\n /**\n * Returns the decoded option value.\n *\n * @throws if decoding failed.\n */\n getAndDecodeValue(): Value;\n};\n\n/**\n * Creates a boolean flag option (`--verbose`, optionally `--flag=no`).\n *\n * Syntax: `--long`, `--long=no`, `-s`, `-s=no`.\n * Parsing logic:\n * - absent → default value\n * - `--flag` / `--flag=yes` → `true`\n * - `--flag=no` → `false`\n * - specified more than once → throws.\n *\n * @param definition.long - Long-form name (without `--`).\n * @param definition.short - Short-form name (without `-`).\n * @param definition.description - Help text.\n * @param definition.hint - Short note shown in parentheses.\n * @param definition.aliases - Additional names.\n * @param definition.default - Default value when absent.\n * @returns An {@link Option}`<boolean>`.\n *\n * @example\n * ```ts\n * const verboseFlag = optionFlag({\n * long: \"verbose\",\n * short: \"v\",\n * description: \"Enable verbose output\",\n * });\n * ```\n */\nexport function optionFlag(definition: {\n long: string;\n short?: string;\n description?: string;\n hint?: string;\n aliases?: { longs?: Array<string>; shorts?: Array<string> };\n default?: boolean;\n}): Option<boolean> {\n const type = typeBoolean(\"value\");\n const { long, short, description, hint, aliases } = definition;\n return {\n generateUsage() {\n return { short, long, annotation: \"[=no]\", description, hint };\n },\n registerAndMakeDecoder(readerOptions: ReaderOptions) {\n const resultsGetter = setupOptionAliased(readerOptions, {\n longKey: long,\n shortKey: short,\n aliasLongKeys: aliases?.longs,\n aliasShortKeys: aliases?.shorts,\n nextGuard: () => false,\n consumeGroupRestAsValue: false,\n });\n return {\n getAndDecodeValue() {\n const results = resultsGetter();\n if (results.length > 1) {\n throwSetMultipleTimesError(results.map((r) => r.identifier));\n }\n if (results.length === 0) {\n return definition.default === undefined\n ? false\n : definition.default;\n }\n const input = results[0]!.value.inlined;\n if (input === null) {\n return true;\n }\n return decodeValue({ long, label: undefined, type, input });\n },\n };\n },\n };\n}\n\n/**\n * Creates an option that accepts exactly one value (e.g. `--output dist/`).\n *\n * Syntax: `--long value`, `--long=value`, `-s value`, `-s=value`, `-svalue`.\n * Parsing logic:\n * - absent → `fallbackValueIfAbsent()`\n * - `--long value` → decoded with `type.decoder(\"value\")`\n * - more than once → throws\n * - if `impliedValueIfNotInlined` is not provided, then: `--long` / `-s` without a value → throws\n * - if `impliedValueIfNotInlined` is provided, then: `--long` / `-s` without an inline value → `impliedValueIfNotInlined()`\n *\n * @typeParam Value - Type produced by the decoder.\n *\n * @param definition.long - Long-form name (without `--`).\n * @param definition.short - Short-form name (without `-`).\n * @param definition.description - Help text.\n * @param definition.hint - Short note shown in parentheses.\n * @param definition.aliases - Additional names.\n * @param definition.type - Decoder for the raw string value.\n * @param definition.fallbackValueIfAbsent - Default value when the option is not specified at all.\n * @param definition.impliedValueIfNotInlined - Default value when the option is specified without an inline value (e.g. `--option` or `-o`).\n * @returns An {@link Option}`<Value>`.\n *\n * @example\n * ```ts\n * const outputOption = optionSingleValue({\n * long: \"output\",\n * short: \"o\",\n * type: typePath(),\n * description: \"Output directory\",\n * fallbackValueIfAbsent: () => \"dist\",\n * });\n * ```\n */\nexport function optionSingleValue<Value>(definition: {\n long: string;\n short?: string;\n description?: string;\n hint?: string;\n aliases?: { longs?: Array<string>; shorts?: Array<string> };\n type: Type<Value>;\n fallbackValueIfAbsent?: () => Value;\n impliedValueIfNotInlined?: () => Value;\n}): Option<Value> {\n const { long, short, description, hint, aliases, type } = definition;\n const label = definition.impliedValueIfNotInlined\n ? undefined\n : `<${type.content}>`;\n const annotation = definition.impliedValueIfNotInlined\n ? `[=${type.content}]`\n : undefined; // TODO - handle implied value and default better in usage and errors\n return {\n generateUsage() {\n return { short, long, label, annotation, description, hint };\n },\n registerAndMakeDecoder(readerOptions: ReaderOptions) {\n const resultsGetter = setupOptionAliased(readerOptions, {\n longKey: long,\n shortKey: short,\n aliasLongKeys: aliases?.longs,\n aliasShortKeys: aliases?.shorts,\n nextGuard: (value) => {\n if (definition.impliedValueIfNotInlined !== undefined) {\n return false;\n }\n if (value.inlined !== null) {\n return false;\n }\n if (value.separated.length !== 0) {\n return false;\n }\n return true;\n },\n consumeGroupRestAsValue:\n definition.impliedValueIfNotInlined === undefined,\n });\n return {\n getAndDecodeValue() {\n const results = resultsGetter();\n if (results.length > 1) {\n throwSetMultipleTimesError(\n results.map((result) => result.identifier),\n );\n }\n const result = results[0];\n if (result === undefined) {\n if (definition.fallbackValueIfAbsent === undefined) {\n const errorText = makeErrorText({ long, label, type });\n errorText.push(new TypoString(`: Is required, but was not set.`));\n throw new TypoError(errorText);\n }\n try {\n return definition.fallbackValueIfAbsent();\n } catch (error) {\n const errorText = makeErrorText({ long, label, type });\n errorText.push(new TypoString(`: Failed to get fallback value.`));\n throw new TypoError(errorText, error);\n }\n }\n const inlined = result.value.inlined;\n if (inlined !== null) {\n return decodeValue({ long, label, type, input: inlined });\n }\n if (definition.impliedValueIfNotInlined !== undefined) {\n try {\n return definition.impliedValueIfNotInlined();\n } catch (error) {\n const errorText = makeErrorText({ long, label, type });\n errorText.push(new TypoString(`: Failed to get implied value.`));\n throw new TypoError(errorText, error);\n }\n }\n const separated = result.value.separated[0]!;\n return decodeValue({ long, label, type, input: separated });\n },\n };\n },\n };\n}\n\n/**\n * Creates an option that collects every occurrence into an array (e.g. `--file a.ts --file b.ts`).\n *\n * Syntax: `--long value`, `--long=value`, `-s value`, `-s=value`, `-svalue`.\n * Parsing logic:\n * - absent → `[]`\n * - N occurrences → array of N decoded values in order.\n *\n * @typeParam Value - Type produced by the decoder for each occurrence.\n *\n * @param definition.long - Long-form name (without `--`).\n * @param definition.short - Short-form name (without `-`).\n * @param definition.description - Help text.\n * @param definition.hint - Short note shown in parentheses.\n * @param definition.aliases - Additional names.\n * @param definition.type - Decoder applied to each raw string value.\n * @returns An {@link Option}`<Array<Value>>`.\n *\n * @example\n * ```ts\n * const filesOption = optionRepeatable({\n * long: \"file\",\n * short: \"f\",\n * type: typeString,\n * label: \"PATH\",\n * description: \"Input file (may be repeated)\",\n * });\n * ```\n */\nexport function optionRepeatable<Value>(definition: {\n long: string;\n short?: string;\n description?: string;\n hint?: string;\n aliases?: { longs?: Array<string>; shorts?: Array<string> };\n type: Type<Value>;\n}): Option<Array<Value>> {\n const { long, short, description, hint, aliases, type } = definition;\n const label = `<${type.content}>`;\n return {\n generateUsage() {\n return { short, long, label, annotation: \" [*]\", description, hint };\n },\n registerAndMakeDecoder(readerOptions: ReaderOptions) {\n const resultsGetter = setupOptionAliased(readerOptions, {\n longKey: long,\n shortKey: short,\n aliasLongKeys: aliases?.longs,\n aliasShortKeys: aliases?.shorts,\n nextGuard: (value) => {\n if (value.inlined !== null) {\n return false;\n }\n if (value.separated.length !== 0) {\n return false;\n }\n return true;\n },\n consumeGroupRestAsValue: true,\n });\n return {\n getAndDecodeValue() {\n return resultsGetter().map((result) => {\n const value = result.value;\n const input = value.inlined ?? value.separated[0]!;\n return decodeValue({ long, label, type, input });\n });\n },\n };\n },\n };\n}\n\nfunction decodeValue<Value>(params: {\n long: string;\n label: string | undefined;\n type: Type<Value>;\n input: string;\n}): Value {\n const { long, label, type, input } = params;\n return TypoError.tryWithContext(\n () => type.decoder(input),\n () => makeErrorText({ long, label, type }),\n );\n}\n\nfunction makeErrorText(params: {\n long: string;\n label: string | undefined;\n type: Type<any>;\n}): TypoText {\n const errorText = new TypoText();\n errorText.push(new TypoString(`--${params.long}`, typoStyleConstants));\n if (params.label !== undefined) {\n errorText.push(new TypoString(`: `));\n errorText.push(new TypoString(params.label, typoStyleUserInput));\n } else {\n errorText.push(new TypoString(`: `));\n errorText.push(new TypoString(params.type.content, typoStyleLogic));\n }\n return errorText;\n}\n\nfunction setupOptionAliased(\n readerOptions: ReaderOptions,\n params: {\n longKey: string;\n shortKey: string | undefined;\n aliasLongKeys: Array<string> | undefined;\n aliasShortKeys: Array<string> | undefined;\n nextGuard: ReaderOptionNextGuard;\n consumeGroupRestAsValue: boolean;\n },\n): () => Array<{ identifier: string; value: ReaderOptionValue }> {\n const { longKey, shortKey, aliasLongKeys, aliasShortKeys } = params;\n const longKeys = [longKey];\n if (aliasLongKeys !== undefined) {\n longKeys.push(...aliasLongKeys);\n }\n const shortKeys = shortKey ? [shortKey] : [];\n if (aliasShortKeys !== undefined) {\n shortKeys.push(...aliasShortKeys);\n }\n return setupOptionMany(readerOptions, {\n longKeys,\n shortKeys,\n nextGuard: params.nextGuard,\n consumeGroupRestAsValue: params.consumeGroupRestAsValue,\n });\n}\n\nfunction setupOptionMany(\n readerOptions: ReaderOptions,\n params: {\n longKeys: Array<string>;\n shortKeys: Array<string>;\n nextGuard: ReaderOptionNextGuard;\n consumeGroupRestAsValue: boolean;\n },\n): () => Array<{ identifier: string; value: ReaderOptionValue }> {\n const { longKeys, shortKeys, nextGuard, consumeGroupRestAsValue } = params;\n const getters = new Map<string, ReaderOptionGetter>();\n for (const key of longKeys) {\n getters.set(\n `--${key}`,\n readerOptions.registerOptionLong({ key, nextGuard }),\n );\n }\n for (const key of shortKeys) {\n getters.set(\n `-${key}`,\n readerOptions.registerOptionShort({\n key,\n nextGuard,\n consumeGroupRestAsValue,\n }),\n );\n }\n return () => {\n const results = new Array();\n for (const [identifier, getter] of getters.entries()) {\n for (const value of getter()) {\n results.push({ identifier, value });\n }\n }\n return results;\n };\n}\n\nfunction throwSetMultipleTimesError(identifiers: Array<string>): never {\n const identifiersTexts = Array.from(new Set(identifiers)).map(\n (identifier) => new TypoString(identifier, typoStyleConstants),\n );\n const errorText = new TypoText();\n errorText.pushJoined(identifiersTexts, new TypoString(\", \"), 3);\n errorText.push(new TypoString(`: Must not be set multiple times.`));\n throw new TypoError(errorText);\n}\n","import { ReaderPositionals } from \"./Reader\";\nimport { Type } from \"./Type\";\nimport {\n TypoError,\n TypoString,\n typoStyleRegularWeaker,\n typoStyleUserInput,\n TypoText,\n} from \"./Typo\";\nimport { UsagePositional } from \"./Usage\";\n\n/**\n * A positional argument. Created with {@link positionalRequired}, {@link positionalOptional},\n * or {@link positionalVariadics}.\n *\n * @typeParam Value - Decoded value type.\n */\nexport type Positional<Value> = {\n /**\n * Returns metadata for the `Positionals:` section.\n */\n generateUsage(): UsagePositional;\n /**\n * Consumes the next positional token from `readerPositionals`.\n * Returns a decoder that produces the final value.\n */\n consumeAndMakeDecoder(\n readerPositionals: ReaderPositionals,\n ): PositionalDecoder<Value>;\n};\n\n/**\n * Produced by {@link Positional.consumeAndMakeDecoder}.\n *\n * @typeParam Value - Decoded value type.\n */\nexport type PositionalDecoder<Value> = {\n /**\n * Returns the decoded positional value.\n *\n * @throws if decoding failed.\n */\n decodeValue(): Value;\n};\n\n/**\n * Creates a required positional — missing token throws.\n *\n * Syntax: `<type>`, e.g. `<NAME>`.\n * Parsing logic:\n * - \"token\" → decoded with `type.decoder(\"token\")`\n * - token missing → throws\n *\n * @typeParam Value - Type produced by the decoder.\n *\n * @param definition.description - Help text.\n * @param definition.hint - Short note shown in parentheses.\n * @param definition.type - Decoder for the raw token.\n * @param definition.missing - Message shown when the token is missing.\n * @returns A {@link Positional}`<Value>`.\n *\n * @example\n * ```ts\n * const namePositional = positionalRequired({\n * type: type(\"name\"),\n * description: \"The name to greet\",\n * });\n * ```\n */\nexport function positionalRequired<Value>(definition: {\n description?: string;\n hint?: string;\n type: Type<Value>;\n}): Positional<Value> {\n const { description, hint, type } = definition;\n const label = `<${type.content}>`;\n return {\n generateUsage() {\n return { description, hint, label };\n },\n consumeAndMakeDecoder(readerPositionals: ReaderPositionals) {\n const positional = readerPositionals.consumePositional();\n if (positional === undefined) {\n const errorText = makeErrorTextLabel(\"Missing argument\", label);\n if (description !== undefined) {\n errorText.push(\n new TypoString(`: `),\n new TypoString(`${description}`),\n );\n }\n if (hint !== undefined) {\n errorText.push(\n new TypoString(` `),\n new TypoString(`(${hint})`, typoStyleRegularWeaker),\n );\n }\n throw new TypoError(errorText);\n }\n return {\n decodeValue() {\n return decodeValue(label, definition.type, positional);\n },\n };\n },\n };\n}\n\n/**\n * Creates an optional positional — absent token falls back to `default()`.\n *\n * Syntax: `[type]`, e.g. `[NAME]`.\n * Parsing logic:\n * - \"token\" → decoded with `type.decoder(\"token\")`\n * - token missing → `default()`\n *\n * @typeParam Value - Type produced by the decoder (or the default).\n *\n * @param definition.description - Help text.\n * @param definition.hint - Short note shown in parentheses.\n * @param definition.type - Decoder for the raw token.\n * @param definition.default - Value when absent. Throw to make it required.\n * @returns A {@link Positional}`<Value>`.\n *\n * @example\n * ```ts\n * const greeteePositional = positionalOptional({\n * type: type(\"name\"),\n * description: \"Name to greet\",\n * hint: \"Defaults to \\\"world\\\"\",\n * default: () => \"world\",\n * });\n * ```\n */\nexport function positionalOptional<Value>(definition: {\n description?: string;\n hint?: string;\n type: Type<Value>;\n default: () => Value;\n}): Positional<Value> {\n const { description, hint, type } = definition;\n const label = `[${type.content}]`;\n return {\n generateUsage() {\n return { description, hint, label };\n },\n consumeAndMakeDecoder(readerPositionals: ReaderPositionals) {\n const positional = readerPositionals.consumePositional();\n return {\n decodeValue() {\n if (positional === undefined) {\n try {\n return definition.default();\n } catch (error) {\n const errorText = makeErrorTextLabel(\n \"Failed to get default value\",\n label,\n );\n errorText.push(new TypoString(\".\"));\n throw new TypoError(errorText, error);\n }\n }\n return decodeValue(label, definition.type, positional);\n },\n };\n },\n };\n}\n\n/**\n * Creates a variadic positional that collects zero or more remaining tokens into an array.\n * Optionally stops at `endDelimiter` (consumed, not included).\n *\n * Syntax: `[type]...`, e.g. `[NAME]...`.\n * Parsing logic:\n * - \"a b ...\" → decoded with `[type.decoder(\"a\")`, `type.decoder(\"b\"), ...]``\n * - token missing → stops collection\n * - endDelimiter encountered → stops collection\n *\n * @typeParam Value - Type produced by the decoder for each token.\n *\n * @param definition.endDelimiter - Sentinel token that stops collection (consumed, not included).\n * @param definition.description - Help text.\n * @param definition.hint - Short note shown in parentheses.\n * @param definition.type - Decoder applied to each token.\n * @returns A {@link Positional}`<Array<Value>>`.\n *\n * @example\n * ```ts\n * const filesPositional = positionalVariadics({\n * type: typePath(),\n * description: \"Files to process\",\n * });\n * ```\n */\nexport function positionalVariadics<Value>(definition: {\n endDelimiter?: string;\n description?: string;\n hint?: string;\n type: Type<Value>;\n}): Positional<Array<Value>> {\n const { description, hint, type } = definition;\n const labelSingle = `[${type.content}]`;\n const labelMultiple =\n `${labelSingle}...` +\n (definition.endDelimiter ? ` [\"${definition.endDelimiter}\"]` : \"\");\n return {\n generateUsage() {\n return { description, hint, label: labelMultiple };\n },\n consumeAndMakeDecoder(readerPositionals: ReaderPositionals) {\n const positionals = new Array<string>();\n while (true) {\n const positional = readerPositionals.consumePositional();\n if (\n positional === undefined ||\n positional === definition.endDelimiter\n ) {\n break;\n }\n positionals.push(positional);\n }\n return {\n decodeValue() {\n return positionals.map((positional) =>\n decodeValue(labelSingle, definition.type, positional),\n );\n },\n };\n },\n };\n}\n\nfunction decodeValue<Value>(\n label: string,\n type: Type<Value>,\n input: string,\n): Value {\n return TypoError.tryWithContext(\n () => type.decoder(input),\n () => new TypoText(new TypoString(label, typoStyleUserInput)),\n );\n}\n\nfunction makeErrorTextLabel(message: string, label: string): TypoText {\n const errorText = new TypoText();\n errorText.push(new TypoString(`${message}: `));\n errorText.push(new TypoString(label, typoStyleUserInput));\n return errorText;\n}\n","import { suggestTextPushMessage } from \"./Suggest\";\nimport {\n TypoError,\n TypoString,\n typoStyleConstants,\n typoStyleQuote,\n TypoText,\n} from \"./Typo\";\n\n/**\n * Represents the parsing specification for a long option\n */\nexport type ReaderOptionLongSpec = {\n key: string;\n nextGuard: ReaderOptionNextGuard;\n};\n\n/**\n * Represents the parsing specification for a short option\n */\nexport type ReaderOptionShortSpec = ReaderOptionLongSpec & {\n consumeGroupRestAsValue: boolean;\n};\n\n/**\n * Determines whether the next token is valid for a given option.\n */\nexport type ReaderOptionNextGuard = (\n value: ReaderOptionValue,\n next: string | undefined,\n) => boolean;\n\n/**\n * Represents the values parsed for an option.\n */\nexport type ReaderOptionValue = {\n inlined: string | null;\n separated: ReadonlyArray<string>;\n};\n\n/**\n * Returns the parsed values for a registered option.\n */\nexport type ReaderOptionGetter = () => ReadonlyArray<ReaderOptionValue>;\n\n/**\n * Option registration/query interface. Subset of {@link ReaderArgs}.\n */\nexport type ReaderOptions = {\n registerOptionLong(longSpec: ReaderOptionLongSpec): ReaderOptionGetter;\n registerOptionShort(shortSpec: ReaderOptionShortSpec): ReaderOptionGetter;\n};\n\n/**\n * Positional consumption interface. Subset of {@link ReaderArgs}.\n */\nexport type ReaderPositionals = {\n /**\n * Returns the next positional token, parsing intervening options as side-effects.\n *\n * @returns The next positional, or `undefined` when exhausted.\n * @throws on an unrecognised option.\n */\n consumePositional(): string | undefined;\n};\n\n/**\n * Core argument parser: converts raw CLI tokens into named options and positionals.\n * Options must be registered before {@link ReaderArgs.consumePositional} is called.\n *\n * Supported syntax: `--name`, `--name value`, `--name=value`,\n * `-n`, `-n value`, `-nvalue`, `-abc` (stacked), `--` (end-of-options).\n *\n * Created internally by {@link runAndExit}; exposed for advanced / custom runners.\n */\nexport class ReaderArgs {\n #tokens: ReadonlyArray<string>;\n #parsedIndex: number;\n #parsedDouble: boolean;\n #optionLongContextByIdentifier: Map<string, Context<ReaderOptionLongSpec>>;\n #optionShortContextByIdentifier: Map<string, Context<ReaderOptionShortSpec>>;\n\n /**\n * @param tokens - Raw CLI tokens (e.g. `process.argv.slice(2)`).\n */\n constructor(tokens: ReadonlyArray<string>) {\n this.#tokens = tokens;\n this.#parsedIndex = 0;\n this.#parsedDouble = false;\n this.#optionLongContextByIdentifier = new Map();\n this.#optionShortContextByIdentifier = new Map();\n }\n\n /**\n * Registers a long option and returns a getter for its parsed values.\n */\n registerOptionLong(longSpec: ReaderOptionLongSpec): ReaderOptionGetter {\n const identifier = `--${longSpec.key}`; // TODO - is this necessary ?\n if (!isValidOptionKey(longSpec.key)) {\n throw new Error(`Option identifier is invalid: ${identifier}.`);\n }\n if (this.#optionLongContextByIdentifier.has(identifier)) {\n throw new Error(`Option already registered: ${identifier}.`);\n }\n const values = new Array<ReaderOptionValue>();\n this.#optionLongContextByIdentifier.set(identifier, {\n identifier,\n spec: longSpec,\n values,\n });\n return () => values;\n }\n\n /**\n * Registers a short option and returns a getter for its parsed values.\n */\n registerOptionShort(shortSpec: ReaderOptionShortSpec): ReaderOptionGetter {\n const identifier = `-${shortSpec.key}`;\n if (!isValidOptionKey(shortSpec.key)) {\n throw new Error(`Option identifier is invalid: ${identifier}.`);\n }\n if (this.#optionShortContextByIdentifier.has(identifier)) {\n throw new Error(`Option already registered: ${identifier}.`);\n }\n for (let i = 0; i < identifier.length; i++) {\n const slicedIdentifier = identifier.slice(0, 1 + i);\n if (this.#optionShortContextByIdentifier.has(slicedIdentifier)) {\n throw new Error(\n `Option ${identifier} overlap with shorter option: ${slicedIdentifier}.`,\n );\n }\n }\n for (const otherIdentifier of this.#optionShortContextByIdentifier.keys()) {\n if (otherIdentifier.startsWith(identifier)) {\n throw new Error(\n `Option ${identifier} overlap with longer option: ${otherIdentifier}.`,\n );\n }\n }\n const values = new Array<ReaderOptionValue>();\n this.#optionShortContextByIdentifier.set(identifier, {\n identifier,\n spec: shortSpec,\n values,\n });\n return () => values;\n }\n\n /**\n * Returns the next positional token; parses intervening options as a side-effect.\n * All tokens after `--` are treated as positionals.\n *\n * @returns The next positional, or `undefined` when exhausted.\n * @throws on an unrecognised option.\n */\n consumePositional(): string | undefined {\n while (true) {\n const token = this.#consumeToken();\n if (token === undefined) {\n return undefined;\n }\n if (!this.#tryConsumeAsOption(token)) {\n return token;\n }\n }\n }\n\n #consumeToken(): string | undefined {\n const token = this.#tokens[this.#parsedIndex];\n if (token === undefined) {\n return undefined;\n }\n this.#parsedIndex++;\n if (!this.#parsedDouble) {\n if (token === \"--\") {\n this.#parsedDouble = true;\n return this.#consumeToken();\n }\n }\n return token;\n }\n\n #tryConsumeAsOption(token: string): boolean {\n if (this.#parsedDouble) {\n return false;\n }\n if (token.startsWith(\"--\")) {\n const valueIndexStart = token.indexOf(\"=\");\n if (valueIndexStart === -1) {\n this.#consumeOptionLong(token, null);\n } else {\n this.#consumeOptionLong(\n token.slice(0, valueIndexStart),\n token.slice(valueIndexStart + 1),\n );\n }\n return true;\n }\n if (token.startsWith(\"-\")) {\n let shortIndexStart = 1;\n let shortIndexEnd = 2;\n while (shortIndexEnd <= token.length) {\n const identifier = `-${token.slice(shortIndexStart, shortIndexEnd)}`;\n const shortContext =\n this.#optionShortContextByIdentifier.get(identifier);\n if (shortContext !== undefined) {\n const tokenRest = token.slice(shortIndexEnd);\n if (this.#tryConsumeOptionShort(shortContext, tokenRest)) {\n return true;\n }\n shortIndexStart = shortIndexEnd;\n }\n shortIndexEnd++;\n }\n this.#throwUnknownOptionError(`-${token.slice(shortIndexStart)}`);\n }\n return false;\n }\n\n #consumeOptionLong(identifier: string, valueInlined: string | null): void {\n const longContext = this.#optionLongContextByIdentifier.get(identifier);\n if (longContext !== undefined) {\n return this.#consumeOptionValues(longContext, valueInlined);\n }\n this.#throwUnknownOptionError(identifier);\n }\n\n #tryConsumeOptionShort(\n shortContext: Context<ReaderOptionShortSpec>,\n tokenRest: string,\n ): boolean {\n if (tokenRest.startsWith(\"=\")) {\n this.#consumeOptionValues(shortContext, tokenRest.slice(1));\n return true;\n }\n if (tokenRest.length === 0) {\n this.#consumeOptionValues(shortContext, null);\n return true;\n }\n if (shortContext.spec.consumeGroupRestAsValue) {\n this.#consumeOptionValues(shortContext, tokenRest);\n return true;\n }\n this.#consumeOptionValues(shortContext, null);\n return false;\n }\n\n #consumeOptionValues(\n context: Context<{ nextGuard: ReaderOptionNextGuard }>,\n valueInlined: string | null,\n ) {\n const value = { inlined: valueInlined, separated: new Array<string>() };\n const { identifier, values, spec } = context;\n values.push(value);\n while (true) {\n const nextToken = this.#tokens[this.#parsedIndex];\n if (!spec.nextGuard(value, nextToken)) {\n return;\n }\n const token = this.#consumeToken();\n if (this.#parsedDouble) {\n throw new TypoError(\n new TypoText(\n new TypoString(identifier, typoStyleConstants),\n new TypoString(`: Requires a value but got: `),\n new TypoString(`\"--\"`, typoStyleQuote),\n new TypoString(`.`),\n ),\n );\n }\n // TODO - should we allow consuming the EOF token ?\n if (token === undefined) {\n throw new TypoError(\n new TypoText(\n new TypoString(identifier, typoStyleConstants),\n new TypoString(`: Requires a value, but got end of input.`), // TODO - hint at option value syntax ?\n ),\n );\n }\n // TODO - is that weird, could a valid value start with dash ?\n if (token.startsWith(\"-\")) {\n throw new TypoError(\n new TypoText(\n new TypoString(identifier, typoStyleConstants),\n new TypoString(`: Requires a value, but got: `),\n new TypoString(`\"${token}\"`, typoStyleQuote),\n new TypoString(`.`),\n ),\n );\n }\n value.separated.push(token);\n }\n }\n\n #throwUnknownOptionError(inputIdentifier: string): never {\n const candidatesIdentifiers = [];\n for (const identifier of this.#optionLongContextByIdentifier.keys()) {\n candidatesIdentifiers.push(identifier);\n }\n for (const identifier of this.#optionShortContextByIdentifier.keys()) {\n candidatesIdentifiers.push(identifier);\n }\n const errorText = new TypoText();\n errorText.push(new TypoString(`Unknown option: `));\n errorText.push(new TypoString(`\"${inputIdentifier}\"`, typoStyleQuote));\n if (candidatesIdentifiers.length === 0) {\n errorText.push(new TypoString(`, no options are registered.`));\n } else {\n errorText.push(new TypoString(`.`));\n suggestTextPushMessage(\n errorText,\n inputIdentifier,\n candidatesIdentifiers.map((candidateIdentifier) => ({\n reference: candidateIdentifier,\n hint: new TypoString(candidateIdentifier, typoStyleConstants),\n })),\n );\n }\n throw new TypoError(errorText);\n }\n}\n\nfunction isValidOptionKey(name: string): boolean {\n return name.length > 0 && !name.includes(\"=\") && !name.includes(\"\\0\");\n}\n\ntype Context<Spec> = {\n identifier: string;\n spec: Spec;\n values: Array<ReaderOptionValue>;\n};\n","import { CommandInformation } from \"./Command\";\nimport {\n TypoGrid,\n TypoString,\n typoStyleConstants,\n typoStyleLogic,\n typoStyleRegularStrong,\n typoStyleRegularWeaker,\n typoStyleTitle,\n typoStyleUserInput,\n TypoSupport,\n TypoText,\n} from \"./Typo\";\n\n/**\n * Usage model. Produced by {@link CommandDecoder.generateUsage}, consumed by {@link usageToStyledLines}.\n */\nexport type UsageCommand = {\n /**\n * Segments of the usage line\n */\n segments: Array<{ positional: string } | { subcommand: string }>;\n /**\n * Command metadata.\n */\n information: CommandInformation;\n /**\n * Positionals in declaration order.\n */\n positionals: Array<UsagePositional>;\n /**\n * Subcommands, populated when none was selected.\n */\n subcommands: Array<UsageSubcommand>;\n /**\n * Options in registration order.\n */\n options: Array<UsageOption>;\n};\n\n/**\n * Positional metadata for the `Positionals:` section of help.\n */\nexport type UsagePositional = {\n /**\n * Help text.\n */\n description?: string | undefined;\n /**\n * Short note shown in parentheses.\n */\n hint?: string | undefined;\n /**\n * Placeholder label shown in the usage line and the `Positionals:` section.\n */\n label: string;\n};\n\n/**\n * Entry in the `Subcommands:` section.\n */\nexport type UsageSubcommand = {\n /**\n * Token the user types (e.g. `\"deploy\"`).\n */\n name: string;\n /**\n * From {@link CommandInformation.description}.\n */\n description?: string | undefined;\n /**\n * From {@link CommandInformation.hint}.\n */\n hint?: string | undefined;\n};\n\n/**\n * Option metadata for the `Options:` section of help.\n */\nexport type UsageOption = {\n /**\n * Short-form name without `-` (e.g. `\"v\"`).\n */\n short?: string | undefined;\n /**\n * Long-form name without `--` (e.g. `\"verbose\"`).\n */\n long: string;\n /**\n * Value placeholder in help (e.g. `\"<FILE>\"`).\n */\n label?: string | undefined;\n /**\n * Extra annotation appended to the option label in help.\n */\n annotation?: string | undefined; // TODO - maybe prefix/postfix would be more useful\n /**\n * Help text.\n */\n description?: string | undefined;\n /**\n * Short note shown in parentheses.\n */\n hint?: string | undefined;\n};\n\n/**\n * Converts a {@link UsageCommand} model into an array of styled lines ready to be\n * joined with `\"\\n\"` and printed to the terminal.\n *\n * The output format is:\n * ```\n * Usage: <cliName> [segments...]\n *\n * <description> (<hint>)\n * <detail lines...>\n *\n * Positionals:\n * <label> <description> (<hint>)\n *\n * Subcommands:\n * <name> <description> (<hint>)\n *\n * Options:\n * -s, --long <label><annotation> <description> (<hint>)\n *\n * Examples:\n * <explanation>\n * <command line>\n *\n * ```\n * Sections that have no entries are omitted. The trailing empty line is always included.\n *\n * Column alignment per section via {@link TypoGrid}.\n *\n * @param params.cliName - Program name for the usage line.\n * @param params.usage - From {@link CommandDecoder.generateUsage}.\n * @param params.typoSupport - Rendering mode.\n * @returns Styled lines; includes a trailing empty string.\n *\n * @example\n * ```ts\n * const lines = usageToStyledLines({\n * cliName: \"my-cli\",\n * usage: commandDecoder.generateUsage(),\n * typoSupport: TypoSupport.tty(),\n * });\n * process.stdout.write(lines.join(\"\\n\"));\n * ```\n */\nexport function usageToStyledLines(params: {\n cliName: string;\n usage: UsageCommand;\n typoSupport: TypoSupport;\n}) {\n const { cliName, usage, typoSupport } = params;\n\n const lines = new Array<string>();\n\n const segmentsText = new TypoText();\n segmentsText.push(textUsageHero(\"Usage:\"));\n segmentsText.push(textDelimiter(\" \"));\n segmentsText.push(textConstants(cliName));\n for (const segment of usage.segments) {\n segmentsText.push(textDelimiter(\" \"));\n if (\"positional\" in segment) {\n segmentsText.push(textUserInput(segment.positional));\n }\n if (\"subcommand\" in segment) {\n segmentsText.push(textConstants(segment.subcommand));\n }\n }\n lines.push(segmentsText.computeStyledString(typoSupport));\n\n lines.push(\"\");\n const introText = new TypoText();\n introText.push(textUsageText(usage.information.description));\n if (usage.information.hint !== undefined) {\n introText.push(textDelimiter(\" \"));\n introText.push(textSubtleInfo(`(${usage.information.hint})`));\n }\n lines.push(introText.computeStyledString(typoSupport));\n for (const detail of usage.information.details ?? []) {\n const detailText = new TypoText();\n detailText.push(textSubtleInfo(detail));\n lines.push(detailText.computeStyledString(typoSupport));\n }\n\n if (usage.positionals.length > 0) {\n lines.push(\"\");\n lines.push(textBlockTitle(\"Positionals:\").computeStyledString(typoSupport));\n const typoGrid = new TypoGrid();\n for (const positionalUsage of usage.positionals) {\n const typoGridRow = new Array<TypoText>();\n typoGridRow.push(new TypoText(textDelimiter(\" \")));\n typoGridRow.push(new TypoText(textUserInput(positionalUsage.label)));\n typoGridRow.push(...createInformationals(positionalUsage));\n typoGrid.pushRow(typoGridRow);\n }\n lines.push(...typoGrid.computeStyledLines(typoSupport));\n }\n\n if (usage.subcommands.length > 0) {\n lines.push(\"\");\n lines.push(textBlockTitle(\"Subcommands:\").computeStyledString(typoSupport));\n const typoGrid = new TypoGrid();\n for (const subcommandUsage of usage.subcommands) {\n const typoGridRow = new Array<TypoText>();\n typoGridRow.push(new TypoText(textDelimiter(\" \")));\n typoGridRow.push(new TypoText(textConstants(subcommandUsage.name)));\n typoGridRow.push(...createInformationals(subcommandUsage));\n typoGrid.pushRow(typoGridRow);\n }\n lines.push(...typoGrid.computeStyledLines(typoSupport));\n }\n\n if (usage.options.length > 0) {\n lines.push(\"\");\n lines.push(textBlockTitle(\"Options:\").computeStyledString(typoSupport));\n const typoGrid = new TypoGrid();\n for (const optionUsage of usage.options) {\n const typoGridRow = new Array<TypoText>();\n typoGridRow.push(new TypoText(textDelimiter(\" \")));\n if (optionUsage.short !== undefined) {\n typoGridRow.push(\n new TypoText(\n textConstants(`-${optionUsage.short}`),\n textDelimiter(\", \"),\n ),\n );\n } else {\n typoGridRow.push(new TypoText());\n }\n const longOptionText = new TypoText(\n textConstants(`--${optionUsage.long}`),\n );\n if (optionUsage.label !== undefined) {\n longOptionText.push(textDelimiter(\" \"));\n longOptionText.push(textUserInput(optionUsage.label));\n }\n if (optionUsage.annotation !== undefined) {\n longOptionText.push(textSubtleInfo(optionUsage.annotation));\n }\n typoGridRow.push(longOptionText);\n typoGridRow.push(...createInformationals(optionUsage));\n typoGrid.pushRow(typoGridRow);\n }\n lines.push(...typoGrid.computeStyledLines(typoSupport));\n }\n\n if (usage.information.examples !== undefined) {\n lines.push(\"\");\n lines.push(textBlockTitle(\"Examples:\").computeStyledString(typoSupport));\n for (const example of usage.information.examples) {\n const explanationText = new TypoText();\n explanationText.push(textDelimiter(\" \"));\n explanationText.push(textSubtleInfo(`# ${example.explanation}`));\n lines.push(explanationText.computeStyledString(typoSupport));\n const commandLineText = new TypoText();\n commandLineText.push(textDelimiter(\" \"));\n commandLineText.push(textConstants(cliName));\n for (const commandArg of example.commandArgs) {\n commandLineText.push(textDelimiter(\" \"));\n if (typeof commandArg === \"string\") {\n commandLineText.push(new TypoString(commandArg));\n } else if (\"positional\" in commandArg) {\n commandLineText.push(textUserInput(commandArg.positional));\n } else if (\"subcommand\" in commandArg) {\n commandLineText.push(textConstants(commandArg.subcommand));\n } else if (\"option\" in commandArg) {\n const option = commandArg.option;\n if (\"short\" in option) {\n commandLineText.push(textConstants(`-${option.short}`));\n } else {\n commandLineText.push(textConstants(`--${option.long}`));\n }\n if (option.inlined !== undefined) {\n commandLineText.push(textSubtleInfo(\"=\"));\n commandLineText.push(textUserInput(option.inlined));\n }\n if (option.separated !== undefined) {\n for (const separatedValue of option.separated) {\n commandLineText.push(textDelimiter(\" \"));\n commandLineText.push(textUserInput(separatedValue));\n }\n }\n }\n }\n lines.push(commandLineText.computeStyledString(typoSupport));\n }\n }\n\n lines.push(\"\");\n return lines;\n}\n\nfunction createInformationals(usage: {\n description?: string | undefined;\n hint?: string | undefined;\n}): Array<TypoText> {\n const informationals = [];\n if (usage.description !== undefined) {\n informationals.push(textDelimiter(\" \"));\n informationals.push(textUsefulInfo(usage.description));\n }\n if (usage.hint !== undefined) {\n informationals.push(textDelimiter(\" \"));\n informationals.push(textSubtleInfo(`(${usage.hint})`));\n }\n if (informationals.length > 0) {\n return [new TypoText(textDelimiter(\" \"), ...informationals)];\n }\n return [];\n}\n\nfunction textUsageHero(value: string): TypoString {\n return new TypoString(value, typoStyleLogic);\n}\n\nfunction textUsageText(value: string): TypoString {\n return new TypoString(value, typoStyleRegularStrong);\n}\n\nfunction textUsefulInfo(value: string): TypoString {\n return new TypoString(value);\n}\n\nfunction textBlockTitle(value: string): TypoString {\n return new TypoString(value, typoStyleTitle);\n}\n\nfunction textSubtleInfo(value: string): TypoString {\n return new TypoString(value, typoStyleRegularWeaker);\n}\n\nfunction textConstants(value: string): TypoString {\n return new TypoString(value, typoStyleConstants);\n}\n\nfunction textUserInput(value: string): TypoString {\n return new TypoString(value, typoStyleUserInput);\n}\n\nfunction textDelimiter(value: string): TypoString {\n return new TypoString(value);\n}\n","import { Command, CommandDecoder } from \"./Command\";\nimport { optionFlag, optionSingleValue } from \"./Option\";\nimport { ReaderArgs } from \"./Reader\";\nimport { typeChoice } from \"./Type\";\nimport { TypoSupport } from \"./Typo\";\nimport { usageToStyledLines } from \"./Usage\";\n\n/**\n * Color selection modes availables\n */\nexport type RunColorMode = \"env\" | \"always\" | \"never\" | \"mock\";\n\n/**\n * Main entry point: parses CLI arguments, executes the matched command, and exits.\n * Handles `--help`, `--version`, usage-on-error, and exit codes.\n *\n * Exit codes:\n * - `0` on success / `--help` / `--version`\n * - `1` on parse error or execution error.\n *\n * @typeParam Context - Forwarded unchanged to the handler.\n *\n * @param cliName - Program name used in usage and `--version` output.\n * @param cliArgs - Raw arguments, typically `process.argv.slice(2)`.\n * @param context - Forwarded to the handler.\n * @param command - Root {@link Command}.\n * @param options.colorSetup - Configures color support; enables `--color` flag if set to `\"flag\"`.\n * @param options.usageOnHelp - Enables `--help` flag (default `true`).\n * @param options.usageOnError - Prints usage to stderr on parse error (default `true`).\n * @param options.buildVersion - Enables `--version`; prints `<cliName> <buildVersion>`.\n * @param options.onError - Custom handler for errors.\n * @param options.onExit - Overrides `process.exit`; useful for testing.\n *\n * @returns `Promise<never>` — always calls `onExit`.\n *\n * @example\n * ```ts\n * import { runAndExit, command, operation, positionalRequired, type } from \"cli-kiss\";\n *\n * const greetCommand = command(\n * { description: \"Greet someone\" },\n * operation(\n * { options: {}, positionals: [positionalRequired({ type: type(\"name\") })] },\n * async function (_ctx, { positionals: [name] }) {\n * console.log(`Hello, ${name}!`);\n * },\n * ),\n * );\n *\n * await runAndExit(\"greet\", process.argv.slice(2), undefined, greetCommand, {\n * buildVersion: \"1.0.0\",\n * });\n * ```\n */\nexport async function runAndExit<Context>(\n cliName: string,\n cliArgs: ReadonlyArray<string>,\n context: Context,\n command: Command<Context, void>,\n options?: {\n colorSetup?: \"flag\" | RunColorMode | undefined;\n usageOnHelp?: boolean | undefined;\n usageOnError?: boolean | undefined;\n buildVersion?: string | undefined;\n onError?: ((error: unknown) => void) | undefined;\n onExit?: ((code: number) => never) | undefined;\n },\n): Promise<never> {\n const readerArgs = new ReaderArgs(cliArgs);\n const preprocessors = new Array<\n (commandDecoder: CommandDecoder<Context, void>) => undefined | number\n >();\n let typoSupport = TypoSupport.none();\n const colorSetup = options?.colorSetup ?? \"flag\";\n if (colorSetup === \"flag\") {\n const colorOption = optionSingleValue<\"auto\" | RunColorMode>({\n long: \"color\",\n type: typeChoice(\"color-mode\", [\"auto\", \"always\", \"never\"]),\n fallbackValueIfAbsent: () => \"auto\",\n impliedValueIfNotInlined: () => \"always\",\n }).registerAndMakeDecoder(readerArgs);\n preprocessors.push(() => {\n try {\n typoSupport = computeTypoSupport(colorOption.getAndDecodeValue());\n } catch (error) {\n typoSupport = TypoSupport.inferFromEnv();\n throw error;\n }\n return undefined;\n });\n } else {\n typoSupport = computeTypoSupport(colorSetup);\n }\n if (options?.usageOnHelp ?? true) {\n const helpOption = optionFlag({ long: \"help\" }).registerAndMakeDecoder(\n readerArgs,\n );\n preprocessors.push((commandDecoder) => {\n if (!helpOption.getAndDecodeValue()) {\n return undefined;\n }\n console.log(computeUsageString(cliName, commandDecoder, typoSupport));\n return 0;\n });\n }\n if (options?.buildVersion !== undefined) {\n const versionOption = optionFlag({\n long: \"version\",\n }).registerAndMakeDecoder(readerArgs);\n preprocessors.push(() => {\n if (!versionOption.getAndDecodeValue()) {\n return undefined;\n }\n console.log([cliName, options.buildVersion].join(\" \"));\n return 0;\n });\n }\n // TODO - the lifecycle of this function should be improved\n // TODO - how to pass the color TypoSupport to the command logic ?\n // TODO - handle completions generators ?\n /*\n readerArgs.registerFlag({\n key: \"completion\",\n shorts: [],\n longs: [\"completion\"],\n });\n */\n const commandDecoder = command.consumeAndMakeDecoder(readerArgs);\n while (true) {\n try {\n const positional = readerArgs.consumePositional();\n if (positional === undefined) {\n break;\n }\n } catch (_) {}\n }\n const onExit = options?.onExit ?? process.exit;\n try {\n for (const preprocessor of preprocessors) {\n const preprocessorResult = preprocessor(commandDecoder);\n if (preprocessorResult !== undefined) {\n return onExit(preprocessorResult);\n }\n }\n const commandInterpreter = commandDecoder.decodeAndMakeInterpreter();\n try {\n await commandInterpreter.executeWithContext(context);\n return onExit(0);\n } catch (executionError) {\n handleError(cliName, options?.onError, executionError, typoSupport);\n return onExit(1);\n }\n } catch (parsingError) {\n if (options?.usageOnError ?? true) {\n console.error(computeUsageString(cliName, commandDecoder, typoSupport));\n }\n handleError(cliName, options?.onError, parsingError, typoSupport);\n return onExit(1);\n }\n}\n\nfunction handleError(\n _cliName: string,\n onError: ((error: unknown) => void) | undefined,\n error: unknown,\n typoSupport: TypoSupport,\n) {\n // TODO - should the cliName be part of the error message for logs ?\n const finalError = error;\n /*\n const finalError = new TypoError(\n new TypoText(new TypoString(cliName, typoStyleConstants)),\n error,\n );\n */\n if (onError !== undefined) {\n onError(finalError);\n } else {\n console.error(typoSupport.computeStyledErrorMessage(finalError));\n }\n}\n\nfunction computeUsageString<Context, Result>(\n cliName: string,\n commandDecoder: CommandDecoder<Context, Result>,\n typoSupport: TypoSupport,\n) {\n return usageToStyledLines({\n cliName,\n usage: commandDecoder.generateUsage(),\n typoSupport,\n }).join(\"\\n\");\n}\n\nfunction computeTypoSupport(colorMode: \"auto\" | RunColorMode): TypoSupport {\n switch (colorMode) {\n case \"auto\":\n return TypoSupport.inferFromEnv();\n case \"env\":\n return TypoSupport.inferFromEnv();\n case \"always\":\n return TypoSupport.tty();\n case \"never\":\n return TypoSupport.none();\n case \"mock\":\n return TypoSupport.mock();\n }\n}\n"],"mappings":"23BAAA,IAAAA,GAAA,GAAAC,GAAAD,GAAA,gBAAAE,EAAA,cAAAC,EAAA,aAAAC,EAAA,eAAAC,EAAA,gBAAAC,EAAA,aAAAC,EAAA,YAAAC,GAAA,mBAAAC,GAAA,2BAAAC,GAAA,cAAAC,GAAA,eAAAC,GAAA,qBAAAC,GAAA,sBAAAC,GAAA,uBAAAC,GAAA,uBAAAC,GAAA,wBAAAC,GAAA,eAAAC,GAAA,2BAAAC,EAAA,gBAAAC,GAAA,eAAAC,GAAA,iBAAAC,GAAA,gBAAAC,GAAA,aAAAC,GAAA,eAAAC,GAAA,eAAAC,GAAA,aAAAC,GAAA,gBAAAC,GAAA,eAAAC,GAAA,cAAAC,GAAA,YAAAC,GAAA,uBAAAC,EAAA,qBAAAC,GAAA,mBAAAC,EA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AAA/B,EACA,MAAOkB,EAAe,cAAc,EACpC,YAAAV,CACF,CAAC,EAAE,KAAK;AAAA,CAAI,CACd,CAEA,SAASM,GAAmBkB,EAA+C,CACzE,OAAQA,EAAW,CACjB,IAAK,OACH,OAAOvB,EAAY,aAAa,EAClC,IAAK,MACH,OAAOA,EAAY,aAAa,EAClC,IAAK,SACH,OAAOA,EAAY,IAAI,EACzB,IAAK,QACH,OAAOA,EAAY,KAAK,EAC1B,IAAK,OACH,OAAOA,EAAY,KAAK,CAC5B,CACF","names":["index_exports","__export","ReaderArgs","TypoError","TypoGrid","TypoString","TypoSupport","TypoText","command","commandChained","commandWithSubcommands","operation","optionFlag","optionRepeatable","optionSingleValue","positionalOptional","positionalRequired","positionalVariadics","runAndExit","suggestTextPushMessage","typeBoolean","typeChoice","typeDatetime","typeInteger","typeList","typeMapped","typeNumber","typePath","typeRenamed","typeString","typeTuple","typeUrl","typoStyleConstants","typoStyleFailure","typoStyleLogic","typoStyleQuote","typoStyleRegularStrong","typoStyleRegularWeaker","typoStyleTitle","typoStyleUserInput","usageToStyledLines","__toCommonJS","typoStyleTitle","typoStyleLogic","typoStyleQuote","typoStyleFailure","typoStyleConstants","typoStyleUserInput","typoStyleRegularStrong","typoStyleRegularWeaker","_value","_style","_TypoString","value","style","__privateAdd","__privateSet","typoSupport","__privateGet","TypoString","_strings","_TypoText","segments","segment","part","separator","ellipsisLimit","index","t","length","typoString","TypoText","_typoRows","TypoGrid","cells","widths","styledLines","typoGridRow","typoGridColumnIndex","width","styledGridRow","typoGridCell","padding","_typoText","_TypoError","currentTypoText","source","typoText","thrower","context","error","TypoError","_kind","_TypoSupport","kind","readEnvVar","envForceColor","typoStyle","styledValue","fgColorCode","ttyCodeFgColors","bgColorCode","ttyCodeBgColors","boldCode","ttyCodeBold","dimCode","ttyCodeDim","italicCode","ttyCodeItalic","underlineCode","ttyCodeUnderline","strikethroughCode","ttyCodeStrikethrough","ttyCodeReset","fgColorPart","bgColorPart","boldPart","dimPart","italicPart","underlinePart","TypoSupport","name","suggestTextPushMessage","text","query","candidates","reasonableHints","suggestReasonablePayloads","reference","hint","TypoString","sortedAlternatives","computeAndSortByDivergences","divergenceThreshold","acceptablePayloads","divergence","payload","queryNormalized","referenceNormalized","distanceDamerauLevenshtein","a","b","m","n","dp","i","j","cost","command","information","operation","readerArgs","operationDecoder","endPositional","errorText","TypoText","TypoString","typoStyleQuote","TypoError","generateUsageLeaf","operationInterpreter","context","error","commandWithSubcommands","subcommands","subcommandNames","name","subcommandName","typoStyleUserInput","suggestSubcommandNames","subcommandInput","subcommandDecoder","subcommandUsage","currentUsage","subcommandInterpreter","subcommand","description","hint","commandChained","positionals","options","p","input","suggestTextPushMessage","typoStyleConstants","operation","inputs","handler","optionsUsage","optionKey","optionInput","positionalsUsage","positionalInput","readerArgs","optionsDecoders","positionalsDecoders","optionsValues","positionalsValues","positionalDecoder","context","import_fs","typeString","name","input","typeBoolean","lowerInput","typeBooleanValuesTrue","typeBooleanValuesFalse","throwInvalidValue","typeNumber","parsed","typeInteger","typeDatetime","timestampMs","typeUrl","typePath","checks","safeStatSync","path","error","TypoError","TypoText","TypoString","typoStyleQuote","stats","preview","typeChoice","values","caseSensitive","normalize","valueByNormalized","value","errorText","suggestTextPushMessage","typeMapped","before","mapper","typoStyleLogic","typeRenamed","type","typeTuple","elementTypes","separator","elementType","splits","split","index","typeList","kind","optionFlag","definition","type","typeBoolean","long","short","description","hint","aliases","readerOptions","resultsGetter","setupOptionAliased","results","throwSetMultipleTimesError","r","input","decodeValue","optionSingleValue","label","annotation","value","result","errorText","makeErrorText","TypoString","TypoError","error","inlined","separated","optionRepeatable","params","TypoText","typoStyleConstants","typoStyleUserInput","typoStyleLogic","longKey","shortKey","aliasLongKeys","aliasShortKeys","longKeys","shortKeys","setupOptionMany","nextGuard","consumeGroupRestAsValue","getters","key","identifier","getter","identifiers","identifiersTexts","positionalRequired","definition","description","hint","type","label","readerPositionals","positional","errorText","makeErrorTextLabel","TypoString","typoStyleRegularWeaker","TypoError","decodeValue","positionalOptional","error","positionalVariadics","labelSingle","labelMultiple","positionals","input","TypoText","typoStyleUserInput","message","_tokens","_parsedIndex","_parsedDouble","_optionLongContextByIdentifier","_optionShortContextByIdentifier","_ReaderArgs_instances","consumeToken_fn","tryConsumeAsOption_fn","consumeOptionLong_fn","tryConsumeOptionShort_fn","consumeOptionValues_fn","throwUnknownOptionError_fn","ReaderArgs","tokens","__privateAdd","__privateSet","longSpec","identifier","isValidOptionKey","__privateGet","values","shortSpec","i","slicedIdentifier","otherIdentifier","token","__privateMethod","__privateWrapper","valueIndexStart","shortIndexStart","shortIndexEnd","shortContext","tokenRest","valueInlined","longContext","context","value","spec","nextToken","TypoError","TypoText","TypoString","typoStyleConstants","typoStyleQuote","inputIdentifier","candidatesIdentifiers","errorText","suggestTextPushMessage","candidateIdentifier","name","usageToStyledLines","params","cliName","usage","typoSupport","lines","segmentsText","TypoText","textUsageHero","textDelimiter","textConstants","segment","textUserInput","introText","textUsageText","textSubtleInfo","detail","detailText","textBlockTitle","typoGrid","TypoGrid","positionalUsage","typoGridRow","createInformationals","subcommandUsage","optionUsage","longOptionText","example","explanationText","commandLineText","commandArg","TypoString","option","separatedValue","informationals","textUsefulInfo","value","typoStyleLogic","typoStyleRegularStrong","typoStyleTitle","typoStyleRegularWeaker","typoStyleConstants","typoStyleUserInput","runAndExit","cliName","cliArgs","context","command","options","readerArgs","ReaderArgs","preprocessors","typoSupport","TypoSupport","colorSetup","colorOption","optionSingleValue","typeChoice","computeTypoSupport","error","helpOption","optionFlag","commandDecoder","computeUsageString","versionOption","onExit","preprocessor","preprocessorResult","commandInterpreter","executionError","handleError","parsingError","_cliName","onError","finalError","usageToStyledLines","colorMode"]}