Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,12 @@ All notable changes to this project will be documented in this file.

The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).

## [1.0.1] - 2026-08-09

### Added

- `positionals` now also accepts `{ schema, label }`; when a `label` is given, `buildUsage()`/`cli.usage` prepends it before the flag list instead of silently omitting positionals.

## [1.0.0] - 2026-08-08

### Added
Expand Down
17 changes: 17 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,23 @@ const cli = defineCli({

Omit `positionals` and a stray bare argument is a parse error.

`positionals` also accepts `{ schema, label }` to include the positionals in the auto-generated `cli.usage`, prepended before the flags:

```ts
const cli = defineCli({
flags: { output: { schema: z.string() } },
positionals: {
schema: z
.array(z.string())
.length(2)
.transform(([source, destination]) => ({ source, destination })),
label: "<source> <destination>",
},
});

cli.usage; // "Usage: <source> <destination> --output <value>"
```

## Copyright

Copyright 2026, Figulus Project.
Expand Down
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "zod-cli-flags",
"version": "1.0.0",
"version": "1.0.1",
"description": "Define a CLI's flags as a single Zod schema and parse argv into a typed result.",
"type": "module",
"main": "./dist/index.js",
Expand Down
31 changes: 31 additions & 0 deletions src/defineCli.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -258,6 +258,37 @@ describe("defineCli - positionals", () => {
const result = cli.parse(["--output", "/tmp", "stray"]);
expect(result.success).toBe(false);
});

it("still accepts a bare schema (no label) and omits positionals from usage", () => {
const cli = defineCli({
flags: { output: { schema: z.string() } },
positionals: z.array(z.string()),
});
expect(cli.usage).toBe("Usage: --output <value>");

const result = cli.parse(["--output", "/tmp", "one", "two"]);
expect(result.success).toBe(true);
if (result.success) expect(result.positionals).toEqual(["one", "two"]);
});

it("prepends the label before the flags when positionals carry one", () => {
const cli = defineCli({
flags: { output: { schema: z.string() } },
positionals: {
schema: z
.array(z.string())
.length(2)
.transform(([source, destination]) => ({ source, destination })),
label: "<source> <destination>",
},
});
expect(cli.usage).toBe("Usage: <source> <destination> --output <value>");

const result = cli.parse(["--output", "/tmp", "a", "b"]);
expect(result.success).toBe(true);
if (result.success)
expect(result.positionals).toEqual({ source: "a", destination: "b" });
});
});

describe("defineCli - parseOrExit", () => {
Expand Down
56 changes: 39 additions & 17 deletions src/defineCli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import type {
FlagDescriptors,
FlagRawValue,
ParseResult,
PositionalsDescriptor,
} from "./types.js";
import { buildUsage } from "./usage.js";

Expand Down Expand Up @@ -87,47 +88,67 @@ function toCliIssues(error: z.ZodError): CliIssue[] {
}));
}

type PositionalsInput = z.ZodType | PositionalsDescriptor;

type SchemaOf<TPositionalsInput> =
TPositionalsInput extends PositionalsDescriptor<infer T>
? z.ZodType<T, any>
: TPositionalsInput extends z.ZodType
? TPositionalsInput
: undefined;

function resolvePositionals(positionals: PositionalsInput | undefined): {
schema?: z.ZodType;
label?: string;
} {
if (positionals === undefined) return {};
if (positionals instanceof z.ZodType) return { schema: positionals };
return { schema: positionals.schema, label: positionals.label };
}

export interface DefineCliOptions<
TFlags extends FlagDescriptors,
TPositionalsSchema extends z.ZodType | undefined,
TPositionalsInput extends PositionalsInput | undefined,
> {
flags: TFlags;
positionals?: TPositionalsSchema;
positionals?: TPositionalsInput;
usage?: string;
}

type InferFlags<TFlags extends FlagDescriptors> = {
[K in keyof TFlags]: z.infer<TFlags[K]["schema"]>;
};
type InferPositionals<TPositionalsSchema> = TPositionalsSchema extends z.ZodType
? z.infer<TPositionalsSchema>
: string[];
type InferPositionals<TPositionalsInput> =
SchemaOf<TPositionalsInput> extends z.ZodType
? z.infer<SchemaOf<TPositionalsInput>>
: string[];

export interface CliDefinition<
TFlags extends FlagDescriptors,
TPositionalsSchema extends z.ZodType | undefined,
TPositionalsInput extends PositionalsInput | undefined,
> {
flagsSchema: z.ZodObject<{ [K in keyof TFlags]: TFlags[K]["schema"] }>;
parseArgsOptions: Record<string, ParseArgsOptionDescriptor>;
usage: string;
parse<TOut = InferFlags<TFlags>>(
argv: string[],
overrideFlagsSchema?: z.ZodType<TOut, any>,
): ParseResult<TOut, InferPositionals<TPositionalsSchema>>;
): ParseResult<TOut, InferPositionals<TPositionalsInput>>;
parseOrExit<TOut = InferFlags<TFlags>>(
argv: string[],
overrideFlagsSchema?: z.ZodType<TOut, any>,
): { data: TOut; positionals: InferPositionals<TPositionalsSchema> };
): { data: TOut; positionals: InferPositionals<TPositionalsInput> };
}

export function defineCli<
TFlags extends FlagDescriptors,
TPositionalsSchema extends z.ZodType | undefined = undefined,
TPositionalsInput extends PositionalsInput | undefined = undefined,
>(
def: DefineCliOptions<TFlags, TPositionalsSchema>,
): CliDefinition<TFlags, TPositionalsSchema> {
def: DefineCliOptions<TFlags, TPositionalsInput>,
): CliDefinition<TFlags, TPositionalsInput> {
const resolved = resolveFlags(def.flags);
const parseArgsOptions = buildParseArgsOptions(resolved);
const positionalsConfig = resolvePositionals(def.positionals);

const shape = Object.fromEntries(
resolved.map(({ key, descriptor }) => [key, descriptor.schema]),
Expand All @@ -145,19 +166,20 @@ export function defineCli<
isBoolean,
isOptional: isOptionalFlag(descriptor.schema),
})),
positionalsConfig.label,
);

function parse<TOut = InferFlags<TFlags>>(
argv: string[],
overrideFlagsSchema?: z.ZodType<TOut, any>,
): ParseResult<TOut, InferPositionals<TPositionalsSchema>> {
): ParseResult<TOut, InferPositionals<TPositionalsInput>> {
let values: Record<string, FlagRawValue>;
let positionalsRaw: string[];
try {
const parsed = parseArgs({
args: normalizeArgv(argv),
options: parseArgsOptions,
allowPositionals: def.positionals !== undefined,
allowPositionals: positionalsConfig.schema !== undefined,
strict: true,
});
values = parsed.values as Record<string, FlagRawValue>;
Expand Down Expand Up @@ -185,8 +207,8 @@ export function defineCli<
any
>;
const flagsResult = schemaToUse.safeParse(raw);
const positionalsResult = def.positionals
? def.positionals.safeParse(positionalsRaw)
const positionalsResult = positionalsConfig.schema
? positionalsConfig.schema.safeParse(positionalsRaw)
: { success: true as const, data: positionalsRaw };

if (!flagsResult.success || !positionalsResult.success) {
Expand All @@ -209,14 +231,14 @@ export function defineCli<
success: true,
data: flagsResult.data,
positionals:
positionalsResult.data as InferPositionals<TPositionalsSchema>,
positionalsResult.data as InferPositionals<TPositionalsInput>,
};
}

function parseOrExit<TOut = InferFlags<TFlags>>(
argv: string[],
overrideFlagsSchema?: z.ZodType<TOut, any>,
): { data: TOut; positionals: InferPositionals<TPositionalsSchema> } {
): { data: TOut; positionals: InferPositionals<TPositionalsInput> } {
const result = parse(argv, overrideFlagsSchema);
if (!result.success) {
console.error(result.error.message);
Expand Down
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,5 @@ export type {
CliIssue,
CliParseError,
ParseResult,
PositionalsDescriptor,
} from "./types.js";
6 changes: 6 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,12 @@ export interface FlagDescriptor<T = unknown> {

export type FlagDescriptors = Record<string, FlagDescriptor<any>>;

export interface PositionalsDescriptor<T = unknown> {
schema: z.ZodType<T, any>;
/** Shown in the auto-generated usage string, prepended before the flags. */
label?: string;
}

export interface CliIssue {
path: (string | number)[];
message: string;
Expand Down
8 changes: 6 additions & 2 deletions src/usage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,10 @@ interface UsageFlag {
}

// Auto-generated default for cli.usage; override via defineCli({ usage: "..." }).
export function buildUsage(resolved: UsageFlag[]): string {
export function buildUsage(
resolved: UsageFlag[],
positionalsLabel?: string,
): string {
const parts = resolved.map(({ long, descriptor, isBoolean, isOptional }) => {
const alias = descriptor.short
? `--${long}/-${descriptor.short}`
Expand All @@ -29,5 +32,6 @@ export function buildUsage(resolved: UsageFlag[]): string {

return isOptional || descriptor.negatable ? `[${core}]` : core;
});
return `Usage: ${parts.join(" ")}`;
const allParts = positionalsLabel ? [positionalsLabel, ...parts] : parts;
return `Usage: ${allParts.join(" ")}`;
}
Loading