### Implementing Command Hooks (Setup and Cleanup) in Citty Source: https://github.com/unjs/citty/blob/main/README.md This example illustrates the use of `setup` and `cleanup` hooks within a Citty command. These hooks execute before and after the main `run` function, respectively, ensuring essential tasks are performed and resources are managed. ```javascript import { defineCommand, runMain } from "citty"; const main = defineCommand({ meta: { name: "hello", version: "1.0.0", description: "My Awesome CLI App" }, setup() { console.log("Setting up..."); }, cleanup() { console.log("Cleaning up..."); }, run() { console.log("Hello World!"); }, }); runMain(main); ``` -------------------------------- ### Define and Run a CLI with Sub-Commands using Citty Source: https://github.com/unjs/citty/blob/main/README.md This example shows how to define a main command that includes nested sub-commands. It illustrates the structure for organizing commands and their respective arguments. ```javascript import { defineCommand, runMain } from "citty"; const sub = defineCommand({ meta: { name: "sub", description: "Sub command" }, args: { name: { type: "positional", description: "Your name", required: true }, }, run({ args }) { console.log(`Hello ${args.name}!`); }, }); const main = defineCommand({ meta: { name: "hello", version: "1.0.0", description: "My Awesome CLI App" }, subCommands: { sub }, }); runMain(main); ``` -------------------------------- ### Define and Run a Basic CLI Command with Citty Source: https://github.com/unjs/citty/blob/main/README.md This snippet demonstrates how to define a main command with positional and boolean arguments, along with setup and cleanup hooks. It then runs the command using `runMain`. ```javascript import { defineCommand, runMain } from "citty"; const main = defineCommand({ meta: { name: "hello", version: "1.0.0", description: "My Awesome CLI App", }, args: { name: { type: "positional", description: "Your name", required: true, }, friendly: { type: "boolean", description: "Use friendly greeting", }, }, setup({ args }) { console.log(`now setup ${args.command}`); }, cleanup({ args }) { console.log(`now cleanup ${args.command}`); }, run({ args }) { console.log(`${args.friendly ? "Hi" : "Greetings"} ${args.name}!`); }, }); runMain(main); ``` -------------------------------- ### Implement Lifecycle Hooks in Citty Source: https://context7.com/unjs/citty/llms.txt Shows how to utilize setup and cleanup hooks to manage resources like database connections. The cleanup hook is guaranteed to execute even if the main run handler throws an error. ```javascript import { defineCommand, runMain } from "citty"; const command = defineCommand({ meta: { name: "database-task", description: "Run database operations" }, args: { query: { type: "string", description: "SQL query to execute", required: true, }, }, async setup({ args }) { console.log("Connecting to database..."); await new Promise((resolve) => setTimeout(resolve, 100)); console.log("Connected!"); }, async run({ args }) { console.log(`Executing query: ${args.query}`); if (args.query.includes("DROP")) { throw new Error("Dangerous query detected!"); } return { rows: 10 }; }, async cleanup({ args }) { console.log("Closing database connection..."); await new Promise((resolve) => setTimeout(resolve, 50)); console.log("Connection closed."); }, }); runMain(command); ``` -------------------------------- ### Create and Use Citty Plugins Source: https://context7.com/unjs/citty/llms.txt Shows how to define reusable plugins using defineCittyPlugin to extend command functionality with setup and cleanup hooks. Plugins can be defined as objects, factory functions for state management, or asynchronous functions. ```javascript import { defineCommand, defineCittyPlugin, runMain } from "citty"; // Simple plugin with setup and cleanup const loggerPlugin = defineCittyPlugin({ name: "logger", setup({ args, cmd }) { console.log(`[Logger] Starting command: ${cmd.meta?.name}`); console.log(`[Logger] Args:`, args); }, cleanup({ args }) { console.log(`[Logger] Command completed`); }, }); // Factory function plugin with shared state const timerPlugin = defineCittyPlugin(() => { let startTime; return { name: "timer", setup() { startTime = Date.now(); console.log("[Timer] Started"); }, cleanup() { const duration = Date.now() - startTime; console.log(`[Timer] Completed in ${duration}ms`); }, }; }); // Async plugin const authPlugin = defineCittyPlugin(async () => ({ name: "auth", async setup({ args }) { await new Promise((resolve) => setTimeout(resolve, 100)); console.log("[Auth] User authenticated"); }, })); const command = defineCommand({ meta: { name: "my-cli", description: "CLI with plugins" }, plugins: [loggerPlugin, timerPlugin, authPlugin], args: { task: { type: "positional", required: true }, }, setup() { console.log("[Command] Setup"); }, run({ args }) { console.log(`[Command] Running task: ${args.task}`); }, cleanup() { console.log("[Command] Cleanup"); }, }); runMain(command); ``` -------------------------------- ### Using Plugins for Reusable Command Logic in Citty Source: https://github.com/unjs/citty/blob/main/README.md This code defines and applies a Citty plugin to a command. Plugins allow for the encapsulation and reuse of `setup` and `cleanup` logic across different commands, promoting modularity and maintainability. ```javascript import { defineCommand, defineCittyPlugin, runMain } from "citty"; const logger = defineCittyPlugin({ name: "logger", setup({ args }) { console.log("Logger setup, args:", args); }, cleanup() { console.log("Logger cleanup"); }, }); const main = defineCommand({ meta: { name: "hello", description: "My CLI App" }, plugins: [logger], run() { console.log("Hello!"); }, }); runMain(main); ``` -------------------------------- ### Run Command and Get Result with Citty Source: https://context7.com/unjs/citty/llms.txt Uses the low-level `runCommand` function in Citty to parse arguments and execute a command, returning a result object. This function is useful for programmatic execution of commands and retrieving their output. The example shows how to execute a command with a 'count' argument and access the returned `items` and `total` from the result, as well as passing custom data to the command context. ```javascript import { defineCommand, runCommand } from "citty"; const command = defineCommand({ args: { count: { type: "string", description: "Number of items", default: "5", }, }, run({ args }) { const items = Array.from({ length: parseInt(args.count) }, (_, i) => i + 1); return { items, total: items.length }; }, }); // Execute command and get result const { result } = await runCommand(command, { rawArgs: ["--count", "3"], }); console.log(result); // Output: { items: [1, 2, 3], total: 3 } // Pass custom data to command context const { result: resultWithData } = await runCommand(command, { rawArgs: [], data: { userId: 123 }, }); ``` -------------------------------- ### Define CLI Command with Citty Source: https://context7.com/unjs/citty/llms.txt Defines a type-safe command using `defineCommand` in Citty, including metadata, arguments, hooks, and a run handler. It demonstrates various argument types like positional, string, boolean, and enum, along with default values and aliases. The example also shows how to use `runMain` to execute the command. ```javascript import { defineCommand, runMain } from "citty"; const main = defineCommand({ meta: { name: "my-cli", version: "1.0.0", description: "My Awesome CLI App", }, args: { name: { type: "positional", description: "Your name", required: true, }, greeting: { type: "string", description: "Custom greeting message", default: "Hello", }, friendly: { type: "boolean", description: "Use friendly greeting", alias: ["f"], }, level: { type: "enum", description: "Log level", options: ["debug", "info", "warn", "error"], default: "info", }, }, setup({ args }) { console.log("Setting up with args:", args.name); }, cleanup({ args }) { console.log("Cleaning up after:", args.name); }, run({ args }) { const prefix = args.friendly ? "Hi" : args.greeting; console.log(`${prefix} ${args.name}! (level: ${args.level})`); }, }); runMain(main); // Usage: // $ node cli.mjs john --friendly --level=debug // Output: Hi john! (level: debug) ``` -------------------------------- ### Create Reusable Main Function with Citty Source: https://context7.com/unjs/citty/llms.txt Creates a reusable main function wrapper around a command definition using `createMain` in Citty. This allows the command to be invoked multiple times with different options, either using the default process arguments or custom arguments. The example demonstrates defining a command with positional and enum arguments and then executing the created main function. ```javascript import { defineCommand, createMain } from "citty"; const command = defineCommand({ meta: { name: "hello", version: "1.0.0", description: "My Awesome CLI App", }, args: { name: { type: "positional", description: "Your name", required: true, }, adj: { type: "enum", description: "Adjective to use in greeting", options: ["awesome", "cool", "nice"], default: "awesome", }, }, run({ args }) { console.log(`Hello ${args.adj} ${args.name}!`); }, }); // Create reusable main function const main = createMain(command); // Execute with default process.argv main(); // Execute with custom args main({ rawArgs: ["John", "--adj=cool"] }); // Output: Hello cool John! ``` -------------------------------- ### Render and Display Command Usage Source: https://context7.com/unjs/citty/llms.txt Demonstrates how to generate a formatted usage string using renderUsage or print it directly to the console using showUsage. These functions utilize the command metadata and argument definitions to produce a human-readable help interface. ```javascript import { defineCommand, renderUsage, showUsage } from "citty"; const command = defineCommand({ meta: { name: "deploy", version: "1.0.0", description: "Deploy application to cloud provider", }, args: { target: { type: "positional", description: "Deployment target", required: true, }, env: { type: "enum", description: "Environment", options: ["dev", "staging", "prod"], default: "dev", }, dryRun: { type: "boolean", description: "Perform dry run without deploying", alias: ["n"], }, force: { type: "boolean", description: "Force deployment", default: true, negativeDescription: "Disable forced deployment", }, }, subCommands: { status: defineCommand({ meta: { name: "status", description: "Check deployment status" }, }), rollback: defineCommand({ meta: { name: "rollback", description: "Rollback deployment" }, }), }, }); // Get usage as string const usageText = await renderUsage(command); console.log(usageText); // Print usage directly to console await showUsage(command); ``` -------------------------------- ### Define nested sub-commands with Citty Source: https://context7.com/unjs/citty/llms.txt Demonstrates how to structure a CLI using defineCommand, including sub-command registration, lazy loading via dynamic imports, and argument configuration with aliases. ```javascript import { defineCommand, runMain } from "citty"; const buildCommand = defineCommand({ meta: { name: "build", description: "Build the project", alias: "b", }, args: { prod: { type: "boolean", description: "Production mode", alias: "p", }, outDir: { type: "string", description: "Output directory", default: "dist", }, }, run({ args }) { console.log(`Building in ${args.prod ? "production" : "development"} mode`); console.log(`Output: ${args.outDir}`); }, }); const deployCommand = defineCommand({ meta: { name: "deploy", description: "Deploy to cloud", alias: ["d", "push"], hidden: false, }, args: { env: { type: "enum", options: ["staging", "production"], default: "staging", }, }, run({ args }) { console.log(`Deploying to ${args.env}`); }, }); const main = defineCommand({ meta: { name: "my-cli", version: "1.0.0", description: "Project management CLI", }, subCommands: { build: buildCommand, deploy: deployCommand, test: () => import("./commands/test.mjs").then((m) => m.default), }, }); runMain(main); ``` -------------------------------- ### Run Main CLI Command with Citty Source: https://context7.com/unjs/citty/llms.txt Executes a Citty command as the main entry point using `runMain`. This function automatically handles `--help`/`-h` and `--version`/`-v` flags, provides graceful error handling, and displays usage information on errors. It can run with default process arguments or custom arguments, and allows for a custom usage handler. ```javascript import { defineCommand, runMain } from "citty"; const command = defineCommand({ meta: { name: "greet", version: "2.0.0", description: "A greeting CLI tool", }, args: { name: { type: "positional", description: "Name to greet", required: true, }, }, run({ args }) { console.log(`Hello, ${args.name}!`); }, }); // Run with process.argv by default runMain(command); // Or provide custom arguments runMain(command, { rawArgs: ["world"] }); // Custom usage handler runMain(command, { rawArgs: ["--help"], showUsage: async (cmd) => { console.log("Custom help output for:", cmd.meta?.name); }, }); // Built-in flags: // $ node cli.mjs --help # Shows auto-generated usage // $ node cli.mjs --version # Shows "2.0.0" // $ node cli.mjs world # Output: Hello, world! ``` -------------------------------- ### Command Definition and Execution Source: https://github.com/unjs/citty/blob/main/README.md This section details the core functions for defining and running commands using Citty. ```APIDOC ## API Reference This section details the core functions for defining and running commands using Citty. ### `defineCommand(def)` **Description**: Type helper for defining commands. **Method**: N/A (Function Signature) **Endpoint**: N/A ### `runMain(cmd, opts?)` **Description**: Run a command with usage support and graceful error handling. **Method**: N/A (Function Signature) **Endpoint**: N/A ### `createMain(cmd)` **Description**: Create a wrapper that calls `runMain` when invoked. **Method**: N/A (Function Signature) **Endpoint**: N/A ### `runCommand(cmd, opts)` **Description**: Parse args and run command/sub-commands; access `result` from return value. **Method**: N/A (Function Signature) **Endpoint**: N/A ### `parseArgs(rawArgs, argsDef)` **Description**: Parse input arguments and apply defaults. **Method**: N/A (Function Signature) **Endpoint**: N/A ### `renderUsage(cmd, parent?)` **Description**: Render command usage to a string. **Method**: N/A (Function Signature) **Endpoint**: N/A ### `showUsage(cmd, parent?)` **Description**: Render usage and print to console. **Method**: N/A (Function Signature) **Endpoint**: N/A ### `defineCittyPlugin(def)` **Description**: Type helper for defining plugins. **Method**: N/A (Function Signature) **Endpoint**: N/A ``` -------------------------------- ### Define and Run CLI Commands with Citty Source: https://github.com/unjs/citty/blob/main/AGENTS.md The core API allows developers to define commands using defineCommand and execute them via runMain. These functions handle argument parsing, help text generation, and command lifecycle management. ```typescript import { defineCommand, runMain } from "citty"; const main = defineCommand({ meta: { name: "my-cli", version: "1.0.0", description: "My CLI tool" }, args: { verbose: { type: "boolean", description: "Enable verbose logging" } }, run({ args }) { console.log("Running with verbose:", args.verbose); } }); runMain(main); ``` -------------------------------- ### Utility Functions for Argument Parsing and Usage Source: https://github.com/unjs/citty/blob/main/AGENTS.md Citty provides utility functions to manually parse arguments or generate help documentation strings. These are useful for building custom CLI interfaces or debugging command definitions. ```typescript import { parseArgs, renderUsage } from "citty"; const argsDef = { name: { type: "string" } }; // Parse raw arguments const parsed = parseArgs(["--name", "John"], argsDef); // Generate help text const help = renderUsage(myCommand); ``` -------------------------------- ### Parse command-line arguments with Citty Source: https://context7.com/unjs/citty/llms.txt Shows how to use parseArgs to convert raw CLI input into a typed object. It supports positional arguments, type coercion, default values, and case-agnostic access. ```javascript import { parseArgs } from "citty"; const argsDef = { name: { type: "positional", description: "User name", required: true, }, age: { type: "string", description: "User age", }, verbose: { type: "boolean", description: "Enable verbose output", alias: ["v"], default: false, }, format: { type: "enum", options: ["json", "text", "yaml"], default: "text", }, }; const args = parseArgs(["john", "--age", "25", "-v", "--format=json"], argsDef); console.log(args.name); console.log(args.age); console.log(args.verbose); console.log(args.v); console.log(args.format); console.log(args._); const args2 = parseArgs(["--output-dir", "./dist"], { "output-dir": { type: "string" }, }); console.log(args2["output-dir"]); console.log(args2.outputDir); ``` -------------------------------- ### Lazy Loading Sub-Commands in Citty Source: https://github.com/unjs/citty/blob/main/README.md This snippet demonstrates how to implement lazy loading for sub-commands in Citty. This approach improves performance for large CLIs by only importing commands when they are actually invoked. ```javascript import { defineCommand, runMain } from "citty"; const main = defineCommand({ meta: { name: "hello", version: "1.0.0", description: "My Awesome CLI App" }, subCommands: { sub: () => import("./sub.mjs").then((m) => m.default), }, }); // Assuming './sub.mjs' exports a command named 'default' // runMain(main); ``` -------------------------------- ### Define Command with Arguments - JavaScript Source: https://github.com/unjs/citty/blob/main/README.md Defines a command using `defineCommand` with various argument types: positional, boolean, string, enum, and aliases. The `run` function demonstrates how to access and use these arguments. This function is the core of command definition in Citty. ```javascript const main = defineCommand({ args: { name: { type: "positional", description: "Your name", required: true }, friendly: { type: "boolean", description: "Use friendly greeting", alias: ["f"] }, greeting: { type: "string", description: "Custom greeting", default: "Hello" }, level: { type: "enum", description: "Log level", options: ["debug", "info", "warn", "error"], default: "info", }, }, run({ args }) { console.log(`${args.greeting} ${args.name}! (level: ${args.level})`); }, }); ``` -------------------------------- ### Define CLI Argument Types in Citty Source: https://context7.com/unjs/citty/llms.txt Demonstrates how to define positional, string, boolean, and enum arguments within a Citty command. It showcases validation options, aliases, and default values for flexible CLI input handling. ```javascript import { defineCommand, runMain } from "citty"; const command = defineCommand({ meta: { name: "example", description: "Argument types demo" }, args: { file: { type: "positional", description: "Input file path", required: true, valueHint: "FILE", }, output: { type: "positional", description: "Output directory", required: false, default: "./dist", }, config: { type: "string", description: "Config file path", alias: ["c"], valueHint: "PATH", default: "config.json", }, verbose: { type: "boolean", description: "Enable verbose output", alias: ["v"], default: false, }, cache: { type: "boolean", description: "Enable caching", negativeDescription: "Disable caching", default: true, }, format: { type: "enum", description: "Output format", options: ["json", "yaml", "toml"], default: "json", }, apiKey: { type: "string", description: "API key for authentication", required: true, alias: ["k"], }, }, run({ args }) { console.log("File:", args.file); console.log("Output:", args.output); console.log("Config:", args.config); console.log("Verbose:", args.verbose); console.log("Cache:", args.cache); console.log("Format:", args.format); console.log("API Key:", args.apiKey); }, }); runMain(command); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.