clap_types 0.1.0

Generate strongly-typed command builders from clap command definitions
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
# clap_types

`clap_types` turns Rust CLIs into multi-language client libraries.

If your Rust tool is defined with [`clap`](https://crates.io/crates/clap),
`clap_types` reflects its command tree and generates strongly-typed clients for
TypeScript, Flow-annotated JavaScript, Python, Rust, and Kotlin/JVM. Those clients
know how to build argv, optionally invoke the executable, and optionally describe or
parse structured output contracts.

The goal is to make CLIs feel like real programmatic APIs without giving up why CLIs
are great in the first place: they are easy to install, easy to sandbox, easy to call
from agents and skills, and naturally cross-process.

Rust CLIs are often the best packaging format for local tools, but hand-written
wrappers quickly become stringly typed drift:

- callers guess which arguments are required;
- enums and nested subcommands get duplicated by hand;
- file paths, booleans, counters, and repeated values lose their shape;
- stdout parsing is ad hoc and usually undocumented.

`clap_types` treats your `clap::Command` as the input IDL and explicit output
contracts as the output IDL. It generates clients that can be checked, linted, and
shipped with the same care as any other library.

That means callers get an idiomatic library instead of a pile of string
concatenation. The generated code knows the right subcommand order, where global
arguments belong, how varargs and repeated options expand, and which fields are
required before anything is sent to the tool.

## Status

This project is early and pre-1.0. The architecture is intentionally similar to
`clap_complete`, `clap_mangen`, and `clap-markdown`: reflect a `clap::Command`,
convert it into a language-neutral model, then render one or more target-language
artifacts.

Supported backends:

- TypeScript: dependency-free argv builders.
- TypeScript + Zod: opt-in strict schemas and runtime validation.
- TypeScript + Node: opt-in `child_process` command descriptors, `execFile`, and
  `spawn` helpers.
- Flow: dependency-free JavaScript argv builders with Flow exact object types.
- Flow + Zod / Node: the same opt-in validation and `child_process` helpers as the
  TypeScript backend.
- Python 3.10+: dataclasses, argv builders, single-file modules, package layouts,
  and `subprocess.run` convenience.
- Rust: dependency-free structs, enums, argv builders, and `std::process` helpers.
- Kotlin/JVM: desktop-friendly data classes, enums, argv builders, and
  `ProcessBuilder` helpers.

Every backend can opt into generated output-contract metadata and dependency-free
framing helpers with `.output_contracts()` or the hidden command's
`--output-contracts` flag.

## What You Get

- Multi-language input clients from one Rust CLI definition.
- Generated types for subcommands, globals, required args, enums, counters, booleans,
  repeated options, varargs, paths, numbers, and strings.
- Optional standard-library invocation helpers for Node, Python, Rust, and Kotlin/JVM.
- Runtime validation before invocation in opt-in modes such as TypeScript + Zod or
  Flow + Zod.
- Optional output-contract metadata for JSON, JSON-lines, text, streaming, and
  interactive commands, with automatic parsing where the generated language can do
  that cleanly without extra dependencies.
- A path toward typed success and error returns, so callers can know what to expect
  back instead of scraping stdout and exit codes by hand.
- A hidden `generate-binding` command you can embed in your own CLI so the tool can
  generate clients for itself.
- Generated-code tests in CI across Rust, Python 3.10-3.14, TypeScript and Flow on
  Node and Bun, and Kotlin/JVM.

## Install

Add `clap_types` to the crate that defines your CLI:

```toml
[dependencies]
clap = { version = "4", features = ["derive"] }
clap_types = "0.1"
```

For now, while developing locally, use a path dependency:

```toml
[dependencies]
clap = { version = "4", features = ["derive"] }
clap_types = { path = "../clap_types" }
```

## Quick Start

```rust
use clap::{Arg, ArgAction, Command};
use clap_types::{generate, Flow, Kotlin, Python, Rust, TypeScript};

fn build_cli() -> Command {
    Command::new("demo")
        .about("Example CLI")
        .arg(Arg::new("config").long("config").action(ArgAction::Set))
        .arg(Arg::new("verbose").short('v').action(ArgAction::Count))
}

let cmd = build_cli();
generate(TypeScript::new(), &cmd, "demo", &mut std::io::stdout())?;

let cmd = build_cli();
generate(TypeScript::new().zod(), &cmd, "demo", &mut std::io::stdout())?;

let cmd = build_cli();
generate(TypeScript::new().node(), &cmd, "demo", &mut std::io::stdout())?;

let cmd = build_cli();
generate(Flow::new().zod().node(), &cmd, "demo", &mut std::io::stdout())?;

let cmd = build_cli();
generate(
    Python::new()
        .module_name("demo_bindings")
        .namespace("Demo"),
    &cmd,
    "demo",
    &mut std::io::stdout(),
)?;

let cmd = build_cli();
generate(Rust::new(), &cmd, "demo", &mut std::io::stdout())?;

let cmd = build_cli();
generate(Kotlin::new(), &cmd, "demo", &mut std::io::stdout())?;
# Ok::<(), std::io::Error>(())
```

For file generation, use `generate_to`:

```rust
use clap::Command;
use clap_types::{generate_to, TypeScript};

let cmd = Command::new("demo");
let path = generate_to(TypeScript::new(), &cmd, "demo", "target/generated")?;
assert_eq!(path.file_name().unwrap(), "demo.ts");
# Ok::<(), std::io::Error>(())
```

Hidden subcommands and args are skipped by default. Use
`generate_to_with_options` with `ReflectOptions::all()` to include them:

```rust
use clap::Command;
use clap_types::{generate_to_with_options, ReflectOptions, TypeScript};

let cmd = Command::new("demo");
let path = generate_to_with_options(
    TypeScript::new(),
    &cmd,
    "demo",
    "target/generated",
    ReflectOptions::all(),
)?;
# assert_eq!(path.file_name().unwrap(), "demo.ts");
# Ok::<(), std::io::Error>(())
```

## Hidden Binding Command

Applications can expose every `clap_types` backend through a hidden clap subcommand.
This makes bindings generation part of the tool itself, which is handy for
build scripts, package publishing, and agent environments that install the CLI
first and ask it to describe itself later.

```rust
use clap::{Arg, Command};
use clap_types::{BINDING_COMMAND_NAME, binding_command, generate_binding_from_matches};

fn build_cli() -> Command {
    Command::new("demo").subcommand(Command::new("run").arg(Arg::new("target").required(true)))
}

fn main() -> std::io::Result<()> {
    let matches = build_cli().subcommand(binding_command()).get_matches();

    if let Some((BINDING_COMMAND_NAME, binding_matches)) = matches.subcommand() {
        let cmd = build_cli();
        let path = generate_binding_from_matches(&cmd, "demo", binding_matches)?;
        eprintln!("generated {}", path.display());
        return Ok(());
    }

    Ok(())
}
```

The hidden command supports the current generators and their main options:

```sh
demo generate-binding typescript --path target/generated/typescript
demo generate-binding typescript --zod --node --module-name demo-node --path target/generated/typescript-node
demo generate-binding flow --path target/generated/flow
demo generate-binding flow --zod --node --module-name demo-node --path target/generated/flow-node
demo generate-binding python --module-name demo_bindings --namespace Demo --path target/generated/python
demo generate-binding python --full-module --module-name demo --namespace Demo --path target/generated/python-package
demo generate-binding rust --module-name demo_bindings --output-contracts --path target/generated/rust
demo generate-binding kotlin --module-name demo_bindings --package dev.example.demo --path target/generated/kotlin
```

See
[`examples/generate_binding_subcommand.rs`](examples/generate_binding_subcommand.rs)
for a complete app-shaped example.

## Builder API CLIs

Builder-style clap apps can pass a `Command` directly:

```rust
use std::path::PathBuf;

use clap::{Arg, ArgAction, Command, ValueHint, value_parser};
use clap_types::{generate_to, Python, TypeScript};

fn cli() -> Command {
    Command::new("repo-agent")
        .arg(
            Arg::new("workspace")
                .long("workspace")
                .global(true)
                .value_hint(ValueHint::DirPath)
                .value_parser(value_parser!(PathBuf))
                .action(ArgAction::Set),
        )
        .subcommand(
            Command::new("index")
                .arg(Arg::new("input").required(true))
                .arg(Arg::new("threads").long("threads").value_parser(value_parser!(u16))),
        )
}

let cmd = cli();
generate_to(TypeScript::new(), &cmd, "repo-agent", "target/generated/typescript")?;

let cmd = cli();
generate_to(
    Python::new().module_name("repo_agent_bindings").namespace("RepoAgent"),
    &cmd,
    "repo-agent",
    "target/generated/python",
)?;
# Ok::<(), std::io::Error>(())
```

## Derive API CLIs

Derive-style clap apps work by using `CommandFactory::command()`:

```rust
use clap::{CommandFactory, Parser, Subcommand, ValueEnum};
use clap_types::{generate_to, TypeScript};

#[derive(Parser)]
#[command(name = "opsctl")]
struct OpsCtl {
    #[arg(long, global = true, value_enum, default_value = "table")]
    output: OutputFormat,

    #[command(subcommand)]
    command: OpsCommand,
}

#[derive(Subcommand)]
enum OpsCommand {
    Deploy {
        service: String,
        #[arg(long, required = true)]
        image: String,
    },
}

#[derive(Clone, Copy, ValueEnum)]
enum OutputFormat {
    Table,
    Json,
}

let cmd = OpsCtl::command();
generate_to(TypeScript::new().zod(), &cmd, "opsctl", "target/generated/typescript-zod")?;
# Ok::<(), std::io::Error>(())
```

The full derive example is in
[`examples/generate_derive_bindings.rs`](examples/generate_derive_bindings.rs).

## Generated TypeScript

Default TypeScript output has no runtime dependencies:

```ts
import {
  buildAgentRunCommand,
  type AgentRunArgs,
} from "./generated/repo-agent";

const args: AgentRunArgs = {
  workspace: "/repo",
  verbose: 2,
  task: "summarize",
  maxTokens: 2048,
  dryRun: true,
};

const argv = buildAgentRunCommand(args);
```

Clap metadata is translated conservatively:

- `ValueEnum` and possible values become string literal unions.
- flags become `boolean`;
- counters become `number`;
- integer and float parsers become `number`;
- repeated options become readonly arrays;
- required clap values become required TypeScript properties;
- global args are inherited into subcommand builders.

## Generated TypeScript + Zod

Use Zod mode when runtime validation is useful:

```rust
use clap_types::TypeScript;

let generator = TypeScript::new()
    .module_name("repo-agent-zod")
    .zod();
```

Zod output emits strict schemas and inferred types:

```ts
import {
  AgentRunArgsSchema,
  buildAgentRunCommand,
  type AgentRunArgs,
} from "./generated/repo-agent-zod";

const parsed = AgentRunArgsSchema.parse({
  task: "summarize",
  model: "frontier",
});

const argv = buildAgentRunCommand(parsed);
```

`TypeScript::new().zod()` validates builder inputs with `Schema.parse(args)`.
`TypeScript::new().zod_schemas()` emits schemas and inferred types without parsing
inside the builder.

## Generated TypeScript + Node

Use Node mode when the generated artifact should include idiomatic
`node:child_process` helpers:

```rust
use clap_types::TypeScript;

let generator = TypeScript::new()
    .module_name("repo-agent-node")
    .node();
```

The generated module still exposes the plain argv builder, and adds process-ready
helpers:

```ts
import {
  createAgentRunCommand,
  runAgentRunCommand,
  type AgentRunArgs,
} from "./generated/repo-agent-node";

const args: AgentRunArgs = {
  task: "summarize",
  model: "frontier",
};

const command = createAgentRunCommand(args);
// { file: "repo-agent", args: ["agent", "run", "summarize", "--model", "frontier"] }

const result = await runAgentRunCommand(args, { cwd: "/repo" });
console.log(result.stdout);
```

`create...Command` returns `{ file, args }`, `run...Command` uses `execFile`, and
`spawn...Command` uses `spawn`. Pass `{ program: "/custom/path" }` to override the
executable while keeping the typed argv builder unchanged.

## Generated Flow

Flow output mirrors the TypeScript backend but emits runnable `.js` modules with
Flow annotations:

```rust
use clap_types::Flow;

let generator = Flow::new().module_name("repo-agent");
let zod_generator = Flow::new().module_name("repo-agent-zod").zod();
let node_generator = Flow::new().module_name("repo-agent-node").node();
```

The generated JavaScript uses exact object types, `ReadonlyArray` for repeated
values, optional Zod schemas, and optional Node `child_process` helpers. Every
generated module starts with a `/** @generated @flow strict */` header so
downstream tooling and linters recognize the file as generated. Runtime tests
strip Flow annotations with `flow-remove-types` before executing under Node or
Bun.

## Generated Python

Python output targets Python 3.10 through 3.14 and uses only the standard library:

```python
from repo_agent_bindings import AgentRunArgs, RepoAgent

args = AgentRunArgs(
    workspace="/repo",
    verbose=2,
    task="summarize",
    model="frontier",
    max_tokens=2048,
    dry_run=True,
)

invocation = RepoAgent.agent_run_command(args, program="repo-agent")
argv = invocation.argv()
```

Python generated clients include:

- frozen keyword-only dataclasses;
- `Literal[...]` for possible values;
- `int`, `float`, `bool`, and path-like annotations when clap exposes those parser
  types;
- `build_..._args()` functions returning `tuple[str, ...]`;
- `..._command()` helpers returning `CommandInvocation`;
- `CommandInvocation.run()` as a thin `subprocess.run` wrapper.

Python can also generate a package layout:

```rust
use clap::Command;
use clap_types::{generate_to, Python};

fn build_cli() -> Command {
    Command::new("repo-agent")
}

let cmd = build_cli();
generate_to(
    Python::new()
        .module_name("repo_agent")
        .namespace("RepoAgent")
        .package(),
    &cmd,
    "repo-agent",
    "target/generated/python-package",
)?;
# Ok::<(), std::io::Error>(())
```

The package layout emits `_runtime.py`, `_root.py`, and command modules such as
`agent/run.py`:

```python
from repo_agent.agent.run import Args, command

invocation = command(Args(task="summarize", model="frontier"))
assert invocation.argv() == ["repo-agent", "agent", "run", "summarize", "--model", "frontier"]
```

## Generated Rust

Rust output uses only `std`:

```rust,ignore
use repo_agent_bindings::{AgentRunArgs, AgentRunModel, build_agent_run_command};

let args = AgentRunArgs {
    task: "summarize".to_owned(),
    model: Some(AgentRunModel::Frontier),
    dry_run: true,
    ..Default::default()
};

let argv = build_agent_run_command(&args);
```

The backend emits structs for command args, enums for clap possible values,
`build_..._command()` functions, and `CommandInvocation` helpers over
`std::process::Command`.

## Generated Kotlin

Kotlin output targets Kotlin/JVM desktop clients and uses the standard library:

```kotlin
val args =
    AgentRunArgs(
        task = "summarize",
        model = AgentRunModel.Frontier,
        dryRun = true,
    )

val invocation = agentRunCommand(args)
val process = invocation.processBuilder().start()
```

The backend emits data classes, enum classes, `build...Command()` functions, and a
small `CommandInvocation` wrapper around `ProcessBuilder`.

## Output Contracts

All generators omit output contracts by default. Turn them on when the reflected
`CliSpec` includes explicit output metadata:

```rust,ignore
let generator = TypeScript::new().output_contracts();
let generator = Flow::new().output_contracts();
let generator = Python::new().output_contracts();
let generator = Rust::new().output_contracts();
let generator = Kotlin::new().output_contracts();
```

Generated parsers stay dependency-free. They preserve JSON as parsed `unknown`
in TypeScript and Flow (both call the runtime's built-in `JSON.parse`), use
`json.loads` in Python, and expose framed JSON/JSON-lines strings in Rust and
Kotlin so callers can pick their own deserialization library
(`serde_json`/`simd-json`/`sonic-rs` for Rust; `kotlinx.serialization`/Jackson/
Moshi for Kotlin) and target type.

## Structured Type Hints

Clap already exposes useful input metadata, and `clap_types` preserves it wherever
it can:

- `PathBuf`, `OsString`, and `ValueHint::FilePath` / `ValueHint::DirPath` can tell a
  backend that a string-like value is really a filesystem value;
- `ValueEnum` and possible values become language-native enum or literal types;
- integer, wide integer, float, boolean, repeated, grouped, and optional values keep
  their shape in generated clients.

The next step is explicit schema metadata for cases where clap cannot know enough.
That should mirror output contracts: a command author can attach JSON Schema or
small structured hints to an argument or output payload, and each backend can decide
how much to render. TypeScript might emit Zod or JSON Schema validators, Python
might expose `TypedDict` or dataclass adapters, Rust might support serde-aware modes,
and Kotlin might support kotlinx.serialization. The default path should stay
dependency-free, while schema-aware modes can be opt-in.

In other words: clap reflection should provide the baseline type shape; explicit
schemas should provide richer semantic contracts such as "this string is a file",
"this JSON field is a path", or "this output is a stream of objects with this
schema."

## Examples

Generate all fixtures:

```sh
npm run generate:fixtures
```

This runs:

- `examples/generate_complex_bindings.rs`: builder-style clap examples;
- `examples/generate_derive_bindings.rs`: derive-macro clap example.

Client examples:

```sh
python examples/clients/python_repo_agent.py target/generated
python examples/clients/python_opsctl_derive.py target/generated
bun examples/clients/typescript_repo_agent.ts
bun examples/clients/typescript_zod_opsctl.ts
npm run test:generated:flow
```

See [`docs/examples.md`](docs/examples.md) for the full map.

## Development

Rust checks:

```sh
cargo fmt --check
cargo clippy --all-targets --all-features -- -D warnings
cargo test --all-targets --all-features
cargo test --doc --all-features
```

Generated-code checks:

```sh
npm ci
npm run generate:fixtures
npm run check:generated:ts
npm run check:generated:flow
npm run lint:generated:rust
npm run check:generated:rust
npm run lint:generated:kotlin
npm run check:generated:kotlin
npm run test:generated:ts
npm run test:generated:flow
ruff check tests/generated/python_smoke.py tests/generated/python_package_smoke.py examples/clients/*.py target/generated/python target/generated/python-package
ruff format --check tests/generated/python_smoke.py tests/generated/python_package_smoke.py examples/clients/*.py target/generated/python target/generated/python-package
black --check tests/generated/python_smoke.py tests/generated/python_package_smoke.py examples/clients/*.py target/generated/python target/generated/python-package
python -m compileall -q target/generated/python target/generated/python-package tests/generated/python_smoke.py tests/generated/python_package_smoke.py examples/clients
python tests/generated/python_smoke.py target/generated
python tests/generated/python_package_smoke.py target/generated
```

CI runs Rust checks, Python generated-code checks on Python 3.10 through 3.14,
TypeScript and Flow checks on Node plus Bun, generated Rust compilation, and generated
Kotlin/JVM compilation. Generated Rust is checked with `rustfmt`, `cargo clippy`,
and `rustc -D warnings`; generated Kotlin is compiled with `-Werror`, `-Wextra`,
progressive mode, and bytecode validation so compiler deprecations become CI
failures instead of quiet drift.

## Design Notes

`clap_types` treats clap as the source of truth for inputs. It does not infer stdout
or stderr contracts from help text. Structured output should be declared explicitly;
see [`docs/output-contracts.md`](docs/output-contracts.md).

Output contracts that attach metadata directly to `clap::Command` use clap's
unstable extension API and are gated behind `clap_types`' own
`unstable-output-contracts` feature. The stable IR can already carry JSON,
JSON-lines, text, buffered, streaming, interactive, and JSON Schema metadata.

More design detail lives in:

- [`docs/architecture.md`]docs/architecture.md
- [`docs/typescript-generator.md`]docs/typescript-generator.md
- [`docs/python-generator.md`]docs/python-generator.md
- [`docs/rust-generator.md`]docs/rust-generator.md
- [`docs/kotlin-generator.md`]docs/kotlin-generator.md
- [`docs/testing.md`]docs/testing.md

## License

Licensed under either of

- Apache License, Version 2.0 ([LICENSE-APACHE]LICENSE-APACHE or
  <http://www.apache.org/licenses/LICENSE-2.0>)
- MIT license ([LICENSE-MIT]LICENSE-MIT or
  <http://opensource.org/licenses/MIT>)

at your option.

### Contribution

Unless you explicitly state otherwise, any contribution intentionally submitted
for inclusion in the work by you, as defined in the Apache-2.0 license, shall
be dual licensed as above, without any additional terms or conditions.