How cacjs/cac works
Project Type and Purpose
• This is an open‑source JavaScript/TypeScript library (“CAC”) whose sole purpose is to help other developers build command‑line applications easily. It is not a full‑stack service or microservice, but rather a highly modular CLI framework you import into your programs.
Core Architectural Components
From the file tree and README, we can partition the system into two big domains:
A. Runtime Modules (src/)
1. CAC Core (CAC.ts) – creates the CLI instance, holds commands/options, orchestrates parse → run
2. Command Definition (Command.ts) – models each command, its name, args, options, action callback, examples, aliases
3. Option Definition (Option.ts) – models global & command‑specific options (name, type, default, negation, nested keys)
4. Parser & Utilities (utils.ts, index.ts) – split raw argv, normalize dash/camelCase, coerce types, collect parsedArgs
5. Environment Adapters (node.ts, deno.ts) – glue logic for reading process.argv vs Deno.args, printing output
6. Entry Points (mod.ts, mod.js, index-compat.js) – export a compatible API surface for both ESM and CommonJS
B. Build & QA
1. Bundler (rollup.config.js) – compiles & bundles the library into distributable ESM/CJS files
2. Deno Build Script (scripts/build-deno.ts) – produces a Deno‑friendly module at mod.ts
3. Testing (src/__test__/*, jest.config.js) – unit tests validating command parsing, option behaviors, snapshots
4. Examples (examples/) – sample CLI programs demonstrating usage patterns
Relationships & Data Flows
• Consumer CLI App
↳ import/require cac entry point
↳ call const cli = cac()
↳ declare commands (cli.command(...)), global options (cli.option(...)), help/version handlers
↳ invoke cli.parse()
• CAC Core Flow
1. Capture raw arguments via environment adapter (Node or Deno)
2. Split & Normalize arguments (utils.splitArgv)
3. Match against registered commands (name patterns, default command)
4. Parse global and command‑specific options (using Option models)
5. Trigger help/version if flags present (via cli.help(), cli.version())
6. Execute the matched command’s action callback with parsed args & options
7. Emit events (cli.on('command:foo')) for advanced use
• Build Pipeline
Source TS/JS → Rollup (transpile + bundle) → outputs index-compat.js, mod.js → published to npm
Separate Deno build script generates mod.ts for Deno usage.
Architectural Patterns & Principles
• Modularity & Single Responsibility: each class/file has a distinct role (CLI orchestration vs. command vs. option vs. env abstraction).
• Pluggability & Extensibility: commands and options are registered via method chaining; new adapters (e.g. for another runtime) can slot into the same pipeline.
• Dual Distribution: supports both CommonJS and native ES modules + Deno.
Checklist
• Call out extensibility points: method‑chain registration, event hooks, environment adapters
• Build output artifacts (e.g. mod.js, index-compat.js) separate from source