### Quick Start Example Source: https://github.com/dmmulroy/cloudflare-skill/blob/main/skill/cloudflare/references/do-storage/README.md A basic TypeScript example demonstrating the initialization and usage of the SQL API within a Durable Object for a simple counter. ```APIDOC ## Quick Start Example ### Description This example shows how to initialize a Durable Object with the SQL storage backend and implement a simple counter using SQL `INSERT` and `SELECT` statements. ### Method Constructor and custom method within a Durable Object class. ### Endpoint N/A (Client-side Durable Object implementation) ### Request Body N/A ### Request Example ```typescript export class Counter extends DurableObject { sql: SqlStorage; constructor(ctx: DurableObjectState, env: Env) { super(ctx, env); this.sql = ctx.storage.sql; // Initialize table if it doesn't exist this.sql.exec('CREATE TABLE IF NOT EXISTS data(key TEXT PRIMARY KEY, value INTEGER)'); } async increment(): Promise { // Increment the counter value, inserting or replacing if it exists this.sql.exec('INSERT OR REPLACE INTO data VALUES (?, ?) RETURNING value', 'counter', (this.sql.exec('SELECT value FROM data WHERE key = ?', 'counter').one()?.value || 0) + 1); // Retrieve and return the updated value return this.sql.exec('SELECT value FROM data WHERE key = ?', 'counter').one().value; } } ``` ### Response #### Success Response (200) - **value** (number) - The updated counter value. #### Response Example ```json { "value": 1 } ``` ``` -------------------------------- ### Cloudflare Workers Quick Start Source: https://github.com/dmmulroy/cloudflare-skill/blob/main/skill/cloudflare/references/workers/README.md A quick start guide for setting up a new Cloudflare Worker project using npm. It includes commands to create a 'hello-world' worker, navigate into the project directory, and start the local development server. ```bash npm create cloudflare@latest my-worker -- --type hello-world cd my-worker npx wrangler dev ``` -------------------------------- ### Quick Start: Initialize and Test a Cloudflare Worker Locally Source: https://github.com/dmmulroy/cloudflare-skill/blob/main/skill/cloudflare/references/miniflare/README.md Demonstrates how to initialize Miniflare programmatically, define a simple Worker script, dispatch a fetch request to it, and then dispose of the Miniflare instance. This example requires Node.js and the 'miniflare' package to be installed. ```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(); ``` -------------------------------- ### Usage Example: Set up D1 Database Source: https://github.com/dmmulroy/cloudflare-skill/blob/main/README.md Demonstrates how to use the Cloudflare skill via the `/cloudflare` command to get contextual guidance on setting up a D1 database with migrations. ```bash /cloudflare set up a D1 database with migrations ``` -------------------------------- ### Install RealtimeKit Client SDKs (npm) Source: https://github.com/dmmulroy/cloudflare-skill/blob/main/skill/cloudflare/references/realtimekit/configuration.md Installs the RealtimeKit client SDK and UI packages for various frontend frameworks. Use the appropriate package for your project: React, Angular, or Web Components. ```bash npm install @cloudflare/realtimekit @cloudflare/realtimekit-react-ui ``` ```bash npm install @cloudflare/realtimekit @cloudflare/realtimekit-angular-ui ``` ```bash npm install @cloudflare/realtimekit @cloudflare/realtimekit-ui ``` -------------------------------- ### Wrangler CLI: Setup and Management Commands Source: https://github.com/dmmulroy/cloudflare-skill/blob/main/skill/cloudflare/references/pipelines/README.md Essential Wrangler CLI commands for setting up and managing data pipelines. Includes commands for interactive setup, listing, getting details of, and deleting pipelines. ```bash # Interactive setup (creates stream, sink, pipeline) npx wrangler pipelines setup ``` ```bash # List all pipelines npx wrangler pipelines list ``` ```bash # Get pipeline details npx wrangler pipelines get ``` ```bash # Delete pipeline npx wrangler pipelines delete ``` -------------------------------- ### Wrangler Configuration for RealtimeKit Source: https://github.com/dmmulroy/cloudflare-skill/blob/main/skill/cloudflare/references/realtimekit/configuration.md Configuration examples for `wrangler.jsonc` to integrate RealtimeKit with Cloudflare Workers, including basic setup, database/storage bindings, and multi-environment deployment. ```APIDOC ## Wrangler Configuration ### Basic Configuration ```jsonc // wrangler.jsonc { "name": "realtimekit-app", "main": "src/index.ts", "compatibility_date": "2025-01-01", // Use current date "vars": { "CLOUDFLARE_ACCOUNT_ID": "abc123", "REALTIMEKIT_APP_ID": "xyz789" } // Secrets: wrangler secret put CLOUDFLARE_API_TOKEN } ``` ### With Database & Storage ```jsonc { "d1_databases": [{ "binding": "DB", "database_name": "meetings", "database_id": "d1-id" }], "r2_buckets": [{ "binding": "RECORDINGS", "bucket_name": "recordings" }], "kv_namespaces": [{ "binding": "SESSIONS", "id": "kv-id" }] } ``` ### Multi-Environment ```bash # Deploy to environments wrangler deploy --env staging wrangler deploy --env production ``` ``` -------------------------------- ### RealtimeKit Client SDK Configuration Source: https://github.com/dmmulroy/cloudflare-skill/blob/main/skill/cloudflare/references/realtimekit/configuration.md Configuration examples for integrating RealtimeKit client SDKs into various frontend frameworks and for core SDK usage. ```APIDOC ## Client SDK Configuration ### React UI Kit ```tsx import { RtkMeeting } from '@cloudflare/realtimekit-react-ui'; {}} /> ``` ### Angular UI Kit ```typescript @Component({ template: `` }) export class AppComponent { authToken = ''; onLeave() {} } ``` ### Web Components ```html ``` ### Core SDK Configuration ```typescript import RealtimeKitClient from '@cloudflare/realtimekit'; const meeting = new RealtimeKitClient({ authToken: '', video: true, audio: true, autoSwitchAudioDevice: true, mediaConfiguration: { video: { width: { ideal: 1280 }, height: { ideal: 720 }, frameRate: { ideal: 30 } }, audio: { echoCancellation: true, noiseSuppression: true, autoGainControl: true }, screenshare: { width: { max: 1920 }, height: { max: 1080 }, frameRate: { ideal: 15 } } } }); await meeting.join(); ``` ``` -------------------------------- ### Worker Setup with UserDO Source: https://github.com/dmmulroy/cloudflare-skill/blob/main/tmp/userdo.md This example shows how to set up a Cloudflare Worker using UserDO, including built-in authentication endpoints and custom API routes. ```APIDOC ## Worker Setup ### Description Configure a Cloudflare Worker to handle requests, manage user authentication, and expose custom API endpoints that interact with UserDO instances. This example includes a route for creating blog posts. ### Method POST ### Endpoint `/api/posts` ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body - **title** (string) - Required - The title of the blog post. - **content** (string) - Required - The content of the blog post. ### Request Example ```json { "title": "My First Post", "content": "This is the content of my first post." } ``` ### Response #### Success Response (200) - **post** (object) - The created blog post object, including its ID and creation timestamp. #### Response Example ```json { "post": { "id": "some-uuid", "title": "My First Post", "content": "This is the content of my first post.", "createdAt": "2023-10-27T10:00:00Z" } } ``` ### Code Example ```ts import { createUserDOWorker, createWebSocketHandler, getUserDOFromContext } from 'userdo/server'; import type { BlogDO } from './blog-do'; const app = createUserDOWorker('BLOG_DO'); const wsHandler = createWebSocketHandler('BLOG_DO'); app.post('/api/posts', async (c) => { const user = c.get('user'); if (!user) return c.json({ error: 'Unauthorized' }, 401); const { title, content } = await c.req.json(); const blog = getUserDOFromContext(c, user.email, 'BLOG_DO') as unknown as BlogDO; const post = await blog.createPost(title, content); return c.json({ post }); }); export default { async fetch(request: Request, env: any, ctx: any) { if (request.headers.get('upgrade') === 'websocket') return wsHandler.fetch(request, env, ctx); return app.fetch(request, env, ctx); } }; ``` ``` -------------------------------- ### Core SDK - Basic Setup Source: https://github.com/dmmulroy/cloudflare-skill/blob/main/skill/cloudflare/references/realtimekit/patterns.md Demonstrates the basic setup for initializing the RealtimeKit client and joining a meeting. ```APIDOC ## Core SDK - Basic Setup ### Description Demonstrates the basic setup for initializing the RealtimeKit client and joining a meeting. ### Method N/A (Client-side initialization) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```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(); ``` ### Response #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### RealtimeKit Backend Setup API Source: https://github.com/dmmulroy/cloudflare-skill/blob/main/skill/cloudflare/references/realtimekit/configuration.md API endpoints for creating RealtimeKit applications and presets within your Cloudflare account. ```APIDOC ## Backend Setup ### Create App & Credentials **Dashboard**: https://dash.cloudflare.com/?to=/:account/realtime/kit **API**: ```bash curl -X POST 'https://api.cloudflare.com/client/v4/accounts//realtime/kit/apps' \ -H 'Content-Type: application/json' \ -H 'Authorization: Bearer ' \ -d '{"name": "My RealtimeKit App"}' ``` **Required Permissions**: API token with **Realtime / Realtime Admin** permissions ### Create Presets ```bash curl -X POST 'https://api.cloudflare.com/client/v4/accounts//realtime/kit//presets' \ -H 'Authorization: Bearer ' \ -d '{ "name": "host", "permissions": { "canShareAudio": true, "canShareVideo": true, "canRecord": true, "canLivestream": true, "canStartStopRecording": true } }' ``` ``` -------------------------------- ### Initialize PyIceberg RestCatalog Source: https://github.com/dmmulroy/cloudflare-skill/blob/main/skill/cloudflare/references/r2-sql/README.md Initializes a RestCatalog instance from the PyIceberg library to interact with the R2 Data Catalog. This setup requires the catalog name, warehouse name, catalog URI, and an authentication token. It also demonstrates creating a namespace if it doesn't exist. ```python from pyiceberg.catalog.rest import RestCatalog catalog = RestCatalog( name="my_catalog", warehouse="", uri="", token="", ) # Create namespace catalog.create_namespace_if_not_exists("default") ``` -------------------------------- ### Development Server and Deployment Commands Source: https://github.com/dmmulroy/cloudflare-skill/blob/main/tmp/fleet-pattern.md This Bash script provides commands for setting up, running, and deploying the Fleet Pattern project. It includes cloning the repository, installing dependencies using `bun`, starting a local development server, and deploying the application to Cloudflare. ```bash # Clone and setup git clone https://github.com/acoyfellow/fleet-pattern cd fleet-pattern bun install # Start development server bun run dev # Test hierarchy # http://localhost:8787/ (root manager) # http://localhost:8787/team1 (team manager) # http://localhost:8787/team1/project1 (project manager) # Deploy to Cloudflare bun run deploy ``` -------------------------------- ### Cloudflare D1 CLI Quick Start Source: https://github.com/dmmulroy/cloudflare-skill/blob/main/skill/cloudflare/references/d1/README.md Basic Cloudflare D1 CLI commands for creating a database, executing migrations, and starting local development. ```bash # Create database wrangler d1 create # Execute migration wrangler d1 execute --remote --file=./migrations/0001_schema.sql # Local development wrangler dev ``` -------------------------------- ### Install UserDO Package Source: https://github.com/dmmulroy/cloudflare-skill/blob/main/tmp/userdo.md Installs the UserDO package using Bun. This is the initial step to integrate UserDO into your project. ```bash bun install userdo ``` -------------------------------- ### UI Kit Integration Source: https://github.com/dmmulroy/cloudflare-skill/blob/main/skill/cloudflare/references/realtimekit/patterns.md Examples of how to integrate the RealtimeKit UI Kit into React, Angular, and Web Components for a quick setup. ```APIDOC ## UI Kit Integration ### Description Examples of how to integrate the RealtimeKit UI Kit into React, Angular, and Web Components for a quick setup. ### Method N/A (Client-side integration) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript // React import { RtkMeeting } from '@cloudflare/realtimekit-react-ui'; console.log('Left')} /> // Angular @Component({ template: `` }) export class AppComponent { authToken = ''; onLeave(event: unknown) {} } // HTML/Web Components ``` ### Response #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### Environment Variables Setup and Workerd Serve (Bash) Source: https://github.com/dmmulroy/cloudflare-skill/blob/main/skill/cloudflare/references/workerd/patterns.md Example of setting environment variables in the shell and then serving a Workerd configuration. This is a common pattern for providing configuration secrets or dynamic values to a Workerd application during local development or deployment. ```bash export DATABASE_URL="postgres://..." export API_KEY="secret" workerd serve config.capnp ``` -------------------------------- ### Create Cloudflare Application with C3 CLI Source: https://github.com/dmmulroy/cloudflare-skill/blob/main/skill/cloudflare/references/pages/README.md Initiates the creation of a new Cloudflare application using the C3 CLI. It guides the user through framework selection and automates setup and deployment. ```bash npm create cloudflare@latest my-app ``` -------------------------------- ### Set Up Interactive Dev Environment with TypeScript Source: https://github.com/dmmulroy/cloudflare-skill/blob/main/skill/cloudflare/references/sandbox/patterns.md This pattern describes an Interactive Dev Environment that provisions a Code-Server instance within a sandbox. It handles requests to start the environment, installs Code-Server, launches it, and exposes the necessary port, returning a URL to access the IDE. ```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'); } }; ``` -------------------------------- ### Install Cloudflare Skill (Local) Source: https://github.com/dmmulroy/cloudflare-skill/blob/main/README.md Installs the Cloudflare skill for the current project only. This command fetches an installation script and executes it. ```bash curl -fsSL https://raw.githubusercontent.com/dmmulroy/cloudflare-skill/main/install.sh | bash ``` -------------------------------- ### Install Cloudflare Skill (Bash) Source: https://github.com/dmmulroy/cloudflare-skill/blob/main/command/cloudflare.md Installs the Cloudflare skill locally or globally. It fetches an install script from a GitHub repository and executes it. The --global flag is used for global installation. ```bash curl -fsSL https://raw.githubusercontent.com/dmmulroy/cloudflare-skill/main/install.sh | bash # For global installation curl -fsSL https://raw.githubusercontent.com/dmmulroy/cloudflare-skill/main/install.sh | bash -s -- --global ``` -------------------------------- ### TypeScript Setup for Durable Objects Source: https://github.com/dmmulroy/cloudflare-skill/blob/main/skill/cloudflare/references/do-storage/configuration.md Demonstrates the basic TypeScript setup for a Durable Object, including SQL storage initialization and binding configuration for the Durable Object namespace. It also includes a basic fetch handler to route requests to the DO. ```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); return stub.fetch(request); } } ``` -------------------------------- ### Install Cloudflare Skill (Global) Source: https://github.com/dmmulroy/cloudflare-skill/blob/main/README.md Installs the Cloudflare skill globally, making it available in all projects. This command fetches an installation script and executes it with the --global flag. ```bash curl -fsSL https://raw.githubusercontent.com/dmmulroy/cloudflare-skill/main/install.sh | bash -s -- --global ``` -------------------------------- ### Basic TypeScript Cloudflare Worker Setup Source: https://github.com/dmmulroy/cloudflare-skill/blob/main/skill/cloudflare/references/pages-functions/api.md A minimal example of a Cloudflare Worker written in TypeScript, demonstrating the use of `PagesFunction` and the typed `EventContext`. It shows how to import types and access environment bindings that are fully typed based on the provided `Env` interface. ```typescript import type { PagesFunction, EventContext } from '@cloudflare/workers-types'; interface Env { KV: KVNamespace; DB: D1Database; } export const onRequest: PagesFunction = async (context) => { // context.env fully typed return new Response('OK'); }; ``` -------------------------------- ### Track Access Control Example Source: https://github.com/dmmulroy/cloudflare-skill/blob/main/skill/cloudflare/references/realtime-sfu/gotchas.md Example demonstrating how to control client-side access to tracks using backend authentication. ```APIDOC ## Track Access Control ### Description This endpoint demonstrates how to secure track access by verifying user authorization before allowing track publication. It prevents unauthorized clients from accessing specific tracks. ### Method POST ### Endpoint `/api/sessions/:sid/tracks` ### Parameters #### Request Body - **tracks** (array) - Required - An array of track objects to be published. - **trackName** (string) - Required - The name of the track. ### Request Example ```json { "tracks": [ { "trackName": "user_video_feed" }, { "trackName": "screen_share" } ] } ``` ### Logic ```ts app.post('/api/sessions/:sid/tracks', async (req, res) => { // Iterate through each track the client wants to publish for (const t of req.body.tracks) // Check if the authenticated user has permission to access this track if (!await canAccessTrack(req.user.id, t.trackName)) // If not authorized, return a 403 Forbidden error return res.status(403).json({error: 'Unauth'}); // If all tracks are authorized, proceed with the Cloudflare API call // ... CF API call ... }); ``` ### Security Notes - **Never expose App Secrets client-side.** Use backend environment variables or Wrangler secrets. - Track IDs require capabilities and authorization checks. ``` -------------------------------- ### UserDO Durable Object Example Source: https://github.com/dmmulroy/cloudflare-skill/blob/main/tmp/userdo.md This example demonstrates how to extend the UserDO class to define custom data tables and methods for a blog application. ```APIDOC ## Extend UserDO (Your Data + Logic) ### Description Extend the `UserDO` class to define your data schema using Zod and manage it with built-in table methods. This example shows a `BlogDO` with a `posts` table. ### Method N/A (Class definition) ### Endpoint N/A (Class definition) ### Parameters N/A (Class definition) ### Request Example N/A (Class definition) ### Response N/A (Class definition) ### Code Example ```ts import { UserDO, type Env } from "userdo/server"; import { z } from "zod"; const PostSchema = z.object({ title: z.string(), content: z.string() }); export class BlogDO extends UserDO { posts: any; constructor(state: DurableObjectState, env: Env) { super(state, env); this.posts = this.table('posts', PostSchema, { userScoped: true }); } async createPost(title: string, content: string) { return await this.posts.create({ title, content }); } async getPosts() { return await this.posts.orderBy('createdAt', 'desc').get(); } } ``` ``` -------------------------------- ### Response Constructors Source: https://github.com/dmmulroy/cloudflare-skill/blob/main/skill/cloudflare/references/snippets/api.md Provides examples of creating different types of responses (plain text, JSON, HTML, redirect) in Cloudflare Workers. ```APIDOC ## Response Constructors ### Description Constructs various types of HTTP responses for Cloudflare Workers. ### Method N/A (Used within the worker logic) ### Endpoint N/A ### Parameters None ### Request Example ```javascript // Plain text response new Response("Hello", { status: 200 }) // JSON response Response.json({ key: "value" }) // HTML response new Response("

Hi

", { headers: { "Content-Type": "text/html" } }) // Redirect response Response.redirect("https://example.com", 301) ``` ### Response #### Success Response (200) - **Response Object** - A standard Response object that can be returned by the worker. ``` -------------------------------- ### Install Cloudflare Wrangler CLI Source: https://github.com/dmmulroy/cloudflare-skill/blob/main/skill/cloudflare/references/wrangler/README.md Installs the Cloudflare Wrangler CLI tool. It can be installed as a development dependency in a project or globally for system-wide access. After installation, commands are typically run using `npx wrangler`. ```bash npm install wrangler --save-dev # or globally npm install -g wrangler ``` -------------------------------- ### Iceberg Metadata Structure Example Source: https://github.com/dmmulroy/cloudflare-skill/blob/main/skill/cloudflare/references/r2-sql/README.md This illustrates the hierarchical structure of Iceberg metadata files within a storage bucket. It shows the organization of snapshot, manifest, and data files, as well as the version hint and table metadata JSON. Understanding this structure is key to comprehending how Iceberg manages table state and data. ```text bucket/ metadata/ snap-{id}.avro # Snapshot (points to manifest list) {uuid}-m0.avro # Manifest file (lists data files + stats) version-hint.text # Current metadata version v{n}.metadata.json # Table metadata (schema, snapshots) data/ 00000-0-{uuid}.parquet # Data files ``` -------------------------------- ### Install and Run Cloudflare Tunnel (macOS) Source: https://github.com/dmmulroy/cloudflare-skill/blob/main/skill/cloudflare/references/tunnel/README.md This snippet demonstrates the basic steps to install the `cloudflared` connector on macOS using Homebrew, authenticate with Cloudflare, create a new tunnel, route DNS for a hostname, and finally run the tunnel. ```bash # Install cloudflared brew install cloudflared # macOS # Authenticate cloudflared tunnel login # Create tunnel cloudflared tunnel create my-tunnel # Route DNS cloudflared tunnel route dns my-tunnel app.example.com # Run tunnel cloudflared tunnel run my-tunnel ``` -------------------------------- ### Integrate Jupyter with Dockerfile and TypeScript Source: https://github.com/dmmulroy/cloudflare-skill/blob/main/skill/cloudflare/references/sandbox/patterns.md This example shows Jupyter Integration, setting up a Jupyter Notebook server. It includes a Dockerfile to install necessary Python packages and a Worker script to start the Jupyter server process and expose port 8888, providing a URL to access the Jupyter interface. ```dockerfile FROM docker.io/cloudflare/sandbox:latest RUN pip3 install --no-cache-dir jupyter-server ipykernel matplotlib pandas EXPOSE 8888 ``` ```typescript await sandbox.startProcess('jupyter notebook --ip=0.0.0.0 --port=8888 --no-browser', { processId: 'jupyter', cwd: '/workspace' }); const exposed = await sandbox.exposePort(8888, { name: 'jupyter' }); return Response.json({ url: exposed.url }); ``` -------------------------------- ### Framework Integration Setup (Bash) Source: https://github.com/dmmulroy/cloudflare-skill/blob/main/skill/cloudflare/references/pages/patterns.md Command to create a new Cloudflare Pages project integrated with a specified framework. Supports frameworks like Next.js, SvelteKit, Remix, Nuxt.js, Astro, and Qwik. ```bash npm create cloudflare@latest my-app -- --framework= # next, svelte, remix, nuxt, astro, qwik ``` -------------------------------- ### Service Installation: macOS launchd Source: https://github.com/dmmulroy/cloudflare-skill/blob/main/skill/cloudflare/references/tunnel/patterns.md This section details the commands for installing and managing the Cloudflare Tunnel as a launchd service on macOS. It covers installing the service, starting it, loading the launchd plist, and viewing logs from the specified log file. ```bash sudo cloudflared service install sudo launchctl start com.cloudflare.cloudflared sudo launchctl load -w /Library/LaunchDaemons/com.cloudflare.cloudflared.plist # Logs tail -f /Library/Logs/com.cloudflare.cloudflared.err.log ``` -------------------------------- ### Cloudflare Pages Quick Start Commands Source: https://github.com/dmmulroy/cloudflare-skill/blob/main/skill/cloudflare/references/pages/README.md A collection of essential wrangler CLI commands for managing Cloudflare Pages projects, including creation, local development, deployment, type generation, secret management, and log retrieval. ```bash # Create npm create cloudflare@latest # Local dev npx wrangler pages dev ./dist # Deploy npx wrangler pages deploy ./dist --project-name=my-project # Types npx wrangler types --path='./functions/types.d.ts' # Secrets echo "value" | npx wrangler pages secret put KEY --project-name=my-project # Logs npx wrangler pages deployment tail --project-name=my-project ``` -------------------------------- ### Service Installation: Linux systemd Source: https://github.com/dmmulroy/cloudflare-skill/blob/main/skill/cloudflare/references/tunnel/patterns.md This section provides the commands to install and manage the Cloudflare Tunnel as a systemd service on Linux. It includes commands to install the service, start, enable, and check its status, as well as how to view logs using journalctl. ```bash cloudflared service install systemctl start cloudflared systemctl enable cloudflared systemctl status cloudflared # Logs journalctl -u cloudflared -f ``` -------------------------------- ### Python: Set up Log Analytics Pipeline with PyIceberg Source: https://github.com/dmmulroy/cloudflare-skill/blob/main/skill/cloudflare/references/r2-data-catalog/patterns.md This Python code snippet demonstrates how to set up a log analytics pipeline. It initializes a RestCatalog, creates a namespace and a table with a defined schema, and appends log data incrementally. Dependencies include pyiceberg, pyarrow, and pandas. ```python from pyiceberg.catalog.rest import RestCatalog import pyarrow as pa import pandas as pd # Setup catalog catalog = RestCatalog( name="logs_catalog", warehouse=WAREHOUSE, uri=CATALOG_URI, token=TOKEN, ) catalog.create_namespace_if_not_exists("logs") # Create schema for logs log_schema = pa.schema([ ("timestamp", pa.timestamp("ms")), ("level", pa.string()), ("service", pa.string()), ("message", pa.string()), ("user_id", pa.int64()), ]) # Create table logs_table = catalog.create_table( ("logs", "application_logs"), schema=log_schema, ) # Append logs incrementally log_data = pa.table({ "timestamp": [pd.Timestamp.now(), pd.Timestamp.now()], "level": ["ERROR", "INFO"], "service": ["auth-service", "api-gateway"], "message": ["Failed login attempt", "Request processed"], "user_id": [12345, 67890], }) logs_table.appen ``` -------------------------------- ### Setup Cloudflare Pipelines using Wrangler CLI Source: https://github.com/dmmulroy/cloudflare-skill/blob/main/skill/cloudflare/references/pipelines/README.md Provides commands for interactively and manually setting up Cloudflare Pipelines. This includes creating R2 buckets, enabling catalogs, creating streams, configuring sinks, and defining pipelines. ```bash # Interactive setup (recommended) npx wrangler pipelines setup # Manual setup 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 --namespace default --table my_table \ --catalog-token YOUR_TOKEN npx wrangler pipelines create my-pipeline \ --sql "INSERT INTO my_sink SELECT * FROM my_stream" ``` -------------------------------- ### Implement Conditional GET (304 Not Modified) with R2 in TypeScript Source: https://github.com/dmmulroy/cloudflare-skill/blob/main/skill/cloudflare/references/r2/patterns.md This example demonstrates how to handle conditional GET requests using the 'if-none-match' header to return a '304 Not Modified' response when the object has not changed. It retrieves an object only if its ETag does not match the provided If-None-Match header. ```typescript const ifNoneMatch = request.headers.get('if-none-match'); const object = await env.MY_BUCKET.get(key, { onlyIf: { etagDoesNotMatch: ifNoneMatch?.replace(/'/g, '') || '' } }); if (!object) return new Response('Not found', { status: 404 }); if (!object.body) return new Response(null, { status: 304, headers: { 'etag': object.httpEtag } }); return new Response(object.body, { headers: { 'etag': object.httpEtag } }); ``` -------------------------------- ### Manual JS Snippet Installation for Cloudflare Analytics Source: https://github.com/dmmulroy/cloudflare-skill/blob/main/skill/cloudflare/references/web-analytics/configuration.md This snippet demonstrates how to manually install the Cloudflare Web Analytics JavaScript beacon. It should be placed just before the closing tag of your HTML to ensure it loads correctly for all visitors. This method is typically used for sites not proxied through Cloudflare or when auto-injection is disabled. ```html ``` -------------------------------- ### Configure RealtimeKit Core SDK Source: https://github.com/dmmulroy/cloudflare-skill/blob/main/skill/cloudflare/references/realtimekit/configuration.md Initializes and joins a meeting using the core RealtimeKit SDK. Allows detailed configuration of video, audio, and screen sharing media streams. ```typescript import RealtimeKitClient from '@cloudflare/realtimekit'; const meeting = new RealtimeKitClient({ authToken: '', video: true, audio: true, autoSwitchAudioDevice: true, mediaConfiguration: { video: { width: { ideal: 1280 }, height: { ideal: 720 }, frameRate: { ideal: 30 } }, audio: { echoCancellation: true, noiseSuppression: true, autoGainControl: true }, screenshare: { width: { max: 1920 }, height: { max: 1080 }, frameRate: { ideal: 15 } } } }); await meeting.join(); ``` -------------------------------- ### Manipulate Headers in JavaScript Source: https://github.com/dmmulroy/cloudflare-skill/blob/main/skill/cloudflare/references/snippets/api.md Illustrates how to perform common operations on request and response headers within a Cloudflare Worker. This includes getting, setting, appending, and deleting headers. ```javascript // Request headers request.headers.get("X-Header") request.headers.has("X-Header") request.headers.set("X-Header", "value") request.headers.delete("X-Header") // Response headers (must clone first) const res = new Response(response.body, response); res.headers.set("X-Header", "value") res.headers.append("Set-Cookie", "value") res.headers.delete("X-Header") ``` -------------------------------- ### Cloudflare REST API Store Operations Examples (HTTP) Source: https://github.com/dmmulroy/cloudflare-skill/blob/main/skill/cloudflare/references/secrets-store/api.md Illustrates the basic HTTP methods (GET, POST, DELETE) for managing secrets stores via the Cloudflare REST API. It includes example request formats for listing, creating, and deleting stores, specifying the necessary path parameters and request bodies. ```http # List GET /accounts/{account_id}/secrets_store/stores # Create POST /accounts/{account_id}/secrets_store/stores {"name": "my-store"} # Delete DELETE /accounts/{account_id}/secrets_store/stores/{store_id} ``` -------------------------------- ### Basic Test Setup with node:test and Miniflare Source: https://github.com/dmmulroy/cloudflare-skill/blob/main/skill/cloudflare/references/miniflare/patterns.md Sets up a basic test environment using node:test and Miniflare. It initializes Miniflare with modules, a script path, KV namespaces, and bindings. Tests include fetching responses and performing KV operations. ```javascript import assert from "node:assert"; import test, { after, before } from "node:test"; import { Miniflare } from "miniflare"; let mf; before(async () => { mf = new Miniflare({ modules: true, scriptPath: "src/index.js", kvNamespaces: ["TEST_KV"], bindings: { API_KEY: "test-key" }, }); await mf.ready; }); test("fetch returns hello", async () => { const res = await mf.dispatchFetch("http://localhost/"); assert.strictEqual(await res.text(), "Hello World"); }); test("kv operations", async () => { const kv = await mf.getKVNamespace("TEST_KV"); await kv.put("key", "value"); const res = await mf.dispatchFetch("http://localhost/kv"); assert.strictEqual(await res.text(), "value"); }); after(async () => { await mf.dispose(); }); ``` -------------------------------- ### Sync KV API (SQLite only) Source: https://github.com/dmmulroy/cloudflare-skill/blob/main/skill/cloudflare/references/do-storage/api.md Interact with the Key-Value store synchronously. Supports get, put, delete, and list operations. List operations support options like start, prefix, reverse, and limit. ```APIDOC ## Sync KV API (SQLite only) ### Description Interact with the Key-Value store synchronously. Supports get, put, delete, and list operations. List operations support options like start, prefix, reverse, and limit. ### Method `this.ctx.storage.kv.get(key: string)` `this.ctx.storage.kv.put(key: string, value: any)` `this.ctx.storage.kv.delete(key: string)` `this.ctx.storage.kv.list(options?: { start?: string, prefix?: string, reverse?: boolean, limit?: number })` ### Endpoint N/A (Internal API) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript this.ctx.storage.kv.get("counter"); // undefined if missing this.ctx.storage.kv.put("counter", 42); this.ctx.storage.kv.put("user", { name: "Alice", age: 30 }); this.ctx.storage.kv.delete("counter"); // true if existed for (let [key, value] of this.ctx.storage.kv.list()) {} // List options: start, prefix, reverse, limit this.ctx.storage.kv.list({ start: "user:", prefix: "user:", reverse: true, limit: 100 }); ``` ### Response #### Success Response (200) - `get`: The value associated with the key, or `undefined` if the key does not exist. - `put`: void - `delete`: `true` if the key existed and was deleted, `false` otherwise. - `list`: An iterator yielding `[key, value]` pairs. #### Response Example ```json // Example for get("user") { "name": "Alice", "age": 30 } ``` ```json // Example for list() [ ["counter", 42], ["user", {"name": "Alice", "age": 30}] ] ``` ``` -------------------------------- ### TypeScript Setup for Cloudflare Workers Source: https://github.com/dmmulroy/cloudflare-skill/blob/main/skill/cloudflare/references/workers/configuration.md Provides instructions for setting up TypeScript for Cloudflare Workers, including installing the necessary types package and configuring the tsconfig.json file. It also shows how to define an environment interface for accessing bindings. ```bash npm install -D @cloudflare/workers-types ``` ```json { "compilerOptions": { "target": "ES2022", "lib": ["ES2022"], "types": ["@cloudflare/workers-types"] } } ``` ```typescript interface Env { MY_KV: KVNamespace; DB: D1Database; API_KEY: string; } ``` -------------------------------- ### Cloudflare Pipelines - Setup & Configuration Source: https://github.com/dmmulroy/cloudflare-skill/blob/main/skill/cloudflare/references/pipelines/README.md Provides commands for setting up and configuring Cloudflare Pipelines, including creating streams, sinks, and pipelines. ```APIDOC ## Setup & Configuration ### Quick Start Interactive setup (recommended): ```bash npx wrangler pipelines setup ``` Manual setup: ```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 --namespace default --table my_table \ --catalog-token YOUR_TOKEN npx wrangler pipelines create my-pipeline \ --sql "INSERT INTO my_sink SELECT * FROM my_stream" ``` ``` -------------------------------- ### Get Argo Smart Routing Status - TypeScript SDK Source: https://github.com/dmmulroy/cloudflare-skill/blob/main/skill/cloudflare/references/argo-smart-routing/api.md Demonstrates how to retrieve the Argo Smart Routing enablement status using the Cloudflare TypeScript SDK. This example assumes the API token is stored in an environment variable. ```typescript import Cloudflare from 'cloudflare'; const client = new Cloudflare({ apiToken: process.env.CLOUDFLARE_API_TOKE ``` -------------------------------- ### Set up RealtimeKit Client and Join Meeting (TypeScript) Source: https://github.com/dmmulroy/cloudflare-skill/blob/main/skill/cloudflare/references/realtimekit/patterns.md Provides a basic setup for the RealtimeKit client, enabling video and audio, and joining a meeting. It includes event listeners for room joining and participant updates. Requires the '@cloudflare/realtimekit' package. The function returns a client instance and handles joining the meeting. ```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(); ``` -------------------------------- ### Infrastructure Setup for Ecommerce Analytics Pipeline Source: https://github.com/dmmulroy/cloudflare-skill/blob/main/skill/cloudflare/references/pipelines/README.md Provides bash commands to set up the necessary infrastructure for an ecommerce analytics pipeline using Cloudflare's Wrangler CLI. This includes creating an R2 bucket, enabling its catalog, creating a data stream with the defined schema, and setting up an R2 data catalog sink. ```bash # Create bucket and enable catalog npx wrangler r2 bucket create ecommerce-data npx wrangler r2 bucket catalog enable ecommerce-data # Create stream npx wrangler pipelines streams create ecommerce-stream \ --schema-file ecommerce-schema.json # Create sink npx wrangler pipelines sinks create ecommerce-sink \ --type r2-data-catalog \ --bucket ecommerce-data \ --namespace default \ --table events \ --catalog-token $CATALOG_TOKEN \ --roll-interval 60 ``` -------------------------------- ### Initialize and Join a RealtimeKit Meeting using Core SDK Source: https://github.com/dmmulroy/cloudflare-skill/blob/main/skill/cloudflare/references/realtimekit/README.md This TypeScript snippet demonstrates the core client-side integration of Cloudflare RealtimeKit. It initializes the RealtimeKitClient with an authentication token and specifies whether to enable video and audio. The `join()` method is then called to establish the connection to the real-time meeting session. Ensure the authToken is valid and obtained from the backend. ```typescript import RealtimeKitClient from '@cloudflare/realtimekit'; const meeting = new RealtimeKitClient({ authToken: '', video: true, audio: true }); await meeting.join(); ``` -------------------------------- ### WebRTC Flow: Initialize PeerConnection, Add Tracks, Create Offer Source: https://github.com/dmmulroy/cloudflare-skill/blob/main/skill/cloudflare/references/realtime-sfu/api.md This TypeScript snippet demonstrates the initial steps of a WebRTC flow. It covers creating an RTCPeerConnection with Cloudflare's STUN server, adding local media tracks, creating an SDP offer, and setting it as the local description. ```typescript // 1. Create PeerConnection const pc = new RTCPeerConnection({ iceServers: [{urls: 'stun:stun.cloudflare.com:3478'}] }); // 2. Add tracks const stream = await navigator.mediaDevices.getUserMedia({video: true, audio: true}); stream.getTracks().forEach(track => pc.addTrack(track, stream)); // 3. Create offer const offer = await pc.createOffer(); await pc.setLocalDescription(offer); ``` -------------------------------- ### SQL Aggregation Patterns Source: https://github.com/dmmulroy/cloudflare-skill/blob/main/skill/cloudflare/references/r2-sql/README.md Demonstrates SQL aggregation patterns in R2 SQL, including COUNT, SUM, AVG, MIN, and MAX functions. Examples cover grouping data by a column, performing multiple aggregations, and filtering aggregated results using the HAVING clause. ```sql -- Count by group SELECT department, COUNT(*) FROM ns.sales_data GROUP BY department; -- Multiple aggregates SELECT region, MIN(price), MAX(price), AVG(price) FROM ns.products GROUP BY region ORDER BY AVG(price) DESC; -- With HAVING filter SELECT category, SUM(amount) FROM ns.sales WHERE sale_date >= '2024-01-01' GROUP BY category HAVING SUM(amount) > 10000 LIMIT 10; ``` -------------------------------- ### Synchronous KV Operations with DO Storage API (SQLite only) Source: https://github.com/dmmulroy/cloudflare-skill/blob/main/skill/cloudflare/references/do-storage/api.md Shows how to perform synchronous Key-Value (KV) operations using the DO Storage API, specifically for SQLite. Includes examples for getting, putting, deleting, and listing KV pairs, with support for listing options like prefix and limit. ```typescript this.ctx.storage.kv.get("counter"); // undefined if missing this.ctx.storage.kv.put("counter", 42); this.ctx.storage.kv.put("user", { name: "Alice", age: 30 }); this.ctx.storage.kv.delete("counter"); // true if existed for (let [key, value] of this.ctx.storage.kv.list()) {} // List options: start, prefix, reverse, limit this.ctx.storage.kv.list({ start: "user:", prefix: "user:", reverse: true, limit: 100 }); ``` -------------------------------- ### Create Pipeline with Data Catalog Sink (JSON Schema) Source: https://github.com/dmmulroy/cloudflare-skill/blob/main/skill/cloudflare/references/r2-sql/README.md This JSON defines the schema for data to be ingested into a Cloudflare Pipeline. It specifies the fields 'user_id' (string, required), 'event_type' (string, required), and 'amount' (float64, optional). This schema is used during the pipeline setup process. ```json { "fields": [ {"name": "user_id", "type": "string", "required": true}, {"name": "event_type", "type": "string", "required": true}, {"name": "amount", "type": "float64", "required": false} ] } ``` -------------------------------- ### Compile Workerd Configuration to Binary Source: https://github.com/dmmulroy/cloudflare-skill/blob/main/skill/cloudflare/references/workerd/gotchas.md Optimizes startup performance by compiling the Workerd configuration into a binary executable. This can reduce the overhead associated with parsing Cap'n Proto schemas at runtime. ```bash workerd compile config.capnp name -o binary ``` -------------------------------- ### Interact with Cloudflare R2 Bucket in TypeScript Source: https://github.com/dmmulroy/cloudflare-skill/blob/main/skill/cloudflare/references/pages-functions/api.md Shows how to perform operations on a Cloudflare R2 object storage bucket. Includes examples for `get`, `put`, and `delete` operations. The `put` operation demonstrates setting `httpMetadata` like `contentType`. Requires an `R2Bucket` binding named `BUCKET` in the `Env` interface. ```typescript interface Env { BUCKET: R2Bucket; } export const onRequest: PagesFunction = async (context) => { const url = new URL(context.request.url); const key = url.pathname.slice(1); // GET const obj = await context.env.BUCKET.get(key); if (!obj) return new Response('Not found', { status: 404 }); // PUT await context.env.BUCKET.put(key, context.request.body, { httpMetadata: { contentType: 'application/octet-stream' } }); // DELETE await context.env.BUCKET.delete(key); return new Response(obj.body); }; ``` -------------------------------- ### Send Data to Pipeline (cURL) Source: https://github.com/dmmulroy/cloudflare-skill/blob/main/skill/cloudflare/references/r2-sql/README.md This cURL command demonstrates how to send data to a Cloudflare Pipeline using an HTTP POST request. It includes the necessary 'Content-Type' header and a JSON payload containing sample event data. The stream ID in the URL needs to be replaced with the actual ID obtained during pipeline setup. ```bash curl -X POST https://{stream-id}.ingest.cloudflare.com \ -H "Content-Type: application/json" \ -d \ '[\n {\n "user_id": "user_123",\n "event_type": "purchase",\n "amount": 29.99\n }\n ]' ```