Skip to content

Object options

An option coerced with coerce.object takes a whole object. Users can pass it as a JSON string, or build it up field by field with dotted flags.

import { coerce, defineCLI } from "@staticbolt/args-parser";
import * as z from "zod";
const cli = defineCLI({
cliName: "listy",
options: {
db: {
schema: z
.object({
host: z.string().default("localhost"),
port: z.number().default(5432),
https: z.boolean().default(false),
credentials: z.object({
user: z.string(),
pass: z.string(),
}),
})
.optional(),
coerce: coerce.object({ coerceBoolean: true, coerceNumber: ["port"] }),
meta: {
placeholder: "<.host,.port,.credentials.user,.credentials.pass>",
description: "Database configuration. Parsed as JSON, and supports dotted flags.",
example: "--db.host=prod-db --db.credentials.user=alice --db.credentials.pass=secret",
},
},
},
});
cli.onExecute(({ options }) => {
console.log(options.db);
});

On the command line

Terminal window
# Dotted flags with `=`
listy --db.https=true --db.host=db.local --db.port=3306 --db.credentials.user=root --db.credentials.pass=toor
# Dotted flags without `=`
listy --db.https true --db.host db.local --db.port 3306 --db.credentials.user root --db.credentials.pass toor
# A full JSON string
listy --db '{"host":"db.local","https":true,"credentials":{"user":"root","pass":"toor"}}'

Why the extra coercions

Dotted flags arrive as strings, so --db.port 3306 gives you "3306", not 3306. The options that you pass to coerce.object tell the parser which values to convert after the JSON parse:

Option Converts
coerceBoolean "true" and "false" (lowercase only) to booleans.
coerceNumber Number-like strings to numbers.
coerceBigint Integer-like strings to bigint.
coerceDate Date-like strings to Date.

Each one takes true to apply everywhere, or a list of dotted paths to limit it:

coerce.object({ coerceNumber: true });
coerce.object({ coerceNumber: ["port", "credentials.retries"] });

A value that fails to convert is left as the original string, and the schema decides whether that is acceptable.

Use coerce.json instead when you want the JSON parsed and nothing else.

Note

Dotted flags on an option that is not an object option fail with ParseErrorCode.InvalidKeysForNonObjectOption.