### Localflare Development Setup Source: https://github.com/rohanprasadofficial/localflare/blob/main/README.md Instructions for setting up the Localflare development environment. This involves cloning the repository, installing dependencies using pnpm, building all packages, and running the playground environment. ```bash # Clone the repo git clone https://github.com/rohanprasadofficial/localflare cd localflare # Install dependencies pnpm install # Build all packages pnpm build # Run the playground cd playground pnpm dev ``` -------------------------------- ### Install and Run Localflare CLI Source: https://context7.com/rohanprasadofficial/localflare/llms.txt Installs the Localflare CLI globally and starts the development server by automatically detecting configuration files. It outputs the URLs for the Worker and the dashboard. ```bash # Install globally npm install -g localflare # Navigate to your Cloudflare Worker project cd my-worker-project # Start with default settings (reads wrangler.toml automatically) localflare # Output: # ⚡ Localflare # Local Cloudflare Development Dashboard # # Config: /path/to/wrangler.toml # # ✓ Localflare is running! # # Worker: http://localhost:8787 # Dashboard: http://localhost:8788 ``` -------------------------------- ### Create Custom Dashboard Server with LocalFlare Source: https://context7.com/rohanprasadofficial/localflare/llms.txt Example of building a custom dashboard server using `localflare-server` and `localflare-core`. Demonstrates initializing LocalFlare, creating a dashboard app, adding custom routes, and starting the server on a specified port. ```typescript import { createDashboardApp, startDashboardServer } from 'localflare-server' import { LocalFlare } from 'localflare-core' // Initialize LocalFlare const localflare = new LocalFlare({ configPath: './wrangler.toml', port: 8787 }) await localflare.start() // Create and customize the dashboard app const app = createDashboardApp(localflare) // Add custom routes app.get('/api/custom/stats', async (c) => { const bindings = localflare.getDiscoveredBindings() return c.json({ d1Count: bindings?.d1.length ?? 0, kvCount: bindings?.kv.length ?? 0, r2Count: bindings?.r2.length ?? 0 }) }) // Start server with custom port await startDashboardServer({ localflare, port: 9000, staticPath: './custom-dashboard-ui' }) console.log('Custom dashboard running at http://localhost:9000') ``` -------------------------------- ### Start localflare-server API Source: https://github.com/rohanprasadofficial/localflare/blob/main/packages/server/README.md Demonstrates how to initialize and start the localflare-server API. It requires localflare-core for configuration and starts the Hono-based server on a specified port. ```typescript import { createDashboardServer } from 'localflare-server'; import { LocalFlareCore } from 'localflare-core'; const core = new LocalFlareCore({ configPath: './wrangler.toml' }); await core.start(); const server = createDashboardServer({ core, port: 8788 }); await server.start(); ``` -------------------------------- ### Install localflare-server Source: https://github.com/rohanprasadofficial/localflare/blob/main/packages/server/README.md Installs the localflare-server package using npm or pnpm. This is the first step to using the dashboard API server. ```bash npm install localflare-server # or pnpm add localflare-server ``` -------------------------------- ### CLI Usage Source: https://context7.com/rohanprasadofficial/localflare/llms.txt Instructions on how to install and run Localflare from the command line, including default settings and custom configuration options. ```APIDOC ## CLI Usage Start the development server with automatic configuration detection ```bash # Install globally npm install -g localflare # Navigate to your Cloudflare Worker project cd my-worker-project # Start with default settings (reads wrangler.toml automatically) localflare # Output: # ⚡ Localflare # Local Cloudflare Development Dashboard # # Config: /path/to/wrangler.toml # # ✓ Localflare is running! # # Worker: http://localhost:8787 # Dashboard: http://localhost:8788 ``` ## CLI with Custom Configuration Specify custom ports and configuration paths ```bash # Custom ports localflare -p 3000 -d 3001 # Custom config file path localflare ./custom/wrangler.toml # Custom persistence directory localflare --persist .custom-data # Enable verbose logging localflare -v ``` ``` -------------------------------- ### Install Localflare CLI Source: https://github.com/rohanprasadofficial/localflare/blob/main/README.md Install the Localflare command-line interface globally using npm, pnpm, or npx. This allows you to run Localflare from any directory. ```bash npm install -g localflare # or pnpm add -g localflare # or npx localflare ``` -------------------------------- ### Example Localflare Commands Source: https://github.com/rohanprasadofficial/localflare/blob/main/README.md Demonstrates various ways to run the `localflare` command, including using default settings, specifying custom ports for the Worker and dashboard, and providing a custom path to the `wrangler.toml` configuration file. ```bash # Use default settings localflare # Custom ports localflare -p 3000 -d 3001 # With custom config path localflare ./custom/wrangler.toml ``` -------------------------------- ### Install localflare-core using npm or pnpm Source: https://github.com/rohanprasadofficial/localflare/blob/main/packages/core/README.md Installs the localflare-core package, which is required for using the Localflare tools. This package provides the core functionality for running Cloudflare Workers locally. ```bash npm install localflare-core # or pnpm add localflare-core ``` -------------------------------- ### Initialize and control LocalFlareCore in TypeScript Source: https://github.com/rohanprasadofficial/localflare/blob/main/packages/core/README.md Demonstrates how to initialize and control the LocalFlareCore instance in TypeScript. It covers starting the worker, accessing bindings programmatically, and stopping the worker when finished. Dependencies include 'localflare-core'. ```typescript import { LocalFlareCore } from 'localflare-core'; const core = new LocalFlareCore({ configPath: './wrangler.toml', port: 8787, persist: '.localflare' }); // Start the worker await core.start(); // Access bindings programmatically const bindings = core.getBindings(); // Get D1 databases const d1Databases = bindings.d1; // Get KV namespaces const kvNamespaces = bindings.kv; // Stop when done await core.stop(); ``` -------------------------------- ### Manage Durable Objects (DO) Source: https://context7.com/rohanprasadofficial/localflare/llms.txt API for interacting with Durable Objects, including listing bindings, discovering instances, getting or creating DO IDs, and fetching data from DOs. Requires specifying the DO binding and ID for fetches. ```bash # List all Durable Object bindings curl http://localhost:8788/api/do # Response: { "durableObjects": [{ "name": "COUNTER", "class_name": "Counter" }] } # Discover existing DO instances curl http://localhost:8788/api/do/instances # Response: { "instances": [ # { "binding": "COUNTER", "class_name": "Counter", "id": "abc123..." } # ] } # Get or create DO ID curl -X POST http://localhost:8788/api/do/COUNTER/id \ -H "Content-Type: application/json" \ -d '{"name": "global-counter"}' # Response: { "id": "abc123def456..." } # Create unique ID curl -X POST http://localhost:8788/api/do/COUNTER/id \ -H "Content-Type: application/json" \ -d '{}' # Response: { "id": "unique-hex-id..." } # Fetch from Durable Object curl -X POST "http://localhost:8788/api/do/COUNTER/abc123def456/fetch/increment" \ -H "Content-Type: application/json" \ -d '{"amount": 5}' # Returns the DO's response directly ``` -------------------------------- ### KV Namespace API Source: https://github.com/rohanprasadofficial/localflare/blob/main/packages/server/README.md Endpoints for managing KV namespaces, including listing namespaces, keys, getting, setting, and deleting values. ```APIDOC ## GET /api/kv ### Description Lists all available KV namespaces. ### Method GET ### Endpoint /api/kv ### Parameters #### Query Parameters #### Request Body ### Response #### Success Response (200) - **namespaces** (array) - A list of KV namespace names. #### Response Example ```json { "namespaces": [ "my-kv-1", "my-kv-2" ] } ``` ## GET /api/kv/:name/keys ### Description Lists all keys within a specified KV namespace. ### Method GET ### Endpoint /api/kv/:name/keys #### Path Parameters - **name** (string) - Required - The name of the KV namespace. ### Parameters #### Query Parameters #### Request Body ### Response #### Success Response (200) - **keys** (array) - A list of keys in the namespace. #### Response Example ```json { "keys": [ "user:1", "product:abc" ] } ``` ## GET /api/kv/:name/:key ### Description Retrieves the value associated with a specific key in a KV namespace. ### Method GET ### Endpoint /api/kv/:name/:key #### Path Parameters - **name** (string) - Required - The name of the KV namespace. - **key** (string) - Required - The key whose value to retrieve. ### Parameters #### Query Parameters #### Request Body ### Response #### Success Response (200) - **value** (any) - The value associated with the key. #### Response Example ```json { "value": "some data" } ``` ## PUT /api/kv/:name/:key ### Description Sets or updates the value for a specific key in a KV namespace. ### Method PUT ### Endpoint /api/kv/:name/:key #### Path Parameters - **name** (string) - Required - The name of the KV namespace. - **key** (string) - Required - The key to set or update. ### Parameters #### Query Parameters #### Request Body - **value** (any) - Required - The value to set for the key. ### Request Example ```json { "value": "new data" } ``` ### Response #### Success Response (200) - **success** (boolean) - Indicates if the operation was successful. #### Response Example ```json { "success": true } ``` ## DELETE /api/kv/:name/:key ### Description Deletes a specific key and its associated value from a KV namespace. ### Method DELETE ### Endpoint /api/kv/:name/:key #### Path Parameters - **name** (string) - Required - The name of the KV namespace. - **key** (string) - Required - The key to delete. ### Parameters #### Query Parameters #### Request Body ### Response #### Success Response (200) - **success** (boolean) - Indicates if the operation was successful. #### Response Example ```json { "success": true } ``` ``` -------------------------------- ### Key-Value (KV) Store API Source: https://context7.com/rohanprasadofficial/localflare/llms.txt APIs for interacting with the Key-Value store, including getting, setting, and deleting entries. ```APIDOC ## GET /api/kv/:binding/keys/:key ### Description Retrieves a value from the KV store. ### Method GET ### Endpoint `/api/kv/:binding/keys/:key` ### Parameters #### Path Parameters - **binding** (string) - Required - The KV namespace binding name. - **key** (string) - Required - The key to retrieve. #### Query Parameters - **type** (string) - Optional - The expected type of the value (e.g., `json`). ### Response #### Success Response (200) - **key** (string) - The retrieved key. - **value** (any) - The retrieved value. - **metadata** (object) - Metadata associated with the value. #### Response Example ```json { "key": "user:123", "value": "...", "metadata": {...} } ``` ## PUT /api/kv/:binding/keys/:key ### Description Sets or updates a value in the KV store. ### Method PUT ### Endpoint `/api/kv/:binding/keys/:key` ### Parameters #### Path Parameters - **binding** (string) - Required - The KV namespace binding name. - **key** (string) - Required - The key to set. #### Request Body - **value** (any) - Required - The value to store. - **expirationTtl** (number) - Optional - Time-to-live in seconds for the value. - **metadata** (object) - Optional - Metadata to associate with the value. ### Request Example ```json { "value": "{\"name\":\"Alice\"}", "expirationTtl": 3600, "metadata": {"version": 1} } ``` ### Response #### Success Response (200) - **success** (boolean) - Indicates if the operation was successful. #### Response Example ```json { "success": true } ``` ## DELETE /api/kv/:binding/keys/:key ### Description Deletes a key-value pair from the KV store. ### Method DELETE ### Endpoint `/api/kv/:binding/keys/:key` ### Response #### Success Response (200) - **success** (boolean) - Indicates if the operation was successful. #### Response Example ```json { "success": true } ``` ## POST /api/kv/:binding/bulk-delete ### Description Deletes multiple keys from the KV store in a single request. ### Method POST ### Endpoint `/api/kv/:binding/bulk-delete` ### Parameters #### Path Parameters - **binding** (string) - Required - The KV namespace binding name. #### Request Body - **keys** (array) - Required - An array of keys to delete. ### Request Example ```json { "keys": ["user:1", "user:2", "user:3"] } ``` ### Response #### Success Response (200) - **success** (boolean) - Indicates if the operation was successful. - **deleted** (number) - The number of keys deleted. #### Response Example ```json { "success": true, "deleted": 3 } ``` ``` -------------------------------- ### Run Localflare in Project Directory Source: https://github.com/rohanprasadofficial/localflare/blob/main/README.md Navigate to your Cloudflare Worker project directory and execute the `localflare` command. This command automatically reads your `wrangler.toml` file and starts your Worker on http://localhost:8787 and the dashboard on http://localhost:8788. ```bash localflare ``` -------------------------------- ### Initialize and Control Localflare Worker (TypeScript) Source: https://context7.com/rohanprasadofficial/localflare/llms.txt Shows how to initialize and control a Miniflare instance with Cloudflare Worker bindings using the LocalFlare class from the 'localflare-core' library. It covers starting, checking the running status, and stopping the worker, with options for configuration path, ports, persistence, verbosity, and custom log handling. ```typescript import { LocalFlare } from 'localflare-core' // Create instance with options const localflare = new LocalFlare({ configPath: './wrangler.toml', port: 8787, dashboardPort: 8788, persistPath: '.localflare', verbose: true, onWorkerLog: (entry) => { console.log(`[${entry.level}] ${entry.message}`) } }) // Start the Worker await localflare.start() // Check if running if (localflare.isRunning()) { console.log('Worker is running') } // Stop the Worker await localflare.stop() ``` -------------------------------- ### R2 Bucket API Source: https://github.com/rohanprasadofficial/localflare/blob/main/packages/server/README.md Endpoints for managing R2 buckets, including listing buckets, objects, getting, uploading, and deleting objects. ```APIDOC ## GET /api/r2 ### Description Lists all available R2 buckets. ### Method GET ### Endpoint /api/r2 ### Parameters #### Query Parameters #### Request Body ### Response #### Success Response (200) - **buckets** (array) - A list of R2 bucket names. #### Response Example ```json { "buckets": [ "my-bucket-1", "my-bucket-2" ] } ``` ## GET /api/r2/:name/objects ### Description Lists all objects within a specified R2 bucket. ### Method GET ### Endpoint /api/r2/:name/objects #### Path Parameters - **name** (string) - Required - The name of the R2 bucket. ### Parameters #### Query Parameters #### Request Body ### Response #### Success Response (200) - **objects** (array) - A list of objects in the bucket. #### Response Example ```json { "objects": [ "path/to/file1.txt", "images/image.jpg" ] } ``` ## GET /api/r2/:name/:key ### Description Retrieves a specific object from an R2 bucket. ### Method GET ### Endpoint /api/r2/:name/:key #### Path Parameters - **name** (string) - Required - The name of the R2 bucket. - **key** (string) - Required - The key (path) of the object to retrieve. ### Parameters #### Query Parameters #### Request Body ### Response #### Success Response (200) - **object** (Blob/Stream) - The content of the R2 object. #### Response Example ``` [Binary content of the object] ``` ## PUT /api/r2/:name/:key ### Description Uploads or replaces an object in an R2 bucket. ### Method PUT ### Endpoint /api/r2/:name/:key #### Path Parameters - **name** (string) - Required - The name of the R2 bucket. - **key** (string) - Required - The key (path) for the object. ### Parameters #### Query Parameters #### Request Body - **file** (File/Blob) - Required - The file content to upload. ### Request Example ``` [Binary file content] ``` ### Response #### Success Response (200) - **success** (boolean) - Indicates if the upload was successful. #### Response Example ```json { "success": true } ``` ## DELETE /api/r2/:name/:key ### Description Deletes a specific object from an R2 bucket. ### Method DELETE ### Endpoint /api/r2/:name/:key #### Path Parameters - **name** (string) - Required - The name of the R2 bucket. - **key** (string) - Required - The key (path) of the object to delete. ### Parameters #### Query Parameters #### Request Body ### Response #### Success Response (200) - **success** (boolean) - Indicates if the deletion was successful. #### Response Example ```json { "success": true } ``` ``` -------------------------------- ### Interact with Key-Value Store (KV) Source: https://context7.com/rohanprasadofficial/localflare/llms.txt Provides endpoints for managing data in the Key-Value store. Supports getting, setting, and deleting single or multiple keys. Values can be plain text or JSON. ```bash # Get JSON value curl "http://localhost:8788/api/kv/CACHE/keys/config?type=json" # Response: { "key": "config", "value": {...}, "metadata": null } # Set value curl -X PUT http://localhost:8788/api/kv/CACHE/keys/user:123 \ -H "Content-Type: application/json" \ -d '{"value": "{\"name\":\"Alice\"}", "expirationTtl": 3600, "metadata": {"version": 1}}' # Response: { "success": true } # Delete key curl -X DELETE http://localhost:8788/api/kv/CACHE/keys/user:123 # Response: { "success": true } # Bulk delete keys curl -X POST http://localhost:8788/api/kv/CACHE/bulk-delete \ -H "Content-Type: application/json" \ -d '{"keys": ["user:1", "user:2", "user:3"]}' # Response: { "success": true, "deleted": 3 } ``` -------------------------------- ### Configure Localflare CLI Ports and Paths Source: https://context7.com/rohanprasadofficial/localflare/llms.txt Demonstrates how to customize the ports for the Worker and dashboard, specify a custom configuration file path, set a custom persistence directory, and enable verbose logging for the Localflare CLI. ```bash # Custom ports localflare -p 3000 -d 3001 # Custom config file path localflare ./custom/wrangler.toml # Custom persistence directory localflare --persist .custom-data # Enable verbose logging localflare -v ``` -------------------------------- ### Localflare CLI Options Source: https://github.com/rohanprasadofficial/localflare/blob/main/README.md The `localflare` command accepts a configuration path and several options to customize the Worker and dashboard ports, specify a persistence directory, enable verbose output, or display help information. ```bash localflare [configPath] [options] Options: -p, --port Worker port (default: 8787) -d, --dashboard-port Dashboard port (default: 8788) --persist Persistence directory (default: .localflare) -v, --verbose Verbose output -h, --help Display help --version Display version ``` -------------------------------- ### Manage R2 Storage Buckets and Objects Source: https://context7.com/rohanprasadofficial/localflare/llms.txt Enables interaction with R2 buckets for managing objects. Supports listing buckets, objects, downloading, uploading, and deleting objects individually or in bulk. Content-Type is important for uploads. ```bash # List all R2 buckets curl http://localhost:8788/api/r2 # Response: { "buckets": [{ "binding": "STORAGE", "bucket_name": "my-bucket" }] } # List objects in bucket curl "http://localhost:8788/api/r2/STORAGE/objects?prefix=docs/&limit=50" # Response: { "objects": [...], "truncated": false, "cursor": null } # Get object metadata curl http://localhost:8788/api/r2/STORAGE/objects/file.pdf/meta # Response: { "key": "file.pdf", "size": 12345, "etag": "...", "uploaded": "..." } # Download object curl http://localhost:8788/api/r2/STORAGE/objects/file.pdf -o file.pdf # Returns object body with appropriate Content-Type header # Upload object curl -X PUT http://localhost:8788/api/r2/STORAGE/objects/docs/report.pdf \ -H "Content-Type: application/pdf" \ --data-binary @report.pdf # Response: { "success": true, "key": "docs/report.pdf", "size": 54321, "etag": "..." } # Delete object curl -X DELETE http://localhost:8788/api/r2/STORAGE/objects/docs/report.pdf # Response: { "success": true } # Bulk delete objects curl -X POST http://localhost:8788/api/r2/STORAGE/bulk-delete \ -H "Content-Type: application/json" \ -d '{"keys": ["file1.txt", "file2.txt", "file3.txt"]}' # Response: { "success": true, "deleted": 3 } ``` -------------------------------- ### Access D1 Database Source: https://context7.com/rohanprasadofficial/localflare/llms.txt Demonstrates how to access and interact with D1 databases using the `LocalFlare` instance. ```APIDOC ## Access D1 Database Query and manipulate D1 databases through the LocalFlare instance ```typescript // Get D1 database binding const db = await localflare.getD1Database('DB') // Query data const result = await db.prepare('SELECT * FROM users WHERE role = ?') .bind('admin') .all() console.log(result.results) // Array of user records console.log(result.meta) // Query metadata // Insert data const insertResult = await db.prepare('INSERT INTO users (email, name) VALUES (?, ?)') .bind('user@example.com', 'John Doe') .run() console.log(insertResult.success) // true console.log(insertResult.meta.last_row_id) // New row ID ``` ### Method - **`getD1Database(bindingName: string): Promise`** - **Description**: Retrieves a D1 database instance associated with the given binding name. - **Parameters**: - `bindingName` (string) - The name of the D1 database binding as defined in `wrangler.toml`. - **Returns**: A promise that resolves to a `D1Database` object. ### D1Database Interface Mimics the Cloudflare D1Database interface, providing methods for database operations: - **`prepare(query: string): D1PreparedStatement`** - **Description**: Prepares a SQL statement for execution. ### D1PreparedStatement Interface - **`bind(...values: any[]): D1PreparedStatement`** - **Description**: Binds values to placeholders in the prepared statement. - **`all(): Promise`** - **Description**: Executes the prepared statement and returns all results. - **`run(): Promise`** - **Description**: Executes the prepared statement and returns metadata, useful for INSERT, UPDATE, DELETE. ### Types - **`D1Database`**: Represents a D1 database connection. - **`D1PreparedStatement`**: Represents a prepared SQL statement. - **`D1Result`**: Object containing query results (`results` array) and metadata (`meta` object). ``` -------------------------------- ### Access Durable Objects in TypeScript Source: https://context7.com/rohanprasadofficial/localflare/llms.txt Interacts with Durable Object instances. Allows getting a namespace, creating object IDs from names or uniquely, and fetching data from object stubs. Supports POST requests with JSON bodies. ```typescript // Get Durable Object namespace const namespace = await localflare.getDurableObjectNamespace('COUNTER') // Get or create ID from name const id = namespace.idFromName('global-counter') // Get stub const stub = namespace.get(id) // Fetch from Durable Object const response = await stub.fetch('http://do.internal/increment', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ amount: 5 }) }) const result = await response.json() console.log(result) // { value: 105 } // Create unique ID const uniqueId = namespace.newUniqueId() console.log(uniqueId.toString()) // Unique hex string ``` -------------------------------- ### Queue API Source: https://context7.com/rohanprasadofficial/localflare/llms.txt APIs for managing queues, including listing, sending messages, and sending batches. ```APIDOC ## GET /api/queues ### Description Lists all available queues (producers and consumers). ### Method GET ### Endpoint `/api/queues` ### Response #### Success Response (200) - **producers** (array) - Information about queue producers. - **consumers** (array) - Information about queue consumers. #### Response Example ```json { "producers": [{ "binding": "TASKS", "queue": "task-queue" }], "consumers": [{ "queue": "task-queue", "max_batch_size": 10, ... }] } ``` ## POST /api/queues/:binding/send ### Description Sends a single message to a queue. ### Method POST ### Endpoint `/api/queues/:binding/send` ### Parameters #### Path Parameters - **binding** (string) - Required - The queue binding name. #### Request Body - **message** (object) - Required - The message payload. - **options** (object) - Optional - Sending options like `delaySeconds`. ### Request Example ```json { "message": {"type": "email", "to": "user@example.com"}, "options": {"delaySeconds": 60} } ``` ### Response #### Success Response (200) - **success** (boolean) - Indicates if the operation was successful. #### Response Example ```json { "success": true } ``` ## POST /api/queues/:binding/send-batch ### Description Sends a batch of messages to a queue. ### Method POST ### Endpoint `/api/queues/:binding/send-batch` ### Parameters #### Path Parameters - **binding** (string) - Required - The queue binding name. #### Request Body - **messages** (array) - Required - An array of message objects. - **body** (object) - Required - The message payload. - **delaySeconds** (number) - Optional - Delay in seconds for this specific message. ### Request Example ```json { "messages": [ {"body": {"task": "process-1"}}, {"body": {"task": "process-2"}, "delaySeconds": 30} ] } ``` ### Response #### Success Response (200) - **success** (boolean) - Indicates if the operation was successful. - **sent** (number) - The number of messages sent. #### Response Example ```json { "success": true, "sent": 2 } ``` ``` -------------------------------- ### Set Worker Log Callback with Localflare TypeScript Source: https://context7.com/rohanprasadofficial/localflare/llms.txt This snippet demonstrates how to capture and process Worker console logs using the `onWorkerLog` callback during Localflare initialization or by using the `setLogCallback` method after initialization. It shows how to format log entries and includes an example of handling error logs. ```typescript const localflare = new LocalFlare({ configPath: './wrangler.toml', onWorkerLog: (entry) => { const timestamp = new Date().toISOString() const level = entry.level.toUpperCase() console.log(`[${timestamp}] ${level}: ${entry.message}`) // Store logs in database, send to monitoring service, etc. if (entry.level === 'error') { // Send error alert } } }) await localflare.start() // Or set callback after initialization localflare.setLogCallback((entry) => { console.log(`Worker log: ${entry.message}`) }) ``` -------------------------------- ### Dashboard Server API - D1 Endpoints Management Source: https://context7.com/rohanprasadofficial/localflare/llms.txt Provides REST API endpoints for managing D1 databases. Supports listing databases, getting schema and table information, querying rows with pagination, executing SQL queries, and performing CRUD operations on rows. Uses bash for command-line interaction. ```bash # List all D1 databases curl http://localhost:8788/api/d1 # Response: { "databases": [{ "binding": "DB", "database_name": "my-db", ... }] } # Get database schema curl http://localhost:8788/api/d1/DB/schema # Response: { "tables": [{ "name": "users", "sql": "CREATE TABLE..." }] } # Get table info curl http://localhost:8788/api/d1/DB/tables/users # Response: { "table": "users", "columns": [...], "rowCount": 42 } # Query table rows with pagination curl "http://localhost:8788/api/d1/DB/tables/users/rows?limit=10&offset=0" # Response: { "rows": [...], "meta": {...} } # Execute SQL query curl -X POST http://localhost:8788/api/d1/DB/query \ -H "Content-Type: application/json" \ -d '{"sql": "SELECT * FROM users WHERE role = ?", "params": ["admin"]}' # Response: { "success": true, "results": [...], "meta": {...} } # Insert row curl -X POST http://localhost:8788/api/d1/DB/tables/users/rows \ -H "Content-Type: application/json" \ -d '{"email": "user@example.com", "name": "John", "role": "user"}' # Response: { "success": true, "meta": { "last_row_id": 123 } } # Update row curl -X PUT http://localhost:8788/api/d1/DB/tables/users/rows/123 \ -H "Content-Type: application/json" \ -d '{"name": "Jane Doe", "role": "admin"}' # Response: { "success": true, "meta": {...} } # Delete row curl -X DELETE http://localhost:8788/api/d1/DB/tables/users/rows/123 # Response: { "success": true } ``` -------------------------------- ### Discover Bindings Source: https://context7.com/rohanprasadofficial/localflare/llms.txt Utilities for extracting and summarizing various Cloudflare Worker bindings (D1, KV, R2, Durable Objects, Queues, Vars) from parsed configuration. ```APIDOC ## Discover Bindings Extract all bindings from parsed configuration ```typescript import { parseWranglerConfig, discoverBindings, getBindingSummary } from 'localflare-core' const config = parseWranglerConfig('./wrangler.toml') const bindings = discoverBindings(config) console.log(bindings) // { // d1: [{ binding: 'DB', database_name: 'my-db', database_id: 'local-db' }], // kv: [{ binding: 'CACHE', id: 'cache-ns' }], // r2: [{ binding: 'STORAGE', bucket_name: 'my-bucket' }], // durableObjects: [{ name: 'COUNTER', class_name: 'Counter' }], // queues: { // producers: [{ binding: 'TASKS', queue: 'task-queue' }], // consumers: [{ queue: 'task-queue', max_batch_size: 10 }] // }, // vars: { ENVIRONMENT: 'development' } // } const summary = getBindingSummary(bindings) summary.forEach(line => console.log(line)) // D1 Databases: DB // KV Namespaces: CACHE // R2 Buckets: STORAGE ``` ### Functions - **`discoverBindings(config: WorkerConfig): AllBindings`** - **Description**: Analyzes the provided `WorkerConfig` to identify and categorize all available bindings. - **Parameters**: - `config` (`WorkerConfig`) - The parsed worker configuration object. - **Returns**: An object containing categorized bindings (d1, kv, r2, durableObjects, queues, vars). - **`getBindingSummary(bindings: AllBindings): string[]`** - **Description**: Generates a human-readable summary of the discovered bindings. - **Parameters**: - `bindings` (`AllBindings`) - The output from `discoverBindings`. - **Returns**: An array of strings, where each string represents a line in the binding summary. ### Types - **`AllBindings`**: An object containing different types of bindings. - `d1`: Array of D1 database binding information. - `kv`: Array of KV namespace binding information. - `r2`: Array of R2 bucket binding information. - `durableObjects`: Array of Durable Object binding information. - `queues`: Object containing queue producer and consumer binding information. - `vars`: Object containing environment variables. ``` -------------------------------- ### Core Library - LocalFlare Class Source: https://context7.com/rohanprasadofficial/localflare/llms.txt Documentation for the `LocalFlare` class, used to initialize and control a Miniflare instance with Cloudflare Worker bindings programmatically. ```APIDOC ## Core Library - LocalFlare Class Initialize and control a Miniflare instance with Cloudflare Worker bindings ```typescript import { LocalFlare } from 'localflare-core' // Create instance with options const localflare = new LocalFlare({ configPath: './wrangler.toml', port: 8787, dashboardPort: 8788, persistPath: '.localflare', verbose: true, onWorkerLog: (entry) => { console.log(`[${entry.level}] ${entry.message}`) } }) // Start the Worker await localflare.start() // Check if running if (localflare.isRunning()) { console.log('Worker is running') } // Stop the Worker await localflare.stop() ``` ### Class: `LocalFlare` #### Constructor `new LocalFlare(options?: LocalFlareOptions)` #### Options - **configPath** (`string`, optional) - Path to the wrangler configuration file. - **port** (`number`, optional) - The port for the Worker server. Defaults to 8787. - **dashboardPort** (`number`, optional) - The port for the dashboard server. Defaults to 8788. - **persistPath** (`string`, optional) - Directory for persistence data. Defaults to '.localflare'. - **verbose** (`boolean`, optional) - Enable verbose logging. Defaults to false. - **onWorkerLog** (`(entry: LogEntry) => void`, optional) - Callback function for worker logs. ### Methods - **`start(): Promise`**: Starts the Worker and dashboard server. - **`stop(): Promise`**: Stops the Worker and dashboard server. - **`isRunning(): boolean`**: Returns true if the Worker is running, false otherwise. - **`getD1Database(bindingName: string): Promise`**: Retrieves a D1 database instance by its binding name. ### Types - **`LocalFlareOptions`**: Interface for constructor options. - **`LogEntry`**: Object representing a log entry with `level` and `message` properties. - **`D1Database`**: Miniflare's D1Database interface. ``` -------------------------------- ### Queues API Source: https://github.com/rohanprasadofficial/localflare/blob/main/packages/server/README.md Endpoints for interacting with Queues, including listing queues and sending messages. ```APIDOC ## GET /api/queues ### Description Lists all available Queues. ### Method GET ### Endpoint /api/queues ### Parameters #### Query Parameters #### Request Body ### Response #### Success Response (200) - **queues** (array) - A list of queue names. #### Response Example ```json { "queues": [ "my-queue-1", "my-queue-2" ] } ``` ## POST /api/queues/:name/send ### Description Sends a message to a specified queue. ### Method POST ### Endpoint /api/queues/:name/send #### Path Parameters - **name** (string) - Required - The name of the queue. ### Parameters #### Query Parameters #### Request Body - **message** (object) - Required - The message payload to send. - **options** (object) - Optional - Additional options for sending the message (e.g., `}=`delay`, `}=`retries`). ### Request Example ```json { "message": { "user_id": 123, "action": "process_order" }, "options": { "delay": 60 } } ``` ### Response #### Success Response (200) - **success** (boolean) - Indicates if the message was sent successfully. #### Response Example ```json { "success": true } ``` ``` -------------------------------- ### KV Endpoints Source: https://context7.com/rohanprasadofficial/localflare/llms.txt REST API for managing KV namespaces. ```APIDOC ## Dashboard Server API - KV Endpoints REST API for managing KV namespaces. ### Method `GET` ### Endpoint `/api/kv` ### Description List all KV namespaces. ### Method `GET` ### Endpoint `/api/kv/{namespace}/keys` ### Description List keys in a KV namespace with optional prefix and limit. ### Parameters #### Path Parameters - **namespace** (string) - Required - The name of the KV namespace. #### Query Parameters - **prefix** (string) - Optional - Filter keys by a prefix. - **limit** (number) - Optional - The maximum number of keys to return. ### Method `GET` ### Endpoint `/api/kv/{namespace}/keys/{key}` ### Description Get the value associated with a key in a KV namespace. ``` -------------------------------- ### R2 Bucket API Source: https://context7.com/rohanprasadofficial/localflare/llms.txt APIs for uploading, downloading, and managing objects in R2 buckets. ```APIDOC ## Access R2 Bucket Upload, download, and manage objects in R2 buckets. ### Method `GET` ### Endpoint `/rohanprasadofficial/localflare/getR2Bucket` ### Description Get an R2 bucket binding. ### Method `PUT` ### Endpoint `/rohanprasadofficial/localflare/r2Bucket/put` ### Description Upload an object to the R2 bucket. ### Parameters #### Request Body - **key** (string) - Required - The key for the object. - **body** (Buffer/ReadableStream) - Required - The content of the object. - **options** (object) - Optional - Options for uploading the object, such as `httpMetadata` and `customMetadata`. ### Method `GET` ### Endpoint `/rohanprasadofficial/localflare/r2Bucket/get` ### Description Get an object from the R2 bucket. ### Parameters #### Query Parameters - **key** (string) - Required - The key of the object to retrieve. ### Method `GET` ### Endpoint `/rohanprasadofficial/localflare/r2Bucket/list` ### Description List objects in the R2 bucket with a specified prefix and limit. ### Parameters #### Query Parameters - **prefix** (string) - Optional - Filter objects by a prefix. - **limit** (number) - Optional - The maximum number of objects to return. ### Method `DELETE` ### Endpoint `/rohanprasadofficial/localflare/r2Bucket/delete` ### Description Delete an object from the R2 bucket. ``` -------------------------------- ### Manage Queues Source: https://context7.com/rohanprasadofficial/localflare/llms.txt Endpoints for managing message queues, including listing producers and consumers, sending single messages with optional delays, and sending batches of messages. ```bash # List all queues (producers and consumers) curl http://localhost:8788/api/queues # Response: { # "producers": [{ "binding": "TASKS", "queue": "task-queue" }], # "consumers": [{ "queue": "task-queue", "max_batch_size": 10, ... }] # } # Send message to queue curl -X POST http://localhost:8788/api/queues/TASKS/send \ -H "Content-Type: application/json" \ -d '{"message": {"type": "email", "to": "user@example.com"}, "options": {"delaySeconds": 60}}' # Response: { "success": true } # Send batch of messages curl -X POST http://localhost:8788/api/queues/TASKS/send-batch \ -H "Content-Type: application/json" \ -d '{"messages": [ {"body": {"task": "process-1"}}, {"body": {"task": "process-2"}, "delaySeconds": 30} ]}' # Response: { "success": true, "sent": 2 } ``` -------------------------------- ### KV Namespace API Source: https://context7.com/rohanprasadofficial/localflare/llms.txt APIs for reading and writing key-value pairs in KV namespaces. ```APIDOC ## Access KV Namespace Read and write key-value pairs in KV namespaces. ### Method `GET` ### Endpoint `/rohanprasadofficial/localflare/getKVNamespace` ### Description Get a KV namespace binding. ### Method `PUT` ### Endpoint `/rohanprasadofficial/localflare/kvNamespace/put` ### Description Put a value with options, including expiration and metadata. ### Parameters #### Request Body - **key** (string) - Required - The key for the value. - **value** (any) - Required - The value to store. - **options** (object) - Optional - Options for storing the value, such as `expirationTtl` and `metadata`. ### Method `GET` ### Endpoint `/rohanprasadofficial/localflare/kvNamespace/get` ### Description Get a value with metadata. ### Parameters #### Query Parameters - **key** (string) - Required - The key of the value to retrieve. - **options** (object) - Optional - Options for retrieving the value, such as `type`. ### Method `GET` ### Endpoint `/rohanprasadofficial/localflare/kvNamespace/list` ### Description List keys with a specified prefix and limit. ### Parameters #### Query Parameters - **prefix** (string) - Optional - Filter keys by a prefix. - **limit** (number) - Optional - The maximum number of keys to return. ### Method `DELETE` ### Endpoint `/rohanprasadofficial/localflare/kvNamespace/delete` ### Description Delete a key from the KV namespace. ``` -------------------------------- ### D1 Database API Source: https://github.com/rohanprasadofficial/localflare/blob/main/packages/server/README.md Endpoints for interacting with D1 databases, including listing databases, tables, and executing SQL queries. ```APIDOC ## GET /api/d1 ### Description Lists all available D1 databases. ### Method GET ### Endpoint /api/d1 ### Parameters #### Query Parameters #### Request Body ### Response #### Success Response (200) - **databases** (array) - A list of D1 database names. #### Response Example ```json { "databases": [ "my-db-1", "my-db-2" ] } ``` ## GET /api/d1/:name/tables ### Description Lists all tables within a specified D1 database. ### Method GET ### Endpoint /api/d1/:name/tables #### Path Parameters - **name** (string) - Required - The name of the D1 database. ### Parameters #### Query Parameters #### Request Body ### Response #### Success Response (200) - **tables** (array) - A list of table names in the database. #### Response Example ```json { "tables": [ "users", "products" ] } ``` ## POST /api/d1/:name/query ### Description Executes a given SQL query against a specified D1 database. ### Method POST ### Endpoint /api/d1/:name/query #### Path Parameters - **name** (string) - Required - The name of the D1 database. ### Parameters #### Query Parameters #### Request Body - **sql** (string) - Required - The SQL query to execute. ### Request Example ```json { "sql": "SELECT * FROM users" } ``` ### Response #### Success Response (200) - **results** (array) - The results of the SQL query. #### Response Example ```json { "results": [ { "id": 1, "name": "John Doe" } ] } ``` ```