# 🚀 Deployment Guide

Complete step-by-step instructions for deploying Anthropic Fonts CDN to production.

## Table of Contents

1. [GitHub Pages + jsDelivr (Free & Fast)](#github-pages--jsdelivr)
2. [Cloudflare R2 (Affordable & Fast)](#cloudflare-r2)
3. [AWS S3 + CloudFront (Enterprise)](#aws-s3--cloudfront)
4. [Self-hosted (NGINX/Apache)](#self-hosted)
5. [Vercel/Netlify (Static Hosting)](#vercelnetlify)

---

## GitHub Pages + jsDelivr

**Best for:** Open-source projects, free CDN with global coverage

### Step 1: Initialize Git Repository

```bash
cd /path/to/AnthropicFont
git init
git add .
git commit -m "Initial commit: Anthropic Fonts CDN"
```

### Step 2: Add Remote & Push

```bash
git remote add origin https://github.com/devchauhann/fonts.git
git branch -M main
git push -u origin main
```

### Step 3: Enable GitHub Pages

1. Go to **Settings** → **Pages**
2. Set source to `main` branch, `/cdn` folder
3. GitHub will provide your Pages URL: `https://devchauhann.github.io/AnthropicFont/`

### Step 4: Use jsDelivr CDN (Recommended)

jsDelivr automatically serves your GitHub files with global CDN:

```html
<!-- Static CSS -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/devchauhann/fonts@v1.1.0/cdn/v1/css/all.css">

<!-- Dynamic CSS API -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/devchauhann/fonts@v1.1.0/cdn/api/css?family=AnthropicSans&weights=400;700">

<!-- Font Files -->
https://cdn.jsdelivr.net/gh/devchauhann/fonts@v1.1.0/cdn/v1/fonts/AnthropicSans@700.woff2
```

### Step 5: Create a Release (Optional but Recommended)

```bash
git tag v1.0.0
git push origin v1.0.0
```

Then use versioned URLs:

```html
<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/devchauhann/fonts@v1.0.0/cdn/v1/css/all.css">
```

### ✅ Pros & Cons

**Pros:**
- Free forever
- Global CDN (jsDelivr has 300+ servers)
- No configuration needed
- Automatic version management via Git tags
- Perfect for open-source

**Cons:**
- Slightly slower than commercial CDNs
- Rate limited (but generous)
- Depends on GitHub uptime

---

## Cloudflare R2

**Best for:** Affordable, fast, easy setup, no egress costs

### Step 1: Create Cloudflare Account

1. Sign up at https://dash.cloudflare.com
2. Navigate to **R2** → **Create bucket**
3. Bucket name: `anthropic-fonts`

### Step 2: Upload Files

```bash
# Install wrangler CLI
npm install -g wrangler

# Authenticate
wrangler login

# Upload fonts
wrangler r2 cp cdn/v1/fonts/* r2://anthropic-fonts/fonts/ --recursive
wrangler r2 cp cdn/v1/css/* r2://anthropic-fonts/css/ --recursive
wrangler r2 cp cdn/v1/data.json r2://anthropic-fonts/data.json
```

### Step 3: Create Public URL

1. In R2 bucket settings, click **Settings**
2. Find **Public access** → Create a **Public R2 URL**
3. Example: `https://pub-abc123def.r2.dev`

### Step 4: Configure CORS Headers

In Bucket → **Settings** → add CORS rule:

```json
{
  "AllowedOrigins": ["*"],
  "AllowedMethods": ["GET", "HEAD"],
  "AllowedHeaders": ["Content-Type"],
  "MaxAgeSeconds": 31536000
}
```

### Step 5: Use in Production

```html
<link rel="stylesheet" href="https://pub-abc123def.r2.dev/css/all.css">

<!-- Or with custom domain -->
<link rel="stylesheet" href="https://fonts.example.com/css/all.css">
```

### Step 6: Connect Custom Domain (Optional)

1. Add DNS CNAME pointing to R2 bucket
2. In Cloudflare, enable **Web3 IPFS gateway** for redundancy

### ✅ Pros & Cons

**Pros:**
- Very affordable ($0.015/GB stored, $0.04/GB downloaded)
- **No egress fees** (major advantage!)
- Easy setup
- Cloudflare's global network
- 99.99% uptime SLA

**Cons:**
- Requires Cloudflare account
- Manual sync needed for updates
- Not ideal for frequently changing files

---

## AWS S3 + CloudFront

**Best for:** Enterprise, high-traffic, ultimate control

### Step 1: Create S3 Bucket

```bash
# Install AWS CLI
pip install awscli

# Configure credentials
aws configure

# Create bucket (use globally unique name)
aws s3 mb s3://anthropic-fonts-cdn --region us-east-1
```

### Step 2: Upload Files

```bash
# Upload all files
aws s3 sync cdn/v1/ s3://anthropic-fonts-cdn/v1/ \
  --cache-control "max-age=31536000,immutable" \
  --content-encoding gzip

# Or with specific content types
aws s3 cp cdn/v1/fonts/ s3://anthropic-fonts-cdn/v1/fonts/ \
  --recursive \
  --include "*.woff2" \
  --cache-control "max-age=31536000,immutable"
```

### Step 3: Configure S3 Bucket Policy

Create bucket policy for public read access:

```json
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "PublicReadGetObject",
      "Effect": "Allow",
      "Principal": "*",
      "Action": "s3:GetObject",
      "Resource": "arn:aws:s3:::anthropic-fonts-cdn/*"
    }
  ]
}
```

### Step 4: Create CloudFront Distribution

```bash
# Using AWS CLI or console
aws cloudfront create-distribution --distribution-config file://cloudfront-config.json
```

**Or via Console:**

1. Go to **CloudFront** → **Create distribution**
2. Origin domain: `anthropic-fonts-cdn.s3.amazonaws.com`
3. Viewer protocol: HTTPS only
4. Cache policy: CachingOptimized (1 year)
5. Create distribution

### Step 5: Add Custom Domain

1. In CloudFront, add alternate domain name: `fonts.example.com`
2. Request SSL certificate in **AWS Certificate Manager**
3. Update DNS CNAME to CloudFront domain

### Example CloudFront Config

```json
{
  "S3BucketName": "anthropic-fonts-cdn",
  "CacheBehaviors": [
    {
      "PathPattern": "/v1/fonts/*",
      "CachePolicyId": "658327ea-f89d-4fab-a63d-7e88639e58f6",
      "Compress": true,
      "ViewerProtocolPolicy": "https-only"
    }
  ]
}
```

### ✅ Pros & Cons

**Pros:**
- Highly scalable
- Global CDN with 600+ edge locations
- Ultimate performance
- Enterprise SLA (99.99% uptime)
- Complete control

**Cons:**
- Can be expensive for high traffic
- Egress charges ($0.085/GB)
- Complex setup
- Steeper learning curve

---

## Self-hosted

**Best for:** Maximum control, on-premise, private deployments

### Step 1: Server Setup

```bash
# SSH into your server
ssh user@your-server.com

# Install Node.js
curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash -
sudo apt-get install -y nodejs

# Clone repository
git clone https://github.com/devchauhann/fonts.git
cd AnthropicFont
npm install
```

### Step 2: Configure NGINX Reverse Proxy

```nginx
server {
    listen 443 ssl http2;
    server_name fonts.example.com;

    ssl_certificate /etc/letsencrypt/live/fonts.example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/fonts.example.com/privkey.pem;

    # Enable gzip compression
    gzip on;
    gzip_types text/css application/font-woff2 font/woff2;
    gzip_min_length 1000;

    # Caching headers for fonts
    location /v1/fonts/ {
        proxy_pass http://localhost:3000;
        add_header Cache-Control "public, max-age=31536000, immutable";
        add_header Access-Control-Allow-Origin "*";
        expires 1y;
    }

    location /v1/css/ {
        proxy_pass http://localhost:3000;
        add_header Cache-Control "public, max-age=31536000, immutable";
        expires 1y;
    }

    location /api/ {
        proxy_pass http://localhost:3000;
        add_header Cache-Control "public, max-age=86400";
    }

    # CORS headers
    add_header Access-Control-Allow-Origin "*";
    add_header Access-Control-Allow-Methods "GET, OPTIONS";
    add_header Access-Control-Allow-Headers "Content-Type";
}

# Redirect HTTP to HTTPS
server {
    listen 80;
    server_name fonts.example.com;
    return 301 https://$server_name$request_uri;
}
```

### Step 3: Setup SSL Certificate

```bash
# Using Let's Encrypt
sudo apt-get install certbot python3-certbot-nginx
sudo certbot certonly --nginx -d fonts.example.com
```

### Step 4: Run as Service

Create systemd service file:

```bash
# /etc/systemd/system/anthropic-fonts.service
[Unit]
Description=Anthropic Fonts CDN
After=network.target

[Service]
Type=simple
User=www-data
WorkingDirectory=/home/www-data/AnthropicFont
ExecStart=/usr/bin/node api/server.js
Restart=always
RestartSec=10
Environment="NODE_ENV=production"
Environment="PORT=3000"

[Install]
WantedBy=multi-user.target
```

```bash
# Enable and start
sudo systemctl daemon-reload
sudo systemctl enable anthropic-fonts
sudo systemctl start anthropic-fonts
```

### Step 5: Monitoring & Updates

```bash
# Check status
sudo systemctl status anthropic-fonts

# View logs
sudo journalctl -u anthropic-fonts -f

# Update fonts
cd /home/www-data/AnthropicFont
git pull origin main
npm run build
sudo systemctl restart anthropic-fonts
```

### ✅ Pros & Cons

**Pros:**
- Maximum control
- No vendor lock-in
- Can be cheaper for high traffic
- Private/on-premise option

**Cons:**
- Requires server maintenance
- No global CDN (unless you add one)
- SSL certificate management
- Uptime responsibility

---

## Vercel/Netlify

**Best for:** Easiest deployment, jamstack projects

### Vercel Deployment

```bash
# Install Vercel CLI
npm i -g vercel

# Deploy
vercel --prod
```

**Or connect Git:**

1. Go to https://vercel.com
2. Import Git repository
3. Select `cdn` as root directory
4. Deploy

### Netlify Deployment

```bash
# Install Netlify CLI
npm install -g netlify-cli

# Deploy
netlify deploy --prod --dir=cdn
```

**Or drag & drop:** Simply drag `cdn` folder to Netlify.

### Configure Headers (netlify.toml)

```toml
[[headers]]
for = "/v1/fonts/*"
[headers.values]
Cache-Control = "public, max-age=31536000, immutable"
Access-Control-Allow-Origin = "*"

[[headers]]
for = "/v1/css/*"
[headers.values]
Cache-Control = "public, max-age=31536000, immutable"
```

### ✅ Pros & Cons

**Pros:**
- Simplest deployment
- Free tier available
- Global CDN included
- Automatic HTTPS
- Easy rollbacks

**Cons:**
- Limited to serverless/static
- API endpoint needs adjustment
- Cold starts on function calls

---

## 📊 Comparison Table

| Feature | jsDelivr | Cloudflare R2 | AWS | Self-hosted | Vercel |
|---------|----------|---------------|-----|-------------|--------|
| **Cost** | Free | $0.015/GB | $$$ | $$ | $$ |
| **Setup Time** | 5 min | 15 min | 1 hour | 2 hours | 2 min |
| **Speed** | ⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ | ⭐⭐⭐ | ⭐⭐⭐⭐ |
| **Uptime SLA** | 99.9% | 99.99% | 99.99% | Custom | 99.95% |
| **Best For** | Open-source | Affordable | Enterprise | Control | Quick |

---

## 🔄 Continuous Deployment

### Automatic Updates on Git Push

**GitHub Actions Example:**

Create `.github/workflows/deploy.yml`:

```yaml
name: Deploy to CDN

on:
  push:
    branches: [main]
    paths:
      - 'cdn/**'

jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      
      - name: Deploy to jsDelivr (via purge)
        run: |
          curl https://purge.jsdelivr.net/gh/devchauhann/fonts@v1.1.0/cdn/v1/css/all.css
      
      - name: Deploy to Cloudflare R2
        env:
          AWS_ACCESS_KEY_ID: ${{ secrets.CF_R2_ACCESS_KEY }}
          AWS_SECRET_ACCESS_KEY: ${{ secrets.CF_R2_SECRET_KEY }}
        run: |
          aws s3 sync cdn/v1/ s3://anthropic-fonts/ \
            --endpoint-url https://${{ secrets.CF_ACCOUNT_ID }}.r2.cloudflareclient.com \
            --cache-control "max-age=31536000,immutable"
```

---

## 🎯 Recommended Setup for Production

**For most users:** GitHub + jsDelivr

```html
<!-- Ultra-reliable, free, global CDN -->
<link rel="preconnect" href="https://cdn.jsdelivr.net">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/devchauhann/fonts@v1.1.0/cdn/v1/css/all.css">
```

**For high-traffic sites:** AWS S3 + CloudFront

```html
<!-- Maximum performance, enterprise SLA -->
<link rel="preconnect" href="https://d123xyz.cloudfront.net">
<link rel="stylesheet" href="https://fonts.example.com/v1/css/all.css">
```

**For cost-conscious:** Cloudflare R2 + custom domain

```html
<!-- Cheap, fast, no egress fees -->
<link rel="preconnect" href="https://fonts.example.com">
<link rel="stylesheet" href="https://fonts.example.com/css/all.css">
```

---

## 📝 Monitoring & Analytics

### Track CDN Usage

**jsDelivr:**
- Stats automatically available at `https://www.jsdelivr.com/package/gh/devchauhann/fonts`

**Cloudflare R2:**
- Bucket → **Analytics** tab shows bandwidth and requests

**AWS CloudFront:**
- CloudFront → **Monitoring** → View request, bytes, cache stats

**Self-hosted:**
```bash
# NGINX logs
tail -f /var/log/nginx/access.log | grep fonts

# Monitor Node.js
npm install -g pm2
pm2 monit
```

---

## 🔒 Security Best Practices

1. **Enable HTTPS only** (all modern CDNs do this)
2. **Set CORS headers** for cross-origin requests
3. **Configure cache headers** to prevent stale files
4. **Monitor for unauthorized usage**
5. **Rate limiting** (if self-hosted)
6. **Version your releases** for easy rollbacks

---

## 🚨 Troubleshooting

### Fonts Not Loading

```bash
# Check CORS headers
curl -I https://cdn.example.com/v1/fonts/AnthropicSans@400.woff2

# Should include:
# Access-Control-Allow-Origin: *
```

### Cache Issues

```bash
# Purge jsDelivr cache
curl https://purge.jsdelivr.net/gh/devchauhann/fonts@v1.1.0/cdn/v1/css/all.css

# Purge Cloudflare R2
wrangler r2 cp cdn/v1/ r2://anthropic-fonts/v1/ --recursive --force
```

### Slow Performance

1. Enable gzip compression
2. Set aggressive caching headers
3. Use geographically closest CDN
4. Monitor real user metrics (RUM)

---

## 📚 Next Steps

1. Choose your deployment platform
2. Follow the step-by-step guide above
3. Test font loading: `npm run dev` locally first
4. Monitor performance in production
5. Set up automatic updates via GitHub Actions

**Questions?** Check the main [README.md](../README.md) or [USAGE.md](./USAGE.md)
