@choiceform/automation-plugin-sdk
专业的工作流插件开发框架 - 业内领先的插件开发体验

✨ 特性
- 🚀 零依赖设计 - 完全兼容节点式工作流体系
- 🔧 完善的开发工具链 - 一键创建、构建、调试
- 🎯 类型安全 - 严格的 TypeScript 支持
- 📦 热重载开发 - 实时预览,极速开发体验
- ✅ 内置验证 - 自动代码质量检查和错误处理
- 🎨 nodes-config 兼容 - 严格按照工作流节点标准
- 🔄 工作流级别错误处理 - 企业级可靠性
🚀 快速开始
安装
npm install -g @choiceform/automation-plugin-sdk
pnpm add -g @choiceform/automation-plugin-sdk
创建插件项目
automation-plugin init my-awesome-plugin
cd my-awesome-plugin
pnpm install
automation-plugin dev
📖 CLI 命令
automation-plugin init
创建新的插件项目,支持 5 种插件类型:
- Trigger - 触发器节点 (启动工作流)
- Action - 动作节点 (执行操作)
- Transform - 转换节点 (数据处理)
- Utility - 工具节点 (流程控制)
- Package - 节点包 (多个节点组合)
automation-plugin init [project-name] [options]
Options:
--dir <directory> 指定创建目录
--no-git 不初始化 Git 仓库
--template <name> 使用指定模板
--no-typescript 禁用 TypeScript
automation-plugin dev
启动开发调试模式,支持热重载:
automation-plugin dev [options]
Options:
--port <port> 指定端口 (默认: 3000)
--host <host> 指定主机 (默认: localhost)
--no-open 不自动打开浏览器
--no-watch 禁用文件监听
automation-plugin build
构建插件项目:
automation-plugin build [options]
Options:
--output <dir> 输出目录 (默认: dist)
--minify 压缩代码
--sourcemap 生成 source map
--watch 监听模式
automation-plugin validate
验证插件配置和代码质量:
automation-plugin validate [plugin-path] [options]
Options:
--fix 自动修复可修复的问题
--strict 严格模式检查
automation-plugin debug
连接到远程实例进行调试:
automation-plugin debug [options]
Options:
--url <url> 远程实例地址
--token <token> 认证令牌
🏗️ 插件开发
基础插件结构
import { Action, ExecutionContext, ExecutionResult, PluginValue } from '@choiceform/automation-plugin-sdk';
export class MyAction extends Action {
async execute(
inputs: Record<string, PluginValue>,
context: ExecutionContext
): Promise<ExecutionResult> {
try {
const message = inputs.message as string;
const result = await this.processMessage(message);
return this.createSuccessResult({
output: result,
timestamp: Date.now()
});
} catch (error) {
return this.createErrorResult(
error instanceof Error ? error.message : '处理失败'
);
}
}
private async processMessage(message: string): Promise<string> {
return `处理结果: ${message}`;
}
}
触发器插件示例
import { Trigger, ExecutionContext, PluginValue } from '@choiceform/automation-plugin-sdk';
export class WebhookTrigger extends Trigger {
private server?: HttpServer;
async start(): Promise<void> {
this.server = createHttpServer((req, res) => {
const eventData = this.parseWebhookData(req);
this.triggerEvent(eventData);
res.end('OK');
});
await this.server.listen(3001);
this.log('info', 'Webhook 服务器已启动在端口 3001');
}
async stop(): Promise<void> {
if (this.server) {
await this.server.close();
this.log('info', 'Webhook 服务器已停止');
}
}
async execute(inputs: Record<string, PluginValue>): Promise<ExecutionResult> {
return this.createSuccessResult({
triggered: true,
timestamp: Date.now()
});
}
private parseWebhookData(req: any): Record<string, PluginValue> {
return {
method: req.method,
headers: req.headers,
body: req.body
};
}
}
转换器插件示例
import { Transform, PluginValue } from '@choiceform/automation-plugin-sdk';
export class DataTransform extends Transform {
async transform(input: PluginValue): Promise<PluginValue> {
if (typeof input !== 'object' || input === null) {
throw new Error('输入必须是对象类型');
}
const data = input as Record<string, PluginValue>;
return {
...data,
processed: true,
processedAt: new Date().toISOString(),
version: '1.0.0'
};
}
}
📋 插件配置
plugin.manifest.json
{
"name": "my-awesome-plugin",
"version": "1.0.0",
"description": "一个强大的工作流插件",
"author": "Your Name",
"type": "action",
"features": [
"persistence",
"http",
"credentials"
],
"advanced": true,
"sdk": {
"version": "^1.0.0",
"compatibility": "node-based-workflow",
"features": [
"hot-reload",
"type-safety",
"validation",
"nodes-config-compatible",
"workflow-integration"
]
},
"permissions": [
"credentials"
],
"metadata": {
"createdAt": "2024-01-01T00:00:00.000Z",
"framework": "automation-plugin-sdk",
"compatibility": "workflow-automation-system",
"architecture": "node-based"
}
}
nodes-config 兼容性
插件完全兼容 nodes-config 标准:
export interface NodeDefinition {
identity: {
name: string;
category: string;
label?: Record<string, string>;
};
description: {
ai: string;
human?: Record<string, string>;
};
inputs?: NodePort[];
outputs?: NodePort[];
portStyles?: Record<string, PortStyleConfig>;
layout: LayoutConfig;
toolbar: ToolbarConfig;
registry: NodeRegistryItem;
}
🔧 开发工具
热重载
开发模式下支持文件热重载:
automation-plugin dev --watch
修改源码时自动重新加载,支持:
- TypeScript 文件变更
- 配置文件更新
- 静态资源修改
- 依赖包更新
实时调试
支持 WebSocket 实时通信:
const ws = new WebSocket('ws://localhost:3000');
ws.on('message', (data) => {
const message = JSON.parse(data);
console.log('调试消息:', message);
});
代码质量检查
自动检查代码质量:
automation-plugin validate --strict
automation-plugin validate --fix
检查项目包括:
- TypeScript 编译错误
- 配置文件格式
- 依赖版本兼容性
- 安全漏洞扫描
- 代码规范检查
📚 API 参考
基类
Plugin
所有插件的基类:
abstract class Plugin {
abstract execute(inputs: Record<string, PluginValue>): Promise<ExecutionResult>;
validateInputs(inputs: Record<string, PluginValue>): ValidationResult;
healthCheck(): Promise<HealthCheckResult>;
protected log(level: 'info' | 'warn' | 'error', message: string): void;
protected getCredential(name: string): Promise<string | undefined>;
protected storeData(key: string, value: PluginValue): Promise<void>;
protected retrieveData(key: string): Promise<PluginValue | null>;
}
Trigger
触发器插件基类:
abstract class Trigger extends Plugin {
abstract start(): Promise<void>;
abstract stop(): Promise<void>;
protected triggerEvent(eventData: Record<string, PluginValue>): Promise<void>;
}
Action
动作插件基类:
abstract class Action extends Plugin {
abstract execute(inputs: Record<string, PluginValue>): Promise<ExecutionResult>;
}
Transform
转换器插件基类:
abstract class Transform extends Plugin {
abstract transform(input: PluginValue): Promise<PluginValue>;
}
类型定义
type PluginValue =
| string
| number
| boolean
| null
| undefined
| PluginValue[]
| { [key: string]: PluginValue };
interface ExecutionResult {
success: boolean;
data?: Record<string, PluginValue>;
error?: {
message: string;
code?: string;
details?: PluginValue;
};
metadata?: {
executionTime?: number;
memoryUsage?: number;
warnings?: string[];
};
}
interface ExecutionContext {
nodeId: string;
workflowId: string;
userId: string;
executionId: string;
log: (level: 'info' | 'warn' | 'error', message: string) => void;
getCredential: (name: string) => Promise<string | undefined>;
storeData: (key: string, value: PluginValue) => Promise<void>;
retrieveData: (key: string) => Promise<PluginValue | null>;
getEnvironment: (key: string) => string | undefined;
}
🎯 最佳实践
1. 错误处理
export class RobustAction extends Action {
async execute(inputs: Record<string, PluginValue>): Promise<ExecutionResult> {
try {
const validation = this.validateInputs(inputs);
if (!validation.isValid) {
return this.createErrorResult(
`输入验证失败: ${validation.errors.map(e => e.message).join(', ')}`
);
}
const result = await this.doWork(inputs);
return this.createSuccessResult(result);
} catch (error) {
this.log('error', `执行失败: ${error}`);
return this.createErrorResult(
error instanceof Error ? error.message : '未知错误'
);
}
}
}
2. 参数验证
protected validateInputs(inputs: Record<string, PluginValue>): ValidationResult {
const errors: ValidationResult['errors'] = [];
if (!inputs.apiKey) {
errors.push({
field: 'apiKey',
message: 'API 密钥是必需的',
code: 'REQUIRED_PARAMETER_MISSING'
});
}
if (inputs.timeout && typeof inputs.timeout !== 'number') {
errors.push({
field: 'timeout',
message: '超时时间必须是数字类型',
code: 'TYPE_MISMATCH'
});
}
return {
isValid: errors.length === 0,
errors
};
}
3. 凭据管理
async execute(inputs: Record<string, PluginValue>, context: ExecutionContext): Promise<ExecutionResult> {
const apiKey = await context.getCredential('apiKey');
if (!apiKey) {
return this.createErrorResult('缺少 API 密钥凭据');
}
const response = await fetch('https://api.example.com/data', {
headers: {
'Authorization': `Bearer ${apiKey}`
}
});
}
4. 日志记录
async execute(inputs: Record<string, PluginValue>, context: ExecutionContext): Promise<ExecutionResult> {
context.log('info', '开始执行插件');
try {
const startTime = Date.now();
const result = await this.processData(inputs);
const executionTime = Date.now() - startTime;
context.log('info', `执行完成,耗时 ${executionTime}ms`);
return this.createSuccessResult(result, {
executionTime
});
} catch (error) {
context.log('error', `执行失败: ${error}`);
throw error;
}
}
🔄 版本更新
v1.0.0
- ✨ 初始版本发布
- 🚀 支持 5 种插件类型
- 🔧 完整的 CLI 工具链
- 📦 热重载开发体验
- ✅ 自动代码质量检查
- 🎨 严格的 nodes-config 兼容性
🤝 贡献
欢迎贡献代码!请阅读 贡献指南 了解详情。
📄 许可证
MIT License - 详见 LICENSE 文件。
🆘 支持
@choiceform/automation-plugin-sdk - 让插件开发变得简单而专业 🚀