### Complete Example Deployment Source: https://github.com/mizchi/skills/blob/main/cloudflare/deploy/references/pipelines/configuration.md A comprehensive example demonstrating the setup of R2 bucket, stream, sink, pipeline, and deployment. ```bash npx wrangler r2 bucket create my-bucket npx wrangler r2 bucket catalog enable my-bucket npx wrangler pipelines streams create my-stream --schema-file schema.json npx wrangler pipelines sinks create my-sink --type r2-data-catalog --bucket my-bucket ... npx wrangler pipelines create my-pipeline --sql "INSERT INTO my_sink SELECT * FROM my_stream" npx wrangler deploy ``` -------------------------------- ### Setup Cloudflare Pipelines Source: https://github.com/mizchi/skills/blob/main/cloudflare/deploy/references/pipelines/README.md Run this command to start an interactive setup for Cloudflare Pipelines. ```bash npx wrangler pipelines setup ``` -------------------------------- ### Quick Start Miniflare Example Source: https://github.com/mizchi/skills/blob/main/cloudflare/deploy/references/miniflare/README.md A basic example demonstrating how to initialize Miniflare, dispatch a fetch request, and dispose of the instance. This is useful for quickly running a simple Worker locally. ```javascript import { Miniflare } from "miniflare"; const mf = new Miniflare({ modules: true, script: ` export default { async fetch(request, env, ctx) { return new Response("Hello Miniflare!"); } } `, }); const res = await mf.dispatchFetch("http://localhost:8787/"); console.log(await res.text()); // Hello Miniflare! await mf.dispose(); ``` -------------------------------- ### CI Setup: Replacing actions/setup-node with Nix Source: https://github.com/mizchi/skills/blob/main/tooling/nix-setup/SKILL.md Rewrite CI workflow steps to use Nix-based actions for Node.js setup. This example shows the diff for replacing 'actions/setup-node'. ```diff - - uses: actions/setup-node@v4 - with: - node-version: 24 - cache: pnpm - - run: pnpm install --frozen-lockfile - - run: pnpm test + - uses: DeterminateSystems/nix-installer-action@main + - uses: DeterminateSystems/magic-nix-cache-action@main + - run: nix develop --command just ci ``` -------------------------------- ### Install Devbox Source: https://github.com/mizchi/skills/blob/main/tooling/nix-setup/SKILL.md Installs the devbox CLI using a curl script. This is the initial step to get started with devbox. ```bash curl -fsSL https://get.jetify.com/devbox | bash ``` -------------------------------- ### Quick Start: Basic Workflow Example Source: https://github.com/mizchi/skills/blob/main/cloudflare/deploy/references/workflows/README.md Demonstrates the basic structure of a Cloudflare Workflow, including fetching user data, sleeping for a duration, and sending a reminder. ```typescript import { WorkflowEntrypoint, WorkflowStep, WorkflowEvent } from 'cloudflare:workers'; type Env = { MY_WORKFLOW: Workflow; DB: D1Database }; type Params = { userId: string }; export class MyWorkflow extends WorkflowEntrypoint { async run(event: WorkflowEvent, step: WorkflowStep) { const user = await step.do('fetch user', async () => { return await this.env.DB.prepare('SELECT * FROM users WHERE id = ?') .bind(event.params.userId).first(); }); await step.sleep('wait 7 days', '7 days'); await step.do('send reminder', async () => { await sendEmail(user.email, 'Reminder!'); }); } } ``` -------------------------------- ### Hono Framework Example Source: https://github.com/mizchi/skills/blob/main/cloudflare/deploy/references/workers-playground/patterns.md Demonstrates using the Hono framework for routing and handling requests. Includes basic GET routes and a 404 handler. ```javascript import { Hono } from 'https://esm.sh/hono@3'; const app = new Hono(); app.get('/', (c) => c.text('Hello')); app.get('/api/users/:id', (c) => c.json({ id: c.req.param('id') })); app.notFound((c) => c.json({ error: 'Not found' }, 404)); export default app; ``` -------------------------------- ### Platform Starter Kit Deployment Source: https://github.com/mizchi/skills/blob/main/cloudflare/deploy/references/workers-for-platforms/README.md One-click deployment for a complete Workers for Platforms setup, including dispatch namespace, dispatch worker, and a user worker example. ```bash https://deploy.workers.cloudflare.com/?url=https://github.com/cloudflare/workers-for-platforms-example ``` -------------------------------- ### Complete WAF Setup Example Source: https://github.com/mizchi/skills/blob/main/cloudflare/deploy/references/waf/patterns.md Combines custom rules, managed ruleset execution, and rate limiting for comprehensive WAF protection. Ensure CF_API_TOKEN and ZONE_ID environment variables are set. ```typescript const client = new Cloudflare({ apiToken: process.env.CF_API_TOKEN }); const zoneId = process.env.ZONE_ID; // 1. Custom rules (execute first) await client.rulesets.create({ zone_id: zoneId, phase: 'http_request_firewall_custom', rules: [ { action: 'skip', action_parameters: { phases: ['http_request_firewall_managed', 'http_ratelimit'] }, expression: 'ip.src in {192.0.2.0/24}' }, { action: 'block', expression: 'cf.waf.score gt 50' }, { action: 'managed_challenge', expression: 'cf.waf.score gt 20' }, ], }); // 2. Managed ruleset (execute second) await client.rulesets.create({ zone_id: zoneId, phase: 'http_request_firewall_managed', rules: [{ action: 'execute', action_parameters: { id: 'efb7b8c949ac4650a09736fc376e9aee', overrides: { categories: [{ category: 'wordpress', enabled: false }] } }, expression: 'true', }], }); // 3. Rate limiting (execute third) await client.rulesets.create({ zone_id: zoneId, phase: 'http_ratelimit', rules: [ { action: 'block', expression: 'true', action_parameters: { ratelimit: { characteristics: ['cf.colo.id', 'ip.src'], period: 60, requests_per_period: 100, mitigation_timeout: 600 } } }, { action: 'block', expression: 'http.request.uri.path eq "/api/login"', action_parameters: { ratelimit: { characteristics: ['ip.src'], period: 60, requests_per_period: 5, mitigation_timeout: 600 } } }, ], }); ``` -------------------------------- ### Install MoonBit Project Template with Nix Source: https://github.com/mizchi/skills/blob/main/tooling/nix-setup/SKILL.md Copy the necessary Nix setup files and enter the development environment. If using direnv, set it up to automatically use the flake. ```bash cp ~/.claude/skills/nix-setup/assets/apm.nix . cp ~/.claude/skills/nix-setup/assets/moonbit/flake.nix . nix develop # builds on the first run # If you're a direnv user: echo 'use flake' > .envrc && direnv allow ``` -------------------------------- ### Stream Setup Commands Source: https://github.com/mizchi/skills/blob/main/cloudflare/deploy/references/pipelines/configuration.md Commands to create, list, get, and delete streams. Use `--schema-file` for structured streams or omit for unstructured. ```bash # With schema npx wrangler pipelines streams create my-stream --schema-file schema.json # Unstructured (no validation) npx wrangler pipelines streams create my-stream # List/get/delete npx wrangler pipelines streams list npx wrangler pipelines streams get npx wrangler pipelines streams delete ``` -------------------------------- ### Minimal HTTP Performance Measurement Example Source: https://github.com/mizchi/skills/blob/main/lang/gleam-practice/SKILL.md Demonstrates a minimal setup for HTTP load testing using shell commands. Assumes the existence of a `bench/http.js` file. ```shell just run k6 run bench/http.js ``` -------------------------------- ### Interactive Dev Environment Setup Source: https://github.com/mizchi/skills/blob/main/cloudflare/deploy/references/sandbox/patterns.md Set up an interactive development environment like code-server by executing installation scripts and starting a process within the sandbox. This pattern exposes a port for remote access. ```typescript export default { async fetch(request: Request, env: Env): Promise { const proxyResponse = await proxyToSandbox(request, env); if (proxyResponse) return proxyResponse; const sandbox = getSandbox(env.Sandbox, 'ide', { normalizeId: true }); if (request.url.endsWith('/start')) { await sandbox.exec('curl -fsSL https://code-server.dev/install.sh | sh'); await sandbox.startProcess('code-server --bind-addr 0.0.0.0:8080', { processId: 'vscode' }); const exposed = await sandbox.exposePort(8080); return Response.json({ url: exposed.url }); } return new Response('Try /start'); } }; ``` -------------------------------- ### Nix Setup Script for Containers Source: https://github.com/mizchi/skills/blob/main/tooling/nix-setup/SKILL.md Installer script to set up single-user Nix with sandbox disabled, suitable for containerized environments or Cloud Code Web. ```shell # Installer that sets up single-user Nix with sandbox disabled (for container / CCW) ``` -------------------------------- ### Basic Hono Setup Source: https://github.com/mizchi/skills/blob/main/cloudflare/deploy/references/workers/frameworks.md Set up a basic Hono application with GET and POST routes. Handles plain text responses and JSON requests/responses. ```typescript import { Hono } from 'hono'; const app = new Hono(); app.get('/', (c) => c.text('Hello World!')); app.post('/api/users', async (c) => { const body = await c.req.json(); return c.json({ id: 1, ...body }, 201); }); export default app; ``` -------------------------------- ### Install Hono Source: https://github.com/mizchi/skills/blob/main/cloudflare/deploy/references/workers/frameworks.md Install the Hono framework using npm. This is the first step to using Hono in your project. ```bash npm install hono ``` -------------------------------- ### Environment Configuration Example Source: https://github.com/mizchi/skills/blob/main/cloudflare/deploy/references/wrangler/patterns.md Example JSONC configuration for defining environment-specific variables. ```jsonc { "env": { "staging": { "vars": { "ENV": "staging" } } } } ``` -------------------------------- ### ORDER BY Clause Examples Source: https://github.com/mizchi/skills/blob/main/cloudflare/deploy/references/r2-sql/api.md Examples of sorting results by partition key or aggregation function. ```sql -- Order by partition key SELECT * FROM logs.requests ORDER BY timestamp DESC LIMIT 100; -- Order by aggregation (repeat function, aliases not supported) SELECT region, SUM(amount) FROM sales.transactions GROUP BY region ORDER BY SUM(amount) DESC; ``` -------------------------------- ### Dry run installation Source: https://github.com/mizchi/skills/blob/main/tooling/apm-usage/SKILL.md Simulates the installation process without making any actual changes to the project or dependencies. Useful for previewing the effects of an installation. ```bash apm install --dry-run ``` -------------------------------- ### Install Git-Cliff Source: https://github.com/mizchi/skills/blob/main/tooling/conventional-changelog/SKILL.md Install git-cliff using Cargo or Homebrew. ```bash cargo install git-cliff # or brew install git-cliff ``` -------------------------------- ### Install secretlint and Preset Source: https://github.com/mizchi/skills/blob/main/sql/security/SKILL.md Install secretlint and the recommended rule preset as development dependencies using pnpm. ```bash pnpm add -D secretlint @secretlint/secretlint-rule-preset-recommend ``` -------------------------------- ### Tail Worker Quick Example Source: https://github.com/mizchi/skills/blob/main/cloudflare/deploy/references/tail-workers/README.md A basic example of a Tail Worker that processes events and sends them to a specified log endpoint. Use this to get started with real-time event processing. ```typescript export default { async tail(events, env, ctx) { // Process events from producer Worker ctx.waitUntil( fetch(env.LOG_ENDPOINT, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(events), }) ); } }; ``` -------------------------------- ### Practical Justfile Example for Project Automation Source: https://github.com/mizchi/skills/blob/main/tooling/justfile/SKILL.md A comprehensive `justfile` example demonstrating common project tasks like development server, build, test, linting, releasing, and cleanup, with settings for `.env` loading and shell configuration. ```justfile set dotenv-load set shell := ["bash", "-cu"] default: @just --list # Dev server dev: npm run dev # Build build: npm run build # Test test *args: npm test {{args}} # Lint + format check: npm run lint npm run format:check # CI (called from GitHub Actions) ci: check build test # Release release version: git tag -a v{{version}} -m "Release v{{version}}" git push origin v{{version}} # Cleanup clean: rm -rf dist node_modules ``` -------------------------------- ### Install RealtimeKit for Web Components/HTML Source: https://github.com/mizchi/skills/blob/main/cloudflare/deploy/references/realtimekit/configuration.md Install the RealtimeKit and generic UI kit packages using npm. ```bash npm install @cloudflare/realtimekit @cloudflare/realtimekit-ui ``` -------------------------------- ### Start Container and Wait for Ports Source: https://github.com/mizchi/skills/blob/main/cloudflare/deploy/references/containers/api.md Recommended method to start a container and wait until its specified ports are listening. Includes a 20-second timeout. Allows overriding ports and start options. ```typescript await container.startAndWaitForPorts(); // Uses requiredPorts await container.startAndWaitForPorts({ ports: [8080, 9090] }); await container.startAndWaitForPorts({ ports: [8080], startOptions: { envVars: { KEY: "value" } } }); ``` -------------------------------- ### macOS launchd Service Installation Source: https://github.com/mizchi/skills/blob/main/cloudflare/deploy/references/tunnel/patterns.md Commands to install and start the cloudflared service on macOS using launchd. ```bash sudo cloudflared service install sudo launchctl start com.cloudflare.cloudflared ``` -------------------------------- ### Justfile Basic Syntax Examples Source: https://github.com/mizchi/skills/blob/main/tooling/justfile/SKILL.md Illustrates fundamental `just` syntax including default recipes, basic recipes, dependencies, argument handling, default arguments, and variadic arguments. ```justfile # Default recipe (runs when just is called without arguments) default: @echo "Available: just --list" # Basic recipe build: cargo build --release # Dependencies test: build cargo test # Arguments greet name: echo "Hello, {{name}}" # Default arguments serve port="8080": python -m http.server {{port}} # Variadic arguments run *args: cargo run -- {{args}} ``` -------------------------------- ### Install RealtimeKit for React Source: https://github.com/mizchi/skills/blob/main/cloudflare/deploy/references/realtimekit/configuration.md Install the RealtimeKit and React UI kit packages using npm. ```bash npm install @cloudflare/realtimekit @cloudflare/realtimekit-react-ui ``` -------------------------------- ### TCP Sockets Client Example Source: https://github.com/mizchi/skills/blob/main/cloudflare/deploy/references/workerd/api.md Experimental example demonstrating connecting to a TCP socket, sending an HTTP GET request, and reading the response. ```javascript const socket = await connect({ hostname: 'example.com', port: 80 }); const writer = socket.writable.getWriter(); await writer.write(new TextEncoder().encode('GET / HTTP/1.1\r\n\r\n')); const reader = socket.readable.getReader(); const { value } = await reader.read(); return new Response(value); ``` -------------------------------- ### Install Nix, Bootstrap Chezmoi, and Apply Configurations Source: https://github.com/mizchi/skills/blob/main/tooling/chezmoi-management/SKILL.md This script installs Nix, initializes Chezmoi with a Git repository, applies the configuration, and then switches to the Nix-Darwin system configuration. It also sets up a pre-push Git hook for secretlint. ```bash # 1. Install Nix (Determinate Systems installer recommended). curl -fsSL https://install.determinate.systems/nix | sh -s -- install # 2. Bootstrap chezmoi (clones repo + applies; the brew script runs once here). chezmoi init https://github.com/mizchi/chezmoi-dotfiles.git --apply # 3. Switch home-manager / nix-darwin (installs pkfire, pkl, awscli2, …). nix run nix-darwin -- switch --flake ~/.config/home-manager#macos # (or for standalone HM without system-layer changes: # nix run home-manager/master -- switch --flake ~/.config/home-manager#macos) # 4. Arm the pre-push gate on this repo's source. cd $(chezmoi source-path) pkf hooks install # writes .git/hooks/pre-push (secretlint over outgoing diff) # 5. apm install -g already fired via run_after_apm-install.sh during step 2. # To pick up upstream updates later: apm install -g --update ``` -------------------------------- ### Linux systemd Service Installation Source: https://github.com/mizchi/skills/blob/main/cloudflare/deploy/references/tunnel/patterns.md Commands to install and manage the cloudflared service on Linux using systemd. Includes starting, enabling, and viewing logs. ```bash cloudflared service install systemctl start cloudflared && systemctl enable cloudflared journalctl -u cloudflared -f # Logs ``` -------------------------------- ### Justfile Settings Examples Source: https://github.com/mizchi/skills/blob/main/tooling/justfile/SKILL.md Shows how to configure `just` behavior using settings like specifying the shell, loading `.env` files, ignoring errors, suppressing command echoing, and setting the working directory. ```justfile # Shell set shell := ["bash", "-cu"] # Load .env set dotenv-load # Continue on error set ignore-errors # Suppress command echo set quiet # Working directory set working-directory := "subdir" ``` -------------------------------- ### Send Redis RESP GET Command Source: https://github.com/mizchi/skills/blob/main/cloudflare/deploy/references/workers-vpc/patterns.md Example of sending a Redis GET command over a raw TCP socket. Assumes a direct TCP connection to a Redis instance. ```typescript const socket = connect({ hostname: "redis.internal", port: 6379 }); const writer = socket.writable.getWriter(); await writer.write(new TextEncoder().encode(`*2\r\n$3\r\nGET\r\n$3\r\nkey\r\n`)); ``` -------------------------------- ### Core SDK Basic Setup and Event Handling Source: https://github.com/mizchi/skills/blob/main/cloudflare/deploy/references/realtimekit/patterns.md Initializes the RealtimeKit client, joins a meeting, and sets up listeners for room joining and participant events. Requires an `authToken` and specifies whether to enable video and audio. ```typescript import RealtimeKitClient from '@cloudflare/realtimekit'; const meeting = new RealtimeKitClient({ authToken, video: true, audio: true }); meeting.self.on('roomJoined', () => console.log('Joined:', meeting.meta.meetingTitle)); meeting.participants.joined.on('participantJoined', (p) => console.log(`${p.name} joined`)); await meeting.join(); ``` -------------------------------- ### TypeScript Setup for Workers Source: https://github.com/mizchi/skills/blob/main/cloudflare/deploy/references/email-routing/configuration.md Installs necessary types and configures tsconfig.json for Cloudflare Workers development. ```bash npm install --save-dev @cloudflare/workers-types ``` ```json // tsconfig.json { "compilerOptions": { "target": "ES2022", "module": "ES2022", "lib": ["ES2022"], "types": ["@cloudflare/workers-types"], "moduleResolution": "bundler", "strict": true } } ``` -------------------------------- ### Create Astro Blog with Deployment Source: https://github.com/mizchi/skills/blob/main/cloudflare/deploy/references/c3/api.md Example of creating an Astro blog project using C3 CLI with npm. The `--deploy` flag initiates deployment after creation. ```bash # Astro blog npm create cloudflare@latest my-blog -- --type=web-app --framework=astro --ts --deploy ``` -------------------------------- ### JSON API Example Source: https://github.com/mizchi/skills/blob/main/cloudflare/deploy/references/workers-playground/patterns.md Handles requests to return JSON responses for different API endpoints. Supports GET and POST methods. ```javascript export default { async fetch(request) { const url = new URL(request.url); if (url.pathname === '/api/hello') return Response.json({ message: 'Hello' }); if (url.pathname === '/api/echo' && request.method === 'POST') { return Response.json({ received: await request.json() }); } return Response.json({ error: 'Not found' }, { status: 404 }); } }; ``` -------------------------------- ### R2 Bucket Binding Example Source: https://github.com/mizchi/skills/blob/main/cloudflare/deploy/references/pages-functions/api.md Illustrates interacting with an R2 bucket to get and put objects. Configure your R2 bucket in wrangler.toml. ```typescript interface Env { BUCKET: R2Bucket; } export const onRequest: PagesFunction = async (ctx) => { const obj = await ctx.env.BUCKET.get('file.txt'); if (!obj) return new Response('Not found', { status: 404 }); await ctx.env.BUCKET.put('file.txt', ctx.request.body); return new Response(obj.body); }; ``` -------------------------------- ### Advanced Configuration Examples Source: https://github.com/mizchi/skills/blob/main/cloudflare/deploy/references/wrangler/configuration.md Demonstrates advanced configuration options including Cron Triggers, Observability, Runtime Limits, Browser Rendering, mTLS Certificates, Logpush, Tail Consumers, Unsafe bindings. ```jsonc // Cron Triggers { "triggers": { "crons": ["0 0 * * *"] } } ``` ```jsonc // Observability (tracing) { "observability": { "enabled": true, "head_sampling_rate": 0.1 } } ``` ```jsonc // Runtime Limits { "limits": { "cpu_ms": 100 } } ``` ```jsonc // Browser Rendering { "browser": { "binding": "BROWSER" } } ``` ```jsonc // mTLS Certificates { "mtls_certificates": [{ "binding": "CERT", "certificate_id": "cert-uuid" }] } ``` ```jsonc // Logpush (stream logs to R2/S3) { "logpush": true } ``` ```jsonc // Tail Consumers (process logs with another Worker) { "tail_consumers": [{ "service": "log-worker" }] } ``` ```jsonc // Unsafe bindings (access to arbitrary bindings) { "unsafe": { "bindings": [{ "name": "MY_BINDING", "type": "plain_text", "text": "value" }] } } ``` -------------------------------- ### APM Configuration with Explicit Targets Source: https://github.com/mizchi/skills/blob/main/tooling/apm-usage/SKILL.md Example `apm.yml` configuration specifying deployment targets. Always declare targets to avoid installation errors. ```yaml name: my-project version: 1.0.0 targets: - claude dependencies: apm: - owner/repo ``` -------------------------------- ### Binding Configuration Examples Source: https://github.com/mizchi/skills/blob/main/cloudflare/deploy/references/wrangler/configuration.md Demonstrates how to configure various types of bindings, including variables, KV namespaces, D1 databases, R2 buckets, Durable Objects, Services, Queues, Vectorize, Hyperdrive, Workers AI, Workflows, Secrets Store, and Constellation. ```jsonc // Variables { "vars": { "API_URL": "https://api.example.com" } } ``` ```jsonc // KV { "kv_namespaces": [{ "binding": "CACHE", "id": "abc123" }] } ``` ```jsonc // D1 { "d1_databases": [{ "binding": "DB", "database_id": "abc-123" }] } ``` ```jsonc // R2 { "r2_buckets": [{ "binding": "ASSETS", "bucket_name": "my-assets" }] } ``` ```jsonc // Durable Objects { "durable_objects": { "bindings": [{ "name": "COUNTER", "class_name": "Counter", "script_name": "my-worker" // Required for external DOs }] } } ``` ```jsonc { "migrations": [{ "tag": "v1", "new_sqlite_classes": ["Counter"] }] } ``` ```jsonc // Service Bindings { "services": [{ "binding": "AUTH", "service": "auth-worker" }] } ``` ```jsonc // Queues { "queues": { "producers": [{ "binding": "TASKS", "queue": "task-queue" }], "consumers": [{ "queue": "task-queue", "max_batch_size": 10 }] } } ``` ```jsonc // Vectorize { "vectorize": [{ "binding": "VECTORS", "index_name": "embeddings" }] } ``` ```jsonc // Hyperdrive (requires nodejs_compat_v2 for pg/postgres) { "hyperdrive": [{ "binding": "HYPERDRIVE", "id": "hyper-id" }] } ``` ```jsonc { "compatibility_flags": ["nodejs_compat_v2"] } // For pg/postgres ``` ```jsonc // Workers AI { "ai": { "binding": "AI" } } ``` ```jsonc // Workflows { "workflows": [{ "binding": "WORKFLOW", "name": "my-workflow", "class_name": "MyWorkflow" }] } ``` ```jsonc // Secrets Store (centralized secrets) { "secrets_store": [{ "binding": "SECRETS", "id": "store-id" }] } ``` ```jsonc // Constellation (AI inference) { "constellation": [{ "binding": "MODEL", "project_id": "proj-id" }] } ``` -------------------------------- ### GitHub Actions Integration Source: https://github.com/mizchi/skills/blob/main/tooling/dotenvx/SKILL.md Example of installing dotenvx within a GitHub Actions workflow and using it to run tests with encrypted environment variables. ```yaml steps: - uses: actions/checkout@v4 - name: Install dotenvx run: curl -sfS https://dotenvx.sh | sh - name: Run tests env: DOTENV_PRIVATE_KEY: ${{ secrets.DOTENV_PRIVATE_KEY }} run: dotenvx run -- npm test ``` -------------------------------- ### Startup Methods: start() and startAndWaitForPorts() Source: https://github.com/mizchi/skills/blob/main/cloudflare/deploy/references/containers/api.md Methods to start a container, with options for environment variables and waiting for ports to become ready. `startAndWaitForPorts()` is recommended for HTTP/TCP communication. ```APIDOC ## Startup Methods ### start() Basic start (8s timeout). Returns when process starts, NOT when ports ready. Use for fire-and-forget. ```typescript await container.start(); await container.start({ envVars: { KEY: "value" } }); ``` ### startAndWaitForPorts() Recommended (20s timeout). Returns when ports listening. Use before HTTP/TCP requests. ```typescript await container.startAndWaitForPorts(); // Uses requiredPorts await container.startAndWaitForPorts({ ports: [8080, 9090] }); await container.startAndWaitForPorts({ ports: [8080], startOptions: { envVars: { KEY: "value" } } }); ``` **Port resolution:** explicit ports → requiredPorts → defaultPort → port 33 ``` -------------------------------- ### Caching Example Source: https://github.com/mizchi/skills/blob/main/cloudflare/deploy/references/workers-playground/patterns.md Implements caching for GET requests using the default cache API. Fetches from origin only if the resource is not in cache or is a non-GET request. ```javascript export default { async fetch(request) { if (request.method !== 'GET') return fetch(request); const cache = caches.default; let response = await cache.match(request); if (!response) { response = await fetch('https://api.example.com'); if (response.status === 200) await cache.put(request, response.clone()); } return response; } }; ``` -------------------------------- ### itty-router Basic Setup Source: https://github.com/mizchi/skills/blob/main/cloudflare/deploy/references/workers/frameworks.md Set up a minimalist router using itty-router for simple routing needs. Handles GET requests with path parameters. ```typescript import { Router } from 'itty-router'; const router = Router(); router.get('/users/:id', ({ params }) => new Response(params.id)); export default { fetch: router.handle }; ``` -------------------------------- ### QuickCheck Setup Source: https://github.com/mizchi/skills/blob/main/lang/moonbit-practice/reference/testing.md Configuration to add the `moonbitlang/quickcheck` package to the project's test dependencies in `moon.pkg.json`. ```json { "test-import": [ "moonbitlang/quickcheck" ] } ``` -------------------------------- ### Get Day-wise Analytics Source: https://github.com/mizchi/skills/blob/main/cloudflare/deploy/references/realtimekit/api.md Retrieves day-wise analytics data for a specified date range. Requires start and end dates in YYYY-MM-DD format. ```bash GET /analytics/daywise?start_date=YYYY-MM-DD&end_date=YYYY-MM-DD # Day-wise analytics ``` -------------------------------- ### Complete Wrangler Configuration Example Source: https://github.com/mizchi/skills/blob/main/cloudflare/deploy/references/bindings/configuration.md A comprehensive example of a Wrangler configuration file, including name, main entry point, compatibility date, and various bindings. ```jsonc { "$schema": "./node_modules/wrangler/config-schema.json", "name": "my-app", "main": "src/index.ts", "compatibility_date": "2025-01-01", "vars": { "API_URL": "https://api.example.com" }, "kv_namespaces": [{ "binding": "CACHE", "id": "abc123" }], "r2_buckets": [{ "binding": "ASSETS", "bucket_name": "my-assets" }], "d1_databases": [{ "binding": "DB", "database_name": "my-db", "database_id": "xyz789" }], "services": [{ "binding": "AUTH", "service": "auth-worker" }], "ai": { "binding": "AI" } } ``` -------------------------------- ### Get External Container State Source: https://github.com/mizchi/skills/blob/main/cloudflare/deploy/references/containers/api.md Retrieves the current status of the container from an external perspective. Possible statuses include 'starting', 'running', 'stopping', and 'stopped'. ```typescript const state = await container.getState(); // state.status: "starting" | "running" | "stopping" | "stopped" ``` -------------------------------- ### Create a Hyperdrive Configuration Source: https://github.com/mizchi/skills/blob/main/cloudflare/deploy/references/wrangler/README.md Set up a Hyperdrive configuration with a database connection string. ```bash wrangler hyperdrive create NAME --connection-string "..." ``` -------------------------------- ### Start Local Development with Remote Bindings Source: https://github.com/mizchi/skills/blob/main/cloudflare/deploy/references/bindings/gotchas.md Starts a local development server that uses production bindings. Useful for testing against live services. ```bash npx wrangler dev --remote ``` -------------------------------- ### Initialize Project Structure Source: https://github.com/mizchi/skills/blob/main/tools/waxa/README.md Create the necessary directories and initialize a git repository for your waxa project. ```bash mkdir my-eval && cd my-eval git init mkdir -p skills/echo-skill evals/echo-skill/tasks ``` -------------------------------- ### Create App from Local Path Template Source: https://github.com/mizchi/skills/blob/main/cloudflare/deploy/references/c3/patterns.md Initialize a new application using a custom template located at a local file path. ```bash # Local path npm create cloudflare@latest my-app -- --template=../my-template ``` -------------------------------- ### Get Schedule Count Example Source: https://github.com/mizchi/skills/blob/main/cloudflare/deploy/references/agents-sdk/gotchas.md Shows how to retrieve the current number of scheduled tasks. This is important for monitoring and staying within the agent's schedule limits. ```javascript await this.getSchedules() ``` -------------------------------- ### PostgreSQL (postgres.js) Example Source: https://github.com/mizchi/skills/blob/main/cloudflare/deploy/references/hyperdrive/api.md Initializes a connection to PostgreSQL using postgres.js with a specified connection string and query preparation enabled. Shows an example of selecting active users. ```APIDOC ## PostgreSQL (postgres.js) ### Description Connects to a PostgreSQL database using the `postgres` library, configuring connection pooling and prepared statements for caching. ### Method Direct execution within a Worker context. ### Endpoint N/A (Worker invocation) ### Parameters #### Environment Variables - **env.HYPERDRIVE.connectionString** (string) - Required - The connection string for the PostgreSQL database. ### Request Example ```typescript import postgres from "postgres"; const sql = postgres(env.HYPERDRIVE.connectionString, { max: 5, // Limit per Worker (Workers max: 6) prepare: true, // Enabled by default, required for caching fetch_types: false, // Reduce latency if not using arrays }); const users = await sql`SELECT * FROM users WHERE active = ${true} LIMIT 10`; ``` ### Response - **users** (array) - An array of user objects matching the query. ``` -------------------------------- ### Chezmoi File Structure Example Source: https://github.com/mizchi/skills/blob/main/tooling/chezmoi-management/SKILL.md Illustrates the typical directory structure used by chezmoi for managing dotfiles and configuration. ```text ~/.local/share/chezmoi/ ├── dot_apm/ → ~/.apm/ (APM config) ├── dot_claude/ → ~/.claude/ (Claude Code) │ ├── CLAUDE.md.tmpl │ ├── settings.json.tmpl │ ├── rules/ │ └── skills/ → ~/.claude/skills/ (self-authored skills) ├── dot_codex/ → ~/.codex/ ├── dot_config/ → ~/.config/ (helix, mise, sheldon, starship, zellij, zsh, home-manager) │ └── home-manager/ → ~/.config/home-manager/ (flake.nix / common.nix / darwin.nix — Nix-evaluated; chezmoi only stages the files, Nix does the actual install) ├── dot_zshrc → ~/.zshrc ├── run_once_before_install-brew.sh (bootstrap: clone Homebrew prefix to ~/brew before nix-darwin first activation) └── run_after_apm-install.sh (every apply: apm install --global --target claude) ``` -------------------------------- ### PartyTracks React Hook Example Source: https://github.com/mizchi/skills/blob/main/cloudflare/deploy/references/realtime-sfu/patterns.md Demonstrates how to use the `useObservableAsValue` hook from `observable-hooks` with PartyTracks to get reactive values for local and remote tracks within a React component. ```typescript // React hook example import {useObservableAsValue} from 'observable-hooks'; function VideoCall() { const localTracks = useObservableAsValue(pt.localTracks$); const remoteTracks = useObservableAsValue(pt.remoteTracks$); return
{/* Render tracks */}
; } ``` -------------------------------- ### README.mbt.md Example Source: https://github.com/mizchi/skills/blob/main/lang/moonbit-practice/reference/testing.md Shows how to include a doc test within a `README.mbt.md` file for package documentation. This test verifies the output of the `hello` function. ```markdown # My Package ## Usage ```mbt test test { inspect(@mypackage.hello(), content="Hello, World!") } ``` ``` -------------------------------- ### Connect to Hyperdrive using pg Client Source: https://github.com/mizchi/skills/blob/main/cloudflare/deploy/references/hyperdrive/README.md Example of fetching data from a database using the Hyperdrive binding with the 'pg' client in a Cloudflare Worker. Ensure the 'pg' library is installed. ```typescript import { Client } from "pg"; export default { async fetch(req: Request, env: Env): Promise { const client = new Client({ connectionString: env.HYPERDRIVE.connectionString, }); await client.connect(); const result = await client.query("SELECT * FROM users WHERE id = $1", [123]); await client.end(); return Response.json(result.rows); }, }; ``` -------------------------------- ### Create Rate Limiting Ruleset with Terraform Source: https://github.com/mizchi/skills/blob/main/cloudflare/deploy/references/waf/configuration.md Define a rate-limiting ruleset resource using Terraform. This example blocks requests to paths starting with '/api' if they exceed a defined threshold. ```hcl resource "cloudflare_ruleset" "rate_limiting" { zone_id = var.zone_id phase = "http_ratelimit" rules { action = "block" expression = "http.request.uri.path starts_with \"/api\"" ratelimit { characteristics = ["cf.colo.id", "ip.src"] period = 60 requests_per_period = 100 mitigation_timeout = 600 } } } ``` -------------------------------- ### Start Local Development with Persistence Source: https://github.com/mizchi/skills/blob/main/cloudflare/deploy/references/bindings/gotchas.md Starts a local development server that persists data across restarts. Useful for stateful testing. ```bash npx wrangler dev --persist ``` -------------------------------- ### Routing Configuration Examples Source: https://github.com/mizchi/skills/blob/main/cloudflare/deploy/references/wrangler/configuration.md Illustrates different methods for configuring routes, including custom domains, zone-based routing, and enabling workers.dev. ```jsonc // Custom domain (recommended) { "routes": [{ "pattern": "api.example.com", "custom_domain": true }] } ``` ```jsonc // Zone-based { "routes": [{ "pattern": "api.example.com/*", "zone_name": "example.com" }] } ``` ```jsonc // workers.dev { "workers_dev": true } ``` -------------------------------- ### Durable Object Input Gate Example Source: https://github.com/mizchi/skills/blob/main/cloudflare/deploy/references/do-storage/gotchas.md Demonstrates how an input gate prevents new requests from starting storage reads during an ongoing read operation within the current request. ```typescript async increment() { const val = await this.ctx.storage.get("counter"); // Input gate blocks other requests await this.ctx.storage.put("counter", val + 1); return val; } ``` -------------------------------- ### Install C3 CLI with NPM Source: https://github.com/mizchi/skills/blob/main/cloudflare/deploy/references/c3/README.md Install the C3 CLI using NPM. This command initiates the project creation process. ```bash npm create cloudflare@latest ``` -------------------------------- ### Create Rate Limiting Ruleset with Pulumi Source: https://github.com/mizchi/skills/blob/main/cloudflare/deploy/references/waf/configuration.md Define a rate-limiting ruleset using Pulumi in TypeScript. This example blocks requests to paths starting with '/api' based on defined characteristics and limits. ```typescript // Rate limiting const rateLimiting = new cloudflare.Ruleset('rate-limiting', { zoneId, phase: 'http_ratelimit', rules: [{ action: 'block', expression: 'http.request.uri.path starts_with "/api"', ratelimit: { characteristics: ['cf.colo.id', 'ip.src'], period: 60, requestsPerPeriod: 100, mitigationTimeout: 600, }, }], }); ``` -------------------------------- ### MySQL (mysql2) Example Source: https://github.com/mizchi/skills/blob/main/cloudflare/deploy/references/hyperdrive/api.md Establishes a connection to a MySQL database using mysql2/promise, configuring connection details and disabling eval for security in Workers. Demonstrates querying for active users. ```APIDOC ## MySQL (mysql2) ### Description Connects to a MySQL database using the `mysql2/promise` library, configuring connection details and ensuring `disableEval` is set to `true` for Worker compatibility. ### Method Direct execution within a Worker context. ### Endpoint N/A (Worker invocation) ### Parameters #### Environment Variables - **env.HYPERDRIVE.host** (string) - Required - The MySQL host. - **env.HYPERDRIVE.port** (number) - Required - The MySQL port. - **env.HYPERDRIVE.user** (string) - Required - The MySQL username. - **env.HYPERDRIVE.password** (string) - Required - The MySQL password. - **env.HYPERDRIVE.database** (string) - Required - The MySQL database name. ### Request Example ```typescript import { createConnection } from "mysql2/promise"; const conn = await createConnection({ host: env.HYPERDRIVE.host, user: env.HYPERDRIVE.user, password: env.HYPERDRIVE.password, database: env.HYPERDRIVE.database, port: env.HYPERDRIVE.port, disableEval: true, // ⚠️ REQUIRED for Workers }); const [results] = await conn.query("SELECT * FROM users WHERE active = ? LIMIT ?", [true, 10]); ctx.waitUntil(conn.end()); ``` ### Response - **results** (array) - An array of user objects matching the query. ``` -------------------------------- ### Python SDK: Spectrum Application Management Source: https://github.com/mizchi/skills/blob/main/cloudflare/deploy/references/spectrum/api.md Demonstrates creating, listing, getting, updating, and deleting Spectrum applications using the Cloudflare Python SDK. Includes an example for fetching analytics. ```python from cloudflare import Cloudflare client = Cloudflare(api_token="your-api-token") # Create app = client.spectrum.apps.create( zone_id="your-zone-id", protocol="tcp/22", dns={"type": "CNAME", "name": "ssh.example.com"}, origin_direct=["tcp://192.0.2.1:22"], ip_firewall=True, tls="off", ) # List apps = client.spectrum.apps.list(zone_id="your-zone-id") # Get app_details = client.spectrum.apps.get(zone_id="your-zone-id", app_id=app.id) # Update client.spectrum.apps.update(zone_id="your-zone-id", app_id=app.id, tls="full") # Delete client.spectrum.apps.delete(zone_id="your-zone-id", app_id=app.id) # Analytics analytics = client.spectrum.analytics.aggregate( zone_id="your-zone-id", metrics=["bytesIngress", "bytesEgress"], since=datetime.now() - timedelta(hours=1), ) ``` -------------------------------- ### Bindings Examples Source: https://github.com/mizchi/skills/blob/main/cloudflare/deploy/references/workers/api.md Shows how to interact with various Cloudflare bindings like KV, R2, D1, Queues, and Secrets/Vars. ```APIDOC ## Bindings ### Description Access to various Cloudflare services and environment variables through the `env` object. ### Available Bindings: - **KV (Key-Value Store)**: - `env.MY_KV.get(key: string)`: Retrieves a value from KV. - `env.MY_KV.put(key: string, value: string, options?: { expirationTtl: number })`: Stores a value in KV. - **R2 (Object Storage)**: - `env.MY_BUCKET.get(key: string)`: Retrieves an object from R2. - `env.MY_BUCKET.put(key: string, value: BodyInit)`: Uploads an object to R2. - **D1 (Database)**: - `env.DB.prepare(sql: string).bind(...values).first()`: Executes a D1 SQL query and returns the first row. - `env.DB.withSession()`: Creates a D1 session for read-after-write consistency. - `session.prepare(sql: string).bind(...values).run()`: Executes a D1 SQL statement within a session. - **Queues**: - `env.MY_QUEUE.send(message: any)`: Sends a message to a Queue. - **Secrets/Vars**: - `env.SECRET_NAME`: Accesses environment secrets or variables. ``` -------------------------------- ### TypeScript SDK: Spectrum Application Management Source: https://github.com/mizchi/skills/blob/main/cloudflare/deploy/references/spectrum/api.md Demonstrates creating, listing, getting, updating, and deleting Spectrum applications using the Cloudflare TypeScript SDK. Includes an example for fetching analytics. ```typescript import Cloudflare from 'cloudflare'; const client = new Cloudflare({ apiToken: process.env.CLOUDFLARE_API_TOKEN }); // Create const app = await client.spectrum.apps.create({ zone_id: 'your-zone-id', protocol: 'tcp/22', dns: { type: 'CNAME', name: 'ssh.example.com' }, origin_direct: ['tcp://192.0.2.1:22'], ip_firewall: true, tls: 'off', }); // List const apps = await client.spectrum.apps.list({ zone_id: 'your-zone-id' }); // Get const appDetails = await client.spectrum.apps.get({ zone_id: 'your-zone-id', app_id: app.id }); // Update await client.spectrum.apps.update({ zone_id: 'your-zone-id', app_id: app.id, tls: 'full' }); // Delete await client.spectrum.apps.delete({ zone_id: 'your-zone-id', app_id: app.id }); // Analytics const analytics = await client.spectrum.analytics.aggregate({ zone_id: 'your-zone-id', metrics: ['bytesIngress', 'bytesEgress'], since: new Date(Date.now() - 3600000).toISOString(), }); ``` -------------------------------- ### Create and Use HashSet Source: https://github.com/mizchi/skills/blob/main/lang/moonbit-practice/reference/stdlib.md Demonstrates creating a hash set, inserting elements, and checking for their presence. ```moonbit let set : @hashset.HashSet[Int] = @hashset.new() set.insert(1) set.insert(2) set.contains(1) // true ``` -------------------------------- ### Example .assetsignore File Source: https://github.com/mizchi/skills/blob/main/cloudflare/deploy/references/static-assets/gotchas.md Use an `.assetsignore` file to exclude unnecessary files from your asset uploads, reducing upload time and deployment package size. ```ignore *.map *.md .DS_Store node_modules/ ``` -------------------------------- ### APM Scripts Configuration Source: https://github.com/mizchi/skills/blob/main/tooling/apm-usage/SKILL.md Registers post-install setup or one-shot tasks for APM projects. 'postinstall' runs automatically after 'apm install', while others like 'verify' or 'audit' must be invoked manually. ```yaml scripts: postinstall: "echo 'skills installed; restart Claude Code to pick them up'" verify: "ls -1 .claude/skills | sort" audit: "apm audit" ``` -------------------------------- ### TypeScript Durable Object Class Setup Source: https://github.com/mizchi/skills/blob/main/cloudflare/deploy/references/do-storage/configuration.md Set up a TypeScript class for a Durable Object, including initializing SQL storage and defining the fetch handler. This example demonstrates modern RPC calls. ```typescript export class MyDurableObject extends DurableObject { sql: SqlStorage; constructor(ctx: DurableObjectState, env: Env) { super(ctx, env); this.sql = ctx.storage.sql; // Initialize schema this.sql.exec(` CREATE TABLE IF NOT EXISTS users( id INTEGER PRIMARY KEY, name TEXT NOT NULL, email TEXT UNIQUE ); `); } } // Binding interface Env { MY_DO: DurableObjectNamespace; } export default { async fetch(request: Request, env: Env): Promise { const id = env.MY_DO.idFromName('singleton'); const stub = env.MY_DO.get(id); // Modern RPC: call methods directly (recommended) const result = await stub.someMethod(); return Response.json(result); // Legacy: forward request (still works) // return stub.fetch(request); } } ``` -------------------------------- ### Python SDK: Network Interconnect Operations Source: https://github.com/mizchi/skills/blob/main/cloudflare/deploy/references/network-interconnect/api.md Use the Python SDK to list, create, and get network interconnects. Also includes examples for creating CNI objects and listing available slots. ```python from cloudflare import Cloudflare client = Cloudflare(api_token=os.environ["CF_TOKEN"]) # List, create, status (same pattern as TypeScript) client.network_interconnects.interconnects.list(account_id=id) client.network_interconnects.interconnects.create(account_id=id, account=id, slot_id="slot_abc", type="direct", facility="EWR1", speed="10G") client.network_interconnects.interconnects.get(account_id=id, icon=icon_id) # CNI objects and slots client.network_interconnects.cnis.create(account_id=id, cust_ip="192.0.2.1/31", cf_ip="192.0.2.0/31", bgp_asn=65000) client.network_interconnects.slots.list(account_id=id, occupied=False) ``` -------------------------------- ### Get Argo Smart Routing Status (Python SDK) Source: https://github.com/mizchi/skills/blob/main/cloudflare/deploy/references/argo-smart-routing/api.md Example using the Cloudflare Python SDK to retrieve the Argo Smart Routing status. The API token should be available as an environment variable. ```python from cloudflare import Cloudflare client = Cloudflare(api_token=os.environ.get('CLOUDFLARE_API_TOKEN')) status = client.argo.smart_routing.get(zone_id='your-zone-id') print(f"Argo status: {status.value}, editable: {status.editable}") ``` -------------------------------- ### MoonBit Package Configuration Options Source: https://github.com/mizchi/skills/blob/main/lang/moonbit-practice/reference/configuration.md Shows how to define build options, such as specifying the main entry point, binary name, and native linking settings, in moon.pkg. ```moonbit options( "is-main": true, "bin-name": "name", link: { "native": { "cc": "gcc" } }, ) ``` -------------------------------- ### Prompt Engineering Patterns Source: https://github.com/mizchi/skills/blob/main/cloudflare/deploy/references/workers-ai/patterns.md Utilize system prompts for setting behavior (e.g., JSON output, brevity, step-by-step thinking) and few-shot examples to guide the model's response format and content. ```typescript // System prompts const PROMPTS = { json: 'Respond with valid JSON only.', concise: 'Keep responses brief.', cot: 'Think step by step before answering.' }; // Few-shot messages: [ { role: 'system', content: 'Extract as JSON' }, { role: 'user', content: 'John bought 3 apples for $5' }, { role: 'assistant', content: '{"name":"John","item":"apples","qty":3}' }, { role: 'user', content: actualInput } ] ``` -------------------------------- ### Configure moon.pkg.json for Async Main/Test Source: https://github.com/mizchi/skills/blob/main/lang/moonbit-practice/reference/stdlib.md Shows the necessary JSON configuration to enable 'async fn main' and 'async test' by importing the 'moonbitlang/async' package. ```json { "import": [ "moonbitlang/async" ] } ``` -------------------------------- ### Get Argo Smart Routing Status (TypeScript SDK) Source: https://github.com/mizchi/skills/blob/main/cloudflare/deploy/references/argo-smart-routing/api.md Example using the Cloudflare TypeScript SDK to fetch the Argo Smart Routing status for a zone. Ensure your API token is set in the environment. ```typescript import Cloudflare from 'cloudflare'; const client = new Cloudflare({ apiToken: process.env.CLOUDFLARE_API_TOKEN }); const status = await client.argo.smartRouting.get({ zone_id: 'your-zone-id' }); console.log(`Argo status: ${status.value}, editable: ${status.editable}`); ```