### Post-Installation Guidance Source: https://github.com/dabit3/create-x402/blob/main/_autodocs/configuration.md These are the suggested commands to run after a project has been successfully scaffolded. They guide the user to navigate into the project, configure environment variables, and start the development server. ```bash Next steps: cd {projectName} Configure your .env file npm run dev ``` -------------------------------- ### Install and Run create-x402 with pnpm Source: https://github.com/dabit3/create-x402/blob/main/_autodocs/api-reference/integration.md Demonstrates installing create-x402 globally using pnpm and then running it via 'pnpm exec' or directly if installed globally. ```bash # Install create-x402 globally with pnpm pnpm add -g create-x402 # Run via pnpm exec (on Windows: pnpm exec npm) pnpm exec npx create-x402 # Or if installed globally create-x402 ``` -------------------------------- ### Local Development Setup for create-x402 Source: https://github.com/dabit3/create-x402/blob/main/_autodocs/api-reference/integration.md Steps to clone the create-x402 repository, install its dependencies locally, and run the tool directly from the command line using Node.js. ```bash # Clone repository git clone https://github.com/dabit3/create-x402.git cd create-x402 # Install dependencies npm install # Run locally node bin.js # Run with debugging NODE_DEBUG=child_process node bin.js ``` -------------------------------- ### Install and Run create-x402 with Yarn Source: https://github.com/dabit3/create-x402/blob/main/_autodocs/api-reference/integration.md Shows how to install create-x402 globally with Yarn and execute it using 'yarn create x402' or directly if installed globally. ```bash # Install create-x402 globally with Yarn yarn global add create-x402 # Run via yarn yarn create x402 # Or if installed globally create-x402 ``` -------------------------------- ### Install and Run create-x402 with Bun Source: https://github.com/dabit3/create-x402/blob/main/_autodocs/api-reference/integration.md Illustrates installing create-x402 globally using Bun and executing it with 'bun x create-x402'. ```bash # Install with bun bun add -g create-x402 # Run via bun bun x create-x402 ``` -------------------------------- ### NPM Installation Steps and Configuration Source: https://github.com/dabit3/create-x402/blob/main/_autodocs/api-reference/workflow.md Outlines the npm installation process, including the command used, spinner feedback, child process execution, and environment variable configuration. ```text Call: runStep(npmCommand, ["install", "--loglevel", "error", "--no-progress"], options) ↓ Spinner shows: "Installing dependencies" ↓ Child process spawns npm with: - cwd: target directory - stdio: "pipe" (silent mode) - env variables: npm_config_fund: "false" npm_config_audit: "false" NODE_OPTIONS: "--no-warnings" ↓ If progressItems defined: Spinner cycles through progress labels every progressInterval ms ↓ Process closes: If code === 0: Spinner shows "Dependencies installed" Resolve promise If code !== 0: Spinner shows "npm install failed" Print stderr/stdout captured during silent execution Exit with npm's code ``` -------------------------------- ### Template Example using Default Repo Source: https://github.com/dabit3/create-x402/blob/main/_autodocs/types.md Example of a Template object that uses the default coinbase/x402 repository structure. ```javascript // Template using coinbase/x402 examples { value: "servers/express", title: "Express server", description: "Express.js with x402-express middleware" // No repo field - uses coinbase/x402/examples/typescript/servers/express } ``` -------------------------------- ### Custom Project Creation Script (Bash) Source: https://github.com/dabit3/create-x402/blob/main/_autodocs/api-reference/integration.md A bash script that wraps create-x402 to automate project scaffolding and subsequent initialization steps like Git setup and dependency installation. ```bash #!/bin/bash # custom-scaffold.sh # Run create-x402 npx create-x402 # Post-creation steps PROJECT_DIR="$1" if [ -d "$PROJECT_DIR" ]; then cd "$PROJECT_DIR" # Run custom initialization git init git add . git commit -m "Initial scaffolding from create-x402" # Install development tools npm install --save-dev @typescript-eslint/eslint-plugin eslint # Copy custom configuration cp ../config/eslint.config.json . fi ``` -------------------------------- ### Quick Start Project Creation Source: https://github.com/dabit3/create-x402/blob/main/README.md Use this command to quickly scaffold a new x402 project. It will prompt you to select a template and name your project. ```bash npx create-x402 ``` -------------------------------- ### Execute npm Install with Error Handling Source: https://github.com/dabit3/create-x402/blob/main/_autodocs/errors.md Runs the npm install command with specific configurations for logging and progress. It captures and displays errors if the installation fails. ```javascript await runStep(npmCommand, ["install", "--loglevel", "error", "--no-progress"], { startText: installLabel, successText: "Dependencies installed", failureText: "npm install failed", silent: true, env: { npm_config_fund: "false", npm_config_audit: "false", NODE_OPTIONS: `${process.env.NODE_OPTIONS ?? ""} --no-warnings` }, cwd: target }); ``` -------------------------------- ### Debug Installation Issues Source: https://github.com/dabit3/create-x402/blob/main/_autodocs/INDEX.md Run the create-x402 CLI with verbose logging enabled to help diagnose installation problems. This will provide more detailed output during the process. ```bash npm_config_loglevel=verbose npx create-x402 ``` -------------------------------- ### Initialization Steps Source: https://github.com/dabit3/create-x402/blob/main/_autodocs/api-reference/workflow.md The initial sequence of commands and script executions when starting the create-x402 scaffolding process. ```bash User runs: npx create-x402 ↓ bin.js sets NODE_NO_WARNINGS = "1" ↓ bin.js imports and runs cli.js ↓ CLI displays headline with chalk formatting ``` -------------------------------- ### Install create-x402 with npm Source: https://github.com/dabit3/create-x402/blob/main/_autodocs/api-reference/integration.md Installs create-x402 using npm, which also generates a package-lock.json file to lock dependency versions. ```bash npm install create-x402 # Creates package-lock.json with locked versions of chalk, giget, ora, prompts ``` -------------------------------- ### RunStepOptions Example Usage Source: https://github.com/dabit3/create-x402/blob/main/_autodocs/types.md An example of how to construct the RunStepOptions object with various configuration properties. ```javascript const options = { startText: "Installing dependencies", successText: "Dependencies installed", failureText: "npm install failed", silent: true, env: { npm_config_fund: "false", npm_config_audit: "false" }, cwd: "/path/to/project", progressItems: ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"], progressInterval: 80 }; ``` -------------------------------- ### Template Example with External Repo Source: https://github.com/dabit3/create-x402/blob/main/_autodocs/types.md Example of a Template object configured with an external GitHub repository. ```javascript // Template with external repo { value: "starter-kit", title: "Starter kit", description: "Full-featured x402 starter with Express, OpenAI, and Docker", repo: "dabit3/x402-starter-kit" } ``` -------------------------------- ### Post-Creation Steps Source: https://github.com/dabit3/create-x402/blob/main/_autodocs/README.md Commands to run after a project has been successfully created. This includes navigating to the project directory, configuring environment variables, and starting the development server. ```bash cd # Configure environment variables (template-specific) # View .env.example for required variables npm run dev ``` -------------------------------- ### Add Tests to create-x402 Source: https://github.com/dabit3/create-x402/blob/main/_autodocs/api-reference/integration.md Example of how to add tests to the create-x402 project. Currently, the module structure makes direct testing difficult. ```javascript // test/cli.test.js import { test } from "node:test"; import assert from "node:assert"; test("runStep executes successfully", async (t) => { // Would require exported functions // Currently difficult due to module structure }); ``` -------------------------------- ### Basic Usage with NPM Source: https://github.com/dabit3/create-x402/blob/main/_autodocs/README.md Initiates the create-x402 tool using npm. Users will be guided through interactive prompts to select a template and specify a project name. ```bash npx create-x402 # Follow interactive prompts to select template and project name ``` -------------------------------- ### CLIResponse Example Usage Source: https://github.com/dabit3/create-x402/blob/main/_autodocs/types.md An example of the response object obtained after user interaction with the CLI prompts. ```javascript const response = { template: "servers/express", projectName: "my-payment-api" }; ``` -------------------------------- ### Configure Monorepo with pnpm-workspace.yaml Source: https://github.com/dabit3/create-x402/blob/main/_autodocs/api-reference/integration.md Sets up a pnpm monorepo by defining workspace packages in 'pnpm-workspace.yaml' after creating projects with create-x402. Then installs all workspace projects. ```bash # Create projects normally npx create-x402 # Creates server-api npx create-x402 # Creates server-auth # Then add workspace configuration cat > pnpm-workspace.yaml << 'EOF' packages: - 'server-api' - 'server-auth' EOF # Install all workspace projects pnpm install ``` -------------------------------- ### Retry npm Install with Verbosity Source: https://github.com/dabit3/create-x402/blob/main/_autodocs/errors.md If npm install fails, navigate to the project directory and retry the command with the --verbose flag. This allows for detailed inspection of the installation process. ```bash cd npm install --verbose ``` -------------------------------- ### Create New x402 Project Source: https://github.com/dabit3/create-x402/blob/main/_autodocs/INDEX.md Initiates the creation of a new x402 project using the CLI. Follow the interactive prompts to select a template and configure your project. Dependencies will be installed automatically. ```bash npx create-x402 # Answer prompts # Project created with dependencies installed ``` -------------------------------- ### Manual Testing of create-x402 Templates Source: https://github.com/dabit3/create-x402/blob/main/_autodocs/api-reference/integration.md Guide for manually testing a specific template generated by create-x402. This involves running the tool, selecting a template, completing the process, and verifying the project. ```bash # Manual testing npx create-x402 # Select a template # Follow through to completion # Verify project works: cd npm run dev ``` -------------------------------- ### Use a Faster npm Registry Mirror Source: https://github.com/dabit3/create-x402/blob/main/_autodocs/api-reference/integration.md To speed up template installation, configure npm to use a faster registry mirror. ```bash # Or use a faster registry mirror npm_config_registry=https://registry.npmjs.org/ npx create-x402 ``` -------------------------------- ### main() Source: https://github.com/dabit3/create-x402/blob/main/_autodocs/api-reference/cli.md The main entry point for the CLI, orchestrating the entire project creation workflow from template selection to dependency installation. It is automatically invoked and not typically called programmatically. ```APIDOC ## main() ### Description Main entry point that orchestrates the template selection, project creation, and dependency installation workflow. ### Behavior Executes the following workflow: 1. Prompts user to select a template from available options 2. Prompts user for project name 3. Validates project name (ensures target directory doesn't exist) 4. Downloads template from GitHub 5. Fixes workspace dependencies in package.json if needed 6. Installs npm dependencies 7. Displays success message with next steps ### Parameters None ### Return Type `Promise` — Resolves when the full workflow completes successfully or rejects/exits on error ### Throws - **Process exit code 1** if target directory already exists - **Process exit code 1** if template download fails - **Process exit code N** if npm install fails (where N is the npm error code) ### Example ```javascript // This is the main CLI entry point, automatically invoked via ./bin.js // Not typically called programmatically import("./cli.js").then(() => { // CLI execution begins }); ``` ### Source `cli.js:191-272` ``` -------------------------------- ### ChildProcess Example Usage Source: https://github.com/dabit3/create-x402/blob/main/_autodocs/types.md Demonstrates how to use Node.js's built-in ChildProcess interface, specifically with the spawn function, to execute commands and handle their output and exit codes. ```javascript import { spawn } from "node:child_process"; const child = spawn("npm", ["install"], { cwd: targetDir, stdio: "inherit", env: { ...process.env } }); child.on("error", (err) => { console.error(err); process.exit(1); }); child.on("close", (code) => { if (code !== 0) process.exit(code); console.log("Success"); }); ``` -------------------------------- ### Set Environment Variables During npm Install Source: https://github.com/dabit3/create-x402/blob/main/_autodocs/api-reference/workflow.md Configures npm install by setting specific npm_config flags and appending to NODE_OPTIONS to disable warnings. ```javascript npm_config_fund: "false" npm_config_audit: "false" NODE_OPTIONS: "--no-warnings" (appended to existing) ``` -------------------------------- ### Workspace Dependency Transformation Example Source: https://github.com/dabit3/create-x402/blob/main/_autodocs/api-reference/workflow.md Shows the transformation of 'workspace:*' dependencies to 'latest' in package.json for npm compatibility. ```json // Before { "dependencies": { "x402-core": "workspace:*", "x402-express": "workspace:^1.0.0" } } // After { "dependencies": { "x402-core": "latest", "x402-express": "latest" } } ``` -------------------------------- ### Run Step with Progress Tracking Source: https://github.com/dabit3/create-x402/blob/main/_autodocs/api-reference/workflow.md Executes a command with optional progress tracking using an ora spinner. Useful for long-running operations like package installation. ```javascript await runStep("npm", ["install"], { startText: "Installing", progressItems: ["⠋", "⠙", "⠹", "⠸"], progressInterval: 200 }); ``` -------------------------------- ### Increase Template Installation Timeout Source: https://github.com/dabit3/create-x402/blob/main/_autodocs/api-reference/integration.md If templates take too long to install due to large dependencies or slow networks, increase the fetch timeout. ```bash # Increase timeout npm_config_fetch_timeout=180000 npx create-x402 ``` -------------------------------- ### Environment Variable Merging Logic Source: https://github.com/dabit3/create-x402/blob/main/_autodocs/api-reference/workflow.md Demonstrates the merging strategy for environment variables, starting with the user's environment and then applying create-x402 specific overrides. ```javascript env: { ...process.env, // Start with user's env ...{ npm_config_fund: "false" } // Override/add specific vars } ``` -------------------------------- ### Start and Manage Ora Spinner Source: https://github.com/dabit3/create-x402/blob/main/_autodocs/types.md Use the 'ora' library to display a spinner during asynchronous operations. Start the spinner with a message, update its status to succeed or fail, or stop it without a message. ```javascript import ora from "ora"; const spinner = ora("Downloading template").start(); try { await downloadTemplate(repo, { dir: target }); spinner.succeed("Template downloaded"); } catch (err) { spinner.fail("Download failed"); process.exit(1); } ``` -------------------------------- ### Check Node.js and npm Versions Source: https://github.com/dabit3/create-x402/blob/main/_autodocs/errors.md Verify the installed versions of Node.js and npm. This is crucial for ensuring compatibility with the template's specified engines in package.json. ```bash node --version npm --version ``` -------------------------------- ### Execute Child Process with Progress Source: https://github.com/dabit3/create-x402/blob/main/_autodocs/api-reference/cli.md Executes a child process with progress tracking and formatted output using an ora spinner. Use this to run commands like npm install with clear feedback. ```javascript import { spawn } from "node:child_process"; import ora from "ora"; // Execute npm install with progress tracking await runStep("npm", ["install"], { startText: "Installing dependencies", successText: "Dependencies installed", failureText: "npm install failed", silent: true, cwd: "/path/to/project", progressItems: [".", "..", "..."], progressInterval: 200 }); // The spinner will show "Installing dependencies ." then "Installing dependencies .." etc // until the command completes ``` -------------------------------- ### Initial Function Behavior for Text Prompt Source: https://github.com/dabit3/create-x402/blob/main/_autodocs/types.md Provides an example of an 'initial' function for a text prompt. This function takes the previous input value and derives a default value for the current prompt, often by extracting a path segment. ```javascript (prev) => prev.split("/").pop() ``` -------------------------------- ### Manually Check Workspace Dependencies Source: https://github.com/dabit3/create-x402/blob/main/_autodocs/errors.md After template download but before npm install, manually inspect the package.json file for workspace dependencies. This helps confirm if the fixWorkspaceDeps function was effective. ```bash cd cat package.json | grep workspace ``` -------------------------------- ### Create Multiple Projects Sequentially Source: https://github.com/dabit3/create-x402/blob/main/_autodocs/api-reference/integration.md Demonstrates creating multiple x402 projects in sequence within a new directory. Each project will prompt for configuration separately. ```bash mkdir x402-workspace cd x402-workspace npx create-x402 # Creates project 1 npx create-x402 # Creates project 2 npx create-x402 # Creates project 3 ``` -------------------------------- ### CLI Entry Point Source: https://github.com/dabit3/create-x402/blob/main/_autodocs/README.md The bin.js file serves as the entry point for the CLI, disabling Node.js warnings and importing the main CLI module. ```javascript // bin.js process.env.NODE_NO_WARNINGS = "1"; import("./cli.js"); ``` -------------------------------- ### Set Environment Variables at Startup Source: https://github.com/dabit3/create-x402/blob/main/_autodocs/api-reference/workflow.md Sets NODE_NO_WARNINGS to '1' at the startup of the create-x402 CLI process. ```javascript process.env.NODE_NO_WARNINGS = "1" ``` -------------------------------- ### Project Directory Structure Source: https://github.com/dabit3/create-x402/blob/main/_autodocs/INDEX.md Illustrates the file and directory layout of the create-x402 project. ```text /output/ ├── INDEX.md ← You are here ├── README.md ← Overview & features ├── configuration.md ← Templates & settings ├── types.md ← Type definitions ├── errors.md ← Error reference └── api-reference/ ├── cli.md ← Core API functions ├── workflow.md ← Process & execution flow └── integration.md ← Integration patterns ``` -------------------------------- ### Importing create-x402 Functions (ES Module) Source: https://github.com/dabit3/create-x402/blob/main/_autodocs/api-reference/integration.md Demonstrates how to import functions from create-x402 using ES module syntax. Note that functions are not exported by default and may require refactoring. ```javascript // Import as ES module import { default as cli } from "./cli.js"; // Note: Functions are not exported; they are internal to the main() execution flow // To use functions programmatically, you would need to refactor the module ``` -------------------------------- ### Redirect create-x402 Output to a Log File Source: https://github.com/dabit3/create-x402/blob/main/_autodocs/api-reference/integration.md Captures all standard output and standard error from 'npx create-x402' into a file named 'scaffolding.log' for later review. ```bash npx create-x402 > scaffolding.log 2>&1 ``` -------------------------------- ### Required Dependencies for create-x402 Source: https://github.com/dabit3/create-x402/blob/main/_autodocs/api-reference/integration.md List of dependencies required by create-x402, including chalk, giget, ora, and prompts. Ensure your Node.js version is compatible. ```json { "dependencies": { "chalk": "^5.3.0", // CLI color formatting "giget": "^1.2.3", // GitHub template download "ora": "^8.2.0", // Spinner UI "prompts": "^2.4.2" // Interactive CLI prompts } } ``` -------------------------------- ### Pseudo-example: Composite Project Monorepo Script Source: https://github.com/dabit3/create-x402/blob/main/_autodocs/api-reference/integration.md A conceptual Node.js script demonstrating how one might programmatically create multiple project templates within a monorepo structure using create-x402, though direct function import is not currently supported. ```javascript // scripts/create-templates.js - Create multiple templates in one monorepo import { spawn } from "node:child_process"; import fs from "node:fs"; import path from "node:path"; const templates = [ { name: "api", template: "servers/express" }, { name: "web", template: "fullstack/next" }, { name: "agent", template: "agent" } ]; const baseDir = "./packages"; fs.mkdirSync(baseDir, { recursive: true }); for (const { name, template } of templates) { const target = path.join(baseDir, name); // Would need refactored create-x402 to import functions // This is a pseudo-example of what's possible console.log(`Creating ${name} with template ${template}`); } ``` -------------------------------- ### Read, Modify, and Write package.json Source: https://github.com/dabit3/create-x402/blob/main/_autodocs/types.md Demonstrates how to check for the existence of a package.json file, read its content, parse it as JSON, modify the parsed object, and then write it back to the file with pretty-printing. ```javascript import fs from "node:fs"; import path from "node:path"; const pkgPath = path.join(targetDir, "package.json"); if (!fs.existsSync(pkgPath)) { return false; } const content = fs.readFileSync(pkgPath, "utf8"); const pkg = JSON.parse(content); // Modify pkg... fs.writeFileSync(pkgPath, JSON.stringify(pkg, null, 2) + "\n"); ``` -------------------------------- ### Setting npm Proxy Configuration Source: https://github.com/dabit3/create-x402/blob/main/_autodocs/api-reference/integration.md Demonstrates how to configure npm proxy settings for corporate environments using 'npm config set' or environment variables. ```bash npm config set proxy http://proxy.company.com:8080 npm config set https-proxy http://proxy.company.com:8080 npx create-x402 ``` ```bash npm_config_proxy=http://proxy:8080 npx create-x402 ``` -------------------------------- ### Main CLI Entry Point Source: https://github.com/dabit3/create-x402/blob/main/_autodocs/api-reference/cli.md This is the main CLI entry point, automatically invoked via ./bin.js. It is not typically called programmatically. ```javascript import("./cli.js").then(() => { // CLI execution begins }); ``` -------------------------------- ### Log create-x402 Output to File Source: https://github.com/dabit3/create-x402/blob/main/_autodocs/api-reference/integration.md Redirects the standard output and standard error of create-x402 to a file named scaffold-log.txt, then checks for errors and displays them. ```bash #!/bin/bash npx create-x402 2>&1 | tee scaffold-log.txt if [ $? -ne 0 ]; then echo "Error details saved to scaffold-log.txt" cat scaffold-log.txt fi ``` -------------------------------- ### Set NPM Registry Source: https://github.com/dabit3/create-x402/blob/main/_autodocs/README.md Execute create-x402 and specify a custom npm registry using the npm_config_registry environment variable. ```bash npm_config_registry=https://registry.npmjs.org/ npx create-x402 ``` -------------------------------- ### npm Scripts for Build System Integration Source: https://github.com/dabit3/create-x402/blob/main/_autodocs/api-reference/integration.md Defines npm scripts to integrate create-x402 into a project's build process, including basic scaffolding and template-specific scaffolding via a helper script. ```json { "scripts": { "scaffold": "npx create-x402", "scaffold:express": "node ./scripts/scaffold-with-template.js servers/express", "create": "npm run scaffold" } } ``` -------------------------------- ### Node.js Script for Template-Specific Scaffolding Source: https://github.com/dabit3/create-x402/blob/main/_autodocs/api-reference/integration.md A Node.js script to spawn create-x402 as a child process, intended for use with npm scripts to scaffold specific templates. Requires refactoring of create-x402 for direct function import. ```javascript #!/usr/bin/env node import { spawn } from "node:child_process"; import prompts from "prompts"; const template = process.argv[2] || "starter-kit"; const projectName = process.argv[3] || "my-project"; // Would need refactored create-x402 to import functions // Current approach: spawn npx create-x402 as child process const child = spawn("npx", ["create-x402"], { stdio: "inherit" }); child.on("close", (code) => { process.exit(code); }); ``` -------------------------------- ### Template Resolution Logic Source: https://github.com/dabit3/create-x402/blob/main/_autodocs/api-reference/workflow.md Illustrates how the tool determines the repository URL for downloading templates based on user selection or default paths. ```text If template has repo field: URL = "github:" + repo Else: URL = "github:coinbase/x402/examples/typescript/" + template_value Example routing: "starter-kit" → github:dabit3/x402-starter-kit "servers/express" → github:coinbase/x402/examples/typescript/servers/express ``` -------------------------------- ### Suggested Refactoring for Exporting create-x402 Functions Source: https://github.com/dabit3/create-x402/blob/main/_autodocs/api-reference/integration.md Shows how to refactor cli.js to export functions like runStep, fixWorkspaceDeps, and main for programmatic use in external code. ```javascript // cli.js exports export const runStep = (cmd, args, options) => { /* ... */ }; export const fixWorkspaceDeps = (targetDir) => { /* ... */ }; export const main = async () => { /* ... */ }; // Usage in external code import { runStep, fixWorkspaceDeps } from "./cli.js"; const myCustomScaffold = async () => { const targetDir = "./my-project"; fixWorkspaceDeps(targetDir); await runStep("npm", ["install"], { /* ... */ }); }; ``` -------------------------------- ### Project Name Prompt Configuration Source: https://github.com/dabit3/create-x402/blob/main/_autodocs/configuration.md This snippet outlines the configuration for the project name prompt. It defines the type, name, message, and how the initial value is derived from the selected template. ```json { "Type": "text", "Name": "projectName", "Message": "Project name", "Initial": (derived from template value by splitting on "/" and taking last segment) } ``` -------------------------------- ### GitHub Actions Workflow for Testing Scaffolding Source: https://github.com/dabit3/create-x402/blob/main/_autodocs/api-reference/integration.md A GitHub Actions workflow to test template scaffolding in a CI environment. Note that current create-x402 requires interactive prompts, limiting direct CI integration. ```yaml name: Test Template Scaffolding on: [push, pull_request] jobs: scaffold-test: runs-on: ubuntu-latest strategy: matrix: template: - starter-kit - servers/express - fullstack/next steps: - uses: actions/setup-node@v3 with: node-version: '18' - name: Install create-x402 run: npm install -g create-x402 - name: Scaffold with template run: | # Non-interactive scaffolding would require separate script # Current implementation requires user input via prompts echo "Note: Current create-x402 requires interactive prompts" ``` -------------------------------- ### Inherit User Environment Variables Source: https://github.com/dabit3/create-x402/blob/main/_autodocs/api-reference/workflow.md Shows how child processes inherit the user's environment variables. These can be further overridden by create-x402 specific settings. ```javascript env: { ...process.env, ...env } ``` -------------------------------- ### Spawn Child Process Source: https://github.com/dabit3/create-x402/blob/main/_autodocs/api-reference/workflow.md Spawns a child process with configurable working directory, stdio handling, and environment variables. Supports both 'inherit' and 'silent' stdio modes. ```javascript const child = spawn(cmd, args, { cwd, stdio: silent ? ["ignore", "pipe", "pipe"] : "inherit", env: { ...process.env, ...env } }); ``` -------------------------------- ### Template Download Process Source: https://github.com/dabit3/create-x402/blob/main/_autodocs/api-reference/workflow.md Details the process of downloading a selected template using the giget package, including spinner feedback and error handling. ```text Call: downloadTemplate(repo_url, { dir: target, force: true }) ↓ Spinner shows: "Downloading {template}" ↓ Success: Spinner shows "Template downloaded" Failure: Spinner shows "Failed to download template" Print error message Exit with code 1 ``` -------------------------------- ### Determine npm Command based on Platform Source: https://github.com/dabit3/create-x402/blob/main/_autodocs/api-reference/workflow.md Selects the correct npm executable based on the operating system. Uses 'npm.cmd' on Windows and 'npm' on other platforms. ```javascript const npmCommand = process.platform === "win32" ? "npm.cmd" : "npm"; ``` -------------------------------- ### File Statistics Table Source: https://github.com/dabit3/create-x402/blob/main/_autodocs/INDEX.md Provides a summary of file sizes and their purposes within the project. ```text | File | Lines | Purpose | |------|-------|---------| | README.md | 100+ | Project overview and key concepts | | configuration.md | 300+ | All templates and environment configuration | | types.md | 400+ | Complete type definitions and interfaces | | errors.md | 350+ | Error catalog and recovery strategies | | api-reference/cli.md | 250+ | Core function API documentation | | api-reference/workflow.md | 500+ | Complete workflow and process documentation | | api-reference/integration.md | 400+ | Integration guides and usage patterns | | **Total** | **2,300+** | **Comprehensive technical reference** | ``` -------------------------------- ### User Input Prompts and Validation Source: https://github.com/dabit3/create-x402/blob/main/_autodocs/api-reference/workflow.md Describes the user interaction for selecting a template and entering a project name, including validation for directory existence. ```text Display: "Select a template" User selects from 16 templates ↓ Display: "Project name" User enters project name (with auto-suggested value) ↓ Validate: Target directory must not exist If exists: Exit with code 1 ``` -------------------------------- ### runStep(cmd, args, options) Source: https://github.com/dabit3/create-x402/blob/main/_autodocs/api-reference/cli.md Executes a child process with progress tracking and formatted output using an ora spinner. This function is a utility for running external commands during the CLI workflow. ```APIDOC ## runStep(cmd, args, options) ### Description Executes a child process with progress tracking and formatted output using ora spinner. ### Parameters | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | cmd | string | Yes | — | Command to execute (e.g., "npm") | | args | string[] | Yes | — | Arguments to pass to the command | | options.startText | string | Yes | — | Message to display when task starts | | options.successText | string | Yes | — | Message to display on successful completion | | options.failureText | string | Yes | — | Message to display on failure | | options.silent | boolean | No | false | If true, suppress command output unless there's an error | | options.env | object | No | {} | Environment variables to merge with process.env | | options.cwd | string | No | process.cwd() | Working directory to execute command in | | options.progressItems | string[] | No | undefined | Array of labels to cycle through during execution | | options.progressInterval | number | No | 350 | Milliseconds between progress label updates | ### Return Type `Promise` — Resolves when the process exits with code 0, rejects otherwise ### Throws - **Process exit code from child** if command fails (child process non-zero exit) - **Process exit 1** if spawn fails to launch the command ### Example ```javascript import { spawn } from "node:child_process"; import ora from "ora"; // Execute npm install with progress tracking await runStep("npm", ["install"], { startText: "Installing dependencies", successText: "Dependencies installed", failureText: "npm install failed", silent: true, cwd: "/path/to/project", progressItems: [".", "..", "..."], progressInterval: 200 }); // The spinner will show "Installing dependencies ." then "Installing dependencies .." etc // until the command completes ``` ### Implementation Details - Uses `ora` for spinner UI updates - If `progressItems` is provided, cycles through the labels every `progressInterval` milliseconds - Captures stdout and stderr when `silent: true`; only displays them on failure - Inherits stdio from parent process when `silent: false` - Clears progress interval before resolving to avoid lingering timers ### Source `cli.js:130-189` ``` -------------------------------- ### Import CLI Module Programmatically Source: https://github.com/dabit3/create-x402/blob/main/_autodocs/INDEX.md Demonstrates how to import the CLI module for potential programmatic use. Note that functions are not currently exported and would require refactoring. ```javascript import("./cli.js") // Imports module // Functions are not exported, so must refactor to use ``` -------------------------------- ### Programmatic CLI Entry Source: https://github.com/dabit3/create-x402/blob/main/_autodocs/README.md This snippet shows how to programmatically invoke the CLI module, which begins the scaffolding process after the import is resolved. ```javascript import("./cli.js").then(() => { // CLI begins }); ``` -------------------------------- ### Resolve 'EACCES: permission denied' Errors Source: https://github.com/dabit3/create-x402/blob/main/_autodocs/api-reference/integration.md Address permission issues on node_modules by changing ownership or configuring a different npm prefix. ```bash # On macOS/Linux sudo chown -R $USER:$USER ~/.npm # Or use a different npm prefix mkdir ~/.npm-global npm config set prefix '~/.npm-global' export PATH=~/.npm-global/bin:$PATH ``` -------------------------------- ### Setting npm Registry Configuration Source: https://github.com/dabit3/create-x402/blob/main/_autodocs/api-reference/integration.md Shows how to override the default npm registry using 'npm config set' or environment variables, useful for private registries. ```bash npm config set registry https://custom-registry.npm/ npx create-x402 ``` ```bash npm_config_registry=https://custom-registry.npm/ npx create-x402 ``` -------------------------------- ### Fix 'npm: command not found' Source: https://github.com/dabit3/create-x402/blob/main/_autodocs/api-reference/integration.md If npm is not found, check its location and ensure it's in your PATH. Reinstalling Node.js is another option. ```bash # Check npm location which npm export PATH="/usr/local/bin:$PATH" # Or reinstall Node.js ``` -------------------------------- ### Template Selection Prompt Configuration Source: https://github.com/dabit3/create-x402/blob/main/_autodocs/configuration.md This snippet shows the configuration for the interactive template selection prompt. It specifies the type, name, message, and initial value for the prompt. ```json { "Type": "select", "Name": "template", "Message": "Select a template", "Initial": 0 (first template) } ``` -------------------------------- ### Suppress Node.js Warnings Source: https://github.com/dabit3/create-x402/blob/main/_autodocs/README.md Run create-x402 while suppressing Node.js warnings by setting the NODE_NO_WARNINGS environment variable. ```bash NODE_NO_WARNINGS=1 npx create-x402 ``` -------------------------------- ### Configure Select Prompt Source: https://github.com/dabit3/create-x402/blob/main/_autodocs/types.md Defines the structure for a 'select' type prompt, used for choosing an option from a list. It includes properties for type, name, message, choices, and an initial selection. ```javascript { type: "select", name: "template", message: "Select a template", choices: Template[], initial: number } ``` -------------------------------- ### Mitigate GitHub Rate Limiting in CI Source: https://github.com/dabit3/create-x402/blob/main/_autodocs/api-reference/integration.md To avoid 'Failed to download template' errors in CI caused by GitHub rate limiting, add a delay between attempts. ```bash # Add delay between attempts sleep 2 npx create-x402 ``` -------------------------------- ### Handle Directory Already Exists Error Source: https://github.com/dabit3/create-x402/blob/main/_autodocs/errors.md Checks if a target directory exists before creating a project. If it exists, an error message is displayed, and the process exits with code 1. ```javascript if (fs.existsSync(target)) { console.error(chalk.red(` Folder ${projectName} already exists. Pick another name.`)); process.exit(1); } ``` -------------------------------- ### Fail-Fast Error Recovery Strategy Source: https://github.com/dabit3/create-x402/blob/main/_autodocs/api-reference/workflow.md Illustrates the CLI's fail-fast error handling. Errors result in a message and a non-zero exit code, requiring manual user intervention. ```bash # Scaffold attempt 1 npx create-x402 # Error: npm install fails # Manual recovery cd my-project rm -rf node_modules package-lock.json npm cache clean --force npm install # Or retry scaffolding rm -rf my-project npx create-x402 ``` -------------------------------- ### Manually Fix Workspace Dependencies Source: https://github.com/dabit3/create-x402/blob/main/_autodocs/INDEX.md Provides steps to manually fix workspace dependencies if needed. This involves searching for 'workspace:' in package.json and editing or re-running create-x402. ```bash cd grep -l "workspace:" package.json # Edit manually or re-run create-x402 and let it fix ``` -------------------------------- ### Handle Template Download Failure Source: https://github.com/dabit3/create-x402/blob/main/_autodocs/errors.md Attempts to download a project template, displaying success or failure messages. On failure, it logs the error message and exits with code 1. ```javascript try { await downloadTemplate(repo, { dir: target, force: true }); spinner.succeed("Template downloaded"); } catch (err) { spinner.fail("Failed to download template"); console.error(chalk.red(err.message)); process.exit(1); } ``` -------------------------------- ### Read package.json Source: https://github.com/dabit3/create-x402/blob/main/_autodocs/api-reference/workflow.md Reads and parses the package.json file. Assumes the file exists and is valid JSON; otherwise, it will throw an error. ```javascript const content = fs.readFileSync(pkgPath, "utf8"); const pkg = JSON.parse(content); ``` -------------------------------- ### Check Directory Existence Source: https://github.com/dabit3/create-x402/blob/main/_autodocs/api-reference/workflow.md Synchronously checks if a target directory exists. Returns a boolean and does not throw an error if the directory is missing. ```javascript if (fs.existsSync(target)) { // Error: directory exists } ``` -------------------------------- ### Write package.json Source: https://github.com/dabit3/create-x402/blob/main/_autodocs/api-reference/workflow.md Writes the package.json object back to the file with 2-space indentation and a trailing newline. Overwrites the existing file. ```javascript fs.writeFileSync(pkgPath, JSON.stringify(pkg, null, 2) + "\n"); ``` -------------------------------- ### Handling GitHub Rate Limiting Source: https://github.com/dabit3/create-x402/blob/main/_autodocs/api-reference/integration.md Provides methods to mitigate GitHub rate limiting issues when downloading templates, such as increasing fetch timeout or using a GitHub token for private repositories. ```bash # Increase retry timeout npm_config_fetch_timeout=120000 npx create-x402 ``` ```bash # Or use GitHub token (if downloading private repos) GITHUB_TOKEN=ghp_xxxxxxxxxxxx npx create-x402 ``` -------------------------------- ### Success Message Display Source: https://github.com/dabit3/create-x402/blob/main/_autodocs/api-reference/workflow.md The final output displayed to the user upon successful project scaffolding, including next steps. ```text If all steps complete: ↓ Print: "Success! {projectName} is ready." ↓ Print: "Next steps:" Print: " cd {projectName}" Print: " Configure your .env file" Print: " npm run dev" ``` -------------------------------- ### Configure Text Prompt Source: https://github.com/dabit3/create-x402/blob/main/_autodocs/types.md Defines the structure for a 'text' type prompt, used for capturing string input from the user. It includes properties for type, name, message, and an initial value that can be derived from previous input. ```javascript { type: "text", name: "projectName", message: "Project name", initial: (prev: string) => string } ``` -------------------------------- ### Capture Exit Codes in Bash Scripts Source: https://github.com/dabit3/create-x402/blob/main/_autodocs/api-reference/integration.md This script executes create-x402 and captures its exit code to determine success or failure, providing specific messages for different error conditions. ```bash #!/bin/bash npx create-x402 exit_code=$? if [ $exit_code -eq 0 ]; then echo "Scaffolding succeeded" elif [ $exit_code -eq 1 ]; then echo "Scaffolding failed (directory exists, download failed, or install failed)" else echo "Scaffolding failed with code: $exit_code" fi exit $exit_code ``` -------------------------------- ### Template Object Structure Source: https://github.com/dabit3/create-x402/blob/main/_autodocs/api-reference/cli.md Defines the expected properties for a template object used in CLI scaffolding. The 'repo' field is optional for specifying custom GitHub repositories. ```javascript { value: string, // Template identifier for routing title: string, // Display name in CLI prompt description: string, // Brief description shown to user repo?: string // Optional custom GitHub repo path } ``` -------------------------------- ### Conditional Execution with && Operator Source: https://github.com/dabit3/create-x402/blob/main/_autodocs/api-reference/integration.md Executes 'npm run dev' only if the preceding 'npx create-x402' command completes successfully (returns an exit code of 0). ```bash npx create-x402 && npm run dev # Runs "npm run dev" only if scaffolding succeeds ``` -------------------------------- ### Template Type Definition Source: https://github.com/dabit3/create-x402/blob/main/_autodocs/types.md Defines the configuration object for a scaffold template. Includes value, title, description, and an optional repository field. ```javascript { value: string, title: string, description: string, repo?: string } ``` -------------------------------- ### Handle Workspace Dependencies Fix Status Source: https://github.com/dabit3/create-x402/blob/main/_autodocs/errors.md This snippet shows how to provide user feedback based on whether workspace dependencies were successfully fixed. The spinner stops without a message if the fix fails, which could lead to silent issues. ```javascript const fixSpinner = ora("Preparing package.json").start(); const wasFixed = fixWorkspaceDeps(target); if (wasModified) { fixSpinner.succeed("Fixed workspace dependencies"); } else { fixSpinner.stop(); // Spinner stops, no message - could be silent about the issue } ``` -------------------------------- ### Handle Child Process Spawn Errors Source: https://github.com/dabit3/create-x402/blob/main/_autodocs/errors.md Listens for 'error' events on a child process. If an error occurs during spawning, it logs the error message and exits the process with code 1. ```javascript child.on("error", (err) => { if (ticker) clearInterval(ticker); task.fail(failureText); console.error(chalk.red(err.message)); process.exit(1); }); ``` -------------------------------- ### Append to NODE_OPTIONS Source: https://github.com/dabit3/create-x402/blob/main/_autodocs/api-reference/workflow.md Safely appends '--no-warnings' to the existing NODE_OPTIONS environment variable, preserving any user-defined settings. ```javascript NODE_OPTIONS: `${process.env.NODE_OPTIONS ?? ""} --no-warnings` ``` -------------------------------- ### Fix Workspace Dependencies Source: https://github.com/dabit3/create-x402/blob/main/_autodocs/api-reference/cli.md Scans package.json for dependencies using the 'workspace:' protocol and replaces them with 'latest' versions. This is useful when cloning templates from monorepos. ```javascript import path from "node:path"; import { fixWorkspaceDeps } from "./cli.js"; const projectDir = path.resolve(process.cwd(), "my-project"); // Returns true if modifications were made const wasModified = fixWorkspaceDeps(projectDir); if (wasModified) { console.log("Fixed workspace dependencies to use 'latest'"); } else { console.log("No workspace dependencies found"); } ``` -------------------------------- ### RunStepOptions Type Definition Source: https://github.com/dabit3/create-x402/blob/main/_autodocs/types.md Defines the configuration object for the runStep() function. Includes options for text messages, silent execution, environment variables, working directory, and progress indicators. ```javascript { startText: string, successText: string, failureText: string, silent?: boolean, env?: Record, cwd?: string, progressItems?: string[], progressInterval?: number } ``` -------------------------------- ### Process Exit Source: https://github.com/dabit3/create-x402/blob/main/_autodocs/api-reference/workflow.md The final step where the Node.js process completes and exits with a success code. ```text main() completes Node.js process exits with code 0 ``` -------------------------------- ### fixWorkspaceDeps(targetDir) Source: https://github.com/dabit3/create-x402/blob/main/_autodocs/api-reference/cli.md Fixes workspace protocol dependencies in package.json to "latest" versions. This utility is used to ensure compatibility when cloning templates from monorepos. ```APIDOC ## fixWorkspaceDeps(targetDir) ### Description Fixes workspace protocol dependencies in package.json to "latest" versions. ### Parameters | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | targetDir | string | Yes | — | Path to project directory containing package.json | ### Return Type `boolean` — Returns true if package.json was modified, false otherwise ### Behavior Scans package.json for dependencies using the `workspace:` protocol (common in monorepo setups) and replaces them with `"latest"` version specifiers. This is necessary when cloning a template from a monorepo that uses workspace protocol. Checks three dependency types: - `dependencies` - `devDependencies` - `peerDependencies` Only modifies the file if at least one `workspace:` dependency is found. ### Example ```javascript import path from "node:path"; import { fixWorkspaceDeps } from "./cli.js"; const projectDir = path.resolve(process.cwd(), "my-project"); // Returns true if modifications were made const wasModified = fixWorkspaceDeps(projectDir); if (wasModified) { console.log("Fixed workspace dependencies to use 'latest'"); } else { console.log("No workspace dependencies found"); } ``` ``` -------------------------------- ### Handle User Cancellation Source: https://github.com/dabit3/create-x402/blob/main/_autodocs/errors.md Defines an onCancel callback for interactive prompts. When triggered (e.g., by Ctrl+C), it logs a cancellation message and exits cleanly with code 0. ```javascript { onCancel: () => { console.log(chalk.yellow("\nCancelled.")); process.exit(0); } } ``` -------------------------------- ### CLIResponse Type Definition Source: https://github.com/dabit3/create-x402/blob/main/_autodocs/types.md Defines the shape of the object returned by the interactive prompts in the CLI. ```javascript { template: string, projectName: string } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.