### Clone and Setup ZCF Project Source: https://github.com/ufomiao/zcf/blob/main/docs/en/development/index.md Instructions to fork, clone the ZCF repository, install dependencies using pnpm, and verify the installation by running tests and type checks. ```bash # Fork and clone repository git clone https://github.com/YOUR_USERNAME/zcf.git cd zcf # Install dependencies pnpm install # Verify installation pnpm test:run pnpm typecheck ``` -------------------------------- ### Verifying Development Environment Setup Source: https://github.com/ufomiao/zcf/blob/main/docs/en/development/contributing.md Commands to verify the development environment by running tests, type checking, and linting. These checks ensure your setup is correct. ```bash # Run tests to ensure environment is normal pnpm test:run # Type checking pnpm typecheck # Code checking pnpm lint ``` -------------------------------- ### Testing MCP Service Functionality Source: https://github.com/ufomiao/zcf/blob/main/docs/en/features/mcp.md Provides example prompts to test the functionality of installed MCP services like Context7, Open Web Search, and DeepWiki. ```bash # Context7 Test Please query the latest documentation for React hooks # Open Web Search Test Search for the latest Vue 3.5 update content # DeepWiki Test Query the documentation for TypeScript official repository ``` -------------------------------- ### Install Output Styles with npx zcf init Source: https://github.com/ufomiao/zcf/blob/main/docs/en/best-practices/output-styles.md Demonstrates how to install output styles using the `npx zcf init` command. It shows options for installing all styles, specific styles by comma-separated IDs, or skipping installation entirely. ```bash npx zcf init -o all npx zcf init -o engineer-professional,nekomata-engineer npx zcf init -o skip ``` -------------------------------- ### Manually Install Playwright Browsers Source: https://github.com/ufomiao/zcf/blob/main/docs/en/advanced/troubleshooting.md Guide to resolving Playwright browser download failures during initial setup. This includes manually initiating the browser download and setting a download host environment variable if a proxy is required. ```bash # 1. Manually install browser npx playwright install # 2. Set environment variable (if proxy needed) export PLAYWRIGHT_DOWNLOAD_HOST=https://npm.taobao.org/mirrors # 3. Wait for download to complete (may take a few minutes) # 4. Check browser installation npx playwright --version ``` -------------------------------- ### Installing Project Dependencies Source: https://github.com/ufomiao/zcf/blob/main/docs/en/development/contributing.md Command to install all necessary project dependencies using the pnpm package manager. Ensure you have pnpm installed before running this. ```bash # Install dependencies using pnpm pnpm install ``` -------------------------------- ### Run ZCF Interactive Menu Source: https://github.com/ufomiao/zcf/blob/main/README.md Execute the ZCF command to open an interactive menu for guiding users through installation and updates. This is the recommended way to start with ZCF. ```bash npx zcf ``` -------------------------------- ### JavaScript: Automate BMad Installation with Expect Source: https://github.com/ufomiao/zcf/blob/main/templates/claude-code/en/workflow/bmad/commands/bmad-init.md This snippet automates the installation of the BMad Method using the `expect` tool. It checks for `expect` availability and uses it to script interactive prompts during the installation of `bmad-method@latest`. If `expect` is not found, it falls back to a manual interactive installation. ```javascript const { execSync } = require('node:child_process') const fs = require('node:fs') const path = require('node:path') // Check if expect tool is available function checkExpectAvailability() { try { execSync('which expect', { stdio: 'ignore' }) return true } catch (error) { return false } } // Use expect to automate interactive installation function installWithExpect() { const expectScript = ` spawn npx bmad-method@latest install -f -d . -i claude-code expect "What would you like to do?" send "1\r" expect "How would you like to proceed?" send "1\r" expect eof ` execSync(`expect -c '${expectScript}'`, { stdio: 'inherit', cwd: process.cwd(), shell: true }) } // Fallback installation method function fallbackInstallation() { console.log('âš ī¸ expect tool not found, using interactive installation') console.log('Please follow the installation prompts and select:') console.log(' 1. Choose "Upgrade BMad core" when prompted') console.log(' 2. Choose "Backup and overwrite modified files" when prompted') console.log('') execSync('npx bmad-method@latest install -f -d . -i claude-code', { stdio: 'inherit', cwd: process.cwd(), shell: true }) } async function initBmad() { // Check if already installed and get version const manifestPath = path.join(process.cwd(), '.bmad-core', 'install-manifest.yaml') let needsInstall = true let currentVersion = null if (fs.existsSync(manifestPath)) { try { // Simple version check - just check if file exists // Full YAML parsing would require js-yaml package const manifestContent = fs.readFileSync(manifestPath, 'utf8') const versionMatch = manifestContent.match(/version:\s*(.+)/) if (versionMatch) { currentVersion = versionMatch[1].trim() } // Get latest version from npm const latestVersion = execSync('npm view bmad-method version', { encoding: 'utf8' }).trim() if (currentVersion === latestVersion) { console.log(`✅ BMad Method is up to date (v${currentVersion}) `) console.log('You can use BMad commands to begin your workflow') needsInstall = false } else { console.log(`🔄 BMad Method update available: v${currentVersion} → v${latestVersion}`) } } catch (error) { console.log('âš ī¸ Could not verify BMad version, will reinstall') } } if (needsInstall === false) { return } // Install BMad - Using expect-first approach console.log('🚀 Installing BMad Method...') try { const hasExpect = checkExpectAvailability() if (hasExpect) { console.log('📋 Using automated installation (expect tool available)') installWithExpect() } else { fallbackInstallation() } console.log('') console.log('✅ BMad Method installed successfully!') console.log('') console.log('═══════════════════════════════════════════════════════════════') console.log('📌 IMPORTANT: Please restart Claude Code to load BMad agents') console.log('═══════════════════════════════════════════════════════════════') console.log('') console.log('📂 Installation Details:') console.log(' â€ĸ All agents and task commands are installed in:') console.log(' .claude/commands/BMad/') console.log('') console.log('🔧 Git Configuration (Optional):') console.log(' If you prefer not to commit BMad workflow files, add these to .gitignore:') console.log(' â€ĸ .bmad-core') console.log(' â€ĸ .claude/commands/BMad') console.log(' â€ĸ docs/') console.log('') console.log('🚀 Getting Started:') console.log(' 1. Restart Claude Code') console.log(' 2. For first-time users, run:') console.log(' /BMad:agents:bmad-orchestrator *help') console.log(' This will start the BMad workflow guidance system') console.log('') console.log('💡 Tip: The BMad Orchestrator will help you choose the right workflow') console.log(' and guide you through the entire development process.') } catch (error) { console.error('❌ Installation failed:', error.message) console.log('') console.log('đŸ› ī¸ Manual Installation Guide:') console.log('Please run the following command and follow the prompts:') console.log(' npx bmad-method@latest install -f -d . -i claude-code') console.log('') console.log('Installation Tips:') console.log(' 1. When asked "What would you like to do?", choose the first option') console.log(' 2. When asked "How would you like to proceed?", choose "Backup and overwrite"') console.log('') console.log('💡 Tip: For automated installation, consider installing expect tool:') console.log(' â€ĸ macOS: brew install expect') console.log(' â€ĸ Ubuntu: sudo apt-get install expect') console.log(' â€ĸ CentOS: sudo yum install expect') } } // Execute initBmad() ``` -------------------------------- ### Optimize ZCF MCP Service Installation (Bash) Source: https://github.com/ufomiao/zcf/blob/main/docs/en/best-practices/tips.md Demonstrates how to optimize ZCF by installing only necessary MCP services. It shows the command to install specific services like 'context7' and 'open-websearch', and how to view all available services. ```bash # Only install necessary services npx zcf init -s -m context7,open-websearch # View all available services npx zcf # Select 4 (Configure MCP), view list ``` -------------------------------- ### Install Dependencies with pnpm Source: https://github.com/ufomiao/zcf/blob/main/CONTRIBUTING.md After cloning the repository, this command installs all project dependencies using pnpm. This is a prerequisite for running the project and its development commands. Ensure you have pnpm version 9.15.9+ installed. ```bash pnpm install ``` -------------------------------- ### Interactive ZCF Initialization - Step 3: Detect and Install Claude Code Source: https://github.com/ufomiao/zcf/blob/main/docs/en/getting-started/installation.md Checks for Claude Code installation and prompts the user to install it if not found. Offers multiple installation methods like npm, homebrew, curl, powershell, and cmd, with automatic platform detection and upgrade capabilities. ```bash ? Claude Code not detected, automatically install? (Y/n) ``` ```bash ? Select installation method for Claude Code: ❯ npm [Recommended] - Install via npm (works on all platforms) homebrew [Recommended] - Install via Homebrew (macOS/Linux) curl - Install via curl script (Linux/macOS/WSL) powershell - Install via PowerShell script (Windows) cmd - Install via CMD script (Windows) ``` -------------------------------- ### zcf CLI Initialization with Presets vs. Custom Source: https://github.com/ufomiao/zcf/blob/main/docs/en/advanced/api-providers.md This example contrasts the recommended method of initializing zcf using provider presets (-p) with the less recommended approach of manually specifying all parameters (-t, -k, -u, -M). Using presets simplifies configuration and ensures compatibility. ```bash # Recommended: Use preset npx zcf init -s -p 302ai -k "sk-xxx" # Not recommended: Manually configure all parameters npx zcf init -s -t api_key -k "sk-xxx" -u "https://api.302.ai/cc" -M "claude-sonnet-4-5" ``` -------------------------------- ### Install Codex CLI Source: https://github.com/ufomiao/zcf/blob/main/docs/en/advanced/troubleshooting.md Instructions for installing the Codex CLI, including checking Node.js version requirements, manual installation, permission handling, and using nvm for Node.js version management. ```bash # 1. Check Node.js version node --version # Requires >= 18 # 2. Manually install Codex CLI npm install -g @openai/codex # 3. Check permissions (macOS/Linux) sudo npm install -g @openai/codex # 4. Use nvm to manage Node.js (recommended) nvm install 20 nvm use 20 npm install -g @openai/codex # 5. Verify installation codex --version ``` -------------------------------- ### ZCF CLI: Using API Provider Presets Source: https://github.com/ufomiao/zcf/blob/main/docs/en/getting-started/installation.md Shows how to use ZCF with API provider presets for simplified configuration, requiring only the provider name and API key. Examples include 302.AI, GLM, MiniMax, and Kimi. ```bash # Use 302.AI provider (recommended) npx zcf i -s -p 302ai -k "sk-xxx" # Other providers npx zcf i -s -p glm -k "sk-xxx" # GLM npx zcf i -s -p minimax -k "sk-xxx" # MiniMax npx zcf i -s -p kimi -k "sk-xxx" # Kimi ``` -------------------------------- ### Interactive Installation with ZCF Source: https://github.com/ufomiao/zcf/blob/main/docs/en/features/mcp.md Initiates an interactive installation process for MCP services via the ZCF menu. Users can select services, enter API keys, and view descriptions. ```bash npx zcf # Select 4. Configure MCP ``` -------------------------------- ### Initialize ZCF CLI (Bash) Source: https://context7.com/ufomiao/zcf/llms.txt Demonstrates various ways to initialize ZCF using the command-line interface. Supports interactive setup, direct initialization, non-interactive modes with provider presets, and multi-language/multi-configuration setups. ```bash # Interactive mode - opens menu for complete setup npx zcf # Direct initialization with all prompts npx zcf i # Non-interactive mode with provider preset (302.AI example) npx zcf i --skip-prompt --provider 302ai --api-key "sk-xxxxx" # Complete non-interactive setup with all options npx zcf i -s \ --provider glm \ --api-key "your-api-key" \ --config-action backup \ --mcp-services all \ --workflows all \ --output-styles engineer-professional,nekomata-engineer \ --default-output-style engineer-professional \ --install-cometix-line true # Multi-language setup (Chinese interface, English AI output) npx zcf i --lang zh-CN --ai-output-lang en # Multi-configuration setup from JSON npx zcf i -s --api-configs '[ {"provider":"302ai","key":"sk-xxx","name":"302AI","default":true}, {"provider":"glm","key":"glm-xxx","name":"GLM"} ]' # Multi-configuration from file npx zcf i -s --api-configs-file ./api-configs.json ``` -------------------------------- ### Interactive ZCF Initialization - Step 4: Handle Existing Configuration Source: https://github.com/ufomiao/zcf/blob/main/docs/en/getting-started/installation.md Addresses the scenario where existing configuration files are detected, offering options to backup and overwrite, update documents only, merge configurations, or skip the update. ```bash ? Existing configuration files detected, how to handle? ❯ Backup and Overwrite - Backup existing configuration to ~/.claude/backup/ Update Documents Only - Only update workflows and documents, keep existing API configuration Merge Configuration - Merge with existing configuration, preserve user customizations Skip - Skip configuration update ``` -------------------------------- ### Conventional Commits Format Example (Bash) Source: https://github.com/ufomiao/zcf/blob/main/docs/en/development/contributing.md Shows examples of commit messages following the Conventional Commits specification. These examples cover different types like 'feat', 'fix', and 'docs', including commits with and without detailed descriptions. ```bash # New feature git commit -m "feat(config): add multi-config support" ``` ```bash # Bug fix git commit -m "fix(ccr): resolve port conflict issue" ``` ```bash # Documentation update git commit -m "docs(readme): update installation instructions" ``` ```bash # With detailed description git commit -m "feat(workflow): add new workflow template - Add six-phase workflow template - Support custom workflow configuration - Update workflow installer to handle new template" ``` -------------------------------- ### Interactive ZCF Initialization - Step 1: Select Configuration Language Source: https://github.com/ufomiao/zcf/blob/main/docs/en/getting-started/installation.md Guides the user to select the configuration language for ZCF. Options include English, Simplified Chinese, and Japanese, with recommendations based on token consumption and user preference. ```bash ? Select configuration language: ❯ English (en) - English version (lower token consumption) įŽ€äŊ“中文 (zh-CN) - Chinese version (convenient for Chinese users to customize) æ—ĨæœŦčĒž (ja) - Japanese version ``` -------------------------------- ### Check Cometix Status Source: https://github.com/ufomiao/zcf/blob/main/src/utils/cometix/CLAUDE.md Illustrates how to retrieve the current status of Cometix. The `getCometixStatus` function returns an object containing installation and running status, as well as the installed version. This example shows how to check if Cometix is installed and running, and log its version. ```typescript const status = await getCometixStatus() if (status.installed && status.running) { console.log(`Cometix v${status.version} is running`) } ``` -------------------------------- ### TypeScript Code Style Example Source: https://github.com/ufomiao/zcf/blob/main/docs/en/development/contributing.md Demonstrates recommended TypeScript code style practices, including import statements, indentation, and avoiding unnecessary awaits. It contrasts good and bad examples. ```typescript // ✅ Good example import type { Config } from '../types/config' import { readConfig } from '../utils/config' export async function processConfig(): Promise { const config = await readConfig() return config } // ❌ Avoid import {Config} from "../types/config"; // Using double quotes and semicolons const config = await readConfig(); // Avoid unnecessary await ``` -------------------------------- ### ZCF CLI: Customizing Output Styles and Workflows Source: https://github.com/ufomiao/zcf/blob/main/docs/en/getting-started/installation.md Demonstrates how to specify custom output styles and workflows during ZCF initialization using command-line arguments. ```bash # Specify output styles and workflows npx zcf i -s -p 302ai -k "sk-xxx" \ --output-styles engineer-professional,nekomata-engineer \ --workflows commonTools,sixStepsWorkflow \ --default-output-style engineer-professional ``` -------------------------------- ### Interactive ZCF Initialization - Step 5: Configure API Source: https://github.com/ufomiao/zcf/blob/main/docs/en/getting-started/installation.md Presents options for API authentication, including official login, auth token (OAuth), API key, CCR Proxy configuration, or skipping manual configuration. ```bash ? Select API authentication method ❯ Use Official Login Use Auth Token (OAuth authentication) Use API Key (Key authentication) Configure CCR Proxy (Claude Code Router) Skip (configure manually later) ``` -------------------------------- ### Running the ZCF Development Server Source: https://github.com/ufomiao/zcf/blob/main/docs/en/development/contributing.md Commands to run the ZCF project in development mode with hot-reloading or to build and start the compiled version. ```bash # Run development version using tsx (supports hot reload) pnpm dev # Or directly run compiled version pnpm build pnpm start ``` -------------------------------- ### Initialize ZCF Environment (Interactive) Source: https://github.com/ufomiao/zcf/blob/main/docs/en/cli/init.md Executes the interactive wizard for ZCF initialization, guiding users through setup steps. This is the recommended mode for a guided experience. It uses 'npx zcf init', 'npx zcf i', or 'npx zcf' followed by menu selection. ```bash npx zcf init # Or use abbreviation npx zcf i # Or through main menu npx zcf # Then select 1 (Complete Initialization) ``` -------------------------------- ### JSDoc Comment Example in TypeScript Source: https://github.com/ufomiao/zcf/blob/main/docs/en/development/contributing.md Illustrates the use of JSDoc comments for documenting public APIs in TypeScript. This includes a description of the function, its parameters, and its return value. ```typescript /** * Reads configuration from the specified file * @param filePath - Path to the configuration file * @returns Configuration object or null if file doesn't exist */ export function readConfig(filePath: string): Config | null { // Implementation } ``` -------------------------------- ### ZCF Provider Presets Initialization (Bash) Source: https://github.com/ufomiao/zcf/blob/main/docs/en/cli/ccr.md This command-line instruction demonstrates how to initialize ZCF with provider presets using Node Package Execute (npx). It guides the user through selecting initialization options and choosing from supported provider presets like 302.AI, GLM, MiniMax, or a custom configuration. ```bash npx zcf ccr # Select 1. Initialize CCR # Select provider preset ``` -------------------------------- ### Configure CCR Proxy Management Source: https://github.com/ufomiao/zcf/blob/main/docs/en/getting-started/installation.md CLI commands and menu options for configuring and managing the CCR (Claude Code Router) proxy. This includes installation, starting the UI, service control, and status checks. ```bash npx zcf ccr After entering the CCR management menu, you can choose: - `1` Initialize CCR - Install and configure CCR - `2` Start UI - Start CCR Web interface - `3` Service Control - Start/Stop/Restart CCR service - `4` Check Status - View current CCR service status ``` -------------------------------- ### Initialize ZCF with API Provider Presets (Bash) Source: https://github.com/ufomiao/zcf/blob/main/docs/en/best-practices/tips.md Demonstrates how to initialize ZCF using API provider presets, significantly reducing the number of required parameters compared to the traditional method. It shows the simplified command using the '-p' flag for provider selection. ```bash # Traditional method (requires multiple parameters) npx zcf init -s \ -t api_key \ -k "sk-xxx" \ -u "https://api.302.ai/v1" \ -M "claude-sonnet-4-5" \ -F "claude-haiku-4-5" # Use preset (only 2 parameters needed) npx zcf init -s -p 302ai -k "sk-xxx" ``` -------------------------------- ### Configure Termux Environment for ZCF Source: https://github.com/ufomiao/zcf/blob/main/docs/en/advanced/troubleshooting.md This section explains how to ensure ZCF runs correctly in the Termux environment. It recommends using nvm to manage Node.js versions and provides installation steps. ```bash # ZCF supports Termux environment # Ensure using latest Node.js version # Use nvm (recommended) curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.0/install.sh | bash nvm install 20 ``` -------------------------------- ### Test Performance Limits with Vitest Source: https://github.com/ufomiao/zcf/blob/main/docs/en/development/testing.md Provides an example of how to test the performance of a critical operation within a specified time limit. This involves measuring the duration of an asynchronous function call. ```typescript it('should complete within time limit', async () => { const start = Date.now() await performOperation() const duration = Date.now() - start expect(duration).toBeLessThan(1000) // Complete within 1 second }) ``` -------------------------------- ### Complete ZCF Configuration Example (JSON) Source: https://github.com/ufomiao/zcf/blob/main/docs/en/cli/ccr.md This JSON object demonstrates a comprehensive configuration for the ZCF service, including logging, host, port, API keys, timeouts, proxy settings, provider details, and routing rules for various scenarios. It serves as a template for setting up ZCF. ```json { "LOG": true, "HOST": "127.0.0.1", "PORT": 3456, "APIKEY": "sk-zcf-x-ccr", "API_TIMEOUT_MS": "600000", "PROXY_URL": "", "Providers": [ { "name": "openrouter", "api_base_url": "https://openrouter.ai/api/v1/chat/completions", "api_key": "sk-xxx", "models": [ "google/gemini-2.5-pro-preview", "anthropic/claude-sonnet-4", "anthropic/claude-3.5-sonnet" ], "transformer": { "use": ["openrouter"] } }, { "name": "deepseek", "api_base_url": "https://api.deepseek.com/v1/chat/completions", "api_key": "sk-xxx", "models": ["deepseek-chat", "deepseek-reasoner"], "transformer": { "use": ["deepseek"], "deepseek-chat": { "use": ["tooluse"] } } }, { "name": "ollama", "api_base_url": "http://localhost:11434/v1/chat/completions", "api_key": "ollama", "models": ["qwen2.5-coder:latest"], "transformer": { "use": ["ollama"] } }, { "name": "gemini", "api_base_url": "https://generativelanguage.googleapis.com/v1beta/models/", "api_key": "sk-xxx", "models": ["gemini-2.5-flash", "gemini-2.5-pro"], "transformer": { "use": ["gemini"] } } ], "Router": { "default": "openrouter,google/gemini-2.5-pro-preview", "background": "deepseek,deepseek-chat", "think": "deepseek,deepseek-reasoner", "longContext": "openrouter,anthropic/claude-sonnet-4", "longContextThreshold": 60000, "webSearch": "gemini,gemini-2.5-flash" } } ``` -------------------------------- ### Creating a New Feature Branch Source: https://github.com/ufomiao/zcf/blob/main/docs/en/development/contributing.md Commands to create a new branch for development, starting from the latest main branch. Supports feature and bug fix branch naming conventions. ```bash # Create new branch from latest main branch git checkout main git pull upstream main # Create feature branch (use descriptive name) git checkout -b feat/your-feature-name # Or git checkout -b fix/your-bug-fix ``` -------------------------------- ### ZCF CLI for Worktree Management (Examples) Source: https://github.com/ufomiao/zcf/blob/main/templates/claude-code/en/workflow/git/commands/git-worktree.md Illustrates various command-line interface usages for the ZCF tool, covering worktree creation with different options, content migration scenarios, and essential management operations like listing, removing, and pruning worktrees. ```bash # Basic usage /git-worktree add feature-ui # create new branch 'feature-ui' from main/master /git-worktree add feature-ui -b my-feature # create new branch 'my-feature' with path 'feature-ui' /git-worktree add feature-ui -o # create and open in IDE directly # Content migration scenarios /git-worktree add feature-ui -b feature/new-ui # create new feature worktree /git-worktree migrate feature-ui --from main # migrate uncommitted changes /git-worktree migrate hotfix --stash # migrate stash content # Management operations /git-worktree list # view all worktrees /git-worktree remove feature-ui # remove unneeded worktree /git-worktree prune # clean invalid references ``` -------------------------------- ### Type-Safe Error Handling in TypeScript Source: https://github.com/ufomiao/zcf/blob/main/docs/en/development/contributing.md Provides an example of type-safe error handling using a try-catch block. It demonstrates how to safely access the error message, ensuring it's treated as a string. ```typescript try { await operation() } catch (error) { const message = error instanceof Error ? error.message : String(error) console.error(message) } ``` -------------------------------- ### Test Organization using Nested Describes Source: https://github.com/ufomiao/zcf/blob/main/docs/en/development/testing.md This example showcases how to organize tests by functionality using nested `describe` blocks in Vitest. This hierarchical structure improves test suite maintainability and makes it easier to locate specific tests. ```typescript describe('ConfigManager', () => { describe('readConfig', () => { it('should read valid config', () => {}) it('should return null if file missing', () => {}) }) describe('writeConfig', () => { it('should write config to file', () => {}) it('should create backup before write', () => {}) }) }) ``` -------------------------------- ### Initialize ZCF Configuration Repository with Git Source: https://github.com/ufomiao/zcf/blob/main/docs/en/advanced/configuration.md This snippet shows how to set up a Git repository for managing ZCF configuration files. It includes creating a directory, initializing Git, and setting up a `.gitignore` file to exclude sensitive information like API keys and private settings. ```bash # Create configuration repository mkdir ~/zcf-configs cd ~/zcf-configs git init # Add configuration files (note: exclude sensitive information) cat > .gitignore << EOF *.key auth.json settings.json config.toml EOF # Add templates and workflows (without sensitive information) git add prompts/ workflows/ templates/ git commit -m "Add ZCF templates and workflows" ``` -------------------------------- ### File System Mocking with Vitest Source: https://github.com/ufomiao/zcf/blob/main/docs/en/development/testing.md This example shows how to mock the file system's `readFile` function using Vitest's `vi.spyOn` to control its behavior during tests. It also demonstrates clearing mocks before each test using `beforeEach`. ```typescript import { describe, it, expect, vi, beforeEach } from 'vitest' import { readFile } from 'fs/promises' import { existsSync } from 'fs' describe('File Operations', () => { beforeEach(() => { // Clear mocks vi.clearAllMocks() }) it('should read file', async () => { // Mock readFile vi.spyOn(await import('fs/promises'), 'readFile') .mockResolvedValue('file content') const content = await readFile('test.txt') expect(content).toBe('file content') }) }) ``` -------------------------------- ### Interactive Prompt Mocking with Vitest and Inquirer Source: https://github.com/ufomiao/zcf/blob/main/docs/en/development/testing.md This example demonstrates mocking the `inquirer` library's `prompt` function using `vi.mock`. It allows tests to simulate user input and verify that the `promptUser` function handles the mocked response correctly. ```typescript import inquirer from 'inquirer' import { vi } from 'vitest' vi.mock('inquirer', () => ({ default: { prompt: vi.fn().mockResolvedValue({ choice: 'option1' }), }, })) it('should handle user input', async () => { const result = await promptUser() expect(result).toBe('option1') }) ``` -------------------------------- ### Automate ZCF Deployment with CI/CD Script Source: https://github.com/ufomiao/zcf/blob/main/docs/en/best-practices/tips.md Provides a bash script example for automated ZCF configuration deployment within a CI/CD pipeline. It reads API keys and provider information from environment variables for non-interactive initialization. ```bash #!/bin/bash # deploy-zcf.sh - Automated ZCF configuration deployment # Read configuration from environment variables API_KEY=${ZCF_API_KEY} PROVIDER=${ZCF_PROVIDER:-302ai} LANG=${ZCF_LANG:-zh-CN} # Non-interactive initialization npx zcf init -s \ --provider "$PROVIDER" \ --api-key "$API_KEY" \ --all-lang "$LANG" \ --mcp-services all \ --workflows all \ --output-styles all echo "ZCF configuration deployment completed" ``` -------------------------------- ### Check and Reconfigure MCP Service Source: https://github.com/ufomiao/zcf/blob/main/docs/en/advanced/troubleshooting.md Steps to diagnose and resolve issues with the MCP service not starting. This involves checking configuration files, reconfiguring MCP via the zcf CLI, and verifying service dependencies like npx, Playwright, and Exa API key. ```bash # 1. Check MCP configuration cat ~/.claude/settings.json | jq .mcpServers cat ~/.codex/config.toml | grep -A 10 mcp_server # 2. Reconfigure MCP npx zcf # Select 4 (Configure MCP) # 3. Check service dependencies # Context7: Requires npx available # Playwright: Requires browser environment # Exa: Requires EXA_API_KEY environment variable # 4. Test single service npx @context7/mcp-server ``` -------------------------------- ### Backup Configuration Example Source: https://github.com/ufomiao/zcf/blob/main/docs/en/cli/check-updates.md This command demonstrates a manual backup of the ZCF configuration file, typically located at `~/.claude/settings.json`. This is a recommended safety measure before performing updates. ```bash # Manual backup cp ~/.claude/settings.json ~/.claude/settings.json.backup ``` -------------------------------- ### Initialize zcf with Backup Source: https://github.com/ufomiao/zcf/blob/main/docs/en/cli/check-updates.md Demonstrates how to initialize the zcf project, which includes an automatic backup of configurations before updating. This is crucial for ensuring data safety during updates. ```bash # Initialize before updating (will backup configuration) npx zcf init # Or manually use backup functionality npx zcf i -s -r backup ``` -------------------------------- ### Vitest Unit Test for readConfig in TypeScript Source: https://github.com/ufomiao/zcf/blob/main/docs/en/development/testing.md An example of a unit test for the `readConfig` function using Vitest. This test mocks the Node.js `fs/promises` module to simulate reading a JSON configuration file and verifies that the function correctly parses and returns the configuration object. ```typescript import { describe, it, expect, vi } from 'vitest' import { readConfig } from '../utils/config' describe('readConfig', () => { it('should read valid JSON config', async () => { // Mock file system vi.mock('fs/promises', () => ({ readFile: vi.fn().mockResolvedValue('{"key": "value"}'), })) const config = await readConfig('config.json') expect(config).toEqual({ key: 'value' }) }) }) ``` -------------------------------- ### Testing and Reconfiguring API Keys Source: https://github.com/ufomiao/zcf/blob/main/docs/en/advanced/api-providers.md This sequence demonstrates a best practice for managing API keys: first, initialize with a test key, then test the connection, and finally reconfigure with the production key if the tests are successful. This minimizes the risk of configuration errors with production credentials. ```bash # 1. Initialize using preset npx zcf init -s -p 302ai -k "test-key" # 2. Test API connection # Test conversation in Claude Code or Codex # 3. If normal, reconfigure with production key npx zcf init -s -p 302ai -k "production-key" ``` -------------------------------- ### Combine Template and AI Output Languages with ZCF Source: https://github.com/ufomiao/zcf/blob/main/docs/en/advanced/configuration.md Demonstrates how to combine different template languages with AI output languages for flexible project setups. These examples show how to configure Chinese templates with English output, and vice-versa, catering to international teams or specific project requirements. ```bash # Chinese templates + English output npx zcf init --config-lang zh-CN --ai-output-lang en ``` ```bash # English templates + Chinese output npx zcf init --config-lang en --ai-output-lang zh-CN ``` -------------------------------- ### ZCF Initialization with Configuration Action (Bash) Source: https://github.com/ufomiao/zcf/blob/main/docs/en/advanced/configuration.md This snippet demonstrates how to initialize ZCF with specific configuration handling strategies using the `--config-action` flag. It allows for merging configurations or updating only documentation files. Ensure ZCF is installed and accessible via npx. ```bash npx zcf init -s --config-action merge npx zcf init -s --config-action docs-only ``` -------------------------------- ### Detect and Install Claude Code with ZCF Source: https://context7.com/ufomiao/zcf/llms.txt Manages the installation of Claude Code. This includes checking installation status, detecting the installed version, performing interactive or automated installations, and allowing for custom installation methods. ```typescript import { installClaudeCode, isClaudeCodeInstalled, getInstallationStatus, detectInstalledVersion, selectInstallMethod, executeInstallMethod, } from 'zcf' // Check installation status const installed = await isClaudeCodeInstalled() console.log('Claude Code installed:', installed) // Get detailed installation status const status = await getInstallationStatus() console.log('Has global:', status.hasGlobal) console.log('Has local:', status.hasLocal) console.log('Local path:', status.localPath) // Detect installed version const version = await detectInstalledVersion('claude-code') console.log('Installed version:', version) // Interactive installation with method selection await installClaudeCode(false) // Automated installation (uses npm by default) await installClaudeCode(true) // Custom installation method const method = await selectInstallMethod('claude-code') if (method) { const success = await executeInstallMethod(method, 'claude-code') console.log('Installation success:', success) } ``` -------------------------------- ### Main Codex Integration Operations - TypeScript Source: https://github.com/ufomiao/zcf/blob/main/src/utils/code-tools/CLAUDE.md Provides core operations for Codex integration, including setup, updates, status retrieval, and validation. It reports on installation, configuration status, version, current provider, and provider count. Dependencies include SupportedLang and CodexStatus interfaces. ```typescript export async function setupCodex(lang: SupportedLang): Promise export async function updateCodex(lang: SupportedLang): Promise export async function getCodexStatus(): Promise export async function validateCodexSetup(): Promise export interface CodexStatus { installed: boolean configured: boolean version?: string currentProvider?: string providersCount: number } ``` -------------------------------- ### ZCF Example Output Source: https://github.com/ufomiao/zcf/blob/main/templates/claude-code/en/workflow/git/commands/git-worktree.md A sample output from the ZCF tool, showcasing the successful creation of a worktree, copying of environment files, and prompts for IDE integration. This demonstrates the tool's feedback mechanism. ```bash ✅ Worktree created at ../.zcf/project-name/feature-ui ✅ Copied .env ✅ Copied .env.local 📋 Copied 2 environment file(s) from .gitignore đŸ–Ĩī¸ Open ../.zcf/project-name/feature-ui in IDE? [y/n]: y 🚀 Opening ../.zcf/project-name/feature-ui in VS Code... ```