@cascade-flow/workflow

中文文档
0.3.6发布于 2026/08/12MITTypeScriptES Module零依赖近 30 天下载 2715

Workflow authoring SDK for CascadeFlow with type-safe step definition helpers

原始使用文档
文档目录14 节
  1. Installation
  2. API Reference
  3. Step Definition
  4. Skip and Optional Dependencies
  5. Types
  6. Step Configuration
  7. Organizing Steps in Groups
  8. Examples
  9. Simple Step
  10. Step with Dependencies
  11. Step with Retry Logic
  12. Conditional Skip
  13. Checkpoints
  14. See Also

@cascade-flow/workflow

Workflow authoring SDK for CascadeFlow - provides type-safe step definition helpers and utilities for building workflows.

Installation

bun add @cascade-flow/workflow

API Reference

Step Definition

defineStep(spec)

Default step definition helper for workflows without typed input.

import { defineStep } from "@cascade-flow/workflow";

export const step = defineStep({
  name: "my-step",
  dependencies: {},
  exportOutput: true,
  fn: async ({ ctx }) => {
    return { result: "value" };
  }
});

baseDefineStep<TInput>()

Factory function that creates a typed defineStep function for a workflow with typed input.

Usage pattern:

  1. Create a workflow-specific defineStep.ts:
// workflows/my-workflow/define-step.ts
import { baseDefineStep } from "@cascade-flow/workflow";
import type { WorkflowInput } from "./input-schema";

export const defineStep = baseDefineStep<WorkflowInput>();
  1. Use it in your steps:
// workflows/my-workflow/steps/my-step/step.ts
import { defineStep } from "../../define-step";

export const step = defineStep({
  fn: async ({ ctx }) => {
    // ctx.input is now typed as WorkflowInput!
    const message = ctx.input.message; // Fully typed
    return { processed: message };
  }
});

Skip and Optional Dependencies

Skip

Error class for intentionally skipping steps. Skipped steps:

  • Are marked as "skipped" (not failed)
  • Cascade to dependent steps (they also get skipped)
  • Do not trigger retries
import { Skip } from "@cascade-flow/workflow";

export const step = defineStep({
  fn: async ({ ctx }) => {
    if (!ctx.input.shouldProcess) {
      throw new Skip("Processing not needed");
    }
    return { result: "processed" };
  }
});

With metadata:

throw new Skip("Feature flag disabled", {
  flag: "new-processor",
  environment: process.env.NODE_ENV
});

optional(step)

Marks a dependency as optional. Optional dependencies:

  • Won't cause cascade skips when they are skipped
  • Will be undefined in the dependencies object if skipped
  • Will have their normal output value if they complete successfully
import { defineStep, optional } from "@cascade-flow/workflow";
import { step as validation } from "../validation/step.ts";
import { step as enrichment } from "../enrichment/step.ts";

export const step = defineStep({
  dependencies: {
    validation,                      // Required - will cascade skip
    enrichment: optional(enrichment) // Optional - won't cascade skip
  },
  fn: async ({ dependencies }) => {
    // dependencies.validation is guaranteed to exist
    // dependencies.enrichment is StepOutput | undefined
    if (dependencies.enrichment) {
      // Use enrichment data
    } else {
      // Fallback when enrichment was skipped
    }
    return { result: "processed" };
  }
});

isOptional(dep)

Checks if a dependency is marked as optional. (Internal utility)

Types

RunnerContext

Runtime context available to every step:

type RunnerContext = {
  runId: string;
  workflow: {
    slug: string; // Workflow directory name
    name: string; // Friendly name from workflow.json
  };
  input?: unknown; // Validated workflow input
  log: (...args: any[]) => void;
};

InferStepOutput<T>

Type utility for inferring a step's output type from its function signature.

JSONValue, JSONArray, JSONObject, JSONPrimitive

Types representing JSON-serializable values. All step outputs must be JSON-serializable.

StepOutput

Alias for JSONValue - the type constraint for step return values.

OptionalDependency<T>

Type representing an optional dependency wrapper.

Step Configuration

The defineStep spec accepts:

{
  name?: string;                // Display name (defaults to directory name)
  dependencies?: Record<...>;   // Other steps this step depends on
  exportOutput?: boolean;       // Include in final workflow output
  maxRetries?: number;          // Retry count on failure (default: 0)
  retryDelayMs?: number;        // Delay between retries (default: 0)
  timeoutMs?: number;           // Max execution time (default: 300000ms / 5 min)
  fn: (args) => Promise<Output> | Output;  // Step implementation
}

Organizing Steps in Groups

Steps can be organized in nested directory structures for better organization:

workflows/my-workflow/steps/
├── step-1/step.ts                           # Flat step
└── data-processing/                         # Group directory
    ├── extract/
    │   └── fetch-data/step.ts              # Nested step
    └── transform/
        └── normalize/step.ts                # Nested step

Key Points:

  • Groups are purely organizational (no special behavior)
  • Flat and nested steps can coexist in the same workflow
  • Step IDs use paths: "step-1" (flat) or "data-processing/extract/fetch-data" (nested)
  • Dependencies use relative imports:
// In steps/notifications/send/step.ts
import { step as fetchData } from "../../data-processing/extract/fetch-data/step.ts";

export const step = defineStep({
  dependencies: { fetchData },
  fn: async ({ dependencies }) => {
    // Use data from nested group
    return { sent: true, data: dependencies.fetchData };
  }
});

Examples

Simple Step

import { defineStep } from "@cascade-flow/workflow";

export const step = defineStep({
  exportOutput: true,
  fn: async () => {
    return { timestamp: Date.now() };
  }
});

Step with Dependencies

import { defineStep } from "@cascade-flow/workflow";
import { step as stepA } from "../step-a/step.ts";
import { step as stepB } from "../step-b/step.ts";

export const step = defineStep({
  dependencies: { stepA, stepB },
  fn: async ({ dependencies }) => {
    // Both dependencies are available and fully typed
    const combined = {
      a: dependencies.stepA.value,
      b: dependencies.stepB.result
    };
    return combined;
  }
});

Step with Retry Logic

import { defineStep } from "@cascade-flow/workflow";

export const step = defineStep({
  maxRetries: 3,
  retryDelayMs: 1000,
  fn: async () => {
    const response = await fetch("https://api.example.com/data");
    if (!response.ok) throw new Error("API request failed");
    return await response.json();
  }
});

Conditional Skip

import { defineStep, Skip } from "@cascade-flow/workflow";

export const step = defineStep({
  fn: async ({ ctx }) => {
    if (!ctx.input.featureEnabled) {
      throw new Skip("Feature disabled");
    }

    // Process when enabled
    return { status: "processed" };
  }
});

Checkpoints

Checkpoints save intermediate progress within a step, persisting results across retries:

import { defineStep } from "@cascade-flow/workflow";

export const step = defineStep({
  fn: async ({ ctx }) => {
    for (let i = 0; i < items.length; i++) {
      const result = await ctx.checkpoint?.("process-item", async () => {
        return processItem(items[i]);
      });
    }
    return { processed: items.length };
  }
});

For parallel checkpoints, use awaitCheckpoints() to ensure all complete before errors propagate:

import { defineStep, awaitCheckpoints } from "@cascade-flow/workflow";

export const step = defineStep({
  fn: async ({ ctx }) => {
    const [a, b] = await awaitCheckpoints([
      ctx.checkpoint?.("task-a", async () => fetchData()),
      ctx.checkpoint?.("task-b", async () => validate()),
    ]);
    return { a, b };
  }
});

See Also

版本与发布记录

@cascade-flow/workflow 共发布 15 个版本,首次发布于 2025/11/19;过去 12 个月发布了 15 个版本。

版本发布日期距今
0.3.6latest2026/08/122 个月前
0.3.52026/01/239 个月前
0.3.42025/12/2510 个月前
0.3.32025/12/1710 个月前
0.3.22025/12/1510 个月前
0.3.12025/12/1110 个月前

关于 @cascade-flow/workflow 的常见问题

@cascade-flow/workflow 是什么?

Workflow authoring SDK for CascadeFlow with type-safe step definition helpers

如何安装 @cascade-flow/workflow?

在项目目录运行 npm install @cascade-flow/workflow,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:typescript(^5)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@cascade-flow/workflow 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@cascade-flow/workflow 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@cascade-flow/workflow 可以商用吗?

@cascade-flow/workflow 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@cascade-flow/workflow 的下载量有多少?

根据 npm 官方下载统计,@cascade-flow/workflow 在 2026/10/09 – 2026/11/07 这 30 天内被下载 2,715 次,日均约 91 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@cascade-flow/workflow 还在维护吗?

最新版本 0.3.6 发布于 2026/08/12(2 个月前);至今共发布 15 个版本,其中过去 12 个月发布了 15 个;首次发布于 2025/11/19。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。