@politty/valibot 0.1.1 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/README.md +31 -0
  2. package/dist/cli-main-C8D_mKfv.js +2 -0
  3. package/dist/cli-main-ClQaGXB3.js +1 -0
  4. package/dist/cli-run-gG52V0gu.js +1 -0
  5. package/dist/cli.js +1 -15
  6. package/dist/command-Mbdt0bmN.js +1 -0
  7. package/dist/compile-cache-VuUbFWIo.js +1 -0
  8. package/dist/compile-cache.js +1 -3
  9. package/dist/completion-D8DMrPqg.js +116 -0
  10. package/dist/completion-DUMcvXkT.js +1 -0
  11. package/dist/completion.d.ts +87 -7
  12. package/dist/completion.js +1 -4
  13. package/dist/docs.d.ts +1 -1
  14. package/dist/docs.js +84 -3045
  15. package/dist/dynamic-CMtee4tD.js +1 -0
  16. package/dist/dynamic-CrnlveHj.js +6 -0
  17. package/dist/field-meta-COGya7xp.js +1 -0
  18. package/dist/index.d.ts +20 -16
  19. package/dist/index.js +1 -27
  20. package/dist/log-collector-hiFa3sNm.js +1 -0
  21. package/dist/logger-CJsyJ8sb.js +1 -0
  22. package/dist/prompt-CqmGq1_N.js +1 -0
  23. package/dist/prompt-clack.d.ts +1 -1
  24. package/dist/prompt-clack.js +1 -32
  25. package/dist/prompt-inquirer.d.ts +1 -1
  26. package/dist/prompt-inquirer.js +1 -47
  27. package/dist/prompt.d.ts +1 -1
  28. package/dist/prompt.js +1 -4
  29. package/dist/register-BnpFle4e.js +1 -0
  30. package/dist/runner-C_wCXh6X.js +1 -0
  31. package/dist/runner-uPmkI9Gb.js +29 -0
  32. package/dist/schema-BiUP_KyV.js +1 -0
  33. package/dist/schema-extractor-DU0Vuhbd.js +1 -0
  34. package/dist/skill.d.ts +1 -1
  35. package/dist/skill.js +2 -1801
  36. package/dist/subcommand-router-D8GTMXYL.js +1 -0
  37. package/dist/{arg-registry-B8QvBM_Q.d.ts → types-uIXEHpar.d.ts} +841 -827
  38. package/dist/with-completion-command-DDohm8U6.js +3 -0
  39. package/dist/{index-CMb2xLiJ.d.ts → with-completion-command-by6cMuSQ.d.ts} +3 -74
  40. package/package.json +3 -3
  41. package/dist/cli-main-CgoQvkB6.js +0 -3
  42. package/dist/cli-main-DyfnS8jc.js +0 -314
  43. package/dist/cli-run-G2dThja3.js +0 -8
  44. package/dist/command-k-4yAz4J.js +0 -42
  45. package/dist/compile-cache-BC65o7MH.js +0 -103
  46. package/dist/completion-DW5qVc3l.js +0 -5613
  47. package/dist/field-meta-DMy5BcRr.js +0 -146
  48. package/dist/log-collector-CoUkLVJB.js +0 -114
  49. package/dist/logger-i_bb-Jhc.js +0 -133
  50. package/dist/prompt-BjIZThsH.js +0 -169
  51. package/dist/register-BhFZi5ZA.js +0 -494
  52. package/dist/runner-DAGvxV2P.js +0 -2980
  53. package/dist/runner-MMjpKeEa.js +0 -3
  54. package/dist/schema-extractor-DMSozq40.js +0 -250
  55. package/dist/src-1QsOfU2R.js +0 -6
  56. package/dist/src-BKqoVDbu.js +0 -12
  57. package/dist/subcommand-router-Cskpofdk.js +0 -134
@@ -44,982 +44,996 @@ interface SchemaLike<Output = unknown> {
44
44
  /** Infer the output type of a {@link SchemaLike}. */
45
45
  type InferSchemaOutput<S> = S extends SchemaLike ? NonNullable<S["~standard"]["types"]>["output"] : never;
46
46
  //#endregion
47
- //#region ../core/src/adapter/field-meta.d.ts
47
+ //#region ../core/src/core/dynamic-completion-types.d.ts
48
48
  /**
49
- * Resolved metadata for an argument field
49
+ * Types for in-process dynamic value completion.
50
+ *
51
+ * A `resolve` callback registered on `arg(...)` receives parsed context
52
+ * (other arg values typed so far, previous values supplied to the same
53
+ * option, the current word being completed, target shell) and returns
54
+ * candidates. The callback runs inside the `__complete` command. Dispatcher
55
+ * shell scripts call `__complete` for every completion request; static shell
56
+ * scripts delegate to it for any spec that uses `resolve`.
57
+ *
58
+ * Defined under `core/` (not `completion/`) so `arg-registry.ts` can
59
+ * reference the resolver type without crossing the lint-enforced
60
+ * `completion → core` boundary.
50
61
  */
51
- interface ResolvedFieldMeta {
52
- /** Field name (camelCase, as defined in schema) */
53
- name: string;
54
- /** CLI option name (kebab-case, for command line usage) */
55
- cliName: string;
56
- /**
57
- * Aliases for this option, normalized to an array.
58
- * 1-char entries are short aliases (`-v`); multi-char entries are long
59
- * aliases (`--to-be`).
60
- */
61
- alias?: string[] | undefined;
62
- /**
63
- * Aliases that are accepted at parse time but hidden from help,
64
- * generated docs, and shell completion.
65
- */
66
- hiddenAlias?: string[] | undefined;
67
- /** Argument description */
68
- description?: string | undefined;
69
- /** Whether this is a positional argument */
70
- positional: boolean;
71
- /** Placeholder for help display */
72
- placeholder?: string | undefined;
73
- /**
74
- * Environment variable name(s) to read value from.
75
- * If an array, earlier entries take priority.
76
- */
77
- env?: string | string[] | undefined;
78
- /** Whether this argument is required */
79
- required: boolean;
80
- /** Default value if any */
81
- defaultValue?: unknown;
82
- /** Detected type from schema */
83
- type: "string" | "number" | "boolean" | "array" | "unknown";
62
+ /** Bitmask combining `CompletionDirective` values. */
63
+ type CompletionDirectiveMask = number;
64
+ interface DynamicCompletionContext {
65
+ /** Word being completed. `--field=` inline prefix is stripped before this is set. */
66
+ currentWord: string;
67
+ /** Target shell formatting requested by the caller. */
68
+ shell: "bash" | "zsh" | "fish";
84
69
  /**
85
- * Original field schema, carried through opaquely for downstream
86
- * consumers. Its concrete type belongs to the adapter's schema library
87
- * (zod, valibot, or an internal descriptor); core never calls into it.
70
+ * Best-effort parsed values of OTHER args on the same command, keyed by
71
+ * camelCase name. Includes positionals and other options. Zod validation
72
+ * is NOT applied; values are raw strings (or arrays of raw strings for
73
+ * array-typed options/variadic positionals).
88
74
  */
89
- schema: unknown;
90
- /** True if this overrides built-in aliases (-h, -H) */
91
- overrideBuiltinAlias?: true;
92
- /** Enum values if detected from schema (z.enum) */
93
- enumValues?: string[] | undefined;
94
- /** Completion metadata from arg() */
95
- completion?: CompletionMeta | undefined;
96
- /** Prompt metadata from arg() for interactive input */
97
- prompt?: PromptMeta | undefined;
75
+ parsedArgs: Readonly<Record<string, unknown>>;
98
76
  /**
99
- * Negation configuration for this boolean field.
100
- *
101
- * - String (e.g. `"disable-cache"`): the default `--no-<cliName>` form is
102
- * suppressed and only `--<negation>` (plus its camelCase variant) is
103
- * accepted as the negation flag.
104
- * - `true`: the default `--no-<cliName>` form is accepted **and** shown in
105
- * help, generated docs, and shell completions.
106
- * - `false`: neither the default `--no-<cliName>` nor any custom name is
107
- * accepted; the field only responds to the positive flag.
108
- * - `undefined`: no negation form is accepted or shown.
109
- *
110
- * Only applies to boolean fields; populated as `undefined` otherwise.
77
+ * Values already supplied for the SAME option/positional being completed.
78
+ * Useful for de-duplicating repeated array options.
111
79
  */
112
- negation?: string | boolean | undefined;
80
+ previousValues: readonly string[];
113
81
  /**
114
- * Derived display name (no `--` prefix) for the negation flag in help,
115
- * generated docs, and shell completions. `undefined` means the negation
116
- * is hidden from those surfaces. Computed from `negation` + `cliName`.
82
+ * Subcommand path from root (e.g. ["api"]). Reflects what the user
83
+ * actually typed — aliases are NOT resolved to their canonical names, so
84
+ * resolvers that branch on the path should accept every alias they care
85
+ * about.
117
86
  */
118
- negationDisplay?: string | undefined;
119
- /** Description shown for the negation option in help/docs. */
120
- negationDescription?: string | undefined;
121
- /** Side-effect callback from arg() metadata */
122
- effect?: ((value: unknown, context: EffectContext) => void | PromiseLike<void>) | undefined;
87
+ subcommandPath: readonly string[];
123
88
  }
124
- /**
125
- * Extracted fields from a schema
126
- */
127
- interface ExtractedFields {
128
- /** All field definitions */
129
- fields: ResolvedFieldMeta[];
130
- /** Original schema for validation */
131
- schema: ArgsSchema;
132
- /** Schema type */
133
- schemaType: "object" | "discriminatedUnion" | "union" | "xor" | "intersection";
134
- /** Discriminator key (for discriminatedUnion) */
135
- discriminator?: string;
136
- /** Variants (for discriminatedUnion) */
137
- variants?: Array<{
138
- discriminatorValue: string;
139
- fields: ResolvedFieldMeta[];
140
- description?: string;
141
- }>;
142
- /** Options (for union) */
143
- unionOptions?: ExtractedFields[];
144
- /** Schema description */
89
+ interface DynamicCompletionCandidate {
90
+ value: string;
145
91
  description?: string;
92
+ }
93
+ interface DynamicCompletionResult {
94
+ /** Candidates to surface. Strings or `{value, description}` objects. */
95
+ candidates: Array<string | DynamicCompletionCandidate>;
146
96
  /**
147
- * Unknown keys handling mode
148
- * - "strict": Unknown keys cause validation errors (z.strictObject or z.object().strict())
149
- * - "strip": Unknown keys trigger warnings (default, z.object())
150
- * - "passthrough": Unknown keys are silently ignored (z.looseObject or z.object().passthrough())
97
+ * Optional directive override. When omitted, defaults to
98
+ * `FilterPrefix | NoFileCompletion` (matches `choices` behaviour).
151
99
  */
152
- unknownKeysMode: UnknownKeysMode;
100
+ directive?: CompletionDirectiveMask;
153
101
  }
102
+ type DynamicCompletionResolver = (ctx: DynamicCompletionContext) => DynamicCompletionResult | Promise<DynamicCompletionResult>;
103
+ //#endregion
104
+ //#region ../core/src/core/expand-completion-types.d.ts
154
105
  /**
155
- * Unknown keys handling mode for object schemas
156
- * - "strict": Unknown keys cause validation errors
157
- * - "strip": Unknown keys are silently ignored (default)
158
- * - "passthrough": Unknown keys are passed through
159
- */
160
- type UnknownKeysMode = "strict" | "strip" | "passthrough";
161
- /**
162
- * Convert camelCase to kebab-case
163
- * @example toKebabCase("dryRun") => "dry-run"
164
- * @example toKebabCase("outputDir") => "output-dir"
165
- * @example toKebabCase("XMLParser") => "xml-parser"
106
+ * Types for "expand" completion — candidates that depend on sibling arg
107
+ * values.
108
+ *
109
+ * The user provides `dependsOn` (sibling arg names that must have static
110
+ * `choices` or an enum schema) and `enumerate(deps)`. Dispatcher scripts call
111
+ * `enumerate` inside `__complete` for the dependency values already typed on
112
+ * the command line. Static scripts walk the cartesian product of the
113
+ * dependsOn values, call `enumerate` for each combination, and emit a shell
114
+ * lookup table.
115
+ *
116
+ * Defined under `core/` (not `completion/`) so `arg-registry.ts` can
117
+ * reference these types without crossing the lint-enforced
118
+ * `completion → core` boundary.
166
119
  */
167
- declare function toKebabCase(str: string): string;
120
+ /** Candidate returned by an `enumerate` callback. */
121
+ interface ExpandCandidate {
122
+ value: string;
123
+ description?: string;
124
+ }
125
+ /** Resolved candidate stored on a {@link ValueCompletion} after enumeration. */
126
+ interface ResolvedExpandCandidate {
127
+ value: string;
128
+ description?: string;
129
+ }
168
130
  /**
169
- * Convert hyphen-separated sequences to camelCase.
131
+ * User-facing spec attached to `completion.custom.expand`.
170
132
  *
171
- * Replaces `-x` (hyphen followed by a lowercase letter) with the uppercase
172
- * variant. Non-hyphenated input (e.g., already camelCase) is returned as-is.
133
+ * `dependsOn` lists sibling args (camelCase names) whose values determine
134
+ * which candidates apply. Each named arg must have a static set of values —
135
+ * either an explicit `completion.custom.choices` or an enum schema. The
136
+ * order of `dependsOn` is the order in which `deps` keys are exposed to
137
+ * `enumerate`.
173
138
  *
174
- * @param str - A string that may contain hyphens
175
- * @example toCamelCase("dry-run") => "dryRun"
176
- * @example toCamelCase("output-dir") => "outputDir"
177
- * @example toCamelCase("dryRun") => "dryRun"
139
+ * In dispatcher mode, `enumerate` runs during `__complete` for the dependency
140
+ * values already typed by the user. In static mode, it runs once per
141
+ * cartesian-product combination at script-generation time (e.g. when the user
142
+ * runs `<program> completion zsh --static`). It must be a pure function of
143
+ * `deps`.
178
144
  */
179
- declare function toCamelCase(str: string): string;
145
+ interface ExpandCompletion {
146
+ dependsOn: readonly string[];
147
+ enumerate: (deps: Readonly<Record<string, string>>) => ReadonlyArray<string | ExpandCandidate>;
148
+ }
180
149
  //#endregion
181
- //#region ../core/src/lazy.d.ts
150
+ //#region ../core/src/core/arg-registry.d.ts
182
151
  /**
183
- * A lazily-loaded command that carries synchronous metadata for
184
- * static analysis (completion, help) while deferring full module
185
- * loading to execution time.
152
+ * Built-in completion types
186
153
  */
187
- interface LazyCommand<T extends AnyCommand = AnyCommand> {
188
- readonly __politty_lazy__: true;
189
- readonly meta: T;
190
- readonly load: () => Promise<AnyCommand>;
191
- }
154
+ type CompletionType = "file" | "directory" | "none";
192
155
  /**
193
- * Type guard: check if a value is a LazyCommand
156
+ * Custom completion specification.
157
+ *
158
+ * `choices`, `shellCommand`, `resolve`, and `expand` are mutually exclusive —
159
+ * specifying more than one throws when the field metadata is resolved.
194
160
  */
195
- declare function isLazyCommand(value: unknown): value is LazyCommand;
161
+ interface CustomCompletion {
162
+ /** Static list of choices for completion */
163
+ choices?: string[];
164
+ /** Shell command to execute for dynamic completion */
165
+ shellCommand?: string;
166
+ /**
167
+ * In-process JS callback for dynamic completion. Receives parsed context
168
+ * (other arg values typed so far, previously supplied values for this same
169
+ * option) and returns candidates. Dispatcher scripts call
170
+ * `<program> __complete` for every completion request; static scripts
171
+ * delegate to it whenever this is set.
172
+ */
173
+ resolve?: DynamicCompletionResolver;
174
+ /**
175
+ * Completion whose candidates depend on sibling arg values. Dispatcher
176
+ * scripts call `enumerate` inside `__complete` for the dependency values
177
+ * already typed on the command line. Static scripts pre-enumerate every
178
+ * combination of `dependsOn` values at script-generation time and dispatch
179
+ * via a shell lookup table.
180
+ */
181
+ expand?: ExpandCompletion;
182
+ }
196
183
  /**
197
- * Create a lazily-loaded subcommand with synchronous metadata.
198
- *
199
- * The `meta` command provides names, descriptions, and args schema
200
- * for static analysis (completion scripts, help text) without loading
201
- * the full command module.
202
- *
203
- * The `load` function is called only at execution time.
184
+ * Completion metadata for an argument
204
185
  *
205
186
  * @example
206
187
  * ```ts
207
- * import { lazy, defineCommand } from "politty";
188
+ * // File completion with extension filter
189
+ * input: arg(z.string(), {
190
+ * completion: { type: "file", extensions: ["json", "yaml"] }
191
+ * })
208
192
  *
209
- * const cli = defineCommand({
210
- * name: "mycli",
211
- * subCommands: {
212
- * deploy: lazy(
213
- * defineCommand({
214
- * name: "deploy",
215
- * description: "Deploy the application",
216
- * args: z.object({ env: arg(z.string()) }),
217
- * }),
218
- * () => import("./deploy.js").then((m) => m.deployCommand),
219
- * ),
220
- * },
221
- * });
193
+ * // Directory completion
194
+ * outputDir: arg(z.string(), {
195
+ * completion: { type: "directory" }
196
+ * })
197
+ *
198
+ * // Custom static choices
199
+ * logLevel: arg(z.string(), {
200
+ * completion: { custom: { choices: ["debug", "info", "warn", "error"] } }
201
+ * })
202
+ *
203
+ * // Dynamic completion from shell command
204
+ * branch: arg(z.string(), {
205
+ * completion: { custom: { shellCommand: "git branch --format='%(refname:short)'" } }
206
+ * })
207
+ *
208
+ * // File completion with glob pattern matcher
209
+ * envFile: arg(z.string(), {
210
+ * completion: { type: "file", matcher: [".env.*"] }
211
+ * })
222
212
  * ```
223
213
  */
224
- declare function lazy<T extends AnyCommand>(meta: T, load: () => Promise<AnyCommand>): LazyCommand<T>;
225
- //#endregion
226
- //#region ../core/src/types.d.ts
214
+ type CompletionMeta = {
215
+ /** Built-in completion type */
216
+ type?: CompletionType;
217
+ /** Custom completion (takes precedence over type if both specified) */
218
+ custom?: CustomCompletion;
219
+ } & ({
220
+ /** File extension filter (only applies when type is "file") */ extensions?: string[];
221
+ matcher?: never;
222
+ } | {
223
+ /** Glob patterns for file matching (only applies when type is "file") */ matcher?: string[];
224
+ extensions?: never;
225
+ });
227
226
  /**
228
- * Global args interface for declaration merging (Pattern 3).
229
- * Users can extend this interface to add global options to all commands:
227
+ * Prompt input type for interactive prompts
228
+ *
229
+ * - "text": free-form text input (default for string schemas)
230
+ * - "password": masked text input
231
+ * - "confirm": yes/no prompt (default for boolean schemas)
232
+ * - "select": single selection from choices (default for enum schemas)
233
+ * - "file": file path input (inherited from completion type)
234
+ * - "directory": directory path input (inherited from completion type)
235
+ */
236
+ type PromptType = "text" | "password" | "confirm" | "select" | "file" | "directory";
237
+ /**
238
+ * Prompt metadata for interactive input when a value is missing.
239
+ * Used by the `politty/prompt` module to request user input for unresolved arguments.
230
240
  *
241
+ * @example
231
242
  * ```ts
232
- * declare module "politty" {
233
- * interface GlobalArgs { verbose: boolean; config?: string; }
234
- * }
243
+ * // Custom prompt message
244
+ * name: arg(z.string(), {
245
+ * prompt: { message: "What is your name?" }
246
+ * })
247
+ *
248
+ * // Password input (masked)
249
+ * token: arg(z.string(), {
250
+ * prompt: { type: "password", message: "Enter API token" }
251
+ * })
252
+ *
253
+ * // Select with custom choices
254
+ * region: arg(z.string(), {
255
+ * prompt: { choices: ["us-east-1", "eu-west-1", "ap-northeast-1"] }
256
+ * })
235
257
  * ```
236
258
  */
237
- interface GlobalArgs {}
259
+ interface PromptMeta {
260
+ /** Prompt message shown to the user. Defaults to the field's description or name. */
261
+ message?: string;
262
+ /** Explicit prompt type. Overrides auto-detection from schema/completion. */
263
+ type?: PromptType;
264
+ /** Choices for select prompt. Overrides enum values from schema. */
265
+ choices?: Array<string | {
266
+ label: string;
267
+ value: string;
268
+ }>;
269
+ /** Whether to enable prompting for this field (default: true when prompt is set) */
270
+ enabled?: boolean;
271
+ }
238
272
  /**
239
- * Detect empty interface (used for GlobalArgs declaration merging)
273
+ * Context provided to effect callbacks.
274
+ * When GlobalArgs is extended via declaration merging, `globalArgs` is typed accordingly.
240
275
  */
241
- type IsEmpty<T> = keyof T extends never ? true : false;
276
+ type EffectContext = {
277
+ /** Field name (camelCase) */
278
+ name: string;
279
+ /** Validated args for this schema (global args for global effects, command args for command effects) */
280
+ args: Readonly<Record<string, unknown>>;
281
+ } & (IsEmpty<GlobalArgs> extends true ? {
282
+ globalArgs?: Readonly<Record<string, unknown>>;
283
+ } : {
284
+ globalArgs?: Readonly<GlobalArgs>;
285
+ });
242
286
  /**
243
- * Where a resolved arg value came from:
244
- * - `"cli"`: an explicit CLI token (flag or positional)
245
- * - `"env"`: `field.env` fallback (no CLI token was provided)
246
- * - `"default"`: neither of the above (e.g. a schema default, or a value
247
- * resolved by a `prompt` handler)
287
+ * Base metadata shared by all argument types
248
288
  */
249
- type ArgSource = "cli" | "env" | "default";
289
+ interface BaseArgMeta<TValue = unknown> {
290
+ /** Argument description */
291
+ description?: string;
292
+ /** Treat as positional argument */
293
+ positional?: boolean;
294
+ /** Placeholder for help display */
295
+ placeholder?: string;
296
+ /**
297
+ * Environment variable name(s) to read value from.
298
+ * If an array is provided, earlier entries take priority.
299
+ * CLI arguments always take precedence over environment variables.
300
+ *
301
+ * @example
302
+ * ```ts
303
+ * // Single env var
304
+ * port: arg(z.coerce.number(), { env: "PORT" })
305
+ *
306
+ * // Multiple env vars (PORT takes priority over SERVER_PORT)
307
+ * port: arg(z.coerce.number(), { env: ["PORT", "SERVER_PORT"] })
308
+ * ```
309
+ */
310
+ env?: string | string[];
311
+ /** Completion configuration for shell tab-completion */
312
+ completion?: CompletionMeta;
313
+ /**
314
+ * Interactive prompt configuration for missing values.
315
+ * When set, the `politty/prompt` module will prompt the user interactively
316
+ * if this argument is not provided via CLI args or environment variables.
317
+ *
318
+ * @example
319
+ * ```ts
320
+ * name: arg(z.string(), {
321
+ * description: "User name",
322
+ * prompt: { message: "What is your name?" },
323
+ * })
324
+ * ```
325
+ */
326
+ prompt?: PromptMeta;
327
+ /**
328
+ * Control the boolean negation option.
329
+ *
330
+ * Boolean fields accept `--no-<cliName>` (and the camelCase `--no<Name>`
331
+ * form) to set the value to `false` only when `negation: true` is set.
332
+ * By default no negation form is accepted. This option lets you customize
333
+ * or expose that behavior:
334
+ *
335
+ * - `string` — replaces the auto-generated `--no-*` form with a custom
336
+ * name. The default `--no-*` is no longer recognized.
337
+ * - `true` — enables the default `--no-<cliName>` form and advertises it
338
+ * in help, generated docs, and shell completions.
339
+ * - `false` — disables negation entirely; same as the default, but explicit.
340
+ * Neither the default `--no-*` nor any custom name is accepted.
341
+ *
342
+ * String values follow the same naming conventions as `cliName`
343
+ * (kebab-case is recommended). Only valid on boolean fields; setting
344
+ * `negation` on a non-boolean field is a type error and raises a
345
+ * runtime error during command parsing.
346
+ *
347
+ * @example
348
+ * ```ts
349
+ * // Custom negation name
350
+ * cache: arg(z.boolean().default(true), {
351
+ * description: "Enable caching",
352
+ * negation: "disable-cache",
353
+ * })
354
+ * // Accepts: --cache (true), --disable-cache (false)
355
+ * // No longer accepts: --no-cache
356
+ *
357
+ * // Enable default `--no-X` in parsing/help/docs/completion
358
+ * verbose: arg(z.boolean().default(false), {
359
+ * negation: true,
360
+ * })
361
+ * // Help shows `--verbose / --no-verbose`
362
+ *
363
+ * // Disable negation entirely
364
+ * dryRun: arg(z.boolean().default(false), {
365
+ * negation: false,
366
+ * })
367
+ * // Accepts: --dry-run (true)
368
+ * // No longer accepts: --no-dry-run
369
+ * ```
370
+ */
371
+ negation?: string | boolean;
372
+ /**
373
+ * Description shown for the negation option in help and generated docs.
374
+ * Only meaningful when `negation` is set to a custom name string or `true`.
375
+ * Disallowed when `negation` is `false`.
376
+ */
377
+ negationDescription?: string;
378
+ /**
379
+ * Side-effect callback executed after argument parsing and validation.
380
+ * Runs before the command lifecycle (setup/run/cleanup).
381
+ * Use Zod .transform() for value transformation instead.
382
+ *
383
+ * @example
384
+ * ```ts
385
+ * verbose: arg(z.boolean().default(false), {
386
+ * alias: "v",
387
+ * effect: (value) => {
388
+ * if (value) logger.setLevel("debug");
389
+ * },
390
+ * })
391
+ * ```
392
+ */
393
+ effect?: (value: TValue, context: EffectContext) => void | PromiseLike<void>;
394
+ }
250
395
  /**
251
- * Example definition for a command
396
+ * Metadata for regular arguments (non-builtin aliases)
397
+ *
398
+ * `alias` accepts either a single string or an array of strings.
399
+ * Single-character entries become short options (e.g. `-v`); multi-character
400
+ * entries become additional long options (e.g. `--to-be` for `--tobe`).
252
401
  */
253
- interface Example {
254
- /** Command arguments to execute (e.g., "World" or "--loud Alice") */
255
- cmd: string;
256
- /** Description of the example */
257
- desc: string;
258
- /** Expected output (optional, for documentation) */
259
- output?: string;
402
+ interface RegularArgMeta<TValue = unknown> extends BaseArgMeta<TValue> {
403
+ /**
404
+ * Alias name(s) for this option.
405
+ * - 1-char string → short alias (`-v`)
406
+ * - >1-char string → long alias (`--long-name`)
407
+ * - array → multiple aliases of either kind
408
+ */
409
+ alias?: string | string[] | readonly string[];
410
+ /**
411
+ * Alias name(s) that are accepted by the parser but hidden from help,
412
+ * generated docs, and shell completion. Useful for legacy or deprecated
413
+ * names that should still work without being advertised.
414
+ */
415
+ hiddenAlias?: string | string[] | readonly string[];
260
416
  }
261
417
  /**
262
- * Logger interface for CLI output
263
- * Can be overridden by passing a custom logger to runMain or runCommand
418
+ * Metadata for overriding built-in aliases (-h, -H)
264
419
  */
265
- interface Logger {
266
- /** Log informational message to stdout */
267
- log(message: string): void;
268
- /** Log error message to stderr */
269
- error(message: string): void;
270
- /** Log warning message to stderr */
271
- warn?(message: string): void;
420
+ interface BuiltinOverrideArgMeta<TValue = unknown> extends BaseArgMeta<TValue> {
421
+ /** Built-in alias to override ('h' or 'H'), optionally combined with extra aliases */
422
+ alias: "h" | "H" | Array<"h" | "H" | string> | ReadonlyArray<"h" | "H" | string>;
423
+ /** Hidden aliases (accepted but not surfaced in help/docs/completion) */
424
+ hiddenAlias?: string | string[] | readonly string[];
425
+ /** Must be true to override built-in aliases */
426
+ overrideBuiltinAlias: true;
272
427
  }
273
428
  /**
274
- * Supported schema types for args: any Standard Schema (zod, valibot, ...)
275
- * whose output is an object. Adapter packages narrow this back to their
276
- * library's own schema type in their public exports (e.g. `@politty/zod`
277
- * exports `ArgsSchema = z.ZodType<Record<string, any>>`).
429
+ * Metadata options for argument definition
278
430
  */
279
- type ArgsSchema = SchemaLike<Record<string, any>>;
431
+ type ArgMeta<TValue = unknown> = RegularArgMeta<TValue> | BuiltinOverrideArgMeta<TValue>;
280
432
  /**
281
- * Context provided to setup function
433
+ * Register metadata for a schema
434
+ *
435
+ * @param schema - The schema to attach metadata to
436
+ * @param meta - Argument metadata
437
+ * @returns The same schema (for chaining)
438
+ *
439
+ * @example
440
+ * ```ts
441
+ * import { z } from "zod";
442
+ * import { arg, defineCommand } from "politty";
443
+ *
444
+ * const cmd = defineCommand({
445
+ * args: z.object({
446
+ * name: arg(z.string(), { description: "User name", positional: true }),
447
+ * verbose: arg(z.boolean().default(false), { alias: "v" }),
448
+ * }),
449
+ * run: (args) => {
450
+ * console.log(args.name, args.verbose);
451
+ * },
452
+ * });
453
+ * ```
282
454
  */
283
- interface SetupContext<TArgs = unknown> {
284
- /** Parsed and validated arguments */
285
- args: TArgs;
286
- }
287
455
  /**
288
- * Context provided to cleanup function
456
+ * Detect whether `A` contains a reserved alias ("h" or "H"), for either a
457
+ * plain string or a tuple/array of strings. Uses `[A] extends [never]` to
458
+ * prevent distribution returning `never` for missing fields.
289
459
  */
290
- interface CleanupContext<TArgs = unknown> {
291
- /** Parsed and validated arguments */
292
- args: TArgs;
293
- /** Error if command execution failed */
294
- error?: Error | undefined;
295
- }
460
+ type ContainsReservedAlias<A> = [A] extends [never] ? false : A extends "h" | "H" ? true : A extends readonly (infer E)[] ? [Extract<E, "h" | "H">] extends [never] ? false : true : false;
461
+ type ReservedAliasTypeError<M> = { [K in keyof M]: M[K]; } & {
462
+ __typeError: "Alias 'h' or 'H' requires overrideBuiltinAlias: true";
463
+ };
464
+ type NegationTypeError<M> = { [K in keyof M]: M[K]; } & {
465
+ __typeError: "negation/negationDescription can only be used on boolean fields";
466
+ };
467
+ type AliasFieldOf<M> = M extends {
468
+ alias: infer A;
469
+ } ? A : never;
470
+ type HiddenAliasFieldOf<M> = M extends {
471
+ hiddenAlias: infer H;
472
+ } ? H : never;
296
473
  /**
297
- * Context provided to global setup function (runMain/runCommand level)
474
+ * Check whether a Zod output type is a (possibly optional) boolean.
475
+ * Strips `undefined` to allow `z.boolean().optional()`. Requires both
476
+ * `boolean extends NonNullable<T>` (so `z.literal(true)` is rejected — the full
477
+ * `boolean` domain is needed) and `NonNullable<T> extends boolean` (so unions
478
+ * such as `z.union([z.boolean(), z.string()])` are rejected at the type level
479
+ * to match the runtime check).
298
480
  */
299
- interface GlobalSetupContext {}
481
+ type IsBooleanField<T> = boolean extends NonNullable<T> ? ([NonNullable<T>] extends [boolean] ? true : false) : false;
300
482
  /**
301
- * Context provided to global cleanup function (runMain/runCommand level)
483
+ * Detect whether `M` has `K` set to a non-undefined value.
484
+ *
485
+ * When `M` is inferred from a literal such as `{ negation: "off" }`,
486
+ * `M["negation"]` is `"off"` (without `undefined`), so this returns `true`.
487
+ * When `M` is the wider `ArgMeta` type, `M["negation"]` is
488
+ * `string | boolean | undefined`, so this returns `false` and avoids
489
+ * false-positive type errors on broadly-typed meta values.
302
490
  */
303
- interface GlobalCleanupContext {
304
- /** Error if command execution failed */
305
- error?: Error | undefined;
306
- }
491
+ type HasExplicit<M, K extends string> = K extends keyof M ? undefined extends M[K] ? false : true : false;
307
492
  /**
308
- * Base command interface (shared properties)
309
- * @template TArgsSchema - The args schema type (from the CLI's schema library)
310
- * @template TArgs - The inferred args type from the schema
493
+ * Reject `negation` / `negationDescription` on non-boolean fields.
494
+ * Uses {@link HasExplicit} so the error only fires when the user explicitly
495
+ * sets the field on a narrowly-inferred meta literal.
311
496
  */
312
- interface CommandBase<TArgsSchema extends ArgsSchema | undefined = undefined, TArgs = unknown> {
313
- /** Command name (required) */
314
- name: string;
315
- /** Command description */
316
- description?: string | undefined;
317
- /** Alternative names for this command (used as subcommand aliases) */
318
- aliases?: string[] | undefined;
319
- /** Argument schema (preserves the original schema type) */
320
- args: TArgsSchema;
321
- /** Subcommands */
322
- subCommands?: SubCommandsRecord | undefined;
323
- /** Setup hook */
324
- setup?: ((context: SetupContext<TArgs>) => void | Promise<void>) | undefined;
325
- /** Cleanup hook */
326
- cleanup?: ((context: CleanupContext<TArgs>) => void | Promise<void>) | undefined;
327
- /** Additional notes */
328
- notes?: string | undefined;
329
- /** Example usages for this command */
330
- examples?: Example[] | undefined;
331
- /**
332
- * @internal
333
- * Hook invoked once at the top of `runMain`, before any parsing. Used
334
- * by `withCompletionCommand` to fire its detached background-refresh
335
- * spawn. Best-effort; never throws.
336
- */
337
- runMainHook?: ((argv: readonly string[]) => void) | undefined;
338
- }
497
+ type ValidateNegation<M, TValue> = HasExplicit<M, "negation"> extends true ? IsBooleanField<TValue> extends true ? M : NegationTypeError<M> : HasExplicit<M, "negationDescription"> extends true ? IsBooleanField<TValue> extends true ? M : NegationTypeError<M> : M;
339
498
  /**
340
- * A command with a run function
341
- * @template TArgsSchema - The args schema type (from the CLI's schema library)
342
- * @template TArgs - The inferred args type from the schema
343
- * @template TResult - The return type of the run function
499
+ * Type helper to validate ArgMeta.
500
+ * Forces a type error when a reserved alias ("h" / "H") is used without
501
+ * `overrideBuiltinAlias: true`, whether the alias is provided as a string
502
+ * or as part of an array, and whether it appears in `alias` or `hiddenAlias`.
503
+ * Also rejects `negation` / `negationDescription` on non-boolean fields.
344
504
  */
345
- interface RunnableCommand<TArgsSchema extends ArgsSchema | undefined = undefined, TArgs = unknown, TResult = unknown> extends CommandBase<TArgsSchema, TArgs> {
346
- /** Main run function */
347
- run: (args: TArgs) => TResult;
348
- }
505
+ type ValidateArgMeta<M, TValue = unknown> = M extends {
506
+ overrideBuiltinAlias: true;
507
+ } ? ValidateNegation<M, TValue> : ContainsReservedAlias<AliasFieldOf<M>> extends true ? ReservedAliasTypeError<M> : ContainsReservedAlias<HiddenAliasFieldOf<M>> extends true ? ReservedAliasTypeError<M> : ValidateNegation<M, TValue>;
349
508
  /**
350
- * A command without a run function (e.g., subcommand-only parent)
351
- * @template TArgsSchema - The args schema type (from the CLI's schema library)
352
- * @template TArgs - The inferred args type from the schema
509
+ * The overloaded `arg()` signature, parameterized by the schema constraint.
510
+ * Core's `arg` accepts any Standard Schema; adapter packages re-pin the same
511
+ * runtime function to their library's schema type (e.g. `ArgFn<z.ZodType>`
512
+ * in `@politty/zod`) so a schema from the wrong library is rejected at the
513
+ * type level.
353
514
  */
354
- interface NonRunnableCommand<TArgsSchema extends ArgsSchema | undefined = undefined, TArgs = unknown> extends CommandBase<TArgsSchema, TArgs> {
355
- /** No run function */
356
- run?: undefined;
515
+ interface ArgFn<TSchemaBase extends SchemaLike = SchemaLike> {
516
+ <T extends TSchemaBase>(schema: T): T;
517
+ <T extends TSchemaBase, M extends ArgMeta<InferSchemaOutput<T>>>(schema: T, meta: ValidateArgMeta<M, InferSchemaOutput<T>>): T;
357
518
  }
519
+ //#endregion
520
+ //#region ../core/src/adapter/field-meta.d.ts
358
521
  /**
359
- * A defined command (union of runnable and non-runnable)
522
+ * Resolved metadata for an argument field
360
523
  */
361
- type Command<TArgsSchema extends ArgsSchema | undefined = undefined, TArgs = unknown, TResult = unknown> = RunnableCommand<TArgsSchema, TArgs, TResult> | NonRunnableCommand<TArgsSchema, TArgs>;
524
+ interface ResolvedFieldMeta {
525
+ /** Field name (camelCase, as defined in schema) */
526
+ name: string;
527
+ /** CLI option name (kebab-case, for command line usage) */
528
+ cliName: string;
529
+ /**
530
+ * Aliases for this option, normalized to an array.
531
+ * 1-char entries are short aliases (`-v`); multi-char entries are long
532
+ * aliases (`--to-be`).
533
+ */
534
+ alias?: string[] | undefined;
535
+ /**
536
+ * Aliases that are accepted at parse time but hidden from help,
537
+ * generated docs, and shell completion.
538
+ */
539
+ hiddenAlias?: string[] | undefined;
540
+ /** Argument description */
541
+ description?: string | undefined;
542
+ /** Whether this is a positional argument */
543
+ positional: boolean;
544
+ /** Placeholder for help display */
545
+ placeholder?: string | undefined;
546
+ /**
547
+ * Environment variable name(s) to read value from.
548
+ * If an array, earlier entries take priority.
549
+ */
550
+ env?: string | string[] | undefined;
551
+ /** Whether this argument is required */
552
+ required: boolean;
553
+ /** Default value if any */
554
+ defaultValue?: unknown;
555
+ /** Detected type from schema */
556
+ type: "string" | "number" | "boolean" | "array" | "unknown";
557
+ /**
558
+ * Original field schema, carried through opaquely for downstream
559
+ * consumers. Its concrete type belongs to the adapter's schema library
560
+ * (zod, valibot, or an internal descriptor); core never calls into it.
561
+ */
562
+ schema: unknown;
563
+ /** True if this overrides built-in aliases (-h, -H) */
564
+ overrideBuiltinAlias?: true;
565
+ /** Enum values if detected from schema (z.enum) */
566
+ enumValues?: string[] | undefined;
567
+ /** Completion metadata from arg() */
568
+ completion?: CompletionMeta | undefined;
569
+ /** Prompt metadata from arg() for interactive input */
570
+ prompt?: PromptMeta | undefined;
571
+ /**
572
+ * Negation configuration for this boolean field.
573
+ *
574
+ * - String (e.g. `"disable-cache"`): the default `--no-<cliName>` form is
575
+ * suppressed and only `--<negation>` (plus its camelCase variant) is
576
+ * accepted as the negation flag.
577
+ * - `true`: the default `--no-<cliName>` form is accepted **and** shown in
578
+ * help, generated docs, and shell completions.
579
+ * - `false`: neither the default `--no-<cliName>` nor any custom name is
580
+ * accepted; the field only responds to the positive flag.
581
+ * - `undefined`: no negation form is accepted or shown.
582
+ *
583
+ * Only applies to boolean fields; populated as `undefined` otherwise.
584
+ */
585
+ negation?: string | boolean | undefined;
586
+ /**
587
+ * Derived display name (no `--` prefix) for the negation flag in help,
588
+ * generated docs, and shell completions. `undefined` means the negation
589
+ * is hidden from those surfaces. Computed from `negation` + `cliName`.
590
+ */
591
+ negationDisplay?: string | undefined;
592
+ /** Description shown for the negation option in help/docs. */
593
+ negationDescription?: string | undefined;
594
+ /** Side-effect callback from arg() metadata */
595
+ effect?: ((value: unknown, context: EffectContext) => void | PromiseLike<void>) | undefined;
596
+ }
362
597
  /**
363
- * Type alias for any args type.
364
- * Note: `any` is required here due to TypeScript's function parameter contravariance.
365
- * Using `unknown` would make it impossible to assign concrete command types to AnyCommand.
366
- * @internal
598
+ * Extracted fields from a schema
367
599
  */
368
- type AnyArgs = any;
600
+ interface ExtractedFields {
601
+ /** All field definitions */
602
+ fields: ResolvedFieldMeta[];
603
+ /** Original schema for validation */
604
+ schema: ArgsSchema;
605
+ /** Schema type */
606
+ schemaType: "object" | "discriminatedUnion" | "union" | "xor" | "intersection";
607
+ /** Discriminator key (for discriminatedUnion) */
608
+ discriminator?: string;
609
+ /** Variants (for discriminatedUnion) */
610
+ variants?: Array<{
611
+ discriminatorValue: string;
612
+ fields: ResolvedFieldMeta[];
613
+ description?: string;
614
+ }>;
615
+ /** Options (for union) */
616
+ unionOptions?: ExtractedFields[];
617
+ /** Schema description */
618
+ description?: string;
619
+ /**
620
+ * Unknown keys handling mode
621
+ * - "strict": Unknown keys cause validation errors (z.strictObject or z.object().strict())
622
+ * - "strip": Unknown keys trigger warnings (default, z.object())
623
+ * - "passthrough": Unknown keys are silently ignored (z.looseObject or z.object().passthrough())
624
+ */
625
+ unknownKeysMode: UnknownKeysMode;
626
+ }
369
627
  /**
370
- * Type alias for any result type.
371
- * @internal
628
+ * Unknown keys handling mode for object schemas
629
+ * - "strict": Unknown keys cause validation errors
630
+ * - "strip": Unknown keys are silently ignored (default)
631
+ * - "passthrough": Unknown keys are passed through
372
632
  */
373
- type AnyResult = any;
633
+ type UnknownKeysMode = "strict" | "strip" | "passthrough";
374
634
  /**
375
- * Command type that accepts any args/result types
376
- * Used in internal functions that don't need specific type information
635
+ * Convert camelCase to kebab-case
636
+ * @example toKebabCase("dryRun") => "dry-run"
637
+ * @example toKebabCase("outputDir") => "output-dir"
638
+ * @example toKebabCase("XMLParser") => "xml-parser"
377
639
  */
378
- type AnyCommand = Command<ArgsSchema | undefined, AnyArgs, AnyResult>;
640
+ declare function toKebabCase(str: string): string;
379
641
  /**
380
- * Subcommand value type (either a command or a lazy-loaded command)
642
+ * Convert hyphen-separated sequences to camelCase.
643
+ *
644
+ * Replaces `-x` (hyphen followed by a lowercase letter) with the uppercase
645
+ * variant. Non-hyphenated input (e.g., already camelCase) is returned as-is.
646
+ *
647
+ * @param str - A string that may contain hyphens
648
+ * @example toCamelCase("dry-run") => "dryRun"
649
+ * @example toCamelCase("output-dir") => "outputDir"
650
+ * @example toCamelCase("dryRun") => "dryRun"
381
651
  */
382
- type SubCommandValue = AnyCommand | (() => Promise<AnyCommand>) | LazyCommand;
652
+ declare function toCamelCase(str: string): string;
653
+ //#endregion
654
+ //#region ../core/src/lazy.d.ts
383
655
  /**
384
- * Record of subcommands indexed by name
656
+ * A lazily-loaded command that carries synchronous metadata for
657
+ * static analysis (completion, help) while deferring full module
658
+ * loading to execution time.
385
659
  */
386
- type SubCommandsRecord = Record<string, SubCommandValue>;
660
+ interface LazyCommand<T extends AnyCommand = AnyCommand> {
661
+ readonly __politty_lazy__: true;
662
+ readonly meta: T;
663
+ readonly load: () => Promise<AnyCommand>;
664
+ }
387
665
  /**
388
- * Async callback to resolve missing argument values interactively.
389
- * Called after env fallback, before schema validation.
390
- * Provided by adapter subpath modules (e.g. `politty/prompt/clack`).
666
+ * Type guard: check if a value is a LazyCommand
391
667
  */
392
- type PromptResolver = (rawArgs: Record<string, unknown>, extracted: ExtractedFields) => Promise<Record<string, unknown>>;
668
+ declare function isLazyCommand(value: unknown): value is LazyCommand;
393
669
  /**
394
- * Options for runMain (CLI entry point)
395
- */
396
- interface MainOptions {
397
- /** Command version */
398
- version?: string;
399
- /** Enable debug mode (show stack traces on errors) */
400
- debug?: boolean;
401
- /** Capture console output during execution (default: false) */
402
- captureLogs?: boolean;
403
- /** Skip command definition validation (useful in production where tests already verified) */
404
- skipValidation?: boolean;
405
- /** Custom logger for output (default: console) */
406
- logger?: Logger;
407
- /** Global args schema (shared across all subcommands) */
408
- globalArgs?: ArgsSchema;
409
- /** Global setup hook (runs before command execution) */
410
- setup?: ((context: GlobalSetupContext) => void | Promise<void>) | undefined;
411
- /** Global cleanup hook (runs after command execution, always executes even on error) */
412
- cleanup?: ((context: GlobalCleanupContext) => void | Promise<void>) | undefined;
413
- /** Whether to display errors to stderr before process.exit (default: true) */
414
- displayErrors?: boolean;
415
- /** Prompt resolver for interactive missing-arg prompts (e.g. from `politty/prompt/clack`). */
416
- prompt?: PromptResolver | undefined;
417
- /**
418
- * Fallback hook for CLI plugin dispatch, invoked when a positional is not a
419
- * known subcommand at any level whose command exposes subcommands (e.g. exec
420
- * an external `<cli>-<path...>-<name>` binary).
421
- *
422
- * Return a number to treat it as handled and exit with that code; return
423
- * `undefined` (or omit) to fall back to the default unknown-subcommand/help
424
- * behavior. Not invoked for internal `__*` subcommands.
425
- */
426
- onUnknownSubcommand?: UnknownSubcommandHandler | undefined;
427
- /**
428
- * Node.js on-disk compile cache (V8 code cache) control. `runMain` enables
429
- * it before executing the command so dynamically imported modules (e.g.
430
- * `lazy()` subcommands) skip recompilation on warm starts (Node >= 22.8.0;
431
- * no-op otherwise).
432
- * - omitted / `true`: derive the directory from the command name
433
- * (`${XDG_CACHE_HOME:-$HOME/.cache}/<sanitized name>/node-compile-cache`,
434
- * shared with shell-completion workers; the name is reduced to a single
435
- * safe path segment, e.g. `@scope/cli` → `scope-cli`)
436
- * - `string`: use this cache directory
437
- * - `false`: do not enable
438
- *
439
- * The `NODE_COMPILE_CACHE` environment variable always takes precedence.
440
- * Note: the entry module's static import graph is compiled before `runMain`
441
- * runs and cannot be cached here — see the `compile-cache` subpath for the
442
- * bin-shim pattern that covers it.
443
- */
444
- compileCache?: boolean | string;
445
- }
670
+ * Create a lazily-loaded subcommand with synchronous metadata.
671
+ *
672
+ * The `meta` command provides names, descriptions, and args schema
673
+ * for static analysis (completion scripts, help text) without loading
674
+ * the full command module.
675
+ *
676
+ * The `load` function is called only at execution time.
677
+ *
678
+ * @example
679
+ * ```ts
680
+ * import { lazy, defineCommand } from "politty";
681
+ *
682
+ * const cli = defineCommand({
683
+ * name: "mycli",
684
+ * subCommands: {
685
+ * deploy: lazy(
686
+ * defineCommand({
687
+ * name: "deploy",
688
+ * description: "Deploy the application",
689
+ * args: z.object({ env: arg(z.string()) }),
690
+ * }),
691
+ * () => import("./deploy.js").then((m) => m.deployCommand),
692
+ * ),
693
+ * },
694
+ * });
695
+ * ```
696
+ */
697
+ declare function lazy<T extends AnyCommand>(meta: T, load: () => Promise<AnyCommand>): LazyCommand<T>;
698
+ //#endregion
699
+ //#region ../core/src/types.d.ts
446
700
  /**
447
- * Handler for an unrecognized subcommand. See {@link MainOptions.onUnknownSubcommand}.
701
+ * Global args interface for declaration merging (Pattern 3).
702
+ * Users can extend this interface to add global options to all commands:
703
+ *
704
+ * ```ts
705
+ * declare module "politty" {
706
+ * interface GlobalArgs { verbose: boolean; config?: string; }
707
+ * }
708
+ * ```
448
709
  */
449
- type UnknownSubcommandHandler = (context: {
450
- /**
451
- * Known subcommand names traversed before the unknown name (excludes the
452
- * root command name). Empty at the root level.
453
- */
454
- commandPath: readonly string[];
455
- /** The unrecognized subcommand name (first unmatched positional). */
456
- name: string;
457
- /** Args following the name, forwarded verbatim to the plugin. */
458
- args: readonly string[];
459
- /**
460
- * Option tokens the host consumed before the unknown name across every
461
- * traversed level (e.g. global flags typed before the plugin command),
462
- * excluding the traversed subcommand names themselves. Concatenate with
463
- * `args` to reconstruct the user's full flag set when forwarding to a
464
- * plugin: `[...precedingArgs, ...args]`.
465
- */
466
- precedingArgs: readonly string[];
467
- }) => number | undefined | Promise<number | undefined>;
710
+ interface GlobalArgs {}
468
711
  /**
469
- * Options for runCommand (programmatic/test usage)
712
+ * Detect empty interface (used for GlobalArgs declaration merging)
470
713
  */
471
- interface RunCommandOptions {
472
- /** Enable debug mode (show stack traces on errors) */
473
- debug?: boolean;
474
- /** Capture console output during execution (default: false) */
475
- captureLogs?: boolean;
476
- /** Skip command definition validation (useful in production where tests already verified) */
477
- skipValidation?: boolean;
478
- /** Custom logger for output (default: console) */
479
- logger?: Logger;
480
- /** Global args schema (shared across all subcommands) */
481
- globalArgs?: ArgsSchema;
482
- /** Global setup hook (runs before command execution) */
483
- setup?: ((context: GlobalSetupContext) => void | Promise<void>) | undefined;
484
- /** Global cleanup hook (runs after command execution, always executes even on error) */
485
- cleanup?: ((context: GlobalCleanupContext) => void | Promise<void>) | undefined;
486
- /** Prompt resolver for interactive missing-arg prompts (e.g. from `politty/prompt/clack`). */
487
- prompt?: PromptResolver | undefined;
488
- }
714
+ type IsEmpty<T> = keyof T extends never ? true : false;
489
715
  /**
490
- * Log level type
716
+ * Where a resolved arg value came from:
717
+ * - `"cli"`: an explicit CLI token (flag or positional)
718
+ * - `"env"`: `field.env` fallback (no CLI token was provided)
719
+ * - `"default"`: neither of the above (e.g. a schema default, or a value
720
+ * resolved by a `prompt` handler)
491
721
  */
492
- type LogLevel = "log" | "info" | "debug" | "warn" | "error";
722
+ type ArgSource = "cli" | "env" | "default";
493
723
  /**
494
- * Output stream type
724
+ * Identifies the CLI name a command was invoked with in the current run.
725
+ * - `name`: the literal token typed on the CLI to reach this command
726
+ * (a canonical subcommand name or one of its `aliases`).
727
+ * - `aliasFor`: set only when `name` is an alias, to the canonical
728
+ * subcommand name it resolves to; `undefined` when invoked by its
729
+ * canonical name (or run directly, with no subcommand routing involved).
495
730
  */
496
- type LogStream = "stdout" | "stderr";
731
+ interface RunInvocation {
732
+ /** The name or alias actually typed on the CLI to reach this command */
733
+ name: string;
734
+ /** Canonical name `name` is an alias for; undefined when not an alias */
735
+ aliasFor?: string | undefined;
736
+ }
497
737
  /**
498
- * A single log entry collected during command execution
738
+ * Example definition for a command
499
739
  */
500
- interface LogEntry {
501
- /** Log message */
502
- message: string;
503
- /** Timestamp when the log was recorded */
504
- timestamp: Date;
505
- /** Log level */
506
- level: LogLevel;
507
- /** Output stream (stdout or stderr) */
508
- stream: LogStream;
740
+ interface Example {
741
+ /** Command arguments to execute (e.g., "World" or "--loud Alice") */
742
+ cmd: string;
743
+ /** Description of the example */
744
+ desc: string;
745
+ /** Expected output (optional, for documentation) */
746
+ output?: string;
509
747
  }
510
748
  /**
511
- * Collected logs during command execution
749
+ * Logger interface for CLI output
750
+ * Can be overridden by passing a custom logger to runMain or runCommand
512
751
  */
513
- interface CollectedLogs {
514
- /** All log entries in order */
515
- entries: LogEntry[];
752
+ interface Logger {
753
+ /** Log informational message to stdout */
754
+ log(message: string): void;
755
+ /** Log error message to stderr */
756
+ error(message: string): void;
757
+ /** Log warning message to stderr */
758
+ warn?(message: string): void;
516
759
  }
517
760
  /**
518
- * Successful command execution result
761
+ * Supported schema types for args: any Standard Schema (zod, valibot, ...)
762
+ * whose output is an object. Adapter packages narrow this back to their
763
+ * library's own schema type in their public exports (e.g. `@politty/zod`
764
+ * exports `ArgsSchema = z.ZodType<Record<string, any>>`).
519
765
  */
520
- interface RunResultSuccess<T = unknown> {
521
- /** Indicates successful execution */
522
- success: true;
523
- /** Command return value */
524
- result: T | undefined;
525
- /** Error that occurred during execution */
526
- error?: never;
527
- /** Exit code (always 0 for success) */
528
- exitCode: 0;
529
- /** Collected logs during execution */
530
- logs: CollectedLogs;
766
+ type ArgsSchema = SchemaLike<Record<string, any>>;
767
+ /**
768
+ * Context provided to setup function
769
+ */
770
+ interface SetupContext<TArgs = unknown> {
771
+ /** Parsed and validated arguments */
772
+ args: TArgs;
531
773
  }
532
774
  /**
533
- * Failed command execution result
775
+ * Context provided to cleanup function
534
776
  */
535
- interface RunResultFailure {
536
- /** Indicates failed execution */
537
- success: false;
538
- /** Command return value */
539
- result?: never;
540
- /** Error that occurred during execution */
541
- error: Error;
542
- /** Exit code (non-zero for failure) */
543
- exitCode: number;
544
- /** Collected logs during execution */
545
- logs: CollectedLogs;
777
+ interface CleanupContext<TArgs = unknown> {
778
+ /** Parsed and validated arguments */
779
+ args: TArgs;
780
+ /** Error if command execution failed */
781
+ error?: Error | undefined;
546
782
  }
547
783
  /**
548
- * Result of command execution (discriminated union)
784
+ * Context provided to global setup function (runMain/runCommand level)
549
785
  */
550
- type RunResult<T = unknown> = RunResultSuccess<T> | RunResultFailure;
551
- //#endregion
552
- //#region ../core/src/core/dynamic-completion-types.d.ts
786
+ interface GlobalSetupContext {}
553
787
  /**
554
- * Types for in-process dynamic value completion.
555
- *
556
- * A `resolve` callback registered on `arg(...)` receives parsed context
557
- * (other arg values typed so far, previous values supplied to the same
558
- * option, the current word being completed, target shell) and returns
559
- * candidates. The callback runs inside the `__complete` command. Dispatcher
560
- * shell scripts call `__complete` for every completion request; static shell
561
- * scripts delegate to it for any spec that uses `resolve`.
562
- *
563
- * Defined under `core/` (not `completion/`) so `arg-registry.ts` can
564
- * reference the resolver type without crossing the lint-enforced
565
- * `completion → core` boundary.
788
+ * Context provided to global cleanup function (runMain/runCommand level)
566
789
  */
567
- /** Bitmask combining `CompletionDirective` values. */
568
- type CompletionDirectiveMask = number;
569
- interface DynamicCompletionContext {
570
- /** Word being completed. `--field=` inline prefix is stripped before this is set. */
571
- currentWord: string;
572
- /** Target shell formatting requested by the caller. */
573
- shell: "bash" | "zsh" | "fish";
574
- /**
575
- * Best-effort parsed values of OTHER args on the same command, keyed by
576
- * camelCase name. Includes positionals and other options. Zod validation
577
- * is NOT applied; values are raw strings (or arrays of raw strings for
578
- * array-typed options/variadic positionals).
579
- */
580
- parsedArgs: Readonly<Record<string, unknown>>;
581
- /**
582
- * Values already supplied for the SAME option/positional being completed.
583
- * Useful for de-duplicating repeated array options.
584
- */
585
- previousValues: readonly string[];
586
- /**
587
- * Subcommand path from root (e.g. ["api"]). Reflects what the user
588
- * actually typed — aliases are NOT resolved to their canonical names, so
589
- * resolvers that branch on the path should accept every alias they care
590
- * about.
591
- */
592
- subcommandPath: readonly string[];
593
- }
594
- interface DynamicCompletionCandidate {
595
- value: string;
596
- description?: string;
597
- }
598
- interface DynamicCompletionResult {
599
- /** Candidates to surface. Strings or `{value, description}` objects. */
600
- candidates: Array<string | DynamicCompletionCandidate>;
601
- /**
602
- * Optional directive override. When omitted, defaults to
603
- * `FilterPrefix | NoFileCompletion` (matches `choices` behaviour).
604
- */
605
- directive?: CompletionDirectiveMask;
790
+ interface GlobalCleanupContext {
791
+ /** Error if command execution failed */
792
+ error?: Error | undefined;
606
793
  }
607
- type DynamicCompletionResolver = (ctx: DynamicCompletionContext) => DynamicCompletionResult | Promise<DynamicCompletionResult>;
608
- //#endregion
609
- //#region ../core/src/core/expand-completion-types.d.ts
610
794
  /**
611
- * Types for "expand" completion — candidates that depend on sibling arg
612
- * values.
613
- *
614
- * The user provides `dependsOn` (sibling arg names that must have static
615
- * `choices` or an enum schema) and `enumerate(deps)`. Dispatcher scripts call
616
- * `enumerate` inside `__complete` for the dependency values already typed on
617
- * the command line. Static scripts walk the cartesian product of the
618
- * dependsOn values, call `enumerate` for each combination, and emit a shell
619
- * lookup table.
620
- *
621
- * Defined under `core/` (not `completion/`) so `arg-registry.ts` can
622
- * reference these types without crossing the lint-enforced
623
- * `completion → core` boundary.
795
+ * Base command interface (shared properties)
796
+ * @template TArgsSchema - The args schema type (from the CLI's schema library)
797
+ * @template TArgs - The inferred args type from the schema
624
798
  */
625
- /** Candidate returned by an `enumerate` callback. */
626
- interface ExpandCandidate {
627
- value: string;
628
- description?: string;
629
- }
630
- /** Resolved candidate stored on a {@link ValueCompletion} after enumeration. */
631
- interface ResolvedExpandCandidate {
632
- value: string;
633
- description?: string;
799
+ interface CommandBase<TArgsSchema extends ArgsSchema | undefined = undefined, TArgs = unknown> {
800
+ /** Command name (required) */
801
+ name: string;
802
+ /** Command description */
803
+ description?: string | undefined;
804
+ /** Alternative names for this command (used as subcommand aliases) */
805
+ aliases?: string[] | undefined;
806
+ /** Argument schema (preserves the original schema type) */
807
+ args: TArgsSchema;
808
+ /** Subcommands */
809
+ subCommands?: SubCommandsRecord | undefined;
810
+ /** Setup hook */
811
+ setup?: ((context: SetupContext<TArgs>) => void | Promise<void>) | undefined;
812
+ /** Cleanup hook */
813
+ cleanup?: ((context: CleanupContext<TArgs>) => void | Promise<void>) | undefined;
814
+ /** Additional notes */
815
+ notes?: string | undefined;
816
+ /** Example usages for this command */
817
+ examples?: Example[] | undefined;
818
+ /**
819
+ * @internal
820
+ * Hook invoked once at the top of `runMain`, before any parsing. Used
821
+ * by `withCompletionCommand` to fire its detached background-refresh
822
+ * spawn. Best-effort; never throws.
823
+ */
824
+ runMainHook?: ((argv: readonly string[]) => void) | undefined;
634
825
  }
635
826
  /**
636
- * User-facing spec attached to `completion.custom.expand`.
637
- *
638
- * `dependsOn` lists sibling args (camelCase names) whose values determine
639
- * which candidates apply. Each named arg must have a static set of values —
640
- * either an explicit `completion.custom.choices` or an enum schema. The
641
- * order of `dependsOn` is the order in which `deps` keys are exposed to
642
- * `enumerate`.
643
- *
644
- * In dispatcher mode, `enumerate` runs during `__complete` for the dependency
645
- * values already typed by the user. In static mode, it runs once per
646
- * cartesian-product combination at script-generation time (e.g. when the user
647
- * runs `<program> completion zsh --static`). It must be a pure function of
648
- * `deps`.
827
+ * A command with a run function
828
+ * @template TArgsSchema - The args schema type (from the CLI's schema library)
829
+ * @template TArgs - The inferred args type from the schema
830
+ * @template TResult - The return type of the run function
649
831
  */
650
- interface ExpandCompletion {
651
- dependsOn: readonly string[];
652
- enumerate: (deps: Readonly<Record<string, string>>) => ReadonlyArray<string | ExpandCandidate>;
832
+ interface RunnableCommand<TArgsSchema extends ArgsSchema | undefined = undefined, TArgs = unknown, TResult = unknown> extends CommandBase<TArgsSchema, TArgs> {
833
+ /** Main run function */
834
+ run: (args: TArgs) => TResult;
653
835
  }
654
- //#endregion
655
- //#region ../core/src/core/arg-registry.d.ts
656
- /**
657
- * Built-in completion types
658
- */
659
- type CompletionType = "file" | "directory" | "none";
660
836
  /**
661
- * Custom completion specification.
662
- *
663
- * `choices`, `shellCommand`, `resolve`, and `expand` are mutually exclusive —
664
- * specifying more than one throws when the field metadata is resolved.
837
+ * A command without a run function (e.g., subcommand-only parent)
838
+ * @template TArgsSchema - The args schema type (from the CLI's schema library)
839
+ * @template TArgs - The inferred args type from the schema
665
840
  */
666
- interface CustomCompletion {
667
- /** Static list of choices for completion */
668
- choices?: string[];
669
- /** Shell command to execute for dynamic completion */
670
- shellCommand?: string;
671
- /**
672
- * In-process JS callback for dynamic completion. Receives parsed context
673
- * (other arg values typed so far, previously supplied values for this same
674
- * option) and returns candidates. Dispatcher scripts call
675
- * `<program> __complete` for every completion request; static scripts
676
- * delegate to it whenever this is set.
677
- */
678
- resolve?: DynamicCompletionResolver;
679
- /**
680
- * Completion whose candidates depend on sibling arg values. Dispatcher
681
- * scripts call `enumerate` inside `__complete` for the dependency values
682
- * already typed on the command line. Static scripts pre-enumerate every
683
- * combination of `dependsOn` values at script-generation time and dispatch
684
- * via a shell lookup table.
685
- */
686
- expand?: ExpandCompletion;
841
+ interface NonRunnableCommand<TArgsSchema extends ArgsSchema | undefined = undefined, TArgs = unknown> extends CommandBase<TArgsSchema, TArgs> {
842
+ /** No run function */
843
+ run?: undefined;
687
844
  }
688
845
  /**
689
- * Completion metadata for an argument
690
- *
691
- * @example
692
- * ```ts
693
- * // File completion with extension filter
694
- * input: arg(z.string(), {
695
- * completion: { type: "file", extensions: ["json", "yaml"] }
696
- * })
697
- *
698
- * // Directory completion
699
- * outputDir: arg(z.string(), {
700
- * completion: { type: "directory" }
701
- * })
702
- *
703
- * // Custom static choices
704
- * logLevel: arg(z.string(), {
705
- * completion: { custom: { choices: ["debug", "info", "warn", "error"] } }
706
- * })
707
- *
708
- * // Dynamic completion from shell command
709
- * branch: arg(z.string(), {
710
- * completion: { custom: { shellCommand: "git branch --format='%(refname:short)'" } }
711
- * })
712
- *
713
- * // File completion with glob pattern matcher
714
- * envFile: arg(z.string(), {
715
- * completion: { type: "file", matcher: [".env.*"] }
716
- * })
717
- * ```
846
+ * A defined command (union of runnable and non-runnable)
718
847
  */
719
- type CompletionMeta = {
720
- /** Built-in completion type */
721
- type?: CompletionType;
722
- /** Custom completion (takes precedence over type if both specified) */
723
- custom?: CustomCompletion;
724
- } & ({
725
- /** File extension filter (only applies when type is "file") */ extensions?: string[];
726
- matcher?: never;
727
- } | {
728
- /** Glob patterns for file matching (only applies when type is "file") */ matcher?: string[];
729
- extensions?: never;
730
- });
848
+ type Command<TArgsSchema extends ArgsSchema | undefined = undefined, TArgs = unknown, TResult = unknown> = RunnableCommand<TArgsSchema, TArgs, TResult> | NonRunnableCommand<TArgsSchema, TArgs>;
731
849
  /**
732
- * Prompt input type for interactive prompts
733
- *
734
- * - "text": free-form text input (default for string schemas)
735
- * - "password": masked text input
736
- * - "confirm": yes/no prompt (default for boolean schemas)
737
- * - "select": single selection from choices (default for enum schemas)
738
- * - "file": file path input (inherited from completion type)
739
- * - "directory": directory path input (inherited from completion type)
850
+ * Type alias for any args type.
851
+ * Note: `any` is required here due to TypeScript's function parameter contravariance.
852
+ * Using `unknown` would make it impossible to assign concrete command types to AnyCommand.
853
+ * @internal
740
854
  */
741
- type PromptType = "text" | "password" | "confirm" | "select" | "file" | "directory";
855
+ type AnyArgs = any;
742
856
  /**
743
- * Prompt metadata for interactive input when a value is missing.
744
- * Used by the `politty/prompt` module to request user input for unresolved arguments.
745
- *
746
- * @example
747
- * ```ts
748
- * // Custom prompt message
749
- * name: arg(z.string(), {
750
- * prompt: { message: "What is your name?" }
751
- * })
752
- *
753
- * // Password input (masked)
754
- * token: arg(z.string(), {
755
- * prompt: { type: "password", message: "Enter API token" }
756
- * })
757
- *
758
- * // Select with custom choices
759
- * region: arg(z.string(), {
760
- * prompt: { choices: ["us-east-1", "eu-west-1", "ap-northeast-1"] }
761
- * })
762
- * ```
857
+ * Type alias for any result type.
858
+ * @internal
763
859
  */
764
- interface PromptMeta {
765
- /** Prompt message shown to the user. Defaults to the field's description or name. */
766
- message?: string;
767
- /** Explicit prompt type. Overrides auto-detection from schema/completion. */
768
- type?: PromptType;
769
- /** Choices for select prompt. Overrides enum values from schema. */
770
- choices?: Array<string | {
771
- label: string;
772
- value: string;
773
- }>;
774
- /** Whether to enable prompting for this field (default: true when prompt is set) */
775
- enabled?: boolean;
776
- }
860
+ type AnyResult = any;
777
861
  /**
778
- * Context provided to effect callbacks.
779
- * When GlobalArgs is extended via declaration merging, `globalArgs` is typed accordingly.
862
+ * Command type that accepts any args/result types
863
+ * Used in internal functions that don't need specific type information
780
864
  */
781
- type EffectContext = {
782
- /** Field name (camelCase) */
783
- name: string;
784
- /** Validated args for this schema (global args for global effects, command args for command effects) */
785
- args: Readonly<Record<string, unknown>>;
786
- } & (IsEmpty<GlobalArgs> extends true ? {
787
- globalArgs?: Readonly<Record<string, unknown>>;
788
- } : {
789
- globalArgs?: Readonly<GlobalArgs>;
790
- });
865
+ type AnyCommand = Command<ArgsSchema | undefined, AnyArgs, AnyResult>;
791
866
  /**
792
- * Base metadata shared by all argument types
867
+ * Subcommand value type (either a command or a lazy-loaded command)
793
868
  */
794
- interface BaseArgMeta<TValue = unknown> {
795
- /** Argument description */
796
- description?: string;
797
- /** Treat as positional argument */
798
- positional?: boolean;
799
- /** Placeholder for help display */
800
- placeholder?: string;
801
- /**
802
- * Environment variable name(s) to read value from.
803
- * If an array is provided, earlier entries take priority.
804
- * CLI arguments always take precedence over environment variables.
805
- *
806
- * @example
807
- * ```ts
808
- * // Single env var
809
- * port: arg(z.coerce.number(), { env: "PORT" })
810
- *
811
- * // Multiple env vars (PORT takes priority over SERVER_PORT)
812
- * port: arg(z.coerce.number(), { env: ["PORT", "SERVER_PORT"] })
813
- * ```
814
- */
815
- env?: string | string[];
816
- /** Completion configuration for shell tab-completion */
817
- completion?: CompletionMeta;
818
- /**
819
- * Interactive prompt configuration for missing values.
820
- * When set, the `politty/prompt` module will prompt the user interactively
821
- * if this argument is not provided via CLI args or environment variables.
822
- *
823
- * @example
824
- * ```ts
825
- * name: arg(z.string(), {
826
- * description: "User name",
827
- * prompt: { message: "What is your name?" },
828
- * })
829
- * ```
830
- */
831
- prompt?: PromptMeta;
832
- /**
833
- * Control the boolean negation option.
834
- *
835
- * Boolean fields accept `--no-<cliName>` (and the camelCase `--no<Name>`
836
- * form) to set the value to `false` only when `negation: true` is set.
837
- * By default no negation form is accepted. This option lets you customize
838
- * or expose that behavior:
839
- *
840
- * - `string` — replaces the auto-generated `--no-*` form with a custom
841
- * name. The default `--no-*` is no longer recognized.
842
- * - `true` — enables the default `--no-<cliName>` form and advertises it
843
- * in help, generated docs, and shell completions.
844
- * - `false` — disables negation entirely; same as the default, but explicit.
845
- * Neither the default `--no-*` nor any custom name is accepted.
846
- *
847
- * String values follow the same naming conventions as `cliName`
848
- * (kebab-case is recommended). Only valid on boolean fields; setting
849
- * `negation` on a non-boolean field is a type error and raises a
850
- * runtime error during command parsing.
851
- *
852
- * @example
853
- * ```ts
854
- * // Custom negation name
855
- * cache: arg(z.boolean().default(true), {
856
- * description: "Enable caching",
857
- * negation: "disable-cache",
858
- * })
859
- * // Accepts: --cache (true), --disable-cache (false)
860
- * // No longer accepts: --no-cache
861
- *
862
- * // Enable default `--no-X` in parsing/help/docs/completion
863
- * verbose: arg(z.boolean().default(false), {
864
- * negation: true,
865
- * })
866
- * // Help shows `--verbose / --no-verbose`
867
- *
868
- * // Disable negation entirely
869
- * dryRun: arg(z.boolean().default(false), {
870
- * negation: false,
871
- * })
872
- * // Accepts: --dry-run (true)
873
- * // No longer accepts: --no-dry-run
874
- * ```
875
- */
876
- negation?: string | boolean;
869
+ type SubCommandValue = AnyCommand | (() => Promise<AnyCommand>) | LazyCommand;
870
+ /**
871
+ * Record of subcommands indexed by name
872
+ */
873
+ type SubCommandsRecord = Record<string, SubCommandValue>;
874
+ /**
875
+ * Async callback to resolve missing argument values interactively.
876
+ * Called after env fallback, before schema validation.
877
+ * Provided by adapter subpath modules (e.g. `politty/prompt/clack`).
878
+ */
879
+ type PromptResolver = (rawArgs: Record<string, unknown>, extracted: ExtractedFields) => Promise<Record<string, unknown>>;
880
+ /**
881
+ * Options for runMain (CLI entry point)
882
+ */
883
+ interface MainOptions {
884
+ /** Command version */
885
+ version?: string;
886
+ /** Enable debug mode (show stack traces on errors) */
887
+ debug?: boolean;
888
+ /** Capture console output during execution (default: false) */
889
+ captureLogs?: boolean;
890
+ /** Skip command definition validation (useful in production where tests already verified) */
891
+ skipValidation?: boolean;
892
+ /** Custom logger for output (default: console) */
893
+ logger?: Logger;
894
+ /** Global args schema (shared across all subcommands) */
895
+ globalArgs?: ArgsSchema;
896
+ /** Global setup hook (runs before command execution) */
897
+ setup?: ((context: GlobalSetupContext) => void | Promise<void>) | undefined;
898
+ /** Global cleanup hook (runs after command execution, always executes even on error) */
899
+ cleanup?: ((context: GlobalCleanupContext) => void | Promise<void>) | undefined;
900
+ /** Whether to display errors to stderr before process.exit (default: true) */
901
+ displayErrors?: boolean;
902
+ /** Prompt resolver for interactive missing-arg prompts (e.g. from `politty/prompt/clack`). */
903
+ prompt?: PromptResolver | undefined;
877
904
  /**
878
- * Description shown for the negation option in help and generated docs.
879
- * Only meaningful when `negation` is set to a custom name string or `true`.
880
- * Disallowed when `negation` is `false`.
905
+ * Fallback hook for CLI plugin dispatch, invoked when a positional is not a
906
+ * known subcommand at any level whose command exposes subcommands (e.g. exec
907
+ * an external `<cli>-<path...>-<name>` binary).
908
+ *
909
+ * Return a number to treat it as handled and exit with that code; return
910
+ * `undefined` (or omit) to fall back to the default unknown-subcommand/help
911
+ * behavior. Not invoked for internal `__*` subcommands.
881
912
  */
882
- negationDescription?: string;
913
+ onUnknownSubcommand?: UnknownSubcommandHandler | undefined;
883
914
  /**
884
- * Side-effect callback executed after argument parsing and validation.
885
- * Runs before the command lifecycle (setup/run/cleanup).
886
- * Use Zod .transform() for value transformation instead.
915
+ * Node.js on-disk compile cache (V8 code cache) control. `runMain` enables
916
+ * it before executing the command so dynamically imported modules (e.g.
917
+ * `lazy()` subcommands) skip recompilation on warm starts (Node >= 22.8.0;
918
+ * no-op otherwise).
919
+ * - omitted / `true`: derive the directory from the command name
920
+ * (`${XDG_CACHE_HOME:-$HOME/.cache}/<sanitized name>/node-compile-cache`,
921
+ * shared with shell-completion workers; the name is reduced to a single
922
+ * safe path segment, e.g. `@scope/cli` → `scope-cli`)
923
+ * - `string`: use this cache directory
924
+ * - `false`: do not enable
887
925
  *
888
- * @example
889
- * ```ts
890
- * verbose: arg(z.boolean().default(false), {
891
- * alias: "v",
892
- * effect: (value) => {
893
- * if (value) logger.setLevel("debug");
894
- * },
895
- * })
896
- * ```
926
+ * The `NODE_COMPILE_CACHE` environment variable always takes precedence.
927
+ * Note: the entry module's static import graph is compiled before `runMain`
928
+ * runs and cannot be cached here — see the `compile-cache` subpath for the
929
+ * bin-shim pattern that covers it.
897
930
  */
898
- effect?: (value: TValue, context: EffectContext) => void | PromiseLike<void>;
931
+ compileCache?: boolean | string;
899
932
  }
900
933
  /**
901
- * Metadata for regular arguments (non-builtin aliases)
902
- *
903
- * `alias` accepts either a single string or an array of strings.
904
- * Single-character entries become short options (e.g. `-v`); multi-character
905
- * entries become additional long options (e.g. `--to-be` for `--tobe`).
934
+ * Handler for an unrecognized subcommand. See {@link MainOptions.onUnknownSubcommand}.
906
935
  */
907
- interface RegularArgMeta<TValue = unknown> extends BaseArgMeta<TValue> {
936
+ type UnknownSubcommandHandler = (context: {
908
937
  /**
909
- * Alias name(s) for this option.
910
- * - 1-char string → short alias (`-v`)
911
- * - >1-char string → long alias (`--long-name`)
912
- * - array → multiple aliases of either kind
938
+ * Known subcommand names traversed before the unknown name (excludes the
939
+ * root command name). Empty at the root level.
913
940
  */
914
- alias?: string | string[] | readonly string[];
941
+ commandPath: readonly string[];
942
+ /** The unrecognized subcommand name (first unmatched positional). */
943
+ name: string;
944
+ /** Args following the name, forwarded verbatim to the plugin. */
945
+ args: readonly string[];
915
946
  /**
916
- * Alias name(s) that are accepted by the parser but hidden from help,
917
- * generated docs, and shell completion. Useful for legacy or deprecated
918
- * names that should still work without being advertised.
947
+ * Option tokens the host consumed before the unknown name across every
948
+ * traversed level (e.g. global flags typed before the plugin command),
949
+ * excluding the traversed subcommand names themselves. Concatenate with
950
+ * `args` to reconstruct the user's full flag set when forwarding to a
951
+ * plugin: `[...precedingArgs, ...args]`.
919
952
  */
920
- hiddenAlias?: string | string[] | readonly string[];
921
- }
953
+ precedingArgs: readonly string[];
954
+ }) => number | undefined | Promise<number | undefined>;
922
955
  /**
923
- * Metadata for overriding built-in aliases (-h, -H)
956
+ * Options for runCommand (programmatic/test usage)
924
957
  */
925
- interface BuiltinOverrideArgMeta<TValue = unknown> extends BaseArgMeta<TValue> {
926
- /** Built-in alias to override ('h' or 'H'), optionally combined with extra aliases */
927
- alias: "h" | "H" | Array<"h" | "H" | string> | ReadonlyArray<"h" | "H" | string>;
928
- /** Hidden aliases (accepted but not surfaced in help/docs/completion) */
929
- hiddenAlias?: string | string[] | readonly string[];
930
- /** Must be true to override built-in aliases */
931
- overrideBuiltinAlias: true;
958
+ interface RunCommandOptions {
959
+ /** Enable debug mode (show stack traces on errors) */
960
+ debug?: boolean;
961
+ /** Capture console output during execution (default: false) */
962
+ captureLogs?: boolean;
963
+ /** Skip command definition validation (useful in production where tests already verified) */
964
+ skipValidation?: boolean;
965
+ /** Custom logger for output (default: console) */
966
+ logger?: Logger;
967
+ /** Global args schema (shared across all subcommands) */
968
+ globalArgs?: ArgsSchema;
969
+ /** Global setup hook (runs before command execution) */
970
+ setup?: ((context: GlobalSetupContext) => void | Promise<void>) | undefined;
971
+ /** Global cleanup hook (runs after command execution, always executes even on error) */
972
+ cleanup?: ((context: GlobalCleanupContext) => void | Promise<void>) | undefined;
973
+ /** Prompt resolver for interactive missing-arg prompts (e.g. from `politty/prompt/clack`). */
974
+ prompt?: PromptResolver | undefined;
932
975
  }
933
976
  /**
934
- * Metadata options for argument definition
935
- */
936
- type ArgMeta<TValue = unknown> = RegularArgMeta<TValue> | BuiltinOverrideArgMeta<TValue>;
937
- /**
938
- * Register metadata for a schema
939
- *
940
- * @param schema - The schema to attach metadata to
941
- * @param meta - Argument metadata
942
- * @returns The same schema (for chaining)
943
- *
944
- * @example
945
- * ```ts
946
- * import { z } from "zod";
947
- * import { arg, defineCommand } from "politty";
948
- *
949
- * const cmd = defineCommand({
950
- * args: z.object({
951
- * name: arg(z.string(), { description: "User name", positional: true }),
952
- * verbose: arg(z.boolean().default(false), { alias: "v" }),
953
- * }),
954
- * run: (args) => {
955
- * console.log(args.name, args.verbose);
956
- * },
957
- * });
958
- * ```
977
+ * Log level type
959
978
  */
979
+ type LogLevel = "log" | "info" | "debug" | "warn" | "error";
960
980
  /**
961
- * Detect whether `A` contains a reserved alias ("h" or "H"), for either a
962
- * plain string or a tuple/array of strings. Uses `[A] extends [never]` to
963
- * prevent distribution returning `never` for missing fields.
981
+ * Output stream type
964
982
  */
965
- type ContainsReservedAlias<A> = [A] extends [never] ? false : A extends "h" | "H" ? true : A extends readonly (infer E)[] ? [Extract<E, "h" | "H">] extends [never] ? false : true : false;
966
- type ReservedAliasTypeError<M> = { [K in keyof M]: M[K]; } & {
967
- __typeError: "Alias 'h' or 'H' requires overrideBuiltinAlias: true";
968
- };
969
- type NegationTypeError<M> = { [K in keyof M]: M[K]; } & {
970
- __typeError: "negation/negationDescription can only be used on boolean fields";
971
- };
972
- type AliasFieldOf<M> = M extends {
973
- alias: infer A;
974
- } ? A : never;
975
- type HiddenAliasFieldOf<M> = M extends {
976
- hiddenAlias: infer H;
977
- } ? H : never;
983
+ type LogStream = "stdout" | "stderr";
978
984
  /**
979
- * Check whether a Zod output type is a (possibly optional) boolean.
980
- * Strips `undefined` to allow `z.boolean().optional()`. Requires both
981
- * `boolean extends NonNullable<T>` (so `z.literal(true)` is rejected — the full
982
- * `boolean` domain is needed) and `NonNullable<T> extends boolean` (so unions
983
- * such as `z.union([z.boolean(), z.string()])` are rejected at the type level
984
- * to match the runtime check).
985
+ * A single log entry collected during command execution
985
986
  */
986
- type IsBooleanField<T> = boolean extends NonNullable<T> ? ([NonNullable<T>] extends [boolean] ? true : false) : false;
987
+ interface LogEntry {
988
+ /** Log message */
989
+ message: string;
990
+ /** Timestamp when the log was recorded */
991
+ timestamp: Date;
992
+ /** Log level */
993
+ level: LogLevel;
994
+ /** Output stream (stdout or stderr) */
995
+ stream: LogStream;
996
+ }
987
997
  /**
988
- * Detect whether `M` has `K` set to a non-undefined value.
989
- *
990
- * When `M` is inferred from a literal such as `{ negation: "off" }`,
991
- * `M["negation"]` is `"off"` (without `undefined`), so this returns `true`.
992
- * When `M` is the wider `ArgMeta` type, `M["negation"]` is
993
- * `string | boolean | undefined`, so this returns `false` and avoids
994
- * false-positive type errors on broadly-typed meta values.
998
+ * Collected logs during command execution
995
999
  */
996
- type HasExplicit<M, K extends string> = K extends keyof M ? undefined extends M[K] ? false : true : false;
1000
+ interface CollectedLogs {
1001
+ /** All log entries in order */
1002
+ entries: LogEntry[];
1003
+ }
997
1004
  /**
998
- * Reject `negation` / `negationDescription` on non-boolean fields.
999
- * Uses {@link HasExplicit} so the error only fires when the user explicitly
1000
- * sets the field on a narrowly-inferred meta literal.
1005
+ * Successful command execution result
1001
1006
  */
1002
- type ValidateNegation<M, TValue> = HasExplicit<M, "negation"> extends true ? IsBooleanField<TValue> extends true ? M : NegationTypeError<M> : HasExplicit<M, "negationDescription"> extends true ? IsBooleanField<TValue> extends true ? M : NegationTypeError<M> : M;
1007
+ interface RunResultSuccess<T = unknown> {
1008
+ /** Indicates successful execution */
1009
+ success: true;
1010
+ /** Command return value */
1011
+ result: T | undefined;
1012
+ /** Error that occurred during execution */
1013
+ error?: never;
1014
+ /** Exit code (always 0 for success) */
1015
+ exitCode: 0;
1016
+ /** Collected logs during execution */
1017
+ logs: CollectedLogs;
1018
+ }
1003
1019
  /**
1004
- * Type helper to validate ArgMeta.
1005
- * Forces a type error when a reserved alias ("h" / "H") is used without
1006
- * `overrideBuiltinAlias: true`, whether the alias is provided as a string
1007
- * or as part of an array, and whether it appears in `alias` or `hiddenAlias`.
1008
- * Also rejects `negation` / `negationDescription` on non-boolean fields.
1020
+ * Failed command execution result
1009
1021
  */
1010
- type ValidateArgMeta<M, TValue = unknown> = M extends {
1011
- overrideBuiltinAlias: true;
1012
- } ? ValidateNegation<M, TValue> : ContainsReservedAlias<AliasFieldOf<M>> extends true ? ReservedAliasTypeError<M> : ContainsReservedAlias<HiddenAliasFieldOf<M>> extends true ? ReservedAliasTypeError<M> : ValidateNegation<M, TValue>;
1022
+ interface RunResultFailure {
1023
+ /** Indicates failed execution */
1024
+ success: false;
1025
+ /** Command return value */
1026
+ result?: never;
1027
+ /** Error that occurred during execution */
1028
+ error: Error;
1029
+ /** Exit code (non-zero for failure) */
1030
+ exitCode: number;
1031
+ /** Collected logs during execution */
1032
+ logs: CollectedLogs;
1033
+ }
1013
1034
  /**
1014
- * The overloaded `arg()` signature, parameterized by the schema constraint.
1015
- * Core's `arg` accepts any Standard Schema; adapter packages re-pin the same
1016
- * runtime function to their library's schema type (e.g. `ArgFn<z.ZodType>`
1017
- * in `@politty/zod`) so a schema from the wrong library is rejected at the
1018
- * type level.
1035
+ * Result of command execution (discriminated union)
1019
1036
  */
1020
- interface ArgFn<TSchemaBase extends SchemaLike = SchemaLike> {
1021
- <T extends TSchemaBase>(schema: T): T;
1022
- <T extends TSchemaBase, M extends ArgMeta<InferSchemaOutput<T>>>(schema: T, meta: ValidateArgMeta<M, InferSchemaOutput<T>>): T;
1023
- }
1037
+ type RunResult<T = unknown> = RunResultSuccess<T> | RunResultFailure;
1024
1038
  //#endregion
1025
- export { toKebabCase as $, LogEntry as A, RunResultSuccess as B, Command as C, GlobalCleanupContext as D, GlobalArgs as E, NonRunnableCommand as F, UnknownSubcommandHandler as G, SetupContext as H, PromptResolver as I, lazy as J, LazyCommand as K, RunCommandOptions as L, LogStream as M, Logger as N, GlobalSetupContext as O, MainOptions as P, toCamelCase as Q, RunResult as R, CollectedLogs as S, Example as T, SubCommandValue as U, RunnableCommand as V, SubCommandsRecord as W, ResolvedFieldMeta as X, ExtractedFields as Y, UnknownKeysMode as Z, DynamicCompletionResult as _, CustomCompletion as a, ArgsSchema as b, PromptType as c, ExpandCompletion as d, InferSchemaOutput as et, ResolvedExpandCandidate as f, DynamicCompletionResolver as g, DynamicCompletionContext as h, CompletionType as i, LogLevel as j, IsEmpty as k, ValidateArgMeta as l, DynamicCompletionCandidate as m, ArgMeta as n, EffectContext as o, CompletionDirectiveMask as p, isLazyCommand as q, CompletionMeta as r, PromptMeta as s, ArgFn as t, SchemaLike as tt, ExpandCandidate as u, AnyCommand as v, CommandBase as w, CleanupContext as x, ArgSource as y, RunResultFailure as z };
1039
+ export { DynamicCompletionResolver as $, LazyCommand as A, CompletionMeta as B, RunResultFailure as C, SubCommandValue as D, SetupContext as E, UnknownKeysMode as F, PromptType as G, CustomCompletion as H, toCamelCase as I, ExpandCompletion as J, ValidateArgMeta as K, toKebabCase as L, lazy as M, ExtractedFields as N, SubCommandsRecord as O, ResolvedFieldMeta as P, DynamicCompletionContext as Q, ArgFn as R, RunResult as S, RunnableCommand as T, EffectContext as U, CompletionType as V, PromptMeta as W, CompletionDirectiveMask as X, ResolvedExpandCandidate as Y, DynamicCompletionCandidate as Z, MainOptions as _, CollectedLogs as a, RunCommandOptions as b, Example as c, GlobalSetupContext as d, DynamicCompletionResult as et, IsEmpty as f, Logger as g, LogStream as h, CleanupContext as i, isLazyCommand as j, UnknownSubcommandHandler as k, GlobalArgs as l, LogLevel as m, ArgSource as n, SchemaLike as nt, Command as o, LogEntry as p, ExpandCandidate as q, ArgsSchema as r, CommandBase as s, AnyCommand as t, InferSchemaOutput as tt, GlobalCleanupContext as u, NonRunnableCommand as v, RunResultSuccess as w, RunInvocation as x, PromptResolver as y, ArgMeta as z };