### Get Zone Email Routing Status (TypeScript) Source: https://context7.com/leocolomb/dispoflare/llms.txt This TypeScript function checks if email routing is enabled for a given Cloudflare zone and retrieves its routing configuration details. It requires a Zone object and the environment configuration to interact with the Cloudflare API. ```typescript // sdk/routing.ts import { fetchAPI } from './global' export async function get(zone: Zone, env: Env): Promise { return fetchAPI(`zones/${zone.id}/email/routing`, 'GET', env) } // Usage: Check routing status for a zone const zone = { id: "abc123", name: "example.com" } const routing = await routing.get(zone, env) // Returns: { // enabled: true, // name: "example.com", // status: "ready", // tag: "routing-tag-xyz" // } ``` -------------------------------- ### Get Zone Email Routing Status API Source: https://context7.com/leocolomb/dispoflare/llms.txt Checks if email routing is enabled for a specific zone and returns routing configuration details. ```APIDOC ## Get Zone Email Routing Status ### Description Checks if email routing is enabled for a specific zone and returns routing configuration details. ### Method `GET` ### Endpoint `/zones/{zone.id}/email/routing` ### Parameters #### Path Parameters - **zone.id** (string) - Required - The ID of the zone to check. #### Query Parameters None #### Request Body None ### Request Example ```typescript // sdk/routing.ts import { fetchAPI } from './global' export async function get(zone: Zone, env: Env): Promise { return fetchAPI(`zones/${zone.id}/email/routing`, 'GET', env) } // Usage: Check routing status for a zone const zone = { id: "abc123", name: "example.com" } const routing = await routing.get(zone, env) // Returns: { // enabled: true, // name: "example.com", // status: "ready", // tag: "routing-tag-xyz" // } ``` ### Response #### Success Response (200) - **Routing** (object) - An object containing routing configuration details. - **enabled** (boolean) - Indicates if email routing is enabled. - **name** (string) - The name of the zone. - **status** (string) - The status of the email routing configuration. - **tag** (string) - The tag associated with the routing configuration. #### Response Example ```json { "enabled": true, "name": "example.com", "status": "ready", "tag": "routing-tag-xyz" } ``` ``` -------------------------------- ### Create Disposable Address Route Handler (TypeScript) Source: https://context7.com/leocolomb/dispoflare/llms.txt This TypeScript code defines the action and loader for the index route, which is responsible for creating new disposable email addresses. The `action` handles form submissions to create a rule, and the `loader` fetches necessary data like routing zones and addresses. It depends on functions like `createRule`, `getRoutingZones`, `getZones`, `getAddresses`, and `getSetting`. ```typescript // app/routes/_index.tsx export async function action({ request, context }: Route.ActionArgs) { const formData = await request.formData() const rule = formData.get('rule') // Local part: "temp-shopping" const zone = JSON.parse(formData.get('zone')) // { id: "...", name: "example.com" } const address = formData.get('address') // Forward to: "me@gmail.com" const expire = formData.get('expire') // Expiration date: "2024-06-15" const remove = !!formData.get('remove') // Auto-delete: true/false await createRule({ rule, zone, address, expire, remove }, context) return redirect('/manage') } export async function loader({ context }: Route.LoaderArgs) { return { routingZones: getRoutingZones(getZones(context), context), addresses: getAddresses(context), randomSize: getSetting('random-size', context), } } // POST / - Create new disposable address // Form data: // rule: "shopping-temp" // zone: {"id":"abc","name":"example.com"} // address: "me@gmail.com" // expire: "2024-06-15" // remove: "on" // Result: Creates shopping-temp@example.com -> me@gmail.com ``` -------------------------------- ### Create Email Routing Rule (TypeScript) Source: https://context7.com/leocolomb/dispoflare/llms.txt Creates a new disposable email address rule with forwarding configuration and lifecycle dates. It takes a rule object, zone information, and environment configuration as input. ```typescript // sdk/rules.ts export async function post(rule: any, zone: Zone, env: Env): Promise { return fetchAPI( `zones/${zone.id}/email/routing/rules`, 'POST', env, JSON.stringify(rule), ) } // Usage: Create a new disposable email address const zone = { id: "zone-abc", name: "example.com" } const expireDate = "2024-06-15" const removeDate = new Date(expireDate) removeDate.setMonth(removeDate.getMonth() + 1) const newRule = await rules.post({ actions: [{ type: 'forward', value: ['me@gmail.com'], }], enabled: true, matchers: [{ field: 'to', type: 'literal', value: 'shopping-temp-123@example.com', }], name: JSON.stringify({ dispoflare: true, activate: new Date(), expire: expireDate, remove: removeDate, }), }, zone, env) // Creates: shopping-temp-123@example.com -> forwards to me@gmail.com // Auto-expires: 2024-06-15, Auto-removes: 2024-07-15 ``` -------------------------------- ### List Email Routing Rules (TypeScript) Source: https://context7.com/leocolomb/dispoflare/llms.txt Fetches all Dispoflare-managed email routing rules across all zones. Rules are identified by JSON metadata in the rule name field. It requires a list of zones and environment configuration. ```typescript // sdk/rules.ts import { fetchAPI } from './global' export async function list(zones: Zone[], env: Env): Promise> { const results = await Promise.all( zones.map(async (zone: Zone) => { const api: Array = await fetchAPI( `zones/${zone.id}/email/routing/rules`, 'GET', env, ) // Filter to only Dispoflare-managed rules (identified by JSON name field) return api.map((rule: Rule) => { try { const data: DispoflareData = JSON.parse(rule.name) if (data.dispoflare) { return { ...rule, zone, data } } } catch { return undefined } }).filter((e) => e?.data?.dispoflare) }), ) return results.flat() } // Usage: Get all disposable email rules const zones = await zonesApi.list(env) const rules = await rulesApi.list(zones, env) // Returns: [{ // tag: "rule-abc123", // enabled: true, // matchers: [{ field: "to", type: "literal", value: "temp123@example.com" }], // actions: [{ type: "forward", value: ["me@gmail.com"] }], // zone: { id: "zone-id", name: "example.com" }, // data: { // dispoflare: true, // activate: "2024-01-15T00:00:00.000Z", // expire: "2024-02-15", // remove: "2024-03-15T00:00:00.000Z" // } // }] ``` -------------------------------- ### Fetch API Wrapper for Cloudflare SDK (TypeScript) Source: https://context7.com/leocolomb/dispoflare/llms.txt This TypeScript function serves as a generic API wrapper for interacting with the Cloudflare API. It handles authentication using a Bearer token and validates the success of API responses, throwing an error if the operation fails. It's designed to be used across various SDK operations. ```typescript // sdk/global.ts - Core API fetch function import { fetchAPI } from './global' // Generic API wrapper that handles Cloudflare API authentication // Automatically includes Bearer token and validates response success async function fetchAPI( path: string, method: string = 'GET', env: Env, body: string | undefined = undefined, ): Promise { const response = await fetch(`https://api.cloudflare.com/client/v4/${path}`, { method, headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${env.CLOUDFLARE_API_TOKEN}`, }, body, }) const api = await response.json() if (api.success !== true) { throw new Error(JSON.stringify(api.errors)) } return api.result } // Example: Fetching zones from Cloudflare API const zones: Zone[] = await fetchAPI('zones', 'GET', env) // Returns: [{ id: "zone-id-123", name: "example.com" }, ...] ``` -------------------------------- ### Manage Existing Addresses Route Handler (TypeScript) Source: https://context7.com/leocolomb/dispoflare/llms.txt This TypeScript code defines the loader for the '/manage' route, which displays all Dispoflare-managed rules. It fetches the rules and their current status (Active, Deprecated, Expired) along with their lifecycle milestones. It depends on `getRules` and `getZones` functions. ```typescript // app/routes/manage.tsx export async function loader({ context }: Route.LoaderArgs) { return { rules: getRules(getZones(context), context), } } // GET /manage - Returns all managed rules with status: // - Active (enabled, forwarding directly) // - Deprecated (enabled, routed through worker with warning headers) // - Expired (disabled, no longer receiving mail) // Each rule shows milestones: Activate, Expire, Deprecate, Remove dates ``` -------------------------------- ### Core API Fetch Wrapper Source: https://context7.com/leocolomb/dispoflare/llms.txt The core API wrapper handles all communication with Cloudflare's API, providing authentication and error handling for all SDK operations. It automatically includes the Bearer token and validates response success. ```APIDOC ## Core API Fetch Wrapper ### Description This function serves as a generic API wrapper that handles Cloudflare API authentication. It automatically includes the Bearer token and validates response success. ### Method `POST`, `GET`, `PUT`, `DELETE`, etc. (dynamically determined by the `method` parameter) ### Endpoint `https://api.cloudflare.com/client/v4/[path]` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **body** (string | undefined) - Optional - The request body to send with the API call. ### Request Example ```typescript // sdk/global.ts - Core API fetch function import { fetchAPI } from './global' // Generic API wrapper that handles Cloudflare API authentication // Automatically includes Bearer token and validates response success async function fetchAPI( path: string, method: string = 'GET', env: Env, body: string | undefined = undefined, ): Promise { const response = await fetch(`https://api.cloudflare.com/client/v4/${path}`, { method, headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${env.CLOUDFLARE_API_TOKEN}`, }, body, }) const api = await response.json() if (api.success !== true) { throw new Error(JSON.stringify(api.errors)) } return api.result } // Example: Fetching zones from Cloudflare API const zones: Zone[] = await fetchAPI('zones', 'GET', env) // Returns: [{ id: "zone-id-123", name: "example.com" }, ...] ``` ### Response #### Success Response (200) - **result** (any) - The result of the API call. #### Response Example ```json { "success": true, "errors": [], "messages": [], "result": [ { "id": "zone-id-123", "name": "example.com" } ] } ``` ``` -------------------------------- ### Configure Application Settings with Cloudflare KV Source: https://context7.com/leocolomb/dispoflare/llms.txt Manages application-wide settings like random address generation size and deletion delays stored in Cloudflare KV. It includes loader and action functions for retrieving and updating settings. Dependencies include Cloudflare KV and context objects. ```typescript // app/routes/settings.tsx const defaultSettings: Settings = [ { key: 'random-size', name: 'Random address generator size (1-4)', value: 1, min: 1, max: 4 }, { key: 'deletion-delay', name: 'Deletion delay (days)', value: 7, min: 0, max: 60 }, ] export async function loader({ context }: Route.ActionArgs) { const settings: any = {} for (const setting of defaultSettings) { settings[setting.key] = getSetting(setting.key, context) } return settings } export async function action({ request, context }: Route.LoaderArgs) { const formData = await request.formData() return putSetting( formData.get('setting-key'), formData.get('setting-value'), context, ) } // GET /settings - Load current settings from KV // POST /settings - Update a setting // Form data: setting-key=random-size, setting-value=2 ``` -------------------------------- ### List DNS Zones using Cloudflare API (TypeScript) Source: https://context7.com/leocolomb/dispoflare/llms.txt This TypeScript function retrieves all DNS zones configured within a Cloudflare account. It utilizes the generic fetchAPI wrapper to make the request to the Cloudflare API. The returned data can be used to configure email routing for specific domains. ```typescript // sdk/zones.ts import { fetchAPI } from './global' export async function list(env: Env): Promise> { return fetchAPI('zones', 'GET', env) } // Usage in application import * as zones from 'sdk/zones.js' const allZones = await zones.list(env) // Returns: [ // { id: "abc123", name: "example.com" }, // { id: "def456", name: "mydomain.org" } // ] ``` -------------------------------- ### HTTP Fetch Handler for Web UI (TypeScript) Source: https://context7.com/leocolomb/dispoflare/llms.txt This TypeScript function handles all incoming HTTP requests for the Dispoflare application. It uses React Router to serve the web UI, allowing users to manage disposable email addresses. It depends on `react-router` and `virtual:react-router/server-build`. ```typescript // workers/fetch.ts import { createRequestHandler } from 'react-router' const requestHandler = createRequestHandler( () => import('virtual:react-router/server-build'), import.meta.env.MODE, ) export const fetch = async ( request: Request, env: Env, context: ExecutionContext, ): Promise => { try { return requestHandler(request, { cloudflare: { env, context }, }) } catch (err: any) { return new Response(err.message, { status: 500 }) } } ``` -------------------------------- ### List Verified Email Addresses for Routing (TypeScript) Source: https://context7.com/leocolomb/dispoflare/llms.txt This TypeScript function retrieves a list of all verified email addresses within a Cloudflare account that are configured to receive forwarded mail. It uses the fetchAPI wrapper to query the Cloudflare API for email routing addresses. ```typescript // sdk/addresses.ts import { fetchAPI } from './global' export async function list(env: Env): Promise> { return fetchAPI( `accounts/${env.CLOUDFLARE_ACCOUNT_ID}/email/routing/addresses`, 'GET', env, ) } // Usage: Get all verified forwarding addresses const addresses = await addresses.list(env) // Returns: [ // { email: "me@gmail.com", tag: "addr-tag-123" }, // { email: "work@company.com", tag: "addr-tag-456" } // ] ``` -------------------------------- ### Define Environment Configuration for Cloudflare Workers Source: https://context7.com/leocolomb/dispoflare/llms.txt Defines the environment variables and Cloudflare worker configuration required for the Dispoflare application. This includes Cloudflare API credentials, optional Sentry DSN, and wrangler.jsonc settings for deployment and cron triggers. ```typescript // bindings.d.ts interface Env { KV_SETTINGS: KVNamespace // Cloudflare KV for app settings CLOUDFLARE_API_TOKEN: string // API token with email routing permissions CLOUDFLARE_ACCOUNT_ID: string // Cloudflare account ID SENTRY_DSN: string // Optional: Sentry error tracking } // wrangler.jsonc configuration { "name": "dispoflare", "compatibility_date": "2025-09-01", "main": "./workers/index.ts", "triggers": { "crons": ["0 */12 * * *"] // Run lifecycle check every 12 hours }, "workers_dev": true } // Required API Token Permissions: // - Email Routing Address: Read // - Email Routing Rule: Edit // - Zone: Read // - Zone Settings: Read ``` -------------------------------- ### Application Settings API Source: https://context7.com/leocolomb/dispoflare/llms.txt Configures application-wide settings stored in Cloudflare KV, including random address generation size and deletion delays. Supports loading current settings and updating individual settings. ```APIDOC ## GET /settings ### Description Retrieves the current application settings from Cloudflare KV. ### Method GET ### Endpoint /settings ### Parameters None ### Request Example None ### Response #### Success Response (200) - **random-size** (integer) - The size for the random address generator. - **deletion-delay** (integer) - The delay in days before an address is deleted. #### Response Example ```json { "random-size": 1, "deletion-delay": 7 } ``` ## POST /settings ### Description Updates a specific application setting in Cloudflare KV. ### Method POST ### Endpoint /settings ### Parameters #### Request Body - **setting-key** (string) - Required - The key of the setting to update (e.g., 'random-size', 'deletion-delay'). - **setting-value** (string) - Required - The new value for the setting. ### Request Example ```json { "setting-key": "random-size", "setting-value": "2" } ``` ### Response #### Success Response (200) Indicates that the setting was updated successfully. The response body may contain the updated setting value or a success message. #### Response Example ```json { "message": "Setting updated successfully", "setting": { "key": "random-size", "value": "2" } } ``` ``` -------------------------------- ### Scheduled Event Handler for Rule Lifecycle Management (TypeScript) Source: https://context7.com/leocolomb/dispoflare/llms.txt This TypeScript function runs on a schedule (every 12 hours) to manage the lifecycle of rules. It handles expiring active rules, removing old rules, and deprecating rules before their expiration date. It depends on `zonesApi` and `rulesApi` for interacting with rule and zone data. ```typescript // workers/scheduled.ts function shouldAct(date: Date | string | undefined): Boolean { return Boolean(date && new Date(date) <= new Date()) } export const scheduled = async ( event: ScheduledEvent, env: Env, ctx: ExecutionContext, ): Promise => { const zones = await zonesApi.list(env) const rules = await rulesApi.list(zones, env) await Promise.all( rules.map(async (rule) => { // Disable rules that have expired if (rule.enabled && shouldAct(rule.data?.expire)) { rule.enabled = false await rulesApi.put(rule, env) } // Remove rules after removal date else if (shouldAct(rule.data?.remove)) { await rulesApi.remove(rule, env) } // Deprecate rules (route through worker for warnings) else if (shouldAct(rule.data?.deprecate)) { rule.data.forwardTo = rule.actions[0].value rule.actions = [{ type: 'worker', value: ['dispoflare'] }] await rulesApi.put(rule, env) } }), ) } // Configured via wrangler.jsonc: // "triggers": { "crons": ["0 */12 * * *"] } ``` -------------------------------- ### Email Event Handler for Deprecated Rules (TypeScript) Source: https://context7.com/leocolomb/dispoflare/llms.txt This TypeScript function processes incoming emails for rules marked as deprecated. It adds a deprecation warning header and forwards the email to the original destination. It relies on a `listRules` function to retrieve the rules and `message.forward` to send the email. ```typescript // workers/email.ts export const email = async ( message: EmailMessage, env: Env, ctx: ExecutionContext, ): Promise => { const rules: Rule[] = await listRules(env) const matchingRule: Rule | undefined = rules.find( (rule) => rule.matchers[0].value === message.to, ) if (matchingRule) { // Add deprecation warning header const headers = new Headers([ ['X-Dispoflare-Deprecated', `expire=${matchingRule.data.expire}`], ]) // Forward to original destination with warning header message.forward(matchingRule.data.forwardTo, headers) } } // Email arrives at deprecated address -> Worker adds X-Dispoflare-Deprecated header // -> Email forwarded to original destination with warning ``` -------------------------------- ### List Zones API Source: https://context7.com/leocolomb/dispoflare/llms.txt Retrieves all DNS zones configured in the Cloudflare account that can be used for email routing. ```APIDOC ## List Zones ### Description Retrieves all DNS zones configured in the Cloudflare account that can be used for email routing. ### Method `GET` ### Endpoint `/zones` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript // sdk/zones.ts import { fetchAPI } from './global' export async function list(env: Env): Promise> { return fetchAPI('zones', 'GET', env) } // Usage in application import * as zones from 'sdk/zones.js' const allZones = await zones.list(env) // Returns: [ // { id: "abc123", name: "example.com" }, // { id: "def456", name: "mydomain.org" } // ] ``` ### Response #### Success Response (200) - **Zone** (object) - An array of Zone objects, each containing `id` and `name`. #### Response Example ```json [ { "id": "abc123", "name": "example.com" }, { "id": "def456", "name": "mydomain.org" } ] ``` ``` -------------------------------- ### List Verified Email Addresses API Source: https://context7.com/leocolomb/dispoflare/llms.txt Retrieves all verified destination email addresses that can receive forwarded mail. ```APIDOC ## List Verified Email Addresses ### Description Retrieves all verified destination email addresses that can receive forwarded mail. ### Method `GET` ### Endpoint `/accounts/{env.CLOUDFLARE_ACCOUNT_ID}/email/routing/addresses` ### Parameters #### Path Parameters - **env.CLOUDFLARE_ACCOUNT_ID** (string) - Required - The Cloudflare Account ID. #### Query Parameters None #### Request Body None ### Request Example ```typescript // sdk/addresses.ts import { fetchAPI } from './global' export async function list(env: Env): Promise> { return fetchAPI( `accounts/${env.CLOUDFLARE_ACCOUNT_ID}/email/routing/addresses`, 'GET', env, ) } // Usage: Get all verified forwarding addresses const addresses = await addresses.list(env) // Returns: [ // { email: "me@gmail.com", tag: "addr-tag-123" }, // { email: "work@company.com", tag: "addr-tag-456" } // ] ``` ### Response #### Success Response (200) - **Address** (object) - An array of Address objects, each containing `email` and `tag`. #### Response Example ```json [ { "email": "me@gmail.com", "tag": "addr-tag-123" }, { "email": "work@company.com", "tag": "addr-tag-456" } ] ``` ``` -------------------------------- ### Update Email Routing Rule (TypeScript) Source: https://context7.com/leocolomb/dispoflare/llms.txt Updates an existing email routing rule. This is commonly used to disable expired rules or modify forwarding behavior. It requires the rule object and environment configuration. ```typescript // sdk/rules.ts export async function put(rule: Rule, env: Env): Promise { return fetchAPI( `zones/${rule.zone.id}/email/routing/rules/${rule.tag}`, 'PUT', env, JSON.stringify(rule), ) } // Usage: Disable an expired rule const rule = await rules.get(ruleData, zone, env) rule.enabled = false const updatedRule = await rules.put(rule, env) // Usage: Convert rule to deprecation mode (routes through worker) rule.data.forwardTo = rule.actions[0].value rule.actions = [{ type: 'worker', value: ['dispoflare'], // Routes to Email Worker for header injection }] await rules.put(rule, env) ``` -------------------------------- ### Delete Email Routing Rule (TypeScript) Source: https://context7.com/leocolomb/dispoflare/llms.txt Permanently removes an email routing rule from Cloudflare. It requires the rule object (specifically its tag and zone) and environment configuration. ```typescript // sdk/rules.ts export async function remove({ tag, zone }: Rule, env: Env): Promise { await fetchAPI(`zones/${zone.id}/email/routing/rules/${tag}`, 'DELETE', env) } // Usage: Delete a rule after removal date const rule = rules[0] await rules.remove(rule, env) // Rule is permanently deleted from Cloudflare ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.