From 36f2b7eb056541613c3212d489f572837ad393de Mon Sep 17 00:00:00 2001 From: atmn Date: Wed, 18 Feb 2026 12:20:28 +0000 Subject: [PATCH] Add comprehensive CLI documentation - Add 9 new CLI documentation pages: - getting-started.mdx: Installation, auth, first project setup - authentication.mdx: OAuth flow, API keys, environment management - push-pull.mdx: Config sync workflows and change analysis - data.mdx: Customer, plan, feature, and event data commands - templates.mdx: Built-in project templates and customization - sdk-types.mdx: TypeScript type generation for SDK integration - ci-cd.mdx: Automated deployment and environment setup - commands.mdx: Complete command reference with all options - workflows.mdx: Development patterns and best practices - Replace config.mdx with comprehensive API reference: - Complete feature() and plan() parameter documentation - All feature types: boolean, metered, credit_system - Plan feature configurations with pricing models - Examples for every billing scenario - Update docs.json navigation: - Add all new CLI pages to API Reference tab - Organize in logical order from getting started to advanced Key corrections applied: - API key prefixes: am_sk_test_* (sandbox), am_sk_live_* (production) - Feature types: boolean, metered (with consumable), credit_system - Reference-style documentation with ParamField components - Cross-referenced with actual CLI source code for accuracy --- mintlify/api-reference/cli/authentication.mdx | 217 ++++++ mintlify/api-reference/cli/ci-cd.mdx | 615 ++++++++++++++++ mintlify/api-reference/cli/commands.mdx | 510 ++++++++++++++ mintlify/api-reference/cli/config.mdx | 658 ++++++++++++------ mintlify/api-reference/cli/data.mdx | 436 ++++++++++++ .../api-reference/cli/getting-started.mdx | 179 +++++ mintlify/api-reference/cli/push-pull.mdx | 383 ++++++++++ mintlify/api-reference/cli/sdk-types.mdx | 412 +++++++++++ mintlify/api-reference/cli/templates.mdx | 508 ++++++++++++++ mintlify/api-reference/cli/workflows.mdx | 516 ++++++++++++++ mintlify/docs.json | 13 +- 11 files changed, 4233 insertions(+), 214 deletions(-) create mode 100644 mintlify/api-reference/cli/authentication.mdx create mode 100644 mintlify/api-reference/cli/ci-cd.mdx create mode 100644 mintlify/api-reference/cli/commands.mdx create mode 100644 mintlify/api-reference/cli/data.mdx create mode 100644 mintlify/api-reference/cli/getting-started.mdx create mode 100644 mintlify/api-reference/cli/push-pull.mdx create mode 100644 mintlify/api-reference/cli/sdk-types.mdx create mode 100644 mintlify/api-reference/cli/templates.mdx create mode 100644 mintlify/api-reference/cli/workflows.mdx diff --git a/mintlify/api-reference/cli/authentication.mdx b/mintlify/api-reference/cli/authentication.mdx new file mode 100644 index 0000000..a42b8a6 --- /dev/null +++ b/mintlify/api-reference/cli/authentication.mdx @@ -0,0 +1,217 @@ +--- +title: "Authentication" +description: "OAuth login, API key management, and environment configuration" +--- + +The `atmn` CLI uses OAuth 2.0 for secure authentication and automatically manages API keys for both sandbox and production environments. + +## OAuth Login Flow + +Authenticate with your Autumn account using the login command: + +```bash +atmn login +``` + +### Interactive Mode + +When running in an interactive terminal, the CLI provides a beautiful login experience: + +1. **Local Callback Server**: Starts a temporary server on ports 31448-31452 +2. **Browser Integration**: Opens your default browser to Autumn's Auth0 login page +3. **Organization Selection**: Choose which organization to authenticate with +4. **Automatic Key Generation**: Creates sandbox and production API keys +5. **Environment Setup**: Saves keys to your `.env` file + +### Headless Mode + +For CI/CD environments or when no TTY is available: + +1. The CLI opens your browser with the OAuth URL +2. Provides a fallback URL you can copy/paste manually +3. Waits for the OAuth callback with a timeout + + +The OAuth flow uses PKCE (Proof Key for Code Exchange) for enhanced security. + + +## API Key Management + +### Key Types and Prefixes + +The CLI generates two API keys with distinct prefixes: + + + **Sandbox key** with prefix `am_sk_test_*` — for development and testing + + + + **Production key** with prefix `am_sk_live_*` — for production environment + + +### Environment File Structure + +Keys are automatically saved to a `.env` file in your current directory: + + + +```bash .env +# Autumn API Keys (generated by atmn login) +AUTUMN_SECRET_KEY=am_sk_test_1234567890abcdef1234567890abcdef +AUTUMN_PROD_SECRET_KEY=am_sk_live_abcdef1234567890abcdef1234567890 + +# Your other environment variables +DATABASE_URL=... +STRIPE_SECRET_KEY=... +``` + + + +### Key Resolution + +The CLI looks for environment files in this order: + +1. Current directory `.env` +2. Parent directories (walks up the directory tree) +3. Root directory `.env` + +## Environment Selection + +Control which environment and API server the CLI uses with global flags: + + + Use production environment instead of sandbox + + + + Use localhost:8080 API server instead of api.useautumn.com + + +### Flag Combinations + + + +```bash Default (Sandbox + Remote API) +atmn push +# Uses: AUTUMN_SECRET_KEY → api.useautumn.com +``` + +```bash Production + Remote API +atmn push --prod +# Uses: AUTUMN_PROD_SECRET_KEY → api.useautumn.com +``` + +```bash Local Development Server +atmn push --local +# Uses: AUTUMN_SECRET_KEY → localhost:8080 +``` + +```bash Production + Local API +atmn push --local --prod +# Uses: AUTUMN_PROD_SECRET_KEY → localhost:8080 +``` + + + +### Environment URLs + + + `https://api.useautumn.com` + + + + `https://app.useautumn.com` + + + + `http://localhost:8080` + + + + `http://localhost:3000` + + +## Authentication Commands + +### Check Environment + +Display your current authentication status and organization info: + +```bash +atmn env +``` + +Example output: + +``` +Organization: Acme Corp +Slug: acme-corp +Environment: Sandbox +``` + +### Logout + +Remove stored API keys from your `.env` file: + +```bash +atmn logout +``` + +This removes both `AUTUMN_SECRET_KEY` and `AUTUMN_PROD_SECRET_KEY` from your environment file. + + +After logout, you'll need to run `atmn login` again to use CLI commands. + + +## Error Handling + +### Automatic Re-authentication + +The CLI automatically handles expired or invalid tokens: + +1. **401 Unauthorized** responses trigger the OAuth flow +2. New tokens are generated and stored +3. The original request is retried +4. You're notified of the re-authentication + +### Common Issues + +**No API key found:** +``` +Error: No API key found. Run `atmn login` to authenticate. +``` +**Solution:** Run `atmn login` to generate API keys + +**Invalid API key:** +``` +Error: 401 Unauthorized - Invalid API key +``` +**Solution:** The CLI will automatically prompt for re-authentication + +**Wrong environment:** +``` +Error: API key is for sandbox but --prod flag was used +``` +**Solution:** Remove the `--prod` flag or login again to generate production keys + +## Security Best Practices + + +**Keep your API keys secure:** +- Add `.env` to your `.gitignore` file +- Never commit API keys to version control +- Use different keys for development and production +- Rotate keys regularly through the Autumn dashboard + + +### CI/CD Setup + +For automated deployments, set environment variables directly: + +```bash +# GitHub Actions, etc. +export AUTUMN_SECRET_KEY="am_sk_test_..." +export AUTUMN_PROD_SECRET_KEY="am_sk_live_..." +``` + +See the [CI/CD guide](/api-reference/cli/ci-cd) for complete setup instructions. \ No newline at end of file diff --git a/mintlify/api-reference/cli/ci-cd.mdx b/mintlify/api-reference/cli/ci-cd.mdx new file mode 100644 index 0000000..7f23a43 --- /dev/null +++ b/mintlify/api-reference/cli/ci-cd.mdx @@ -0,0 +1,615 @@ +--- +title: "CI/CD Integration" +description: "Automate Autumn deployments with headless mode, proper exit codes, and environment variables" +--- + +The `atmn` CLI is designed for seamless CI/CD integration with headless mode, proper exit codes, and environment variable support for automated deployments. + +## Headless Mode + +The CLI automatically detects non-TTY environments (CI/CD) and switches to headless mode, providing: + +- **Plain text output** suitable for logs +- **Structured data** in JSON/CSV formats +- **Proper exit codes** for success/failure detection +- **No interactive prompts** that would hang builds +- **Batch operations** optimized for automation + +### Automatic Detection + + + +```bash Local development (TTY detected) +atmn push +# Shows beautiful interactive UI with colors and prompts +``` + +```bash CI/CD environment (no TTY) +atmn push +# Shows plain text output suitable for logs +# Analyzing changes... +# ✓ Pushed 3 features, 2 plans to sandbox +``` + + + +### Force Headless Mode + +Override TTY detection with the `--headless` flag: + +```bash +atmn push --headless # Force headless mode even in terminal +``` + +## Environment Setup + +### API Key Configuration + +Set environment variables in your CI/CD platform: + + + Sandbox API key (format: `am_sk_test_*`) + + + + Production API key (format: `am_sk_live_*`) + + + + +```yaml GitHub Actions +env: + AUTUMN_SECRET_KEY: ${{ secrets.AUTUMN_SECRET_KEY }} + AUTUMN_PROD_SECRET_KEY: ${{ secrets.AUTUMN_PROD_SECRET_KEY }} +``` + +```yaml GitLab CI +variables: + AUTUMN_SECRET_KEY: $AUTUMN_SECRET_KEY + AUTUMN_PROD_SECRET_KEY: $AUTUMN_PROD_SECRET_KEY +``` + +```bash Environment Variables +export AUTUMN_SECRET_KEY="am_sk_test_1234567890abcdef" +export AUTUMN_PROD_SECRET_KEY="am_sk_live_1234567890abcdef" +``` + + + +## GitHub Actions Integration + +### Basic Workflow + + + +```yaml .github/workflows/autumn-deploy.yml +name: Deploy Autumn Configuration + +on: + push: + branches: [main] + paths: ['autumn.config.ts'] + +jobs: + deploy-sandbox: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - name: Setup Node.js + uses: actions/setup-node@v4 + with: + node-version: '18' + + - name: Install atmn CLI + run: npm install -g atmn + + - name: Deploy to Sandbox + run: atmn push --yes + env: + AUTUMN_SECRET_KEY: ${{ secrets.AUTUMN_SECRET_KEY }} + + deploy-production: + runs-on: ubuntu-latest + needs: deploy-sandbox + if: github.ref == 'refs/heads/main' + environment: production + + steps: + - uses: actions/checkout@v4 + + - name: Setup Node.js + uses: actions/setup-node@v4 + with: + node-version: '18' + + - name: Install atmn CLI + run: npm install -g atmn + + - name: Deploy to Production + run: atmn push --prod --yes + env: + AUTUMN_PROD_SECRET_KEY: ${{ secrets.AUTUMN_PROD_SECRET_KEY }} +``` + + + +### Advanced Workflow with Validation + + + +```yaml .github/workflows/autumn-advanced.yml +name: Autumn Configuration Pipeline + +on: + pull_request: + paths: ['autumn.config.ts'] + push: + branches: [main] + paths: ['autumn.config.ts'] + +jobs: + validate: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - name: Setup Node.js + uses: actions/setup-node@v4 + with: + node-version: '18' + + - name: Install dependencies + run: | + npm install -g atmn + npm install typescript + + - name: Validate Configuration + run: | + # Check TypeScript compilation + npx tsc --noEmit autumn.config.ts + + # Validate with Autumn (dry-run) + atmn preview + env: + AUTUMN_SECRET_KEY: ${{ secrets.AUTUMN_SECRET_KEY }} + + deploy-sandbox: + runs-on: ubuntu-latest + needs: validate + steps: + - uses: actions/checkout@v4 + + - name: Setup Node.js + uses: actions/setup-node@v4 + with: + node-version: '18' + + - name: Install atmn CLI + run: npm install -g atmn + + - name: Deploy to Sandbox + run: atmn push --yes + env: + AUTUMN_SECRET_KEY: ${{ secrets.AUTUMN_SECRET_KEY }} + + - name: Generate SDK Types + run: atmn pull + env: + AUTUMN_SECRET_KEY: ${{ secrets.AUTUMN_SECRET_KEY }} + + - name: Commit Updated Types + uses: stefanzweifel/git-auto-commit-action@v5 + with: + commit_message: 'Update SDK types' + file_pattern: '@useautumn-sdk.d.ts' + + deploy-production: + runs-on: ubuntu-latest + needs: deploy-sandbox + if: github.ref == 'refs/heads/main' + environment: production + + steps: + - uses: actions/checkout@v4 + + - name: Setup Node.js + uses: actions/setup-node@v4 + with: + node-version: '18' + + - name: Install atmn CLI + run: npm install -g atmn + + - name: Deploy to Production + run: atmn push --prod --yes + env: + AUTUMN_PROD_SECRET_KEY: ${{ secrets.AUTUMN_PROD_SECRET_KEY }} + + - name: Notify Deployment + run: | + echo "🚀 Autumn configuration deployed to production" + atmn env --prod + env: + AUTUMN_PROD_SECRET_KEY: ${{ secrets.AUTUMN_PROD_SECRET_KEY }} +``` + + + +## GitLab CI Integration + + + +```yaml .gitlab-ci.yml +stages: + - validate + - deploy-sandbox + - deploy-production + +variables: + NODE_VERSION: "18" + +before_script: + - apt-get update -qq && apt-get install -y nodejs npm + - npm install -g atmn + +validate-config: + stage: validate + script: + - atmn preview + only: + changes: + - autumn.config.ts + +deploy-sandbox: + stage: deploy-sandbox + script: + - atmn push --yes + - atmn pull # Generate updated types + artifacts: + paths: + - "@useautumn-sdk.d.ts" + expire_in: 1 hour + only: + - main + environment: + name: sandbox + +deploy-production: + stage: deploy-production + script: + - atmn push --prod --yes + when: manual + only: + - main + environment: + name: production +``` + + + +## Exit Codes & Error Handling + +The CLI provides proper exit codes for CI/CD error detection: + + + **Success** - Operation completed successfully + + + + **General Error** - Command failed (network, auth, validation, etc.) + + + + **Configuration Error** - Invalid autumn.config.ts or missing file + + +### Error Handling Examples + + + +```bash Handling Errors in Scripts +#!/bin/bash +set -e # Exit on any error + +# Deploy to sandbox +if atmn push --yes; then + echo "✅ Sandbox deployment successful" +else + echo "❌ Sandbox deployment failed" + exit 1 +fi + +# Deploy to production only if sandbox succeeded +if atmn push --prod --yes; then + echo "✅ Production deployment successful" + # Send success notification + curl -X POST "$SLACK_WEBHOOK" -d '{"text":"🚀 Autumn config deployed to production"}' +else + echo "❌ Production deployment failed" + # Send failure notification + curl -X POST "$SLACK_WEBHOOK" -d '{"text":"❌ Autumn production deployment failed"}' + exit 1 +fi +``` + + + +## Automated Workflows + +### Scheduled Sync + +Keep your types up-to-date with scheduled pulls: + + + +```yaml .github/workflows/sync-types.yml +name: Sync SDK Types + +on: + schedule: + - cron: '0 2 * * *' # Daily at 2 AM + workflow_dispatch: # Manual trigger + +jobs: + sync-types: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - name: Setup Node.js + uses: actions/setup-node@v4 + with: + node-version: '18' + + - name: Install atmn CLI + run: npm install -g atmn + + - name: Sync from Production + run: atmn pull --prod + env: + AUTUMN_PROD_SECRET_KEY: ${{ secrets.AUTUMN_PROD_SECRET_KEY }} + + - name: Create Pull Request + uses: peter-evans/create-pull-request@v5 + with: + token: ${{ secrets.GITHUB_TOKEN }} + commit-message: 'chore: sync SDK types from production' + title: 'Sync SDK Types' + body: 'Automated sync of SDK types from Autumn production' + branch: 'chore/sync-sdk-types' +``` + + + +### Multi-Environment Deployments + +Deploy different configurations to different environments: + + + +```yaml Multi-environment Pipeline +name: Multi-Environment Deploy + +on: + push: + branches: [develop, staging, main] + +jobs: + deploy: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - name: Setup Node.js + uses: actions/setup-node@v4 + with: + node-version: '18' + + - name: Install atmn CLI + run: npm install -g atmn + + - name: Deploy to Development + if: github.ref == 'refs/heads/develop' + run: atmn push --yes + env: + AUTUMN_SECRET_KEY: ${{ secrets.AUTUMN_DEV_SECRET_KEY }} + + - name: Deploy to Staging + if: github.ref == 'refs/heads/staging' + run: atmn push --yes + env: + AUTUMN_SECRET_KEY: ${{ secrets.AUTUMN_STAGING_SECRET_KEY }} + + - name: Deploy to Production + if: github.ref == 'refs/heads/main' + run: atmn push --prod --yes + env: + AUTUMN_PROD_SECRET_KEY: ${{ secrets.AUTUMN_PROD_SECRET_KEY }} +``` + + + +## Docker Integration + +### Dockerfile + + + +```dockerfile Dockerfile +FROM node:18-alpine + +# Install atmn CLI +RUN npm install -g atmn + +# Copy configuration +COPY autumn.config.ts . + +# Set up entrypoint +COPY deploy.sh . +RUN chmod +x deploy.sh + +ENTRYPOINT ["./deploy.sh"] +``` + +```bash deploy.sh +#!/bin/sh +set -e + +echo "🚀 Deploying Autumn configuration..." + +# Validate environment +if [ "$ENVIRONMENT" = "production" ]; then + if [ -z "$AUTUMN_PROD_SECRET_KEY" ]; then + echo "❌ AUTUMN_PROD_SECRET_KEY required for production" + exit 1 + fi + echo "📦 Deploying to production..." + atmn push --prod --yes +else + if [ -z "$AUTUMN_SECRET_KEY" ]; then + echo "❌ AUTUMN_SECRET_KEY required for sandbox" + exit 1 + fi + echo "📦 Deploying to sandbox..." + atmn push --yes +fi + +echo "✅ Deployment complete!" +``` + + + +### Docker Compose + + + +```yaml docker-compose.yml +version: '3.8' + +services: + autumn-deploy: + build: . + environment: + - ENVIRONMENT=${ENVIRONMENT:-sandbox} + - AUTUMN_SECRET_KEY=${AUTUMN_SECRET_KEY} + - AUTUMN_PROD_SECRET_KEY=${AUTUMN_PROD_SECRET_KEY} + volumes: + - .:/app + working_dir: /app +``` + +```bash Usage +# Deploy to sandbox +ENVIRONMENT=sandbox docker-compose run autumn-deploy + +# Deploy to production +ENVIRONMENT=production docker-compose run autumn-deploy +``` + + + +## Monitoring & Notifications + +### Slack Notifications + + + +```bash Slack Integration +#!/bin/bash + +SLACK_WEBHOOK="https://hooks.slack.com/services/YOUR/SLACK/WEBHOOK" + +# Deploy configuration +if atmn push --prod --yes; then + # Success notification + curl -X POST "$SLACK_WEBHOOK" \ + -H 'Content-type: application/json' \ + -d '{ + "text": "✅ Autumn configuration deployed to production", + "attachments": [{ + "color": "good", + "fields": [{ + "title": "Environment", + "value": "Production", + "short": true + }, { + "title": "Branch", + "value": "'$GITHUB_REF_NAME'", + "short": true + }] + }] + }' +else + # Failure notification + curl -X POST "$SLACK_WEBHOOK" \ + -H 'Content-type: application/json' \ + -d '{ + "text": "❌ Autumn configuration deployment failed", + "attachments": [{ + "color": "danger", + "fields": [{ + "title": "Environment", + "value": "Production", + "short": true + }, { + "title": "Branch", + "value": "'$GITHUB_REF_NAME'", + "short": true + }] + }] + }' + exit 1 +fi +``` + + + +## Security Best Practices + +### Secret Management + + +**Never commit API keys to version control.** Always use your CI/CD platform's secret management system. + + + + +```yaml GitHub Actions Security +# ✅ Good - Use secrets +env: + AUTUMN_PROD_SECRET_KEY: ${{ secrets.AUTUMN_PROD_SECRET_KEY }} + +# ❌ Bad - Hardcoded key +env: + AUTUMN_PROD_SECRET_KEY: "am_sk_live_1234567890abcdef" +``` + + + +### Environment Isolation + +- **Development**: Use separate Autumn organization/sandbox +- **Staging**: Use production organization but sandbox environment +- **Production**: Use production organization and production environment + +### Access Controls + +Limit who can trigger production deployments: + + + +```yaml Protected Production +deploy-production: + runs-on: ubuntu-latest + needs: deploy-sandbox + environment: production # Requires approval + + steps: + - name: Deploy to Production + run: atmn push --prod --yes +``` + + + +The CLI's headless mode and proper exit codes make it ideal for automated deployments while maintaining the safety and validation features you need for production systems. \ No newline at end of file diff --git a/mintlify/api-reference/cli/commands.mdx b/mintlify/api-reference/cli/commands.mdx new file mode 100644 index 0000000..edf4429 --- /dev/null +++ b/mintlify/api-reference/cli/commands.mdx @@ -0,0 +1,510 @@ +--- +title: "Command Reference" +description: "Complete reference for all atmn CLI commands, options, and arguments" +--- + +Complete reference for all `atmn` CLI commands with every flag, argument, and default value. + +## Global Options + +These options are available for all commands: + + + Use production environment instead of sandbox + + + + Use localhost:8080 API server instead of api.useautumn.com + + + + Force non-interactive mode (useful for CI/agents) + + + + Path to configuration file + + +### Global Flag Combinations + +| Flags | Environment | API Server | Use Case | +|-------|-------------|------------|----------| +| (none) | Sandbox | Remote | Default development | +| `-p` | Production | Remote | Production deployment | +| `-l` | Sandbox | Local | Local development | +| `-lp` | Production | Local | Local dev with prod data | + +## Authentication Commands + +### `atmn login` + +Authenticate with Autumn using OAuth 2.0. + +```bash +atmn login +``` + +**Behavior:** +- **Interactive**: Beautiful OAuth flow with browser integration +- **Headless**: Opens browser with fallback URL +- **Creates**: API keys for both sandbox and production +- **Stores**: Keys in `.env` file + +**No additional options** + +### `atmn logout` + +Remove API keys from environment file. + +```bash +atmn logout +``` + +**Removes:** +- `AUTUMN_SECRET_KEY` (sandbox) +- `AUTUMN_PROD_SECRET_KEY` (production) + +**No additional options** + +### `atmn env` + +Display current environment and organization info. + +```bash +atmn env +``` + +**Displays:** +- Organization name and slug +- Current environment (sandbox/production) +- API endpoint being used + +**No additional options** + +## Configuration Commands + +### `atmn init` + +Initialize a new Autumn project with template selection. + +```bash +atmn init +``` + +**Features:** +- **Interactive**: Template selection wizard +- **Headless**: Uses default template +- **Templates**: OpenAI, T3 Chat, Railway, Linear +- **Generates**: `autumn.config.ts` and optional `.env` + +**No additional options** + +### `atmn push` + +Push local configuration to Autumn. + +```bash +atmn push [options] +``` + + + Automatically confirm all prompts (useful for CI/CD) + + +**Features:** +- Change analysis and smart prompts +- Production safety guards +- Plan versioning for customers +- Batch operations + +### `atmn pull` + +Pull configuration from Autumn to local files. + +```bash +atmn pull [options] +``` + + + Force overwrite config instead of in-place updates + + +**Features:** +- Smart in-place updates (preserves local changes) +- SDK type generation +- Multi-environment merging + +## Data Commands + +### `atmn customers` + +Browse and inspect customer data. + +```bash +atmn customers [options] +``` + + + Run in headless mode (output for scripts/agents) + + + + Page number for pagination (headless mode) + + + + Search query for filtering customers (headless mode) + + + + Get specific customer by ID (headless mode) + + + + Number of customers per page (headless mode) + + + + Output format: `text`, `json`, `csv` (headless mode) + + +### `atmn plans` / `atmn products` + +Browse and inspect plans/products. Both commands are identical. + +```bash +atmn plans [options] +atmn products [options] # Alias +``` + + + Run in headless mode (output for scripts/agents) + + + + Page number for pagination (headless mode) + + + + Search query for filtering plans (headless mode) + + + + Get specific plan by ID (headless mode) + + + + Number of plans per page (headless mode) + + + + Output format: `text`, `json`, `csv` (headless mode) + + + + Include archived plans in results + + +### `atmn features` + +Browse and inspect feature definitions. + +```bash +atmn features [options] +``` + + + Run in headless mode (output for scripts/agents) + + + + Page number for pagination (headless mode) + + + + Search query for filtering features (headless mode) + + + + Get specific feature by ID (headless mode) + + + + Number of features per page (headless mode) + + + + Output format: `text`, `json`, `csv` (headless mode) + + + + Include archived features in results + + +### `atmn events` + +Browse and analyze usage events. + +```bash +atmn events [options] +``` + + + Run in headless mode (output for scripts/agents) + + + + Page number for pagination + + + + Filter events by customer ID + + + + Filter by feature ID (comma-separated for multiple) + + + + Number of events per page + + + + Time range: `24h`, `7d`, `30d`, `90d` + + + + View mode: `list` (individual events) or `aggregate` (summary stats) + + + + Bin size for aggregate mode: `hour`, `day`, `month` + + + + Group by property for aggregate mode (e.g., `customer_id`, `feature_id`) + + + + Output format: `text`, `json`, `csv` + + +## Utility Commands + +### `atmn preview` + +Preview plans from local configuration without API calls. + +```bash +atmn preview [options] +``` + + + Preview specific plan by ID (shows all plans if omitted) + + + + Currency code for price display + + +**Features:** +- Renders pricing tables from `autumn.config.ts` +- No API calls required +- Useful for local development and testing + +### `atmn dashboard` + +Open Autumn dashboard in browser. + +```bash +atmn dashboard +``` + +**Opens:** +- `https://app.useautumn.com` (default) +- `http://localhost:3000` (with `--local` flag) + +**No additional options** + +### `atmn nuke` + +**⚠️ DESTRUCTIVE:** Permanently delete all sandbox data. + +```bash +atmn nuke [options] +``` + + + Skip all confirmation prompts (VERY DANGEROUS) + + +**Safety Features:** +- **Sandbox only** - Refuses to run with `--prod` flag +- **Multiple confirmations** required +- **Visual warnings** with red text +- **Explicit flag name** for dangerous skip option + +**Error with Production:** +``` +ERROR: nuke command is only available for sandbox! +Remove the -p/--prod flag to nuke your sandbox. +``` + +### `atmn version` / `atmn v` + +Display CLI version. + +```bash +atmn version +atmn v # Alias +``` + +**Output:** +- Version from `package.json` (e.g., `1.0.0-beta.15`) +- `"dev"` in development environments + +**No additional options** + +## Command Examples + +### Environment Management + + + +```bash Check current environment +atmn env + +# Output: +# Organization: Acme Corp +# Slug: acme-corp +# Environment: Sandbox +``` + +```bash Work with production +atmn env --prod +atmn push --prod +atmn pull --prod +``` + +```bash Local development server +atmn push --local +atmn pull --local +atmn dashboard --local # Opens localhost:3000 +``` + + + +### Configuration Workflow + + + +```bash Complete setup from scratch +atmn login # Authenticate +atmn init # Create project +atmn push # Deploy to sandbox +atmn preview # Preview locally +atmn push --prod # Deploy to production +``` + +```bash Daily development +atmn pull # Get latest changes +# Edit autumn.config.ts +atmn preview --plan pro # Test specific plan +atmn push # Deploy changes +``` + + + +### Data Export + + + +```bash Export customer data +atmn customers --headless --format csv > customers.csv +atmn customers --headless --search "john@" --format json +``` + +```bash Usage analytics +atmn events --headless --mode aggregate --group-by feature_id --time 30d --format csv +atmn events --headless --customer "cus_123" --time 7d --format json +``` + +```bash Plan analysis +atmn plans --headless --include-archived --format json > all_plans.json +atmn features --headless --format csv > features.csv +``` + + + +### CI/CD Usage + + + +```bash Automated deployment +# Headless mode with auto-confirmation +atmn push --prod --yes --headless + +# Exit codes for error handling +if atmn push --yes; then + echo "Deployment successful" +else + echo "Deployment failed" + exit 1 +fi +``` + + + +## Exit Codes + +All commands return appropriate exit codes: + + + Success - Operation completed successfully + + + + General error - Command failed (network, auth, validation, etc.) + + + + Configuration error - Invalid `autumn.config.ts` or missing file + + +## Error Handling + +Common error scenarios and CLI behavior: + +### Authentication Errors + +```bash +# 401 Unauthorized - triggers automatic re-auth +atmn push +# → CLI automatically runs OAuth flow +# → Retries original command +``` + +### Configuration Errors + +```bash +# Missing config file +atmn push +# Error: autumn.config.ts not found +# Run `atmn init` to create a config file + +# Invalid configuration +atmn push +# Error: Feature "invalid-id" uses unsupported characters +# IDs must be lowercase letters, numbers, and underscores only +``` + +### Network Errors + +```bash +# Connection issues - automatic retry with backoff +atmn pull +# Retrying connection... (attempt 2/3) +# ✓ Connected successfully +``` + +The CLI is designed to be resilient with clear error messages and automatic recovery where possible. \ No newline at end of file diff --git a/mintlify/api-reference/cli/config.mdx b/mintlify/api-reference/cli/config.mdx index 6fdcd17..82228b9 100644 --- a/mintlify/api-reference/cli/config.mdx +++ b/mintlify/api-reference/cli/config.mdx @@ -1,330 +1,562 @@ --- -title: "Product Config" -description: "Create your pricing plans and products via our CLI" +title: "Configuration Reference" +description: "Complete reference for autumn.config.ts - features, plans, and pricing configuration" --- -Products can be created via our dashboard, or via our CLI defined in an `autumn.config.ts` file. - -You can export `features` and `products` from this config file, and push them to Autumn using `npx atmn push` +The `autumn.config.ts` file defines your pricing plans, features, and billing logic. This reference covers every parameter and option available. - CLI functionality is in beta. Please let us know any issues you run into and - we'll resolve them ASAP. +Configuration files use TypeScript with full import support. Export your features and plans, then sync them with `atmn push`. -## Feature +## Configuration Structure + +Your config file exports features and plans: -The features of your application that can be gated depending on pricing tier. These will be used to define your products. +```ts autumn.config.ts +import { feature, plan, planFeature } from 'atmn'; + +// Define features first +export const messages = feature({ + id: 'messages', + name: 'AI Messages', + type: 'metered', + consumable: true +}); + +// Use features in plans +export const pro = plan({ + id: 'pro', + name: 'Professional', + items: [ + planFeature({ + feature_id: messages.id, + included: 1000 + }) + ] +}); +``` + +## Features + +Features define what can be metered, gated, or billed in your application. + +### `feature(config)` - The ID of the feature that will be used via Autumn's APIs. + Unique identifier for the feature. Used in API calls and SDK methods. - - The display name of the feature + + Display name for the feature shown in dashboard and billing UI. - - One of `single_use`, `continuous_use`, `credit_system` or `boolean`. See below - for examples. + + Feature type determining behavior: + - `"boolean"` - Simple feature flag (on/off) + - `"metered"` - Usage-based feature with consumption tracking + - `"credit_system"` - Credit-based feature with cost mapping -### Feature Types + + **Required for metered features.** Determines usage behavior: + - `true` - Single-use (consumed when used) like API calls, messages + - `false` - Continuous-use (ongoing usage) like seats, storage + + Not applicable for `boolean` or `credit_system` types. + + + + **Required for credit_system features.** Maps metered features to credit costs. + + Array of objects with: + - `metered_feature_id: string` - ID of the metered feature + - `credit_cost: number` - Credits required per usage + -#### Single-use meter + + Optional array of event names that trigger this feature. Used for webhook integration. + + + + Whether the feature is archived. Archived features are hidden but preserved for existing data. + -Single-use features are those that can be used-up and replenished. They may have a reset interval (eg 200 per month). +### Feature Types -Examples: AI messages, credits, API calls. +#### Boolean Feature + +Simple on/off feature flags: ```ts -export const messages = feature({ - id: "messages", - name: "Messages", - type: "single_use", +export const sso = feature({ + id: 'sso', + name: 'SSO Authentication', + type: 'boolean' + // No consumable field allowed }); ``` -#### Continuous-use meter - -Continuous-use features are those used on an ongoing basis. They do not reset periodically and may be prorated when billed for. +#### Metered Feature (Single-Use) -Examples: Seats, storage, workspaces. +Features consumed when used - like API calls or messages: ```ts -export const messages = feature({ - id: "seats", - name: "Seats", - type: "continuous_use", +export const apiCalls = feature({ + id: 'api_calls', + name: 'API Calls', + type: 'metered', + consumable: true // Consumed when used }); ``` -#### Credit system - -Use a credit system when you have multiple metered features that each cost a different amount. - -Eg, if a basic model message costs 1 credit, and a premium message costs 5 credits. +#### Metered Feature (Continuous-Use) - - If you set the price per credit to be 1 cent when you create your products, - these can be used as monetary credits (eg 0.05 USD per premium message) - +Features for ongoing usage - like seats or storage: ```ts -export const credits = feature({ - id: "ai_credits", - name: "AI Credits", - type: "credit_system", - credit_schema: [ - { - metered_feature_id: basicMessage.id, - credit_cost: 1, - }, - { - metered_feature_id: premiumMessage.id, - credit_cost: 5, - }, - ], +export const seats = feature({ + id: 'seats', + name: 'Team Seats', + type: 'metered', + consumable: false // Ongoing usage }); ``` -#### Boolean +#### Credit System Feature -A feature flag that can be enabled or disabled. +Credit-based features with cost mapping: ```ts -export const sso = feature({ - id: "sso", - name: "SSO Auth", - type: "boolean", +// First define the underlying metered features +export const basicModel = feature({ + id: 'basic_model', + name: 'Basic AI Model', + type: 'metered', + consumable: true +}); + +export const premiumModel = feature({ + id: 'premium_model', + name: 'Premium AI Model', + type: 'metered', + consumable: true +}); + +// Then define the credit system +export const aiCredits = feature({ + id: 'ai_credits', + name: 'AI Credits', + type: 'credit_system', + credit_schema: [ + { metered_feature_id: basicModel.id, credit_cost: 1 }, + { metered_feature_id: premiumModel.id, credit_cost: 5 } + ] }); ``` -## Products +## Plans + +Plans combine features with pricing to create your subscription tiers. -Products are made up of features and prices, and define your pricing plans. You should create products for any free plans, paid plans and any add-ons / top-up products. +### `plan(config)` - The ID of the product that will be used via Autumn's APIs. + Unique identifier for the plan. Used in checkout and subscription APIs. - - The display name of the product. + + Display name for the plan shown in pricing tables and billing. - - Whether the product should be attached by default to new customers + + Optional description of the plan for marketing copy. - - Whether the product is an add-on and can be purchased alongside other products - (as opposed to trigger upgrade/downgrade flows) + + Optional grouping category for organizing plans in the dashboard. - - An array of objects that define the product. Can be one of: - - - `featureItem`: a feature to grant access to when the product is enabled - - `priceItem`: a fixed price to pay for the product - - `pricedFeatureItem`: a feature that has a price associated based on usage or quantity purchased. + + Whether this plan is an add-on that can be purchased alongside other plans. + + + Whether to automatically assign this plan to new customers. -### Item Types + + Base subscription price for the plan: + - `amount: number` - Price in cents (e.g., 2000 = $20.00) + - `interval: string` - Billing interval: `"month"`, `"quarter"`, `"semi_annual"`, `"year"` + -Define your products using a combination of the 3 item types below. + + Array of `planFeature()` objects defining what's included in the plan. + -#### Feature Item + + Optional free trial configuration: + - `duration_length: number` - Trial duration (e.g., 14) + - `duration_type: string` - Duration type: `"day"`, `"month"`, `"year"` + - `card_required: boolean` - Whether card is required to start trial + -A feature that is included with the product. +### Basic Plan Structure - - Feature ID for the product item +```ts +export const pro = plan({ + id: 'pro', + name: 'Professional', + description: 'Perfect for growing teams', + group: 'main', + price: { + amount: 5000, // $50.00 + interval: 'month' + }, + free_trial: { + duration_length: 14, + duration_type: 'day', + card_required: true + }, + items: [ + // Plan features go here + ] +}); +``` + +## Plan Features + +Plan features define what's included with each plan and how it's priced. + +### `planFeature(config)` + + + ID of the feature to include in this plan. - - How much usage is included with this item. This acts as a usage limit. Not - applicable for boolean features. + + Amount included for free with the plan. For boolean features, omit this field. - + + Reset configuration for included amounts: + - `interval: string` - Reset interval: `"hour"`, `"day"`, `"week"`, `"month"`, `"quarter"`, `"semi_annual"`, `"year"` + -`month` | `hour` | `day` | `week` | `quarter` | `semi_annual` | `year` + + Pricing configuration for usage beyond included amounts. + -How often the feature's balance should be reset back to the included_usage. -Set as `null` for one-time grants. + + Proration rules for quantity changes: + - `on_increase: string` - `"prorate"` or `"charge_immediately"` + - `on_decrease: string` - `"refund_immediately"`, `"prorate"`, or `"no_action"` + + + Rollover configuration for unused included amounts: + - `max: number` - Maximum amount that can roll over + - `expiry_duration_type: string` - `"month"`, `"year"`, or `"forever"` + - `expiry_duration_length: number` - Expiry duration (ignored if type is "forever") - - The entity feature to assign this item to: eg, seats. This will set a usage - limit at the entity level (eg, 10 message per seat per month) +### Pricing Configuration + +The `price` object supports multiple billing models: + + + Price per billing unit in cents. -**Example** + + Billing interval: `"month"`, `"quarter"`, `"semi_annual"`, `"year"`. Omit for one-time charges. + -```ts -export const free = product({ - id: "free", - name: "Free", - is_default: true, - items: [ - // 5 messages per month - featureItem({ - feature_id: messages.id, - included_usage: 5, - interval: "month", - }), - // 3 seats (no reset) - featureItem({ - feature_id: seats.id, - included_usage: 3, - }), - // SSO Auth (boolean) - featureItem({ - feature_id: sso.id, - }), - ], -}); -``` + + Billing method: + - `"usage_based"` - Charge based on actual usage + - `"prepaid"` - Customer purchases fixed quantities upfront + -#### Price Item + + Number of units per price. E.g., $5 per 100 credits = `amount: 500, billing_units: 100` + -A fixed price to be charged with the product: either one-time or a subscription. + + Tiered pricing configuration (alternative to flat pricing): + - `to: number | "inf"` - Usage threshold for this tier + - `amount: number` - Price per unit in this tier + - - A fixed amount to charge for this product + + Maximum quantity that can be purchased (for usage_based billing). - +### Plan Feature Examples -`month` | `quarter` | `semi_annual` | `year` +#### Free Allocation with Reset -How often this price should be billed to the customer. Set as `null` for -one-time prices. +```ts +planFeature({ + feature_id: messages.id, + included: 1000, + reset: { interval: 'month' } + // No price = free allocation +}) +``` - +#### Usage-Based Pricing -**Example** +```ts +planFeature({ + feature_id: seats.id, + included: 5, // 5 free seats + price: { + amount: 1000, // $10.00 per additional seat + interval: 'month', + billing_method: 'usage_based', + billing_units: 1 + } +}) +``` + +#### Prepaid Packages ```ts -export const pro = product({ - id: "pro", - name: "Pro", - items: [ - // 20 USD per month - priceItem({ - price: 20, - interval: "month", - }), - // 5 USD (one-time price) - priceItem({ - price: 5, - }), - ], -}); +planFeature({ + feature_id: credits.id, + price: { + amount: 500, // $5.00 per package + billing_units: 100, // 100 credits per package + billing_method: 'prepaid' + } +}) ``` -#### Priced Feature Item +#### Tiered Pricing + +```ts +planFeature({ + feature_id: apiCalls.id, + price: { + tiers: [ + { to: 1000, amount: 1 }, // First 1000: $0.01 each + { to: 10000, amount: 0.8 }, // Next 9000: $0.008 each + { to: 'inf', amount: 0.5 } // Beyond 10k: $0.005 each + ], + billing_method: 'usage_based', + interval: 'month' + } +}) +``` -A price to be charged based on the usage or prepaid quantity of a feature. +#### Advanced Configuration - - Feature ID for the product item - +```ts +planFeature({ + feature_id: storage.id, + included: 10, // 10 GB included + price: { + amount: 200, // $2.00 per additional GB + interval: 'month', + billing_method: 'usage_based', + max_purchase: 100 // Max 100 GB additional + }, + proration: { + on_increase: 'prorate', + on_decrease: 'refund_immediately' + }, + rollover: { + max: 50, // Max 50 GB rollover + expiry_duration_type: 'month', + expiry_duration_length: 3 // Expires after 3 months + } +}) +``` - - A fixed amount to charge per `billing_units` of this feature. - +#### Boolean Features - - The package quantity that the price is charged in (eg 5 USD for 100 messages) - +```ts +planFeature({ + feature_id: sso.id + // No included amount or price - just grants access +}) +``` - +## Complete Example -`prepaid` | `pay_per_use` +Here's a comprehensive example showcasing different feature types and pricing models: -Whether the feature is charged based on how much is used (`pay_per_use`), or if a fixed quantity is purchased upfront (`prepaid`). + -For continuous use meters that are `pay_per_use` (eg paying per seat used), you can define billing behavior in the dashboard (eg, whether to bill immediately or at the end of the cycle). +```ts autumn.config.ts +import { feature, plan, planFeature } from 'atmn'; - +// === Features === - - How much usage is included with this item. - +// Single-use metered feature +export const messages = feature({ + id: 'messages', + name: 'AI Messages', + type: 'metered', + consumable: true +}); - +// Continuous-use metered feature +export const seats = feature({ + id: 'seats', + name: 'Team Seats', + type: 'metered', + consumable: false +}); -`month` | `quarter` | `semi_annual` | `year` +// Boolean feature flag +export const sso = feature({ + id: 'sso', + name: 'SSO Authentication', + type: 'boolean' +}); -How often this price should be billed to the customer. Set as `null` for -one-time prices. +// Credit system with underlying features +export const basicCalls = feature({ + id: 'basic_api_calls', + name: 'Basic API Calls', + type: 'metered', + consumable: true +}); - +export const premiumCalls = feature({ + id: 'premium_api_calls', + name: 'Premium API Calls', + type: 'metered', + consumable: true +}); - - The entity feature to assign this item to: eg, seats. This will set a usage - price at the entity level (eg, 0.01 USD per message per seat per month) - +export const apiCredits = feature({ + id: 'api_credits', + name: 'API Credits', + type: 'credit_system', + credit_schema: [ + { metered_feature_id: basicCalls.id, credit_cost: 1 }, + { metered_feature_id: premiumCalls.id, credit_cost: 5 } + ] +}); -**Example** +// === Plans === -```ts -export const pro = product({ - id: "pro", - name: "Pro", +export const free = plan({ + id: 'free', + name: 'Free', + description: 'Perfect for getting started', + auto_enable: true, // Auto-assign to new customers items: [ - // 100 messages included - // then, 0.01 USD per 10 messages - pricedFeatureItem({ + planFeature({ feature_id: messages.id, - included_usage: 100, - price: 0.01, - billing_units: 10, + included: 100, + reset: { interval: 'month' } }), - ], + planFeature({ + feature_id: seats.id, + included: 2 + }) + ] }); -``` -```ts -export const team = product({ - id: "team", - name: "team", +export const pro = plan({ + id: 'pro', + name: 'Professional', + description: 'For growing teams', + price: { + amount: 2000, // $20.00 + interval: 'month' + }, + free_trial: { + duration_length: 14, + duration_type: 'day', + card_required: true + }, items: [ - // 20 USD per seat per month - // paying per seat used - pricedFeatureItem({ - feature_id: seats.id, - price: 20, - interval: "month", + // Free allocation with reset + planFeature({ + feature_id: messages.id, + included: 2000, + reset: { interval: 'month' } }), - // 10 USD per seat per month - // paying upfront for a fixed quantity - pricedFeatureItem({ + + // Usage-based pricing with included amount + planFeature({ feature_id: seats.id, - price: 10, - interval: "month", - usage_model: "prepaid", + included: 5, + price: { + amount: 800, // $8.00 per additional seat + interval: 'month', + billing_method: 'usage_based', + billing_units: 1 + } }), - ], + + // Boolean feature (just access) + planFeature({ + feature_id: sso.id + }) + ] }); -``` -```ts -export const topUp = product({ - id: "top_up", - name: "Credit top up", +export const enterprise = plan({ + id: 'enterprise', + name: 'Enterprise', + description: 'For large organizations', + price: { + amount: 10000, // $100.00 + interval: 'month' + }, items: [ - // 5 USD per 100 credits - // one-time payment (+ credits don't reset periodically) - pricedFeatureItem({ - feature_id: credits.id, - price: 5, - billing_units: 100, - usage_model: "prepaid", + // Tiered pricing + planFeature({ + feature_id: messages.id, + price: { + tiers: [ + { to: 5000, amount: 0.02 }, // First 5k: $0.02 each + { to: 20000, amount: 0.015 }, // Next 15k: $0.015 each + { to: 'inf', amount: 0.01 } // Beyond 20k: $0.01 each + ], + billing_method: 'usage_based', + interval: 'month' + } + }), + + // Unlimited seats + planFeature({ + feature_id: seats.id + // No included limit or price = unlimited }), - ], + + planFeature({ + feature_id: sso.id + }) + ] +}); + +// Add-on for extra credits +export const creditTopUp = plan({ + id: 'credit_top_up', + name: 'Credit Top-up', + description: 'Extra API credits', + add_on: true, // Can be purchased with other plans + items: [ + planFeature({ + feature_id: apiCredits.id, + price: { + amount: 1000, // $10.00 per package + billing_units: 1000, // 1000 credits per package + billing_method: 'prepaid' + } + }) + ] }); ``` + + + +This configuration creates a complete pricing structure with multiple plan tiers, different billing models, and various feature types that can handle most SaaS pricing scenarios. \ No newline at end of file diff --git a/mintlify/api-reference/cli/data.mdx b/mintlify/api-reference/cli/data.mdx new file mode 100644 index 0000000..a5a8693 --- /dev/null +++ b/mintlify/api-reference/cli/data.mdx @@ -0,0 +1,436 @@ +--- +title: "Data Commands" +description: "Browse customers, plans, features, and events - interactive exploration and headless data export" +--- + +The data commands provide powerful tools to explore and analyze your Autumn data. Each command offers both interactive browsing and headless export capabilities. + +## Customers + +Browse and inspect your customer data, subscriptions, and usage. + +### Basic Usage + +```bash +atmn customers +``` + +Opens an interactive table interface for browsing customers with search, filtering, and pagination. + +### Command Options + + + Run in headless mode for scripting and automation + + + + Page number for pagination (headless mode) + + + + Search customers by name, email, or ID (headless mode) + + + + Get a specific customer by ID (headless mode) + + + + Number of customers per page (headless mode) + + + + Output format: `text`, `json`, `csv` (headless mode) + + +### Interactive Mode + +The interactive interface provides: + +- **Rich Table Display**: Sortable columns with customer info, plans, and usage +- **Live Search**: Filter customers in real-time +- **Detailed View**: Press Enter to see full customer details +- **Pagination**: Navigate through large customer lists +- **Plan Information**: See active subscriptions and add-ons + +### Headless Mode Examples + + + +```bash List all customers +atmn customers --headless --format json +``` + +```bash Search for specific customer +atmn customers --headless --search "john@example.com" --format text +``` + +```bash Get customer by ID +atmn customers --headless --id "cus_1234567890" --format json +``` + +```bash Export to CSV +atmn customers --headless --limit 1000 --format csv > customers.csv +``` + + + +## Plans/Products + +Browse and inspect your pricing plans and product configurations. + +### Basic Usage + +```bash +atmn plans +# or +atmn products +``` + +Both commands are aliases and provide identical functionality. + +### Command Options + + + Run in headless mode for scripting and automation + + + + Page number for pagination (headless mode) + + + + Search plans by name or ID (headless mode) + + + + Get a specific plan by ID (headless mode) + + + + Number of plans per page (headless mode) + + + + Output format: `text`, `json`, `csv` (headless mode) + + + + Include archived plans in the results + + +### Interactive Features + +- **Plan Overview**: See pricing, features, and customer counts +- **Feature Breakdown**: View included features and pricing rules +- **Customer Analytics**: See how many customers are on each plan +- **Version History**: Browse different versions of plans +- **Archive Status**: Filter between active and archived plans + +### Headless Examples + + + +```bash List all active plans +atmn plans --headless --format json +``` + +```bash Include archived plans +atmn plans --headless --include-archived --format csv +``` + +```bash Get specific plan details +atmn plans --headless --id "pro" --format json +``` + + + +## Features + +Browse and inspect your feature definitions and configurations. + +### Basic Usage + +```bash +atmn features +``` + +### Command Options + + + Run in headless mode for scripting and automation + + + + Page number for pagination (headless mode) + + + + Search features by name or ID (headless mode) + + + + Get a specific feature by ID (headless mode) + + + + Number of features per page (headless mode) + + + + Output format: `text`, `json`, `csv` (headless mode) + + + + Include archived features in the results + + +### Interactive Features + +- **Feature Types**: See boolean, metered, and credit system features +- **Usage Analytics**: View usage patterns and limits +- **Plan Usage**: See which plans include each feature +- **Credit Mappings**: For credit system features, see cost mappings +- **Dependencies**: Understand feature relationships + +### Headless Examples + + + +```bash List all features with types +atmn features --headless --format json | jq '.[] | {id, name, type}' +``` + +```bash Find credit system features +atmn features --headless --format json | jq '.[] | select(.type == "credit_system")' +``` + +```bash Export feature definitions +atmn features --headless --format csv > features.csv +``` + + + +## Events + +Browse and analyze usage events from your application. + +### Basic Usage + +```bash +atmn events +``` + +### Command Options + + + Run in headless mode for scripting and automation + + + + Page number for pagination + + + + Filter events by customer ID + + + + Filter by feature ID (comma-separated for multiple) + + + + Number of events per page + + + + Time range: `24h`, `7d`, `30d`, `90d` + + + + View mode: `list` (individual events) or `aggregate` (summary stats) + + + + Bin size for aggregate mode: `hour`, `day`, `month` + + + + Group by property in aggregate mode (e.g., `customer_id`, `feature_id`) + + + + Output format: `text`, `json`, `csv` + + +### Interactive Mode Features + +**List Mode:** +- **Event Stream**: Real-time view of usage events +- **Rich Details**: Customer, feature, amount, timestamp +- **Filtering**: Live filters for customer, feature, and time range +- **Search**: Find specific events or patterns + +**Aggregate Mode:** +- **Usage Charts**: Visual charts of usage patterns +- **Time Series**: Usage trends over time +- **Grouping**: Break down usage by customer, feature, or other dimensions +- **Statistics**: Min, max, average, total usage + +### Headless Examples + + + +```bash Recent events for customer +atmn events --headless --customer "cus_123" --time "24h" --format json +``` + +```bash Feature usage analysis +atmn events --headless --feature "messages,api_calls" --mode aggregate --bin day --format csv +``` + +```bash Usage by customer (last 30 days) +atmn events --headless --mode aggregate --time 30d --group-by customer_id --format json +``` + +```bash Export all events to CSV +atmn events --headless --limit 10000 --format csv > events.csv +``` + + + +### Aggregate Mode Examples + +Aggregate mode is powerful for analytics: + +```bash +# Daily usage totals for last week +atmn events --headless --mode aggregate --bin day --time 7d --format json + +# Usage by feature over last month +atmn events --headless --mode aggregate --group-by feature_id --time 30d --format csv + +# Hourly usage patterns for specific customer +atmn events --headless --mode aggregate --bin hour --customer "cus_123" --time 7d +``` + +## Data Export Workflows + +### Customer Analysis + + + +```bash Export customer list with plans +atmn customers --headless --format csv > customers.csv + +# Get detailed customer data +atmn customers --headless --format json > customers.json +``` + +```bash Find high-usage customers +atmn events --headless --mode aggregate --group-by customer_id --time 30d --format json | \ + jq 'sort_by(.total_usage) | reverse | .[0:10]' +``` + + + +### Usage Analytics + + + +```bash Feature usage report +atmn events --headless --mode aggregate --group-by feature_id --time 30d --format csv > usage_report.csv +``` + +```bash Daily usage trends +atmn events --headless --mode aggregate --bin day --time 30d --format json > daily_usage.json +``` + + + +### Plan Performance + + + +```bash Plan adoption analysis +atmn customers --headless --format json | \ + jq 'group_by(.plan_id) | map({plan: .[0].plan_id, customers: length})' +``` + +```bash Feature utilization by plan +atmn plans --headless --format json > plans.json +atmn events --headless --mode aggregate --group-by feature_id --format json > feature_usage.json +``` + + + +## Automation & Scripting + +### Monitoring Scripts + +Create monitoring dashboards with regular data exports: + +```bash +#!/bin/bash +# Daily usage monitoring script + +DATE=$(date +%Y-%m-%d) + +# Export daily metrics +atmn events --headless --mode aggregate --bin day --time 1d --format json > "usage_${DATE}.json" +atmn customers --headless --format csv > "customers_${DATE}.csv" + +# Alert on high usage +TOTAL_USAGE=$(jq '.[] | .total_usage' "usage_${DATE}.json" | awk '{sum+=$1} END {print sum}') +if (( $(echo "$TOTAL_USAGE > 10000" | bc -l) )); then + echo "Alert: High usage detected: $TOTAL_USAGE" +fi +``` + +### Data Pipeline Integration + +Integrate with analytics platforms: + +```bash +# Export to BigQuery-compatible CSV +atmn events --headless --time 7d --format csv --limit 100000 | \ + bq load --source_format=CSV dataset.events /dev/stdin + +# Send to webhook for real-time processing +atmn events --headless --time 1h --format json | \ + curl -X POST -H "Content-Type: application/json" -d @- https://webhook.example.com/events +``` + +## Environment-Specific Data + +Remember that data is environment-specific: + + + +```bash Sandbox data (default) +atmn customers --headless --format json +``` + +```bash Production data +atmn customers --prod --headless --format json +``` + +```bash Local development data +atmn customers --local --headless --format json +``` + + + + +**Production Data**: Be cautious when exporting production data. Ensure you comply with privacy policies and data protection regulations when handling customer information. + + +## Performance Tips + +For large datasets: + +- Use `--limit` to control memory usage +- Export in batches using `--page` parameter +- Use `--format csv` for better performance with large datasets +- Filter early with `--customer`, `--feature`, or `--time` flags +- Use aggregate mode for summary statistics instead of raw events \ No newline at end of file diff --git a/mintlify/api-reference/cli/getting-started.mdx b/mintlify/api-reference/cli/getting-started.mdx new file mode 100644 index 0000000..5f33e92 --- /dev/null +++ b/mintlify/api-reference/cli/getting-started.mdx @@ -0,0 +1,179 @@ +--- +title: "Getting Started" +description: "Install the atmn CLI and set up your first Autumn project" +--- + +Get up and running with the `atmn` CLI in minutes. This guide will walk you through installation, authentication, and creating your first pricing configuration. + +## Installation + +Install the `atmn` CLI globally using npm: + +```bash +npm install -g atmn +``` + +Or run commands directly with npx (no installation required): + +```bash +npx atmn +``` + + +The CLI requires Node.js 16 or higher. + + +## Authentication + +Before you can use the CLI, you need to authenticate with your Autumn account: + +```bash +atmn login +``` + +This opens your browser to authenticate via OAuth and automatically creates API keys for both sandbox and production environments. + +The login process will: + +1. Open your browser to Autumn's login page +2. Prompt you to select your organization +3. Generate API keys for sandbox (`am_sk_test_*`) and production (`am_sk_live_*`) +4. Save the keys to a `.env` file in your current directory + + + +```bash .env (generated) +AUTUMN_SECRET_KEY=am_sk_test_1234567890abcdef +AUTUMN_PROD_SECRET_KEY=am_sk_live_1234567890abcdef +``` + + + +## Create Your First Project + +Initialize a new Autumn project in your current directory: + +```bash +atmn init +``` + +The interactive wizard will help you choose from several starter templates: + +- **OpenAI**: API credits and usage-based pricing +- **T3 Chat**: Messaging app with seats and message limits +- **Railway**: Infrastructure pricing with usage tiers +- **Linear**: SaaS tool with feature flags and usage limits + +This creates an `autumn.config.ts` file with your pricing configuration: + + + +```ts autumn.config.ts (example) +import { feature, plan, planFeature } from 'atmn'; + +export const messages = feature({ + id: 'messages', + name: 'AI Messages', + type: 'metered', + consumable: true // Single-use (consumed when used) +}); + +export const seats = feature({ + id: 'seats', + name: 'Team Seats', + type: 'metered', + consumable: false // Continuous-use (ongoing usage) +}); + +export const pro = plan({ + id: 'pro', + name: 'Professional', + description: 'For growing teams', + price: { + amount: 50, // $50.00 + interval: 'month' + }, + items: [ + planFeature({ + feature_id: messages.id, + included: 1000, + reset: { interval: 'month' } + }), + planFeature({ + feature_id: seats.id, + included: 5, + price: { + amount: 10, + interval: 'month', + billing_method: 'usage_based', + billing_units: 1 + } + }) + ] +}); +``` + + + +## Sync Your Configuration + +Push your local configuration to Autumn: + +```bash +atmn push +``` + +This will create your features and plans in Autumn's sandbox environment, ready for testing in your application. + +## Next Steps + + + + Learn about OAuth flow, API keys, and environment management + + + + Complete reference for autumn.config.ts file format + + + + Sync changes between local files and Autumn + + + + Complete list of all CLI commands and options + + + +## Verify Your Setup + +Check that everything is working correctly: + +```bash +# Check your environment and organization +atmn env + +# Preview your plans locally +atmn preview + +# Open the Autumn dashboard +atmn dashboard +``` + +You're now ready to integrate Autumn's pricing and billing into your application! \ No newline at end of file diff --git a/mintlify/api-reference/cli/push-pull.mdx b/mintlify/api-reference/cli/push-pull.mdx new file mode 100644 index 0000000..0ddf715 --- /dev/null +++ b/mintlify/api-reference/cli/push-pull.mdx @@ -0,0 +1,383 @@ +--- +title: "Push & Pull" +description: "Sync configuration between local files and Autumn - workflows, change analysis, and production safety" +--- + +The `push` and `pull` commands keep your local `autumn.config.ts` in sync with your Autumn account. This guide covers the workflows, safety features, and best practices for configuration management. + +## Pull Workflow + +Pull changes from Autumn to your local configuration files. + +### Basic Pull + +```bash +atmn pull +``` + +This fetches features and plans from your current environment and updates your local `autumn.config.ts` file. + +### Pull Options + + + Force overwrite the config file instead of using smart in-place updates + + + + Pull from production environment instead of sandbox + + + + Pull from localhost:8080 instead of api.useautumn.com + + +### In-Place Updates vs Force Overwrite + +**In-place updates (default):** +- Preserves your local changes, comments, and code structure +- Merges remote changes with local modifications +- Shows detailed change summary + +**Force overwrite (`--force`):** +- Completely rewrites the config file +- Loses local changes and comments +- Useful for resolving complex conflicts + + + +```bash In-place update (default) +atmn pull + +✓ Pulled 5 features, 3 plans from sandbox + In-place update: 2 features updated, 1 added, 0 deleted + 1 plans updated, 0 added, 0 deleted +✓ Generated SDK types at: @useautumn-sdk.d.ts +``` + +```bash Force overwrite +atmn pull --force + +✓ Pulled 5 features, 3 plans from sandbox +✓ Overwrote autumn.config.ts +✓ Generated SDK types at: @useautumn-sdk.d.ts +``` + + + +### SDK Type Generation + +Pull automatically generates TypeScript definitions for your SDK: + + + +```ts @useautumn-sdk.d.ts (generated) +declare module '@useautumn/sdk' { + // Feature IDs from your config + type FeatureIds = 'messages' | 'seats' | 'sso' | 'api_credits'; + + // Plan IDs from your config + type PlanIds = 'free' | 'pro' | 'enterprise'; + + // Strongly typed SDK methods + export function trackUsage( + feature: FeatureIds, + amount?: number + ): Promise; + + export function useCustomer(): { + features: Record; + plans: PlanIds[]; + }; +} +``` + + + +## Push Workflow + +Push your local configuration to Autumn. + +### Basic Push + +```bash +atmn push +``` + +This analyzes your local config, compares it with remote state, and syncs changes to Autumn. + +### Push Options + + + Automatically confirm all prompts (useful for CI/CD) + + + + Push to production environment instead of sandbox + + + + Push to localhost:8080 instead of api.useautumn.com + + +### Change Analysis + +Before making changes, push analyzes the differences and shows you exactly what will happen: + +```bash +atmn push + +Analyzing changes... + +Features: + ✓ messages (no changes) + + seats (new feature) + ~ sso (updated: name changed) + - old_feature (will be deleted) + +Plans: + ✓ free (no changes) + ~ pro (updated: price changed $20 → $25) + + enterprise (new plan) + +Ready to push 1 new feature, 1 updated feature, 1 deletion + 1 new plan, 1 updated plan +``` + +### Smart Prompts + +Push uses intelligent prompts based on the changes detected: + +#### Production Confirmation + +```bash +atmn push --prod + +⚠️ PRODUCTION PUSH +You are about to push changes to your LIVE production environment. +This will affect real customers and billing. + +Continue? (y/N) +``` + +#### Plan Versioning + +When a plan has active customers, push creates a new version instead of modifying the existing one: + +```bash +Plan "pro" has 15 customers and will create a new version. +Existing customers will remain on the current version. +New customers will get the updated version. + +Continue? (y/N) +``` + +#### Safe Deletions + +Different prompts for different deletion scenarios: + +```bash +# Plan with customers - suggests archiving +Plan "old-plan" has 5 customers. +Deleting it will affect existing subscriptions. +Recommend archiving instead of deleting. + +Delete anyway? (y/N) + +# Feature used by plans - shows dependencies +Feature "seats" is used by 3 plans: pro, enterprise, team +Deleting it will affect these plans. + +Delete anyway? (y/N) + +# Safe deletion - no dependencies +Feature "unused-feature" has no dependencies. +Safe to delete. + +Continue? (y/N) +``` + +#### Archived Item Recovery + +```bash +Plan "archived-plan" is currently archived. +Do you want to unarchive it? (Y/n) +``` + +### Headless Mode + +In CI/CD environments without TTY, push provides clear feedback: + +```bash +# Without --yes flag when prompts are needed +atmn push + +Push requires confirmation for the following: + - Pushing to production environment + - Plan "pro" has customers and will create a new version + - Feature "old_feature" will be deleted + +To proceed, either: + 1. Run this command in an interactive terminal to review each action + 2. Run with --yes to automatically proceed with default actions +``` + +```bash +# With --yes flag - auto-confirms with safe defaults +atmn push --yes + +✓ Pushed 2 features, 1 plan to sandbox + - Created new version of plan "pro" (v1.2) + - Archived feature "old_feature" instead of deleting +``` + +## Environment-Specific Workflows + +### Sandbox Development + +Typical development workflow using sandbox: + +```bash +# Work in sandbox by default +atmn pull +# Edit autumn.config.ts +atmn push +atmn preview # Test locally +``` + +### Production Deployment + +When ready to deploy to production: + +```bash +# Push to production with confirmation +atmn push --prod + +# Or automate in CI/CD +atmn push --prod --yes +``` + +### Local Development Server + +When running Autumn locally: + +```bash +# Use local API server +atmn push --local +atmn pull --local + +# Combined with production data +atmn push --local --prod +``` + +## Best Practices + +### Development Workflow + +1. **Start with Pull**: Always pull before making changes + ```bash + atmn pull + ``` + +2. **Make Changes**: Edit your `autumn.config.ts` file + +3. **Preview Locally**: Test your changes without API calls + ```bash + atmn preview + ``` + +4. **Push to Sandbox**: Test in sandbox environment + ```bash + atmn push + ``` + +5. **Deploy to Production**: When ready + ```bash + atmn push --prod + ``` + +### Team Collaboration + +**Option 1: Config as Source of Truth** +- Commit `autumn.config.ts` to version control +- Team members pull from VCS and push to Autumn +- Good for code-first teams + +**Option 2: Autumn as Source of Truth** +- Make changes in Autumn dashboard +- Run `atmn pull` to sync local files +- Commit the updated config +- Good for less technical team members + +### CI/CD Integration + +```yaml +# GitHub Actions example +- name: Deploy Autumn Config + run: | + atmn push --prod --yes + env: + AUTUMN_PROD_SECRET_KEY: ${{ secrets.AUTUMN_PROD_SECRET_KEY }} +``` + + +**Production Safety**: Always review changes carefully before pushing to production. Use `--yes` flag only in automated environments where you trust the configuration. + + +### Handling Conflicts + +When pull detects conflicts between local and remote changes: + +```bash +# Use force to overwrite with remote +atmn pull --force + +# Or manually resolve and push your changes +atmn push +``` + +## Error Handling + +### Common Issues + +**Config file not found:** +```bash +atmn push + +Error: autumn.config.ts not found +Run `atmn init` to create a config file +``` + +**Invalid configuration:** +```bash +atmn push + +Error: Feature "invalid-id" uses unsupported characters +IDs must be lowercase letters, numbers, and underscores only +``` + +**API key issues:** +```bash +atmn pull + +Error: 401 Unauthorized - Invalid API key +# CLI automatically prompts for re-authentication +``` + +**Network issues:** +```bash +atmn push + +Error: Unable to connect to api.useautumn.com +Check your internet connection and try again +``` + +### Recovery + +Most errors are automatically handled: + +- **Invalid tokens**: Automatic OAuth re-authentication +- **Network issues**: Retry with exponential backoff +- **Validation errors**: Clear error messages with field details +- **Conflicts**: Smart prompts to guide resolution + +The CLI is designed to be resilient and help you recover from common issues without data loss. \ No newline at end of file diff --git a/mintlify/api-reference/cli/sdk-types.mdx b/mintlify/api-reference/cli/sdk-types.mdx new file mode 100644 index 0000000..e8ae9c8 --- /dev/null +++ b/mintlify/api-reference/cli/sdk-types.mdx @@ -0,0 +1,412 @@ +--- +title: "SDK Type Generation" +description: "Automatic TypeScript definition generation for type-safe feature and plan IDs" +--- + +The CLI automatically generates TypeScript definitions from your configuration, providing compile-time type safety for your SDK usage. + +## Generated Types + +When you run `atmn pull`, the CLI generates `@useautumn-sdk.d.ts` with strongly-typed interfaces based on your actual features and plans. + +### File Generation + + + +```bash Automatic generation +atmn pull + +✓ Pulled 5 features, 3 plans from sandbox +✓ Generated SDK types at: @useautumn-sdk.d.ts +``` + +```ts @useautumn-sdk.d.ts (generated) +declare module '@useautumn/sdk' { + // Feature IDs from your configuration + type FeatureIds = 'messages' | 'seats' | 'sso' | 'ai_credits' | 'storage'; + + // Plan IDs from your configuration + type PlanIds = 'free' | 'pro' | 'enterprise' | 'credit_top_up'; + + // Strongly typed SDK methods + export function trackUsage( + feature: FeatureIds, + amount?: number + ): Promise; + + export function useCustomer(): { + features: Record; + plans: PlanIds[]; + // ... other customer properties + }; + + // Other SDK functions with typed parameters + export function checkout(options: { + planIds: PlanIds[]; + // ... other checkout options + }): Promise; +} +``` + + + +## Type Safety Benefits + +### Feature Tracking + +Without types, you might accidentally use wrong feature IDs: + + + +```ts Without Types (Error-prone) +// Runtime error if feature ID is wrong +await trackUsage('mesages', 1); // Typo! +await trackUsage('invalid_feature', 1); // Doesn't exist +``` + +```ts With Types (Compile-time safety) +// TypeScript catches errors at compile time +await trackUsage('messages', 1); // ✓ Valid +await trackUsage('mesages', 1); // ✗ TypeScript error +await trackUsage('invalid_feature', 1); // ✗ TypeScript error +``` + + + +### Plan Management + + + +```ts Checkout with Type Safety +// Only valid plan IDs are accepted +const checkout = await checkout({ + planIds: ['pro'], // ✓ Valid plan + customerId: 'cus_123' +}); + +// TypeScript prevents invalid plans +const badCheckout = await checkout({ + planIds: ['premium'], // ✗ TypeScript error - plan doesn't exist + customerId: 'cus_123' +}); +``` + + + +### Customer Data Access + + + +```ts Type-safe Customer Data +const customer = useCustomer(); + +// Type-safe access to features +const messageUsage = customer.features.messages.usage; // ✓ Type-safe +const seatUsage = customer.features.seats.usage; // ✓ Type-safe +const invalidUsage = customer.features.invalid.usage; // ✗ TypeScript error + +// Type-safe plan checking +const hasProPlan = customer.plans.includes('pro'); // ✓ Type-safe +const hasFakePlan = customer.plans.includes('fake'); // ✗ TypeScript error +``` + + + +## Generation Process + +### Multi-Environment Merging + +The CLI intelligently merges features and plans from both environments to create comprehensive types: + +1. **Fetch from Sandbox**: Gets all features/plans from sandbox environment +2. **Fetch from Production**: Gets all features/plans from production environment +3. **Merge & Deduplicate**: Combines both sets, removing duplicates by ID +4. **Generate Types**: Creates union types from all unique IDs + +This ensures your types include everything from both environments. + +### Configuration Parsing + +The generation process: + + + +```ts Source Configuration +export const messages = feature({ + id: 'messages', + name: 'AI Messages', + type: 'metered', + consumable: true +}); + +export const sso = feature({ + id: 'sso', + name: 'SSO Authentication', + type: 'boolean' +}); + +export const pro = plan({ + id: 'pro', + name: 'Professional', + // ...config +}); +``` + +```ts Generated Types +type FeatureIds = 'messages' | 'sso'; +type PlanIds = 'pro'; + +// Used in SDK method signatures +export function trackUsage( + feature: FeatureIds, + amount?: number +): Promise; +``` + + + +## IDE Integration + +### IntelliSense Support + +Modern editors provide excellent support for the generated types: + +- **Autocomplete**: Feature and plan IDs are suggested as you type +- **Error Detection**: Invalid IDs are highlighted immediately +- **Documentation**: Hover to see feature names and descriptions +- **Refactoring**: Rename features safely across your codebase + +### VSCode Example + + + +```ts IntelliSense in Action +// Typing 'await trackUsage(' shows: +// ✓ 'messages' - AI Messages +// ✓ 'seats' - Team Seats +// ✓ 'sso' - SSO Authentication +// ✓ 'ai_credits' - AI Credits + +await trackUsage('|'); // Cursor here - shows all valid options +``` + + + +## Advanced Usage + +### Custom Type Extensions + +Extend the generated types for your specific needs: + + + +```ts Custom extensions +// types/autumn.d.ts +import type { FeatureIds, PlanIds } from '@useautumn/sdk'; + +// Add custom utilities +export type MeteredFeatureIds = Extract; +export type BooleanFeatureIds = Extract; + +// Custom helper types +export interface FeatureConfig { + id: FeatureIds; + name: string; + description?: string; +} + +export interface PlanConfig { + id: PlanIds; + name: string; + price: number; + features: FeatureIds[]; +} +``` + + + +### Runtime Validation + +Combine types with runtime validation: + + + +```ts Type + Runtime validation +import type { FeatureIds, PlanIds } from '@useautumn/sdk'; +import { z } from 'zod'; + +// Schemas that match your types +const FeatureIdSchema = z.union([ + z.literal('messages'), + z.literal('seats'), + z.literal('sso'), + z.literal('ai_credits') +]); + +const PlanIdSchema = z.union([ + z.literal('free'), + z.literal('pro'), + z.literal('enterprise') +]); + +// Type-safe parsing of external data +function parseApiRequest(data: unknown) { + const parsed = z.object({ + feature: FeatureIdSchema, + plan: PlanIdSchema, + amount: z.number() + }).parse(data); + + // Now you know parsed.feature is a valid FeatureIds + return parsed; +} +``` + + + +## Keeping Types in Sync + +### Development Workflow + +1. **Modify Configuration**: Edit your `autumn.config.ts` +2. **Push Changes**: `atmn push` to update Autumn +3. **Pull Types**: `atmn pull` to regenerate types +4. **Fix Errors**: Address any TypeScript errors in your code + +### Automated Sync + +For CI/CD pipelines: + + + +```bash CI/CD Script +#!/bin/bash +# Deploy configuration and update types + +# Push configuration changes +atmn push --prod --yes + +# Pull to regenerate types (even if no config changes) +atmn pull --prod + +# Commit updated types +git add @useautumn-sdk.d.ts +git commit -m "Update SDK types" +``` + + + +### Type Drift Detection + +Catch when your code uses outdated feature/plan IDs: + + + +```ts Catching drift +// Old code using renamed feature +await trackUsage('old_feature_name', 1); // ✗ TypeScript error + +// Type system guides you to the correct ID +await trackUsage('new_feature_name', 1); // ✓ Updated +``` + + + +## Configuration Options + +### Disable Type Generation + +If you don't want automatic type generation: + + + +```ts autumn.config.ts +// Add this to your config to disable SDK type generation +export const config = { + generateSdkTypes: false +}; +``` + + + +### Custom Output Path + +Change where types are generated: + + + +```ts autumn.config.ts +export const config = { + sdkTypesPath: './src/types/autumn-sdk.d.ts' +}; +``` + + + +## Troubleshooting + +### Types Not Updating + +If types aren't reflecting your changes: + +```bash +# Force regeneration +atmn pull --force + +# Check the generated file +cat @useautumn-sdk.d.ts +``` + +### TypeScript Errors + +Common issues and solutions: + + + +```ts Module not found +// Error: Cannot find module '@useautumn/sdk' +// Solution: Make sure @useautumn-sdk.d.ts is in your project root + +// Add to tsconfig.json if needed: +{ + "compilerOptions": { + "typeRoots": ["./node_modules/@types", "./"] + } +} +``` + +```ts Duplicate declarations +// Error: Duplicate identifier 'FeatureIds' +// Solution: Only keep one @useautumn-sdk.d.ts file + +// Remove old files +rm old-sdk-types.d.ts +``` + + + +### Missing Types + +If features/plans are missing from types: + +1. **Check Environment**: Ensure you're pulling from the right environment +2. **Verify Push**: Make sure your config was successfully pushed +3. **Force Regeneration**: Use `atmn pull --force` to rebuild types + + + +```bash Debug missing types +# Check what's in Autumn +atmn features --headless --format json +atmn plans --headless --format json + +# Force regenerate types +atmn pull --force + +# Verify the generated types +grep -A 5 "type FeatureIds" @useautumn-sdk.d.ts +``` + + + +The generated types provide a seamless bridge between your configuration and your application code, catching errors early and making your billing integration more reliable. \ No newline at end of file diff --git a/mintlify/api-reference/cli/templates.mdx b/mintlify/api-reference/cli/templates.mdx new file mode 100644 index 0000000..7333605 --- /dev/null +++ b/mintlify/api-reference/cli/templates.mdx @@ -0,0 +1,508 @@ +--- +title: "Templates" +description: "Built-in starter templates and project scaffolding with atmn init" +--- + +The `atmn init` command provides pre-built templates to quickly scaffold common pricing models. Each template demonstrates different billing patterns and feature types. + +## Available Templates + +### OpenAI Template +**Use case:** API-based services with credit consumption +**Features:** Credit system for different model tiers + + + +```ts OpenAI Template Structure +// Features +export const basicModel = feature({ + id: 'basic_model', + name: 'Basic AI Model', + type: 'metered', + consumable: true +}); + +export const premiumModel = feature({ + id: 'premium_model', + name: 'Premium AI Model', + type: 'metered', + consumable: true +}); + +export const aiCredits = feature({ + id: 'ai_credits', + name: 'AI Credits', + type: 'credit_system', + credit_schema: [ + { metered_feature_id: basicModel.id, credit_cost: 1 }, + { metered_feature_id: premiumModel.id, credit_cost: 5 } + ] +}); + +// Plans +export const payAsYouGo = plan({ + id: 'pay_as_you_go', + name: 'Pay as you go', + items: [ + planFeature({ + feature_id: aiCredits.id, + price: { + amount: 1000, // $10 per 1000 credits + billing_units: 1000, + billing_method: 'prepaid' + } + }) + ] +}); +``` + + + +**Best for:** AI/ML services, API platforms, consumption-based pricing + +### T3 Chat Template +**Use case:** Messaging applications with seat-based billing +**Features:** Seat management and message limits + + + +```ts T3 Chat Template Structure +// Features +export const seats = feature({ + id: 'seats', + name: 'Seats', + type: 'metered', + consumable: false // Continuous use +}); + +export const messages = feature({ + id: 'messages', + name: 'Messages', + type: 'metered', + consumable: true // Single use +}); + +// Plans +export const free = plan({ + id: 'free', + name: 'Free', + auto_enable: true, + items: [ + planFeature({ + feature_id: seats.id, + included: 2 + }), + planFeature({ + feature_id: messages.id, + included: 100, + reset: { interval: 'month' } + }) + ] +}); + +export const pro = plan({ + id: 'pro', + name: 'Pro', + price: { + amount: 2000, // $20/month + interval: 'month' + }, + items: [ + planFeature({ + feature_id: seats.id, + included: 10, + price: { + amount: 500, // $5 per additional seat + interval: 'month', + billing_method: 'usage_based', + billing_units: 1 + } + }), + planFeature({ + feature_id: messages.id, + included: 10000, + reset: { interval: 'month' } + }) + ] +}); +``` + + + +**Best for:** Team collaboration tools, chat applications, SaaS with user-based pricing + +### Railway Template +**Use case:** Infrastructure services with resource-based pricing +**Features:** Usage tiers and resource limits + + + +```ts Railway Template Structure +// Features +export const cpuHours = feature({ + id: 'cpu_hours', + name: 'CPU Hours', + type: 'metered', + consumable: true +}); + +export const storage = feature({ + id: 'storage', + name: 'Storage GB', + type: 'metered', + consumable: false +}); + +export const bandwidth = feature({ + id: 'bandwidth', + name: 'Bandwidth GB', + type: 'metered', + consumable: true +}); + +// Plans with tiered pricing +export const hobby = plan({ + id: 'hobby', + name: 'Hobby', + price: { + amount: 500, // $5/month + interval: 'month' + }, + items: [ + planFeature({ + feature_id: cpuHours.id, + included: 100, + price: { + amount: 10, // $0.10 per hour after limit + billing_method: 'usage_based', + billing_units: 1 + } + }), + planFeature({ + feature_id: storage.id, + included: 10, // 10GB included + price: { + amount: 200, // $2 per additional GB + interval: 'month', + billing_method: 'usage_based', + billing_units: 1 + } + }) + ] +}); +``` + + + +**Best for:** Infrastructure platforms, hosting services, resource-metered applications + +### Linear Template +**Use case:** SaaS tools with feature flags and usage limits +**Features:** Boolean features and flexible usage controls + + + +```ts Linear Template Structure +// Features +export const issues = feature({ + id: 'issues', + name: 'Issues', + type: 'metered', + consumable: false +}); + +export const projects = feature({ + id: 'projects', + name: 'Projects', + type: 'metered', + consumable: false +}); + +export const apiAccess = feature({ + id: 'api_access', + name: 'API Access', + type: 'boolean' +}); + +export const customFields = feature({ + id: 'custom_fields', + name: 'Custom Fields', + type: 'boolean' +}); + +// Plans with boolean features +export const standard = plan({ + id: 'standard', + name: 'Standard', + price: { + amount: 800, // $8 per seat + interval: 'month' + }, + items: [ + planFeature({ + feature_id: issues.id + // Unlimited issues + }), + planFeature({ + feature_id: projects.id, + included: 10 + }), + planFeature({ + feature_id: apiAccess.id + }) + ] +}); + +export const plus = plan({ + id: 'plus', + name: 'Plus', + price: { + amount: 1400, // $14 per seat + interval: 'month' + }, + items: [ + planFeature({ + feature_id: issues.id + }), + planFeature({ + feature_id: projects.id + // Unlimited projects + }), + planFeature({ + feature_id: apiAccess.id + }), + planFeature({ + feature_id: customFields.id + }) + ] +}); +``` + + + +**Best for:** Project management tools, productivity SaaS, feature flag-driven applications + +## Using Templates + +### Interactive Template Selection + +Run `atmn init` to see the interactive template picker: + +```bash +atmn init +``` + +The CLI will prompt you to: +1. Choose your preferred template +2. Customize plan names and pricing (optional) +3. Set up initial configuration + +### Template Customization + +Each template can be customized during initialization: + +- **Plan Names**: Modify tier names (free → starter, pro → growth, etc.) +- **Pricing**: Adjust base prices and usage rates +- **Features**: Add or remove features from plans +- **Limits**: Change included quantities and reset intervals + +### Template Structure + +All templates follow the same structure: + +``` +Generated Files: +├── autumn.config.ts # Main configuration +└── .env # API keys (if logged in) +``` + +## Customizing Templates + +After initialization, you can modify the generated configuration: + +### Add New Features + + + +```ts Adding a Boolean Feature +export const sso = feature({ + id: 'sso', + name: 'SSO Authentication', + type: 'boolean' +}); + +// Add to enterprise plan +export const enterprise = plan({ + // ... existing config + items: [ + // ... existing features + planFeature({ + feature_id: sso.id + }) + ] +}); +``` + + + +### Modify Pricing Models + + + +```ts Adding Tiered Pricing +planFeature({ + feature_id: apiCalls.id, + price: { + tiers: [ + { to: 1000, amount: 2 }, // $0.02 for first 1000 + { to: 10000, amount: 1.5 }, // $0.015 for next 9000 + { to: 'inf', amount: 1 } // $0.01 for 10000+ + ], + billing_method: 'usage_based', + interval: 'month' + } +}) +``` + + + +### Add Free Trials + + + +```ts Adding Free Trial +export const pro = plan({ + id: 'pro', + name: 'Professional', + free_trial: { + duration_length: 14, + duration_type: 'day', + card_required: true + }, + // ... rest of config +}); +``` + + + +## Template Best Practices + +### Choosing the Right Template + +**OpenAI Template** when you have: +- Variable cost per operation +- Different service tiers (basic vs premium models) +- Credit/token-based consumption + +**T3 Chat Template** when you have: +- Per-user pricing (seats) +- Usage limits per user +- Team/organization billing + +**Railway Template** when you have: +- Resource consumption (CPU, storage, bandwidth) +- Infrastructure-as-a-Service model +- Tiered resource pricing + +**Linear Template** when you have: +- Feature-based differentiation +- Boolean feature flags +- Project/workspace limits + +### Modification Strategies + +1. **Start Simple**: Begin with the closest template +2. **Iterate**: Use `atmn preview` to test changes locally +3. **Sync Often**: Push changes with `atmn push` to test in sandbox +4. **Validate**: Use data commands to verify billing behavior + +### Common Modifications + + + +```ts Add Rollover to Messages +planFeature({ + feature_id: messages.id, + included: 1000, + reset: { interval: 'month' }, + rollover: { + max: 500, // Max 500 rollover + expiry_duration_type: 'month', + expiry_duration_length: 3 // Expires after 3 months + } +}) +``` + +```ts Add Maximum Purchase Limits +planFeature({ + feature_id: seats.id, + included: 10, + price: { + amount: 1000, + interval: 'month', + billing_method: 'usage_based', + billing_units: 1, + max_purchase: 100 // Max 100 additional seats + } +}) +``` + +```ts Add Proration Rules +planFeature({ + feature_id: storage.id, + included: 50, + price: { + amount: 200, + interval: 'month', + billing_method: 'usage_based' + }, + proration: { + on_increase: 'prorate', + on_decrease: 'refund_immediately' + } +}) +``` + + + +## Testing Templates + +### Local Preview + +Test your configuration without API calls: + +```bash +atmn preview +``` + +### Sandbox Testing + +Push to sandbox for full testing: + +```bash +atmn push +atmn customers --headless # Check customer creation +atmn events --headless # Monitor usage events +``` + +### Integration Testing + +Use the generated SDK types for type-safe integration: + + + +```ts Using Generated Types +import { trackUsage, useCustomer } from '@useautumn/sdk'; + +// Type-safe feature tracking +await trackUsage('messages', 1); // ✓ Valid feature ID +await trackUsage('invalid', 1); // ✗ TypeScript error + +// Type-safe customer data +const { features, plans } = useCustomer(); +console.log(features.messages.usage); // ✓ Type-safe access +``` + + + +Templates provide a solid foundation for common pricing models while remaining fully customizable for your specific needs. \ No newline at end of file diff --git a/mintlify/api-reference/cli/workflows.mdx b/mintlify/api-reference/cli/workflows.mdx new file mode 100644 index 0000000..8a72de6 --- /dev/null +++ b/mintlify/api-reference/cli/workflows.mdx @@ -0,0 +1,516 @@ +--- +title: "Development Workflows" +description: "Practical patterns for local development, sandbox testing, production deployment, and team collaboration" +--- + +Learn the practical workflows for using the `atmn` CLI effectively in different development scenarios, from local development to production deployment. + +## Local Development Workflow + +### Quick Start Pattern + +The fastest way to get started with a new project: + + + +```bash Complete Setup +# 1. Authenticate +atmn login + +# 2. Initialize project with template +atmn init +# → Choose template (e.g., T3 Chat) +# → Customize plan names and pricing + +# 3. Deploy to sandbox for testing +atmn push + +# 4. Preview locally while developing +atmn preview +``` + + + +### Iterative Development + +Day-to-day development workflow: + + + +```bash Daily Development Loop +# Start with latest config +atmn pull + +# Edit autumn.config.ts +# - Add new features +# - Modify pricing +# - Adjust plan limits + +# Test locally (no API calls) +atmn preview + +# Deploy to sandbox when ready +atmn push + +# Generate updated SDK types +atmn pull # Auto-generates @useautumn-sdk.d.ts +``` + + + +### Local API Server Development + +When running Autumn locally for development: + + + +```bash Local Development Setup +# Start local Autumn server (separate terminal) +# docker-compose up autumn-api + +# Use local API server +atmn push --local +atmn pull --local + +# Preview connects to local dashboard +atmn dashboard --local # → http://localhost:3000 + +# Mix local API with production data +atmn pull --local --prod # Pull prod data to local server +``` + + + +## Sandbox Testing Workflow + +### Feature Development + +Test new features thoroughly in sandbox: + + + +```bash Feature Testing +# Deploy new feature to sandbox +atmn push + +# Test feature behavior with data commands +atmn customers --headless --limit 5 +atmn features --headless --id "new_feature" + +# Create test usage events (via your app or dashboard) +# Monitor with events command +atmn events --headless --feature "new_feature" --time 24h + +# Verify billing calculations +atmn customers --headless --id "test_customer" --format json +``` + + + +### Plan Modifications + +Test pricing changes safely: + + + +```bash Plan Testing Workflow +# Modify plan in autumn.config.ts +# - Change pricing tiers +# - Adjust included amounts +# - Add/remove features + +# Preview changes locally +atmn preview --plan pro + +# Deploy to sandbox +atmn push +# → CLI shows change analysis +# → Creates new plan version if needed + +# Test with existing sandbox customers +atmn customers --headless --search "test-customer" + +# Monitor usage and billing +atmn events --headless --mode aggregate --time 7d +``` + + + +### Clean Slate Testing + +Use `nuke` for fresh testing environments: + + + +```bash Clean Slate Pattern +# Nuclear option: destroy all sandbox data +atmn nuke +# → Multiple confirmations required +# → Only works in sandbox environment + +# Rebuild from configuration +atmn push + +# Create fresh test data (via dashboard or API) +# Test complete customer journey +``` + + + + +**Nuke is destructive!** Only use `atmn nuke` when you want to completely start over. It permanently deletes all sandbox data. + + +## Production Deployment Workflow + +### Safe Production Deployment + +Deploy to production with proper safety checks: + + + +```bash Production Deployment +# 1. Final testing in sandbox +atmn pull +atmn push # Ensure sandbox is up-to-date + +# 2. Review changes carefully +atmn push --prod +# → CLI shows detailed change analysis +# → Extra confirmation for production +# → Smart prompts for customer impact + +# 3. Confirm deployment +# Y/n prompts for: +# - Production environment confirmation +# - Plan versioning (if customers exist) +# - Feature deletions (if any) + +# 4. Monitor deployment +atmn env --prod # Verify environment +``` + + + +### Automated Production Deployment + +For CI/CD pipelines: + + + +```bash Automated Production +# Skip interactive prompts +atmn push --prod --yes + +# Or use environment variables for conditional deployment +if [ "$ENVIRONMENT" = "production" ]; then + atmn push --prod --yes +else + atmn push --yes +fi +``` + + + +### Rollback Strategy + +Handle production issues: + + + +```bash Emergency Rollback +# Option 1: Revert config file and redeploy +git revert HEAD +atmn push --prod --yes + +# Option 2: Pull previous version from Autumn +atmn pull --prod --force # Overwrites local config +git commit -am "Rollback to production state" + +# Option 3: Manual fixes via dashboard +# Then pull the manual changes +atmn pull --prod +git commit -am "Pull manual production fixes" +``` + + + +## Team Collaboration Workflows + +### Config as Source of Truth + +Best for engineering-focused teams: + + + +```bash Config-First Workflow +# Developer A: +git pull origin main +atmn pull # Sync with remote state +# Edit autumn.config.ts +atmn push +git commit -am "Update pricing for new feature" +git push origin feature/new-pricing + +# Developer B: +git pull origin feature/new-pricing +atmn pull # Get updated types +# Use updated feature IDs in code +git commit -am "Implement new feature integration" +``` + + + +### Dashboard as Source of Truth + +Best for teams with non-technical stakeholders: + + + +```bash Dashboard-First Workflow +# Business team makes changes in dashboard + +# Developer syncs changes: +atmn pull +git commit -am "Sync pricing changes from dashboard" +git push origin main + +# Generated types ensure code stays in sync +# TypeScript will show errors for removed features +``` + + + +### Hybrid Workflow + +Balance between technical and business teams: + + + +```bash Hybrid Workflow +# Major changes: Use config files +# - New features +# - Complex pricing models +# - Bulk changes + +# Minor changes: Use dashboard +# - Price adjustments +# - Plan name changes +# - Feature descriptions + +# Always sync after dashboard changes +atmn pull +git commit -am "Sync dashboard changes" +``` + + + +## Advanced Workflows + +### Multi-Environment Development + +Manage multiple environments (dev, staging, prod): + + + +```bash Multi-Environment Setup +# Different API keys for each environment +# .env.development +AUTUMN_SECRET_KEY=am_sk_test_dev_123... + +# .env.staging +AUTUMN_SECRET_KEY=am_sk_test_staging_123... + +# .env.production +AUTUMN_PROD_SECRET_KEY=am_sk_live_prod_123... + +# Deploy to specific environments +NODE_ENV=development atmn push +NODE_ENV=staging atmn push +NODE_ENV=production atmn push --prod +``` + + + +### Configuration Branching + +Handle complex feature development: + + + +```bash Feature Branch Workflow +# Create feature branch +git checkout -b feature/new-billing-model + +# Develop new pricing model +# Edit autumn.config.ts extensively +atmn preview # Test locally +atmn push # Deploy to sandbox + +# Long-running feature development +# Regularly sync with main +git checkout main +git pull origin main +atmn pull # Get latest production state + +git checkout feature/new-billing-model +git rebase main +# Resolve any config conflicts +atmn push # Test rebased changes + +# When ready to merge +git checkout main +git merge feature/new-billing-model +atmn push --prod # Deploy to production +``` + + + +### Data-Driven Iterations + +Use CLI data commands for product decisions: + + + +```bash Analytics-Driven Development +# Analyze current usage patterns +atmn events --headless --mode aggregate --group-by feature_id --time 30d --format csv > usage.csv + +# Find low-usage features +atmn features --headless --format json | jq '.[] | select(.usage_30d < 100)' + +# Identify high-value customers +atmn customers --headless --format json | jq 'sort_by(.revenue_30d) | reverse | .[0:10]' + +# Design new pricing based on data +# Edit autumn.config.ts with data insights +atmn preview # Validate new pricing +atmn push # Deploy and monitor impact +``` + + + +## Troubleshooting Workflows + +### Configuration Conflicts + +Handle merge conflicts in configuration: + + + +```bash Conflict Resolution +# Conflict in autumn.config.ts during git merge +git status +# both modified: autumn.config.ts + +# Option 1: Use remote version and customize +git checkout --theirs autumn.config.ts +atmn pull --force # Get remote state +# Edit to add your changes +atmn push + +# Option 2: Use local version and sync +git checkout --ours autumn.config.ts +atmn push # Deploy your version +# Handle any conflicts in Autumn +``` + + + +### Environment Sync Issues + +Fix environment synchronization problems: + + + +```bash Environment Sync +# Sandbox and production out of sync +atmn pull --prod # Get production state +atmn push # Push to sandbox + +# Or sync in opposite direction +atmn pull # Get sandbox state +atmn push --prod # Push to production (careful!) + +# Compare environments +atmn plans --prod --headless --format json > prod_plans.json +atmn plans --headless --format json > sandbox_plans.json +diff prod_plans.json sandbox_plans.json +``` + + + +### Recovery Patterns + +Common recovery scenarios: + + + +```bash Recovery Scenarios +# Lost local config file +rm autumn.config.ts +atmn pull --force # Regenerate from Autumn + +# Corrupted environment file +rm .env +atmn login # Re-authenticate + +# Type generation issues +rm @useautumn-sdk.d.ts +atmn pull # Regenerate types + +# Complete reset (sandbox only) +atmn nuke +atmn push # Rebuild from config +``` + + + +## Performance Optimization + +### Efficient Data Usage + +Optimize CLI usage for large datasets: + + + +```bash Performance Tips +# Use pagination for large datasets +atmn customers --headless --limit 1000 --page 1 --format csv +atmn customers --headless --limit 1000 --page 2 --format csv + +# Filter early to reduce data transfer +atmn events --headless --customer "cus_123" --time 7d --format json + +# Use aggregate mode for analytics +atmn events --headless --mode aggregate --bin day --time 30d + +# Batch operations in scripts +for customer in $(atmn customers --headless --format json | jq -r '.[].id'); do + atmn events --headless --customer "$customer" --time 24h --format json +done +``` + + + +## Best Practices Summary + +### Development Phase +1. **Start with templates** - Choose the closest template +2. **Preview locally** - Use `atmn preview` before deploying +3. **Test in sandbox** - Always test before production +4. **Version control config** - Commit `autumn.config.ts` + +### Production Phase +1. **Review changes** - Understand change impact +2. **Plan versioning** - Handle existing customers properly +3. **Monitor deployment** - Use data commands post-deployment +4. **Gradual rollouts** - Consider feature flags for big changes + +### Team Phase +1. **Choose workflow** - Config-first vs dashboard-first +2. **Sync regularly** - Keep environments in sync +3. **Document changes** - Clear commit messages +4. **Share types** - Commit generated SDK types + +These workflows provide battle-tested patterns for using the CLI effectively across different team sizes, technical skill levels, and deployment strategies. \ No newline at end of file diff --git a/mintlify/docs.json b/mintlify/docs.json index 6459c66..5051e5e 100644 --- a/mintlify/docs.json +++ b/mintlify/docs.json @@ -220,7 +220,18 @@ { "group": "CLI", - "pages": ["api-reference/cli/config"] + "pages": [ + "api-reference/cli/getting-started", + "api-reference/cli/authentication", + "api-reference/cli/config", + "api-reference/cli/push-pull", + "api-reference/cli/data", + "api-reference/cli/templates", + "api-reference/cli/sdk-types", + "api-reference/cli/ci-cd", + "api-reference/cli/commands", + "api-reference/cli/workflows" + ] }, { "group": "Platform (Beta)",