> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/wevm/incur/llms.txt
> Use this file to discover all available pages before exploring further.

# Parser

> Parse command-line arguments and environment variables with Zod schema validation

The `Parser` module provides utilities for parsing command-line arguments (`argv`) and environment variables against Zod schemas, with automatic type coercion and validation.

## Functions

### parse

Parses raw argv tokens against Zod schemas for positional arguments and named options.

<ParamField path="argv" type="string[]" required>
  The command-line arguments to parse (e.g., `process.argv.slice(2)`)
</ParamField>

<ParamField path="options" type="parse.Options">
  Configuration for parsing, including schemas for args and options
</ParamField>

<ResponseField name="return" type="parse.ReturnType">
  An object containing parsed `args` and `options`
</ResponseField>

#### Usage: Basic Parsing

```typescript theme={null}
import { z } from 'zod'
import { parse } from 'incur'

const argsSchema = z.object({
  source: z.string(),
  destination: z.string()
})

const optionsSchema = z.object({
  verbose: z.boolean().default(false),
  force: z.boolean().default(false)
})

const { args, options } = parse(
  ['input.txt', 'output.txt', '--verbose'],
  { args: argsSchema, options: optionsSchema }
)

// args: { source: 'input.txt', destination: 'output.txt' }
// options: { verbose: true, force: false }
```

#### Usage: Flag Aliases

```typescript theme={null}
import { z } from 'zod'
import { parse } from 'incur'

const optionsSchema = z.object({
  verbose: z.boolean().default(false),
  output: z.string().optional()
})

const { options } = parse(
  ['-v', '-o', 'result.json'],
  {
    options: optionsSchema,
    alias: { verbose: 'v', output: 'o' }
  }
)

// options: { verbose: true, output: 'result.json' }
```

#### Usage: Stacked Boolean Flags

```typescript theme={null}
import { z } from 'zod'
import { parse } from 'incur'

const optionsSchema = z.object({
  verbose: z.boolean().default(false),
  force: z.boolean().default(false),
  recursive: z.boolean().default(false)
})

const { options } = parse(
  ['-vfr'],
  {
    options: optionsSchema,
    alias: { verbose: 'v', force: 'f', recursive: 'r' }
  }
)

// options: { verbose: true, force: true, recursive: true }
```

#### Usage: Array Options

```typescript theme={null}
import { z } from 'zod'
import { parse } from 'incur'

const optionsSchema = z.object({
  include: z.array(z.string()).default([])
})

const { options } = parse(
  ['--include', 'src', '--include', 'lib', '--include', 'tests'],
  { options: optionsSchema }
)

// options: { include: ['src', 'lib', 'tests'] }
```

#### Usage: Kebab-case to camelCase

```typescript theme={null}
import { z } from 'zod'
import { parse } from 'incur'

const optionsSchema = z.object({
  dryRun: z.boolean().default(false),
  maxRetries: z.number().default(3)
})

const { options } = parse(
  ['--dry-run', '--max-retries', '5'],
  { options: optionsSchema }
)

// options: { dryRun: true, maxRetries: 5 }
```

#### Usage: Boolean Negation

```typescript theme={null}
import { z } from 'zod'
import { parse } from 'incur'

const optionsSchema = z.object({
  colors: z.boolean().default(true)
})

const { options } = parse(
  ['--no-colors'],
  { options: optionsSchema }
)

// options: { colors: false }
```

#### Usage: Equals Syntax

```typescript theme={null}
import { z } from 'zod'
import { parse } from 'incur'

const optionsSchema = z.object({
  config: z.string().optional(),
  port: z.number().default(3000)
})

const { options } = parse(
  ['--config=/path/to/config.json', '--port=8080'],
  { options: optionsSchema }
)

// options: { config: '/path/to/config.json', port: 8080 }
```

### parseEnv

Parses environment variables against a Zod schema with automatic type coercion.

<ParamField path="schema" type="z.ZodObject<any>" required>
  The Zod schema defining expected environment variables
</ParamField>

<ParamField path="source" type="Record<string, string | undefined>">
  The environment variable source. Defaults to `process.env` (Node.js) or `Deno.env` (Deno).
</ParamField>

<ResponseField name="return" type="z.output<env>">
  The parsed and validated environment variables
</ResponseField>

#### Usage: Basic Environment Parsing

```typescript theme={null}
import { z } from 'zod'
import { parseEnv } from 'incur'

const envSchema = z.object({
  NODE_ENV: z.enum(['development', 'production', 'test']).default('development'),
  PORT: z.number().default(3000),
  DATABASE_URL: z.string(),
  ENABLE_LOGGING: z.boolean().default(false)
})

const env = parseEnv(envSchema)
// Reads from process.env and coerces types:
// PORT: '3000' -> 3000 (number)
// ENABLE_LOGGING: 'true' -> true (boolean)
```

#### Usage: Custom Environment Source

```typescript theme={null}
import { z } from 'zod'
import { parseEnv } from 'incur'

const envSchema = z.object({
  API_KEY: z.string(),
  TIMEOUT: z.number().default(5000)
})

const customEnv = {
  API_KEY: 'secret-key',
  TIMEOUT: '10000'
}

const env = parseEnv(envSchema, customEnv)
// env: { API_KEY: 'secret-key', TIMEOUT: 10000 }
```

#### Usage: Boolean Coercion

```typescript theme={null}
import { z } from 'zod'
import { parseEnv } from 'incur'

const envSchema = z.object({
  DEBUG: z.boolean().default(false),
  VERBOSE: z.boolean().default(false)
})

// Boolean coercion:
// 'true' or '1' -> true
// anything else -> false
const env = parseEnv(envSchema, {
  DEBUG: 'true',
  VERBOSE: '1'
})
// env: { DEBUG: true, VERBOSE: true }
```

## Types

### parse.Options

Configuration options for the `parse()` function.

<ResponseField name="args" type="z.ZodObject<any> | undefined">
  Zod schema for positional arguments. Keys define the order of arguments.
</ResponseField>

<ResponseField name="options" type="z.ZodObject<any> | undefined">
  Zod schema for named options/flags.
</ResponseField>

<ResponseField name="alias" type="Record<string, string> | undefined">
  Map of option names to single-character aliases (e.g., `{ verbose: 'v' }`).
</ResponseField>

### parse.ReturnType

The return type of the `parse()` function, providing type-safe access to parsed arguments and options.

<ResponseField name="args" type="z.output<args> | {}">
  Parsed positional arguments, typed according to the schema. Empty object if no schema provided.
</ResponseField>

<ResponseField name="options" type="z.output<options> | {}">
  Parsed named options, typed according to the schema. Empty object if no schema provided.
</ResponseField>

## Error Handling

The parser throws specific error types for different failure scenarios:

* `ParseError`: Thrown when argument parsing fails (e.g., unknown flags, missing values, invalid syntax)
* `ValidationError`: Thrown when values fail Zod schema validation

```typescript theme={null}
import { z } from 'zod'
import { parse, ParseError, ValidationError } from 'incur'

try {
  const { args } = parse(
    ['--unknown-flag'],
    { options: z.object({ verbose: z.boolean() }) }
  )
} catch (err) {
  if (err instanceof ParseError) {
    console.error('Parse error:', err.message)
    // Parse error: Unknown flag: --unknown-flag
  } else if (err instanceof ValidationError) {
    console.error('Validation error:', err.fieldErrors)
  }
}
```
