### Start Local Development Server Source: https://github.com/cloudflare/workflows-starter/blob/main/_autodocs/INDEX.md Starts the local development server for the workflows-starter project. ```bash npm run start ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/cloudflare/workflows-starter/blob/main/_autodocs/INDEX.md Installs the necessary dependencies for the workflows-starter project using npm. ```bash cd workflows-starter npm install ``` -------------------------------- ### Complete Wrangler Configuration Example Source: https://github.com/cloudflare/workflows-starter/blob/main/_autodocs/configuration.md A comprehensive example of a wrangler.jsonc file, including application name, main entry point, compatibility date, observability settings, and workflow definitions. ```json { "name": "workflows-starter", "main": "src/index.ts", "compatibility_date": "2024-10-22", "observability": { "enabled": true, "head_sampling_rate": 1 }, "workflows": [ { "name": "workflows-starter", "binding": "MY_WORKFLOW", "class_name": "MyWorkflow" } ] } ``` -------------------------------- ### Example GET Request to Query Workflow Instance Status Source: https://github.com/cloudflare/workflows-starter/blob/main/_autodocs/endpoints.md Shows an example of a GET request to query the status of a workflow instance using its ID as a query parameter. ```bash curl "https://workflows-starter.example.com/?instanceId=550e8400-e29b-41d4-a716-446655440000" ``` -------------------------------- ### MyWorkflow Usage Example (src/index.ts) Source: https://github.com/cloudflare/workflows-starter/blob/main/_autodocs/api-reference/exports.md Example of how to import and instantiate the MyWorkflow class. Configuration for the workflow binding should be set in wrangler.jsonc. ```typescript import { MyWorkflow } from './src/index'; // Configure in wrangler.jsonc type Env = { MY_WORKFLOW: Workflow; }; // In fetch handler const instance = await env.MY_WORKFLOW.create({ params: { email: 'user@example.com', metadata: { orderId: '123' } } }); ``` -------------------------------- ### Example: Basic step execution Source: https://github.com/cloudflare/workflows-starter/blob/main/_autodocs/api-reference/workflow-step.md This example demonstrates a simple `step.do` call to fetch data from an API. The step is named 'fetch-files' and the asynchronous function returns JSON data. ```typescript const files = await step.do('fetch-files', async () => { const resp = await fetch('https://api.example.com/files'); return await resp.json(); }); ``` -------------------------------- ### Complete Fetch Handler Example Source: https://github.com/cloudflare/workflows-starter/blob/main/_autodocs/api-reference/fetch-handler.md A comprehensive example of a fetch handler that includes logic for ignoring favicon requests, querying workflow status, and creating new workflow instances. ```typescript import { WorkflowEntrypoint, WorkflowStep, WorkflowEvent } from 'cloudflare:workers'; type Env = { MY_WORKFLOW: Workflow; }; type Params = { email: string; metadata: Record; }; export class MyWorkflow extends WorkflowEntrypoint { async run(event: WorkflowEvent, step: WorkflowStep) { // Workflow implementation } } export default { async fetch(req: Request, env: Env): Promise { const url = new URL(req.url); // Ignore favicon requests if (url.pathname.startsWith('/favicon')) { return Response.json({}, { status: 404 }); } // Query status of existing instance const instanceId = url.searchParams.get('instanceId'); if (instanceId) { const instance = await env.MY_WORKFLOW.get(instanceId); return Response.json({ status: await instance.status(), }); } // Create new instance const instance = await env.MY_WORKFLOW.create({ params: { email: 'user@example.com', metadata: { source: 'web' }, }, }); return Response.json({ id: instance.id, details: await instance.status(), }); }, }; ``` -------------------------------- ### Example: Step with retry and timeout Source: https://github.com/cloudflare/workflows-starter/blob/main/_autodocs/api-reference/workflow-step.md This example shows how to configure a step with specific retry limits, delays, backoff strategy, and a timeout. The `write-to-storage` step will retry up to 5 times with exponential backoff if the API call fails. ```typescript await step.do( 'write-to-storage', { retries: { limit: 5, delay: '5 second', backoff: 'exponential', }, timeout: '15 minutes', }, async () => { const resp = await fetch('https://api.example.com/write', { method: 'POST', body: JSON.stringify({ data: 'value' }), }); if (!resp.ok) throw new Error('API error'); return await resp.json(); } ); ``` -------------------------------- ### MyWorkflow (Alternative) Class Source: https://github.com/cloudflare/workflows-starter/blob/main/_autodocs/api-reference/exports.md A minimal example workflow with basic step chaining, provided as an educational example. It extends WorkflowEntrypoint. ```APIDOC ## MyWorkflow (Alternative) Class ### Description Minimal example workflow with basic step chaining, separate from the main implementation in index.ts. ### Class Signature ```typescript export class MyWorkflow extends WorkflowEntrypoint ``` ### Type Parameters - **Env**: `{}` - **Params**: `{}` ### Public Methods #### run - **Signature**: `async run(event: WorkflowEvent, step: WorkflowStep): void` - **Returns**: `Promise` ### Note This file is provided as an educational example and is not imported by the main application. ``` -------------------------------- ### Workflow Configuration Example Source: https://github.com/cloudflare/workflows-starter/blob/main/_autodocs/INDEX.md Configure your workflows, including their binding and class name, within the wrangler.jsonc file. ```jsonc { "workflows": [ { "name": "my-workflow", "binding": "MY_WORKFLOW", "class_name": "MyWorkflow" } ] } ``` -------------------------------- ### Basic Workflow run() Method Example Source: https://github.com/cloudflare/workflows-starter/blob/main/_autodocs/api-reference/workflow-entrypoint.md Illustrates a simple implementation of the `run` method, showing how to define two sequential steps using the `step.do` function. ```typescript export class MyWorkflow extends WorkflowEntrypoint { async run(event: WorkflowEvent, step: WorkflowStep) { console.info(`starting workflow: ${event.instanceId}`); const result = await step.do('my first step', async () => { return [1, 2, 3]; }); await step.do('my second step', async () => { console.log('Received:', result); }); } } ``` -------------------------------- ### Full Workflow Definition Example Source: https://github.com/cloudflare/workflows-starter/blob/main/_autodocs/api-reference/workflow-entrypoint.md A comprehensive example of defining a workflow, including importing necessary types, defining environment and parameter types, and implementing the `run` method with various step functionalities like fetching data, waiting for events, sleeping, and retrying operations. ```typescript import { WorkflowEntrypoint, WorkflowStep, WorkflowEvent } from 'cloudflare:workers'; type Env = { MY_WORKFLOW: Workflow; MY_KV: KVNamespace; }; type Params = { email: string; metadata: Record; }; export class MyWorkflow extends WorkflowEntrypoint { await step.do('fetch-files', async () => { const response = await fetch('https://api.example.com/files'); return await response.json(); }); // Wait for external input const approval = await step.waitForEvent('approval', { type: 'approval', timeout: '1 hour', }); // Sleep for a duration await step.sleep('wait-before-continue', '5 minutes'); // Step with retry strategy await step.do( 'write-data', { retries: { limit: 3, delay: '10 seconds', backoff: 'exponential', }, }, async () => { await fetch('https://api.example.com/write', { method: 'POST' }); } ); } } ``` -------------------------------- ### Example: Sleeping for a duration Source: https://github.com/cloudflare/workflows-starter/blob/main/_autodocs/api-reference/workflow-step.md This example shows how to pause the workflow for 1 minute using `step.sleep`. The step is named 'wait-before-continue'. ```typescript await step.sleep('wait-before-continue', '1 minute'); ``` -------------------------------- ### Development Server Command Source: https://github.com/cloudflare/workflows-starter/blob/main/_autodocs/PROJECT_STRUCTURE.md Starts a local development server using Wrangler for testing your Worker before deployment. It runs on `http://localhost:8787`. ```bash npm run start Runs: `wrangler dev` Starts a local development server on `http://localhost:8787` for testing before deployment. ``` -------------------------------- ### Example POST Request to Create Workflow Instance Source: https://github.com/cloudflare/workflows-starter/blob/main/_autodocs/endpoints.md Demonstrates how to make a POST request to create a workflow instance with custom parameters and an ID. The request body is JSON, specifying user details and metadata. ```bash curl -X POST https://workflows-starter.example.com/ \ -H "Content-Type: application/json" \ -d '{ "id": "order-123", "params": { "email": "user@example.com", "metadata": { "orderId": "123" } } }' ``` -------------------------------- ### Create Workflow Instance Source: https://github.com/cloudflare/workflows-starter/blob/main/_autodocs/api-reference/fetch-handler.md Create a new workflow instance to start its execution, optionally providing a custom ID and parameters. ```APIDOC ## POST / ### Description Creates a new workflow instance to start its execution. ### Method POST ### Endpoint / ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **id** (string) - Optional - A custom ID for the workflow instance. Defaults to a generated UUID. - **params** (object) - Optional - Parameters to pass to the workflow's `run()` method. - **email** (string) - Parameter for the workflow. - **metadata** (object) - Additional metadata for the workflow. - **orderId** (string) - Example metadata field. ### Response #### Success Response (200) - **id** (string) - The ID of the newly created workflow instance. - **details** (object) - An object containing the initial status of the workflow instance. - **status** (string) - The initial status of the workflow ('queued', 'running', 'error', 'success', 'paused'). #### Response Example ```json { "id": "123e4567-e89b-12d3-a456-426614174000", "details": { "status": "queued" } } ``` ``` -------------------------------- ### Request Routing Example Source: https://github.com/cloudflare/workflows-starter/blob/main/_autodocs/api-reference/fetch-handler.md Demonstrates how to route incoming HTTP requests based on method and pathname to different handler functions. ```APIDOC ## Request Routing Logic ### Description This logic within the fetch handler inspects the incoming request's method and URL pathname to determine the appropriate action, such as creating a workflow or retrieving its status. ### Method Any ### Endpoint / ### Parameters None explicitly defined for routing logic itself, but relies on `req.method` and `url.pathname`. ### Example Logic ```typescript async fetch(req: Request, env: Env): Promise { const url = new URL(req.url); if (req.method === 'POST' && url.pathname === '/workflow/create') { // return handleCreateWorkflow(req, env); } if (req.method === 'GET' && url.pathname === '/workflow/status') { // return handleGetStatus(req, env); } return Response.json({ error: 'Not found' }, { status: 404 }); } ``` ``` -------------------------------- ### Create Workflow Instance with Parameters (TypeScript) Source: https://github.com/cloudflare/workflows-starter/blob/main/_autodocs/types.md Example of creating a workflow instance using the MY_WORKFLOW binding, passing user-defined parameters for email and metadata. ```typescript const instance = await env.MY_WORKFLOW.create({ params: { email: 'user@example.com', metadata: { orderId: '12345', source: 'mobile-app', priority: 'high', }, }); ``` -------------------------------- ### Example: Waiting for an approval event Source: https://github.com/cloudflare/workflows-starter/blob/main/_autodocs/api-reference/workflow-step.md This example demonstrates waiting for an event named 'request-approval' with a type discriminator 'approval' and a timeout of 1 hour. The workflow will resume when an event matching these criteria is received. ```typescript const approval = await step.waitForEvent('request-approval', { type: 'approval', timeout: '1 hour', }); ``` -------------------------------- ### Create Cloudflare Application with Workflows Template Source: https://github.com/cloudflare/workflows-starter/blob/main/README.md Use npm to create a new Cloudflare application using the workflows-starter template. This command clones the repository and installs dependencies. ```sh npm create cloudflare@latest workflows-starter -- --template "cloudflare/workflows-starter" ``` -------------------------------- ### Create Workflow Instance Source: https://github.com/cloudflare/workflows-starter/blob/main/_autodocs/api-reference/fetch-handler.md Creates a new workflow instance to start execution. Returns the instance ID and its initial status. ```typescript async fetch(req: Request, env: Env): Promise { const instance = await env.MY_WORKFLOW.create(); return Response.json({ id: instance.id, details: await instance.status(), }); } ``` -------------------------------- ### Interactive npm create cloudflare Prompts Source: https://github.com/cloudflare/workflows-starter/blob/main/README.md This shows the interactive prompts and output when using `npm create cloudflare@latest` to set up the workflows-starter project. It guides through application creation, configuration, and deployment options. ```sh ╭ Create an application with Cloudflare Step 1 of 3 │ ├ In which directory do you want to create your application? │ dir ./workflows-tutorial │ ├ What would you like to start with? │ category Template from a GitHub repo │ ├ What's the url of git repo containing the template you'd like to use? │ repository cloudflare/workflows-starter │ ├Cloning template from: cloudflare/workflows-starter │ ├template cloned and validated │ ├ Copying template files │ files copied to project directory │ ├ Installing dependencies │ installed via `npm install` │ ╰ Application created ╭ Configuring your application for Cloudflare Step 2 of 3 │ ├ Installing @cloudflare/workers-types │ installed via npm │ ├ Adding latest types to `tsconfig.json` │ added @cloudflare/workers-types/2023-07-01 │ ├ Do you want to use git for version control? │ yes git │ ├ Initializing git repo │ initialized git │ ├ Committing new files │ git commit │ ╰ Application configured ╭ Deploy with Cloudflare Step 3 of 3 │ ├ Do you want to deploy your application? │ no deploy via `npm run deploy` │ ╰ Done ──────────────────────────────────────────────────────────── 🎉 SUCCESS Application created successfully! ``` -------------------------------- ### Interact with Workflow Instance (TypeScript) Source: https://github.com/cloudflare/workflows-starter/blob/main/_autodocs/types.md Example of creating a workflow instance, retrieving its status, and logging its ID. The status object contains the current execution state. ```typescript const instance = await env.MY_WORKFLOW.create(); const status = await instance.status(); console.log(instance.id); // "550e8400-e29b-41d4-a716-446655440000" console.log(status.status); // "queued" | "running" | "success" | ... ``` -------------------------------- ### Basic Fetch Handler Routing Source: https://github.com/cloudflare/workflows-starter/blob/main/_autodocs/endpoints.md This TypeScript example demonstrates a basic fetch handler for routing incoming requests based on method and pathname. It includes handling for specific API endpoints and favicon requests. ```typescript export default { await fetch(req: Request, env: Env): Promise { const url = new URL(req.url); if (req.method === 'POST' && url.pathname === '/workflows') { return handleCreateWorkflow(req, env); } if (req.method === 'GET' && url.pathname === '/status') { return handleGetStatus(req, env); } if (url.pathname.startsWith('/favicon')) { return Response.json({}, { status: 404 }); } return Response.json({ error: 'Not found' }, { status: 404 }); } }; ``` -------------------------------- ### Configure Step Execution with Retries and Timeout Source: https://github.com/cloudflare/workflows-starter/blob/main/_autodocs/types.md Example of configuring a step with specific retry settings and a timeout duration. This ensures steps can handle transient failures and complete within a defined timeframe. ```typescript await step.do( 'my-step', { retries: { limit: 5, delay: '5 second', backoff: 'exponential', }, timeout: '30 minutes', }, async () => { // Step logic } ); ``` -------------------------------- ### Fetch Handler: Create New Instance Source: https://github.com/cloudflare/workflows-starter/blob/main/_autodocs/PROJECT_STRUCTURE.md Creates a new workflow instance using the environment binding and returns its ID and initial status. This is the entry point for starting a new workflow execution. ```typescript let instance = await env.MY_WORKFLOW.create(); return Response.json({ id: instance.id, details: await instance.status(), }); ``` -------------------------------- ### Minimal Env Type Definition (src/examples.ts) Source: https://github.com/cloudflare/workflows-starter/blob/main/_autodocs/api-reference/exports.md Defines an empty environment interface for a minimal workflow example. This is used as a type parameter for WorkflowEntrypoint. ```typescript interface Env {} ``` -------------------------------- ### MyWorkflow Class Definition (src/index.ts) Source: https://github.com/cloudflare/workflows-starter/blob/main/_autodocs/api-reference/exports.md This is a complete example implementation of a workflow class. It demonstrates basic steps, event waiting, sleep, retries, and error handling. It is intended for use as a primary workflow entrypoint. ```typescript export class MyWorkflow extends WorkflowEntrypoint ``` -------------------------------- ### MyWorkflow Class Source: https://github.com/cloudflare/workflows-starter/blob/main/_autodocs/api-reference/exports.md Represents a complete example implementation of a workflow class demonstrating basic steps, event waiting, sleep, retries, and error handling. It extends WorkflowEntrypoint and is intended for direct user invocation. ```APIDOC ## MyWorkflow Class ### Description Complete example implementation of a workflow class demonstrating all major features: basic steps, event waiting, sleep, retries, and error handling. ### Class Signature ```typescript export class MyWorkflow extends WorkflowEntrypoint ``` ### Type Parameters - **Env**: `{ MY_WORKFLOW: Workflow }` - **Params**: `{ email: string; metadata: Record }` ### Public Methods #### run - **Signature**: `async run(event: WorkflowEvent, step: WorkflowStep): Promise` - **Returns**: `Promise` ### Usage Example ```typescript import { MyWorkflow } from './src/index'; // Configure in wrangler.jsonc type Env = { MY_WORKFLOW: Workflow; }; // In fetch handler const instance = await env.MY_WORKFLOW.create({ params: { email: 'user@example.com', metadata: { orderId: '123' } } }); ``` ``` -------------------------------- ### Minimal Params Type Definition (src/examples.ts) Source: https://github.com/cloudflare/workflows-starter/blob/main/_autodocs/api-reference/exports.md Defines an empty object type for parameters in a minimal workflow example. This is used as a type parameter for WorkflowEntrypoint. ```typescript type Params = {}; ``` -------------------------------- ### Check Workflow Instance Status Source: https://github.com/cloudflare/workflows-starter/blob/main/_autodocs/types.md Example of how to retrieve and interpret the status of a workflow instance using a switch statement. This is useful for handling different outcomes of a workflow execution. ```typescript const status = await instance.status(); switch (status.status) { case 'success': console.log('Workflow completed'); break; case 'running': console.log('Still executing...'); break; case 'error': console.log('Workflow failed'); break; case 'paused': console.log('Waiting for event'); break; } ``` -------------------------------- ### Fetch Handler: Get Instance Status Source: https://github.com/cloudflare/workflows-starter/blob/main/_autodocs/PROJECT_STRUCTURE.md Retrieves the status of a specific workflow instance using its ID from the environment binding. Returns the status as a JSON response. ```typescript let id = url.searchParams.get('instanceId'); if (id) { let instance = await env.MY_WORKFLOW.get(id); return Response.json({ status: await instance.status() }); } ``` -------------------------------- ### Wait for External Event with Type and Timeout Source: https://github.com/cloudflare/workflows-starter/blob/main/_autodocs/types.md Example of configuring a wait for an event with a specific type and a maximum wait duration. This is crucial for workflows that depend on external triggers. ```typescript const approval = await step.waitForEvent('approval', { type: 'approval', timeout: '24 hours', }); ``` -------------------------------- ### Deploy Workflows Project Source: https://github.com/cloudflare/workflows-starter/blob/main/_autodocs/INDEX.md Deploys the workflows-starter project to Cloudflare. ```bash npm run deploy ``` -------------------------------- ### Get Status Source: https://github.com/cloudflare/workflows-starter/blob/main/_autodocs/endpoints.md Retrieves the status of a workflow or related component. ```APIDOC ## GET /status ### Description Retrieves the status of a workflow or related component. ### Method GET ### Endpoint /status ### Response #### Success Response (200) - **(Response details not specified in source)** ``` -------------------------------- ### Create Workflow Instance with Options Source: https://github.com/cloudflare/workflows-starter/blob/main/_autodocs/api-reference/fetch-handler.md Demonstrates creating a workflow instance with a custom ID and parameters. The ID defaults to a UUID if not provided. ```typescript const instance = await env.MY_WORKFLOW.create({ id: 'order-123-processing', params: { email: 'user@example.com', metadata: { orderId: '123' }, }, }); ``` -------------------------------- ### Get Workflow Instance Status Source: https://github.com/cloudflare/workflows-starter/blob/main/_autodocs/api-reference/fetch-handler.md Query an existing workflow instance to retrieve its current execution status using a provided instance ID. ```APIDOC ## GET /?instanceId= ### Description Retrieves the current execution status of a specific workflow instance. ### Method GET ### Endpoint / ### Parameters #### Path Parameters None #### Query Parameters - **instanceId** (string) - Yes - The ID of the workflow instance to query. #### Request Body None ### Response #### Success Response (200) - **status** (object) - An object containing the status of the workflow instance. - **status** (string) - The current status of the workflow ('queued', 'running', 'error', 'success', 'paused'). #### Response Example ```json { "status": { "status": "success" } } ``` ``` -------------------------------- ### TypeScript Compilation Process Source: https://github.com/cloudflare/workflows-starter/blob/main/_autodocs/PROJECT_STRUCTURE.md Illustrates the build process where TypeScript source files are compiled and bundled for deployment. Wrangler handles this automatically. ```text .ts source → TypeScript compiler → Bundler → JavaScript → Cloudflare CDN ``` -------------------------------- ### Create a Workflow Instance Source: https://github.com/cloudflare/workflows-starter/blob/main/_autodocs/INDEX.md Instantiate a workflow using its binding in the environment. Provide a custom ID and any necessary parameters. ```typescript const instance = await env.MY_WORKFLOW.create({ id: 'custom-id', params: { /* your params */ } }); ``` -------------------------------- ### Deploying Cloudflare Workflows Source: https://github.com/cloudflare/workflows-starter/blob/main/_autodocs/configuration.md Commands to deploy your configured Cloudflare Workflows. Use either `npm run deploy` or `wrangler deploy`. ```bash npm run deploy ``` ```bash wrangler deploy ``` -------------------------------- ### Accessing Environment Bindings Source: https://github.com/cloudflare/workflows-starter/blob/main/_autodocs/api-reference/workflow-entrypoint.md Demonstrates how to access environment bindings, such as KV namespaces, defined in your `wrangler.jsonc` file within a workflow. ```typescript const kv = this.env.MY_KV_NAMESPACE; ``` -------------------------------- ### Get Workflow Instance Status Source: https://github.com/cloudflare/workflows-starter/blob/main/_autodocs/api-reference/fetch-handler.md Queries an existing workflow instance to retrieve its current execution status. Requires an instanceId from the request URL's search parameters. ```typescript async fetch(req: Request, env: Env): Promise { const url = new URL(req.url); const instanceId = url.searchParams.get('instanceId'); if (instanceId) { const instance = await env.MY_WORKFLOW.get(instanceId); const status = await instance.status(); return Response.json({ status }); } return Response.json({ error: 'instanceId required' }, { status: 400 }); } ``` -------------------------------- ### Wrangler Configuration: Main Entry Point Source: https://github.com/cloudflare/workflows-starter/blob/main/_autodocs/configuration.md Specifies the main file for your Workers application. This file must export a fetch handler. ```json { "main": "src/index.ts" } ``` -------------------------------- ### CreateOptions Source: https://github.com/cloudflare/workflows-starter/blob/main/_autodocs/types.md Configuration options for creating a new workflow instance. Allows specifying a custom instance ID and passing parameters to the workflow's run method. ```APIDOC ## CreateOptions Configuration for workflow instance creation. ### Properties - **id** (string) - Optional - Custom instance ID; if omitted, auto-generated. - **params** (`Params`) - Optional - Parameters to pass to workflow's `run()` method. ### Example ```typescript const instance = await env.MY_WORKFLOW.create({ id: 'order-processing-xyz', params: { email: 'user@example.com', metadata: {} }, }); ``` ``` -------------------------------- ### Create Workflow Instance with Parameters Source: https://github.com/cloudflare/workflows-starter/blob/main/_autodocs/REFERENCE.md Instantiate a new workflow execution with custom parameters and metadata. This is typically done from an external trigger like an HTTP request. ```typescript export default { await fetch(req: Request, env: Env): Promise { const instance = await env.MY_WORKFLOW.create({ id: `order-${Date.now()}`, params: { email: req.headers.get('x-user-email'), metadata: { source: 'api', timestamp: new Date().toISOString(), }, }, }); return Response.json({ instanceId: instance.id, status: await instance.status(), }); } }; ``` -------------------------------- ### Module Exports Source: https://github.com/cloudflare/workflows-starter/blob/main/_autodocs/README.md Exposes the public API surface of the Cloudflare Workflows Starter, including classes and functions available for use in your projects. ```APIDOC ## Module Exports ### Description This module exports the core components of the Cloudflare Workflows Starter, making them available for use in your TypeScript projects. ### Exports - `WorkflowEntrypoint`: The base class for defining workflows. - `WorkflowStep`: An object used within the `run` method to manage workflow steps. - `WorkflowEvent`: Represents the event data passed to the workflow. ### Usage These exports are typically used when defining your workflow class and its execution logic. ``` -------------------------------- ### StepOptions Source: https://github.com/cloudflare/workflows-starter/blob/main/_autodocs/types.md Configuration for durable step execution, including retry strategies and timeouts. It allows defining the number of retries, delay between retries, and backoff strategy. ```APIDOC ## StepOptions Configuration for durable step execution, including retry strategy and timeout. ### Properties - **retries** (object) - Optional - Retry configuration. - **retries.limit** (number) - Optional - Maximum number of retries. - **retries.delay** (string) - Optional - Initial delay between retries (e.g., "5 second"). - **retries.backoff** (string) - Optional - Backoff strategy; defaults to exponential. Possible Values: `'exponential'`, `'linear'`. - **timeout** (string) - Optional - Step timeout duration (e.g., "15 minutes"). ### Example ```typescript await step.do( 'my-step', { retries: { limit: 5, delay: '5 second', backoff: 'exponential', }, timeout: '30 minutes', }, await () => { // Step logic } ); ``` ``` -------------------------------- ### Fetch Handler Source: https://github.com/cloudflare/workflows-starter/blob/main/_autodocs/README.md Handles incoming HTTP requests for your workflow, allowing you to create instances and manage their status via an HTTP entry point. ```APIDOC ## Fetch Handler ### Description Handles HTTP requests for your workflow, enabling instance creation and status checks. ### Definition ```typescript export default { async fetch(req: Request, env: Env): Promise { } } ``` ### Usage This export serves as the HTTP entry point for your Cloudflare Worker. It is responsible for routing incoming requests to the appropriate workflow operations. ``` -------------------------------- ### Import Key Workflow Components Source: https://github.com/cloudflare/workflows-starter/blob/main/_autodocs/REFERENCE.md Import essential classes and types for building Cloudflare Workflows, including WorkflowEntrypoint, WorkflowStep, and WorkflowEvent. ```typescript import { WorkflowEntrypoint, WorkflowStep, WorkflowEvent } from 'cloudflare:workers'; ``` -------------------------------- ### Configure Workflows in wrangler.jsonc Source: https://github.com/cloudflare/workflows-starter/blob/main/_autodocs/REFERENCE.md Configure your workflow in wrangler.jsonc by specifying its name, binding, and class name for deployment. ```jsonc { "name": "my-workflows", "main": "src/index.ts", "compatibility_date": "2024-10-22", "workflows": [ { "name": "my-workflow", "binding": "MY_WORKFLOW", "class_name": "MyWorkflow" } ] } ``` -------------------------------- ### Request Routing Logic Source: https://github.com/cloudflare/workflows-starter/blob/main/_autodocs/api-reference/fetch-handler.md Demonstrates how to use request properties like method and pathname to route incoming HTTP requests to different handler functions within the fetch handler. ```typescript async fetch(req: Request, env: Env): Promise { const url = new URL(req.url); if (req.method === 'POST' && url.pathname === '/workflow/create') { return handleCreateWorkflow(req, env); } if (req.method === 'GET' && url.pathname === '/workflow/status') { return handleGetStatus(req, env); } return Response.json({ error: 'Not found' }, { status: 404 }); } ``` -------------------------------- ### Create a Fetch Handler for Workflow Management Source: https://github.com/cloudflare/workflows-starter/blob/main/_autodocs/REFERENCE.md Implement a fetch handler to manage workflow instances, including creation and status queries via HTTP requests. ```typescript export default { aync fetch(req: Request, env: Env): Promise { const url = new URL(req.url); const instanceId = url.searchParams.get('instanceId'); if (instanceId) { const instance = await env.MY_WORKFLOW.get(instanceId); return Response.json({ status: await instance.status() }); } const instance = await env.MY_WORKFLOW.create(); return Response.json({ id: instance.id }); } }; ``` -------------------------------- ### WorkflowEntrypoint.run() Source: https://github.com/cloudflare/workflows-starter/blob/main/_autodocs/api-reference/workflow-entrypoint.md The main method for defining workflow logic. All asynchronous operations within the workflow should be managed through the 'step' parameter for durability. ```APIDOC ## WorkflowEntrypoint.run() ### Description The primary method where all workflow logic is defined. It receives the workflow event and a step handler to manage durable execution of workflow tasks. ### Method `async run(event: WorkflowEvent, step: WorkflowStep): Promise` ### Parameters #### Parameters - **event** (`WorkflowEvent`) - Yes - Contains the workflow instance ID and user-defined parameters. - **step** (`WorkflowStep`) - Yes - Provides methods to define and manage workflow steps, ensuring durability and retries. ### Returns `Promise` ### Example ```typescript export class MyWorkflow extends WorkflowEntrypoint { async run(event: WorkflowEvent, step: WorkflowStep) { console.info(`starting workflow: ${event.instanceId}`); const result = await step.do('my first step', async () => { return [1, 2, 3]; }); await step.do('my second step', async () => { console.log('Received:', result); }); } } ``` ``` -------------------------------- ### Implement Fetch Handler for HTTP Requests Source: https://github.com/cloudflare/workflows-starter/blob/main/_autodocs/README.md This is the default export for handling HTTP requests. It receives a Request object and an environment object, and should return a Response. ```typescript export default { await fetch(req: Request, env: Env): Promise { } } ``` -------------------------------- ### Create Workflow Source: https://github.com/cloudflare/workflows-starter/blob/main/_autodocs/endpoints.md Handles the creation of a new workflow. ```APIDOC ## POST /workflows ### Description Handles the creation of a new workflow. ### Method POST ### Endpoint /workflows ### Response #### Success Response (200) - **(Response details not specified in source)** ``` -------------------------------- ### Workflow Configuration with Observability Source: https://github.com/cloudflare/workflows-starter/blob/main/_autodocs/REFERENCE.md Configure observability features for your workflow project. Enables tracing and sampling to monitor workflow execution. ```jsonc { "name": "my-workflows", "main": "src/index.ts", "compatibility_date": "2024-10-22", "observability": { "enabled": true, "head_sampling_rate": 0.5 }, "workflows": [ { "name": "my-workflow", "binding": "MY_WORKFLOW", "class_name": "MyWorkflow" } ] } ``` -------------------------------- ### Wrangler Configuration: Multiple Workflow Definitions Source: https://github.com/cloudflare/workflows-starter/blob/main/_autodocs/configuration.md Defines multiple Cloudflare Workflows within the same `wrangler.jsonc` file. Each workflow requires a unique name, binding, and class name. ```json { "workflows": [ { "name": "user-onboarding", "binding": "ONBOARDING_WORKFLOW", "class_name": "OnboardingWorkflow" }, { "name": "order-processing", "binding": "ORDER_WORKFLOW", "class_name": "OrderProcessingWorkflow" } ] } ``` -------------------------------- ### Basic Workflow Step Source: https://github.com/cloudflare/workflows-starter/blob/main/_autodocs/PROJECT_STRUCTURE.md A simple workflow step that performs an action and returns a result. Use this for straightforward, non-blocking operations. ```typescript const files = await step.do('my first step', async () => { return { /* ... */ }; }); ``` -------------------------------- ### StepOptions Interface Source: https://github.com/cloudflare/workflows-starter/blob/main/_autodocs/types.md Defines configuration for durable step execution, including retry limits, delays, backoff strategies, and timeouts. Use this to control step behavior and resilience. ```typescript interface StepOptions { retries?: { limit: number; delay: string; backoff?: 'exponential' | 'linear'; }; timeout?: string; } ``` -------------------------------- ### Accessing a Single Workflow in TypeScript Source: https://github.com/cloudflare/workflows-starter/blob/main/_autodocs/configuration.md Demonstrates how to access a configured workflow in your TypeScript code using environment bindings. The `Env` type must match the `binding` name in `wrangler.jsonc`. ```typescript type Env = { MY_WORKFLOW: Workflow; // Matches binding name }; export default { async fetch(req: Request, env: Env): Promise { const instance = await env.MY_WORKFLOW.create(); return Response.json({ id: instance.id }); } }; ``` -------------------------------- ### Package.json Scripts Source: https://github.com/cloudflare/workflows-starter/blob/main/_autodocs/PROJECT_STRUCTURE.md Contains scripts for deploying and developing the Cloudflare Workers project locally. ```json { "scripts": { "deploy": "wrangler deploy", // Deploy to Cloudflare "start": "wrangler dev" // Local development } } ``` -------------------------------- ### Wrangler Configuration: Observability Enabled Source: https://github.com/cloudflare/workflows-starter/blob/main/_autodocs/configuration.md Enables distributed tracing and request sampling for monitoring and debugging. Set `enabled` to true to activate. ```json { "observability": { "enabled": true, "head_sampling_rate": 1 } } ``` -------------------------------- ### Accessing Multiple Workflows in TypeScript Source: https://github.com/cloudflare/workflows-starter/blob/main/_autodocs/configuration.md Shows how to access multiple configured workflows in your TypeScript application. Ensure the `Env` type includes bindings for each workflow. ```typescript type Env = { ONBOARDING_WORKFLOW: Workflow; ORDER_WORKFLOW: Workflow; }; export default { async fetch(req: Request, env: Env): Promise { const url = new URL(req.url); if (url.pathname === '/onboard') { const instance = await env.ONBOARDING_WORKFLOW.create(); return Response.json({ id: instance.id }); } if (url.pathname === '/order') { const instance = await env.ORDER_WORKFLOW.create(); return Response.json({ id: instance.id }); } return Response.json({ error: 'Not found' }, { status: 404 }); } }; ``` -------------------------------- ### Wrangler Configuration: Single Workflow Definition Source: https://github.com/cloudflare/workflows-starter/blob/main/_autodocs/configuration.md Defines a single Cloudflare Workflow. Specify its name, binding for code access, and the class name from your source code. ```json { "workflows": [ { "name": "workflows-starter", "binding": "MY_WORKFLOW", "class_name": "MyWorkflow" } ] } ``` -------------------------------- ### step.do() Source: https://github.com/cloudflare/workflows-starter/blob/main/_autodocs/api-reference/workflow-step.md Defines a durable step that executes a provided asynchronous function. This method supports retries and timeouts, and if the step fails and is retried, it will resume from the beginning of the step's function. ```APIDOC ## step.do() ### Description Defines a durable step that executes the provided function. If the step fails and is retried, it will resume from the beginning of the step's function. ### Method Signature ```typescript step.do(name: string, fn: () => Promise): Promise ``` ```typescript step.do(name: string, options: StepOptions, fn: () => Promise): Promise ``` ### Parameters #### Parameters - **name** (string) - Required - Unique name for this step (used for logging and state tracking) - **options** (StepOptions) - Optional - Configuration options for retry, timeout, and other behaviors - **fn** (() => Promise) - Required - Async function containing the step's logic ### StepOptions Type ```typescript interface StepOptions { retries?: { limit: number; // Maximum number of retries delay: string; // Initial delay (e.g., "5 second", "1 minute") backoff?: 'exponential' | 'linear'; // Backoff strategy }; timeout?: string; // Step timeout (e.g., "15 minutes", "2 hours") } ``` ### Returns `Promise` - The return value of the `fn()` function ### Example - Basic step ```typescript const files = await step.do('fetch-files', async () => { const resp = await fetch('https://api.example.com/files'); return await resp.json(); }); ``` ### Example - Step with retry strategy ```typescript await step.do( 'write-to-storage', { retries: { limit: 5, delay: '5 second', backoff: 'exponential', }, timeout: '15 minutes', }, async () => { const resp = await fetch('https://api.example.com/write', { method: 'POST', body: JSON.stringify({ data: 'value' }), }); if (!resp.ok) throw new Error('API error'); return await resp.json(); } ); ``` ``` -------------------------------- ### WorkflowStep Methods Source: https://github.com/cloudflare/workflows-starter/blob/main/_autodocs/README.md Methods for defining and managing durable workflow steps, including executing tasks, waiting for events, and sleeping. ```APIDOC ## WorkflowStep ### Description An object to manage workflow steps, allowing for durable operations, event waiting, and delays. ### Methods #### do - **do**(name: string, options?: { retries?: { limit: number, delay: string, backoff: 'exponential' | 'linear' }, timeout: string }, work: () => Promise) - **Description**: Executes a durable operation with optional retries and timeout. - **Parameters**: - `name` (string) - The name of the step. - `options` (object, optional) - Configuration for retries and timeout. - `retries` (object, optional) - Retry configuration. - `limit` (number) - Maximum number of retries. - `delay` (string) - Initial delay between retries (e.g., '5 second'). - `backoff` ('exponential' | 'linear') - Backoff strategy. - `timeout` (string) - Maximum duration for the step (e.g., '15 minutes'). - `work` (() => Promise) - The asynchronous function to execute. - **Return Type**: `Promise` #### waitForEvent - **waitForEvent**(name: string, options?: { timeout: string }) - **Description**: Pauses workflow execution until a specific event is received or a timeout occurs. - **Parameters**: - `name` (string) - The name of the event to wait for. - `options` (object, optional) - Timeout configuration. - `timeout` (string) - Maximum duration to wait for the event (e.g., '1 hour'). - **Return Type**: `Promise` #### sleep - **sleep**(name: string, duration: string) - **Description**: Pauses workflow execution for a specified duration. - **Parameters**: - `name` (string) - The name of the sleep operation. - `duration` (string) - The duration to sleep (e.g., '5 minutes'). - **Return Type**: `Promise` ### Usage ```typescript // Define a durable step with retry and timeout await step.do( 'step-name', { retries: { limit: 5, delay: '5 second', backoff: 'exponential' }, timeout: '15 minutes' }, aSync () => { /* work */ } ); // Wait for a specific event const event = await step.waitForEvent('event-name', { timeout: '1 hour' }); // Sleep for a duration await step.sleep('sleep-name', '5 minutes'); ``` ``` -------------------------------- ### Primary Fetch Handler Entry Point Source: https://github.com/cloudflare/workflows-starter/blob/main/_autodocs/PROJECT_STRUCTURE.md The default export for a Cloudflare Worker, handling incoming HTTP requests. ```typescript export default { async fetch(req: Request, env: Env): Promise { // Handle incoming HTTP requests } } ``` -------------------------------- ### Workflow Interface Source: https://github.com/cloudflare/workflows-starter/blob/main/_autodocs/types.md Represents a deployed workflow, providing methods to create new instances and retrieve existing ones by ID. Accessed via environment bindings. ```typescript interface Workflow { create(options?: CreateOptions): Promise; get(id: string): Promise; } ``` -------------------------------- ### Define a durable step with options Source: https://github.com/cloudflare/workflows-starter/blob/main/_autodocs/api-reference/workflow-step.md Configure retry strategies, timeouts, and other behaviors for a durable step using `step.do` with `StepOptions`. Ensure the provided function is idempotent when using retry options. ```typescript step.do( name: string, options: StepOptions, fn: () => Promise ): Promise ``` -------------------------------- ### Workflow Bindings Configuration Source: https://github.com/cloudflare/workflows-starter/blob/main/_autodocs/PROJECT_STRUCTURE.md Defines how a workflow class is bound to an environment variable for use within Cloudflare Workers. ```jsonc "workflows": [ { "name": "workflows-starter", // Workflow identifier "binding": "MY_WORKFLOW", // Environment variable name "class_name": "MyWorkflow" // Class name from source } ] ``` -------------------------------- ### Common Imports for Workflows Source: https://github.com/cloudflare/workflows-starter/blob/main/_autodocs/INDEX.md Import necessary classes and types from the 'cloudflare:workers' module to build your workflows. ```typescript import { WorkflowEntrypoint, WorkflowStep, WorkflowEvent } from 'cloudflare:workers'; ``` -------------------------------- ### Wrangler Configuration: Compatibility Date Source: https://github.com/cloudflare/workflows-starter/blob/main/_autodocs/configuration.md Defines the compatibility level for your Cloudflare Workers. It's recommended to use the current date or a date when features were stable. ```json { "compatibility_date": "2024-10-22" } ``` -------------------------------- ### Deployment Command Source: https://github.com/cloudflare/workflows-starter/blob/main/_autodocs/PROJECT_STRUCTURE.md The command used to deploy the Cloudflare Worker. This typically runs `wrangler deploy` to upload your bundled code. ```bash npm run deploy Runs: `wrangler deploy` ``` -------------------------------- ### Define Workflow Environment Bindings (TypeScript) Source: https://github.com/cloudflare/workflows-starter/blob/main/_autodocs/types.md The Env type defines all available bindings for your workflow and fetch handler. Include bindings for workflows, KV, D1, AI, and other services. ```typescript type Env = { MY_WORKFLOW: Workflow; // Additional bindings (KV, D1, etc.) }; ``` ```typescript type Env = { MY_WORKFLOW: Workflow; MY_KV: KVNamespace; MY_DATABASE: D1Database; MY_AI: Ai; }; ``` -------------------------------- ### Define a WorkflowEntrypoint Class Source: https://github.com/cloudflare/workflows-starter/blob/main/_autodocs/README.md This is the base class for defining your workflow. Implement the `run` method to define the workflow's logic. ```typescript export class MyWorkflow extends WorkflowEntrypoint { await run(event: WorkflowEvent, step: WorkflowStep) { } } ``` -------------------------------- ### Define a Workflow with WorkflowEntrypoint Source: https://github.com/cloudflare/workflows-starter/blob/main/_autodocs/REFERENCE.md Extend WorkflowEntrypoint to define your workflow's logic. Use WorkflowStep for durable execution of tasks. ```typescript import { WorkflowEntrypoint, WorkflowEvent, WorkflowStep } from 'cloudflare:workers'; type Env = { MY_WORKFLOW: Workflow; }; type Params = { email: string; }; export class MyWorkflow extends WorkflowEntrypoint { async run(event: WorkflowEvent, step: WorkflowStep) { const result = await step.do('my-step', async () => { return await fetch('https://api.example.com/data'); }); } } ``` -------------------------------- ### Accessing Workflow Binding in TypeScript Source: https://github.com/cloudflare/workflows-starter/blob/main/_autodocs/api-reference/exports.md Demonstrates how to access a bound workflow instance in TypeScript code using the defined environment variable. Ensure the `Env` type correctly maps the binding name to the `Workflow` type. ```typescript type Env = { MY_WORKFLOW: Workflow; // Matches binding name }; const instance = await env.MY_WORKFLOW.create(); ``` -------------------------------- ### Define a Custom Workflow Entrypoint Source: https://github.com/cloudflare/workflows-starter/blob/main/_autodocs/INDEX.md Extend the WorkflowEntrypoint class to define your workflow's logic. Implement the run method to handle workflow events and steps. ```typescript export class MyWorkflow extends WorkflowEntrypoint { await run(event: WorkflowEvent, step: WorkflowStep) { // Workflow implementation } } ``` -------------------------------- ### Send Approval Event to Workflow Instance Source: https://github.com/cloudflare/workflows-starter/blob/main/_autodocs/endpoints.md Use this cURL command to send an approval event to a specific workflow instance. Ensure you replace placeholders with your actual API token, account ID, and workflow details. The request body must be valid JSON. ```bash curl -X POST \ "https://api.cloudflare.com/client/v4/accounts/abc123/workflows/workflows-starter/instances/order-123/events/request-approval" \ -H "Authorization: Bearer YOUR_API_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "type": "approval", "data": { "approved": true, "reason": "Request validated" } }' ``` -------------------------------- ### fetch Handler Module Source: https://github.com/cloudflare/workflows-starter/blob/main/_autodocs/api-reference/exports.md The HTTP request handler that serves as the entry point for the Workers application. It handles instance creation and status queries. ```APIDOC ## fetch Handler Module ### Description HTTP request handler that serves as the entry point for the Workers application. Handles instance creation and status queries. ### Module Signature ```typescript export default { async fetch(req: Request, env: Env): Promise } ``` ### Method `async fetch(req: Request, env: Env): Promise` ### Parameters - **req** (`Request`): Required - Incoming HTTP request - **env** (`Env`): Required - Environment with workflow bindings ### Returns `Promise` - HTTP response ### Route Handling 1. **Ignore Favicon** - Route: Any path starting with `/favicon` - Response: 404 Not Found 2. **Query Instance Status** - Route: GET `/?instanceId={id}` - Response: JSON with instance status 3. **Create New Instance** - Route: GET or POST `/` (without `instanceId` param) - Response: JSON with new instance ID and status ### Usage Example ```typescript // Request: GET /?instanceId=my-workflow-123 // Response: { "status": { "status": "success" } } // Request: GET / // Response: { "id": "new-uuid", "details": { "status": "queued" } } ``` ``` -------------------------------- ### Define a basic durable step Source: https://github.com/cloudflare/workflows-starter/blob/main/_autodocs/api-reference/workflow-step.md Use `step.do` to define a durable execution step. The function provided will be executed, and if it fails, it will be retried from the beginning. This is suitable for operations that are safe to retry. ```typescript step.do( name: string, fn: () => Promise ): Promise ``` -------------------------------- ### Workflow Step with Retries and Timeout Source: https://github.com/cloudflare/workflows-starter/blob/main/_autodocs/PROJECT_STRUCTURE.md Defines a step that includes retry logic with configurable limits, delays, and backoff strategies, along with a timeout. Ideal for operations prone to transient failures. ```typescript await step.do( 'make a call to write that could maybe, just might, fail', { retries: { limit: 5, delay: '5 second', backoff: 'exponential', }, timeout: '15 minutes', }, async () => { /* ... */ } ); ```