'use strict';

var zod = require('zod');

// src/automation/workflow.zod.ts
zod.z.string().min(2, { message: "System identifier must be at least 2 characters" }).regex(/^[a-z][a-z0-9_.]*$/, {
  message: 'System identifier must be lowercase, starting with a letter, and may contain letters, numbers, underscores, or dots (e.g., "user_profile" or "order.created")'
}).describe("System identifier (lowercase with underscores or dots)");
var SnakeCaseIdentifierSchema = zod.z.string().min(2, { message: "Identifier must be at least 2 characters" }).regex(/^[a-z][a-z0-9_]*$/, {
  message: 'Identifier must be lowercase snake_case, starting with a letter, and may contain only letters, numbers, and underscores (e.g., "user_profile")'
}).describe("Snake case identifier (lowercase with underscores only)");
zod.z.string().min(3, { message: "Event name must be at least 3 characters" }).regex(/^[a-z][a-z0-9_.]*$/, {
  message: 'Event name must be lowercase with dots for namespacing (e.g., "user.created", "order.paid")'
}).describe("Event name (lowercase with dot notation for namespacing)");

// src/automation/workflow.zod.ts
var WorkflowTriggerType = zod.z.enum([
  "on_create",
  // When record is created
  "on_update",
  // When record is updated
  "on_create_or_update",
  // Both
  "on_delete",
  // When record is deleted
  "schedule"
  // Time-based (cron)
]);
var FieldUpdateActionSchema = zod.z.object({
  name: zod.z.string().describe("Action name"),
  type: zod.z.literal("field_update"),
  field: zod.z.string().describe("Field to update"),
  value: zod.z.unknown().describe("Value or Formula to set")
});
var EmailAlertActionSchema = zod.z.object({
  name: zod.z.string().describe("Action name"),
  type: zod.z.literal("email_alert"),
  template: zod.z.string().describe("Email template ID/DevName"),
  recipients: zod.z.array(zod.z.string()).describe("List of recipient emails or user IDs")
});
var ConnectorActionRefSchema = zod.z.object({
  name: zod.z.string().describe("Action name"),
  type: zod.z.literal("connector_action"),
  connectorId: zod.z.string().describe("Target Connector ID (e.g. slack, twilio)"),
  actionId: zod.z.string().describe("Target Action ID (e.g. send_message)"),
  input: zod.z.record(zod.z.string(), zod.z.unknown()).describe("Input parameters matching the action schema")
});
var HttpCallActionSchema = zod.z.object({
  name: zod.z.string().describe("Action name"),
  type: zod.z.literal("http_call"),
  url: zod.z.string().describe("Target URL"),
  method: zod.z.enum(["GET", "POST", "PUT", "DELETE", "PATCH"]).default("POST").describe("HTTP Method"),
  headers: zod.z.record(zod.z.string(), zod.z.string()).optional().describe("HTTP Headers"),
  body: zod.z.string().optional().describe("Request body (JSON or text)")
});
var TaskCreationActionSchema = zod.z.object({
  name: zod.z.string().describe("Action name"),
  type: zod.z.literal("task_creation"),
  taskObject: zod.z.string().describe('Task object name (e.g., "task", "project_task")'),
  subject: zod.z.string().describe("Task subject/title"),
  description: zod.z.string().optional().describe("Task description"),
  assignedTo: zod.z.string().optional().describe("User ID or field reference for assignee"),
  dueDate: zod.z.string().optional().describe("Due date (ISO string or formula)"),
  priority: zod.z.string().optional().describe("Task priority"),
  relatedTo: zod.z.string().optional().describe("Related record ID or field reference"),
  additionalFields: zod.z.record(zod.z.string(), zod.z.unknown()).optional().describe("Additional custom fields")
});
var PushNotificationActionSchema = zod.z.object({
  name: zod.z.string().describe("Action name"),
  type: zod.z.literal("push_notification"),
  title: zod.z.string().describe("Notification title"),
  body: zod.z.string().describe("Notification body text"),
  recipients: zod.z.array(zod.z.string()).describe("User IDs or device tokens"),
  data: zod.z.record(zod.z.string(), zod.z.unknown()).optional().describe("Additional data payload"),
  badge: zod.z.number().optional().describe("Badge count (iOS)"),
  sound: zod.z.string().optional().describe("Notification sound"),
  clickAction: zod.z.string().optional().describe("Action/URL when notification is clicked")
});
var CustomScriptActionSchema = zod.z.object({
  name: zod.z.string().describe("Action name"),
  type: zod.z.literal("custom_script"),
  language: zod.z.enum(["javascript", "typescript", "python"]).default("javascript").describe("Script language"),
  code: zod.z.string().describe("Script code to execute"),
  timeout: zod.z.number().default(3e4).describe("Execution timeout in milliseconds"),
  context: zod.z.record(zod.z.string(), zod.z.unknown()).optional().describe("Additional context variables")
});
var WorkflowActionSchema = zod.z.discriminatedUnion("type", [
  FieldUpdateActionSchema,
  EmailAlertActionSchema,
  HttpCallActionSchema,
  ConnectorActionRefSchema,
  TaskCreationActionSchema,
  PushNotificationActionSchema,
  CustomScriptActionSchema
]);
var TimeTriggerSchema = zod.z.object({
  id: zod.z.string().optional().describe("Unique identifier"),
  /** Timing Logic */
  timeLength: zod.z.number().int().describe("Duration amount (e.g. 1, 30)"),
  timeUnit: zod.z.enum(["minutes", "hours", "days"]).describe("Unit of time"),
  /** Reference Point */
  offsetDirection: zod.z.enum(["before", "after"]).describe("Before or After the reference date"),
  offsetFrom: zod.z.enum(["trigger_date", "date_field"]).describe("Basis for calculation"),
  dateField: zod.z.string().optional().describe("Date field to calculate from (required if offsetFrom is date_field)"),
  /** Actions */
  actions: zod.z.array(WorkflowActionSchema).describe("Actions to execute at the scheduled time")
});
var WorkflowRuleSchema = zod.z.object({
  /** Machine name */
  name: SnakeCaseIdentifierSchema.describe("Unique workflow name (lowercase snake_case)"),
  /** Target Object */
  objectName: zod.z.string().describe("Target Object"),
  /** When to evaluate the rule */
  triggerType: WorkflowTriggerType.describe("When to evaluate"),
  /** 
   * Condition to start the workflow.
   * If empty, runs on every trigger event.
   */
  criteria: zod.z.string().optional().describe("Formula condition. If TRUE, actions execute."),
  /** Actions to execute immediately */
  actions: zod.z.array(WorkflowActionSchema).optional().describe("Immediate actions"),
  /** 
   * Time-Dependent Actions 
   * Actions scheduled to run in the future.
   */
  timeTriggers: zod.z.array(TimeTriggerSchema).optional().describe("Scheduled actions relative to trigger or date field"),
  /** Active status */
  active: zod.z.boolean().default(true).describe("Whether this workflow is active"),
  /** Execution Order */
  executionOrder: zod.z.number().int().min(0).default(100).describe("Deterministic execution order when multiple workflows match (lower runs first)"),
  /** Recursion Control */
  reevaluateOnChange: zod.z.boolean().default(false).describe("Re-evaluate rule if field updates change the record validity")
});
var FlowNodeAction = zod.z.enum([
  "start",
  // Trigger
  "end",
  // Return/Stop
  "decision",
  // If/Else logic
  "assignment",
  // Set Variable
  "loop",
  // For Each
  "create_record",
  // CRUD: Create
  "update_record",
  // CRUD: Update
  "delete_record",
  // CRUD: Delete
  "get_record",
  // CRUD: Get/Query
  "http_request",
  // Webhook/API Call
  "script",
  // Custom Script (JS/TS)
  "screen",
  // Screen / User-Input Element
  "wait",
  // Delay/Sleep
  "subflow",
  // Call another flow
  "connector_action"
  // Zapier-style integration action
]);
var FlowVariableSchema = zod.z.object({
  name: zod.z.string().describe("Variable name"),
  type: zod.z.string().describe("Data type (text, number, boolean, object, list)"),
  isInput: zod.z.boolean().default(false).describe("Is input parameter"),
  isOutput: zod.z.boolean().default(false).describe("Is output parameter")
});
var FlowNodeSchema = zod.z.object({
  id: zod.z.string().describe("Node unique ID"),
  type: FlowNodeAction.describe("Action type"),
  label: zod.z.string().describe("Node label"),
  /** Node Configuration Options (Specific to type) */
  config: zod.z.record(zod.z.string(), zod.z.unknown()).optional().describe("Node configuration"),
  /** 
   * Connector Action Configuration
   * Used when type is 'connector_action'
   */
  connectorConfig: zod.z.object({
    connectorId: zod.z.string(),
    actionId: zod.z.string(),
    input: zod.z.record(zod.z.string(), zod.z.unknown()).describe("Mapped inputs for the action")
  }).optional(),
  /** UI Position (for the canvas) */
  position: zod.z.object({ x: zod.z.number(), y: zod.z.number() }).optional()
});
var FlowEdgeSchema = zod.z.object({
  id: zod.z.string().describe("Edge unique ID"),
  source: zod.z.string().describe("Source Node ID"),
  target: zod.z.string().describe("Target Node ID"),
  /** Condition for this path (only for decision/branch nodes) */
  condition: zod.z.string().optional().describe("Expression returning boolean used for branching"),
  type: zod.z.enum(["default", "fault"]).default("default").describe("Connection type: Standard (Success) or Fault (Error) path"),
  label: zod.z.string().optional().describe("Label on the connector")
});
var FlowSchema = zod.z.object({
  /** Identity */
  name: zod.z.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Machine name"),
  label: zod.z.string().describe("Flow label"),
  description: zod.z.string().optional(),
  /** Metadata & Versioning */
  version: zod.z.number().int().default(1).describe("Version number"),
  status: zod.z.enum(["draft", "active", "obsolete", "invalid"]).default("draft").describe("Deployment status"),
  template: zod.z.boolean().default(false).describe("Is logic template (Subflow)"),
  /** Trigger Type */
  type: zod.z.enum(["autolaunched", "record_change", "schedule", "screen", "api"]).describe("Flow type"),
  /** Configuration Variables */
  variables: zod.z.array(FlowVariableSchema).optional().describe("Flow variables"),
  /** Graph Definition */
  nodes: zod.z.array(FlowNodeSchema).describe("Flow nodes"),
  edges: zod.z.array(FlowEdgeSchema).describe("Flow connections"),
  /** Execution Config */
  active: zod.z.boolean().default(false).describe("Is active (Deprecated: use status)"),
  runAs: zod.z.enum(["system", "user"]).default("user").describe("Execution context"),
  /** Error Handling Strategy */
  errorHandling: zod.z.object({
    strategy: zod.z.enum(["fail", "retry", "continue"]).default("fail").describe("How to handle node execution errors"),
    maxRetries: zod.z.number().int().min(0).max(10).default(0).describe("Number of retry attempts (only for retry strategy)"),
    retryDelayMs: zod.z.number().int().min(0).default(1e3).describe("Delay between retries in milliseconds"),
    fallbackNodeId: zod.z.string().optional().describe("Node ID to jump to on unrecoverable error")
  }).optional().describe("Flow-level error handling configuration")
});
function defineFlow(config) {
  return FlowSchema.parse(config);
}
var WebhookTriggerType = zod.z.enum([
  "create",
  "update",
  "delete",
  "undelete",
  "api"
  // Manually triggered
]);
var WebhookSchema = zod.z.object({
  name: SnakeCaseIdentifierSchema.describe("Webhook unique name (lowercase snake_case)"),
  label: zod.z.string().optional().describe("Human-readable webhook label"),
  /** Scope */
  object: zod.z.string().optional().describe("Object to listen to (optional for manual webhooks)"),
  triggers: zod.z.array(WebhookTriggerType).optional().describe("Events that trigger execution"),
  /** Target */
  url: zod.z.string().url().describe("External webhook endpoint URL"),
  method: zod.z.enum(["GET", "POST", "PUT", "PATCH", "DELETE"]).default("POST").describe("HTTP method"),
  /** Headers */
  headers: zod.z.record(zod.z.string(), zod.z.string()).optional().describe("Custom HTTP headers"),
  /** Body/Payload */
  body: zod.z.unknown().optional().describe("Request body payload (if not using default record data)"),
  /** Payload Configuration */
  payloadFields: zod.z.array(zod.z.string()).optional().describe("Fields to include. Empty = All"),
  includeSession: zod.z.boolean().default(false).describe("Include user session info"),
  /** Authentication */
  authentication: zod.z.object({
    type: zod.z.enum(["none", "bearer", "basic", "api-key"]).describe("Authentication type"),
    credentials: zod.z.record(zod.z.string(), zod.z.string()).optional().describe("Authentication credentials")
  }).optional().describe("Authentication configuration"),
  /** Retry Policy */
  retryPolicy: zod.z.object({
    maxRetries: zod.z.number().int().min(0).max(10).default(3).describe("Maximum retry attempts"),
    backoffStrategy: zod.z.enum(["exponential", "linear", "fixed"]).default("exponential").describe("Backoff strategy"),
    initialDelayMs: zod.z.number().int().min(100).default(1e3).describe("Initial retry delay in milliseconds"),
    maxDelayMs: zod.z.number().int().min(1e3).default(6e4).describe("Maximum retry delay in milliseconds")
  }).optional().describe("Retry policy configuration"),
  /** Timeout */
  timeoutMs: zod.z.number().int().min(1e3).max(3e5).default(3e4).describe("Request timeout in milliseconds"),
  /** Security */
  secret: zod.z.string().optional().describe("Signing secret for HMAC signature verification"),
  /** Status */
  isActive: zod.z.boolean().default(true).describe("Whether webhook is active"),
  /** Metadata */
  description: zod.z.string().optional().describe("Webhook description"),
  tags: zod.z.array(zod.z.string()).optional().describe("Tags for organization")
});
var WebhookReceiverSchema = zod.z.object({
  name: SnakeCaseIdentifierSchema.describe("Webhook receiver unique name (lowercase snake_case)"),
  path: zod.z.string().describe("URL Path (e.g. /webhooks/stripe)"),
  /** Verification */
  verificationType: zod.z.enum(["none", "header_token", "hmac", "ip_whitelist"]).default("none"),
  verificationParams: zod.z.object({
    header: zod.z.string().optional(),
    secret: zod.z.string().optional(),
    ips: zod.z.array(zod.z.string()).optional()
  }).optional(),
  /** Action */
  action: zod.z.enum(["trigger_flow", "script", "upsert_record"]).default("trigger_flow"),
  target: zod.z.string().describe("Flow ID or Script name")
});
var ApproverType = zod.z.enum([
  "user",
  // Specific user(s)
  "role",
  // Users with specific role
  "manager",
  // Submitter's manager
  "field",
  // User ID defined in a record field
  "queue"
  // Data ownership queue
]);
var ApprovalActionType = zod.z.enum([
  "field_update",
  "email_alert",
  "webhook",
  "script",
  "connector_action"
  // Added for Zapier-style integrations
]);
var ApprovalActionSchema = zod.z.object({
  type: ApprovalActionType,
  name: zod.z.string().describe("Action name"),
  config: zod.z.record(zod.z.string(), zod.z.unknown()).describe("Action configuration"),
  /** For connector actions */
  connectorId: zod.z.string().optional(),
  actionId: zod.z.string().optional()
});
var ApprovalStepSchema = zod.z.object({
  name: SnakeCaseIdentifierSchema.describe("Step machine name"),
  label: zod.z.string().describe("Step display label"),
  description: zod.z.string().optional(),
  /** Entry criteria for this step */
  entryCriteria: zod.z.string().optional().describe("Formula expression to enter this step"),
  /** Who can approve */
  approvers: zod.z.array(zod.z.object({
    type: ApproverType,
    value: zod.z.string().describe("User ID, Role Name, or Field Name")
  })).min(1).describe("List of allowed approvers"),
  /** Approval Logic */
  behavior: zod.z.enum(["first_response", "unanimous"]).default("first_response").describe("How to handle multiple approvers"),
  /** Rejection behavior */
  rejectionBehavior: zod.z.enum(["reject_process", "back_to_previous"]).default("reject_process").describe("What happens if rejected"),
  /** Actions */
  onApprove: zod.z.array(ApprovalActionSchema).optional().describe("Actions on step approval"),
  onReject: zod.z.array(ApprovalActionSchema).optional().describe("Actions on step rejection")
});
var ApprovalProcessSchema = zod.z.object({
  name: SnakeCaseIdentifierSchema.describe("Unique process name"),
  label: zod.z.string().describe("Human readable label"),
  object: zod.z.string().describe("Target Object Name"),
  active: zod.z.boolean().default(false),
  description: zod.z.string().optional(),
  /** Entry Criteria for the entire process */
  entryCriteria: zod.z.string().optional().describe("Formula to allow submission"),
  /** Record Locking */
  lockRecord: zod.z.boolean().default(true).describe("Lock record from editing during approval"),
  /** Steps */
  steps: zod.z.array(ApprovalStepSchema).min(1).describe("Sequence of approval steps"),
  /** Escalation Configuration (SLA-based auto-escalation) */
  escalation: zod.z.object({
    enabled: zod.z.boolean().default(false).describe("Enable SLA-based escalation"),
    timeoutHours: zod.z.number().min(1).describe("Hours before escalation triggers"),
    action: zod.z.enum(["reassign", "auto_approve", "auto_reject", "notify"]).default("notify").describe("Action to take on escalation timeout"),
    escalateTo: zod.z.string().optional().describe("User ID, role, or manager level to escalate to"),
    notifySubmitter: zod.z.boolean().default(true).describe("Notify the original submitter on escalation")
  }).optional().describe("SLA escalation configuration for pending approval steps"),
  /** Global Actions */
  onSubmit: zod.z.array(ApprovalActionSchema).optional().describe("Actions on initial submission"),
  onFinalApprove: zod.z.array(ApprovalActionSchema).optional().describe("Actions on final approval"),
  onFinalReject: zod.z.array(ApprovalActionSchema).optional().describe("Actions on final rejection"),
  onRecall: zod.z.array(ApprovalActionSchema).optional().describe("Actions on recall")
});
var ApprovalProcess = Object.assign(ApprovalProcessSchema, {
  create: (config) => config
});
var ETLEndpointTypeSchema = zod.z.enum([
  "database",
  // SQL/NoSQL databases
  "api",
  // REST/GraphQL APIs
  "file",
  // CSV, JSON, XML, Excel files
  "stream",
  // Kafka, RabbitMQ, Kinesis
  "object",
  // ObjectStack object
  "warehouse",
  // Data warehouse (Snowflake, BigQuery, Redshift)
  "storage",
  // S3, Azure Blob, Google Cloud Storage
  "spreadsheet"
  // Google Sheets, Excel Online
]);
var ETLSourceSchema = zod.z.object({
  /**
   * Source type
   */
  type: ETLEndpointTypeSchema.describe("Source type"),
  /**
   * Connector identifier
   * References a registered connector
   * 
   * @example "salesforce", "postgres", "mysql", "s3"
   */
  connector: zod.z.string().optional().describe("Connector ID"),
  /**
   * Source-specific configuration
   * Structure varies by source type
   * 
   * @example For database: { table: 'customers', schema: 'public' }
   * @example For API: { endpoint: '/api/users', method: 'GET' }
   * @example For file: { path: 's3://bucket/data.csv', format: 'csv' }
   */
  config: zod.z.record(zod.z.string(), zod.z.unknown()).describe("Source configuration"),
  /**
   * Incremental sync configuration
   * Allows extracting only changed data
   */
  incremental: zod.z.object({
    enabled: zod.z.boolean().default(false),
    cursorField: zod.z.string().describe("Field to track progress (e.g., updated_at)"),
    cursorValue: zod.z.unknown().optional().describe("Last processed value")
  }).optional().describe("Incremental extraction config")
});
var ETLDestinationSchema = zod.z.object({
  /**
   * Destination type
   */
  type: ETLEndpointTypeSchema.describe("Destination type"),
  /**
   * Connector identifier
   */
  connector: zod.z.string().optional().describe("Connector ID"),
  /**
   * Destination-specific configuration
   */
  config: zod.z.record(zod.z.string(), zod.z.unknown()).describe("Destination configuration"),
  /**
   * Write mode
   */
  writeMode: zod.z.enum([
    "append",
    // Add new records
    "overwrite",
    // Replace all data
    "upsert",
    // Insert or update based on key
    "merge"
    // Smart merge based on business rules
  ]).default("append").describe("How to write data"),
  /**
   * Primary key fields for upsert/merge
   */
  primaryKey: zod.z.array(zod.z.string()).optional().describe("Primary key fields")
});
var ETLTransformationTypeSchema = zod.z.enum([
  "map",
  // Field mapping/renaming
  "filter",
  // Row filtering
  "aggregate",
  // Aggregation/grouping
  "join",
  // Joining with other data
  "script",
  // Custom JavaScript/Python script
  "lookup",
  // Enrich with lookup data
  "split",
  // Split one record into multiple
  "merge",
  // Merge multiple records into one
  "normalize",
  // Data normalization
  "deduplicate"
  // Remove duplicates
]);
var ETLTransformationSchema = zod.z.object({
  /**
   * Transformation name
   */
  name: zod.z.string().optional().describe("Transformation name"),
  /**
   * Transformation type
   */
  type: ETLTransformationTypeSchema.describe("Transformation type"),
  /**
   * Transformation-specific configuration
   * 
   * @example For map: { oldField: 'newField' }
   * @example For filter: { condition: 'status == "active"' }
   * @example For script: { language: 'javascript', code: '...' }
   */
  config: zod.z.record(zod.z.string(), zod.z.unknown()).describe("Transformation config"),
  /**
   * Whether to continue on error
   */
  continueOnError: zod.z.boolean().default(false).describe("Continue on error")
});
var ETLSyncModeSchema = zod.z.enum([
  "full",
  // Full refresh - extract all data every time
  "incremental",
  // Only extract changed data
  "cdc"
  // Change Data Capture - real-time streaming
]);
var ETLPipelineSchema = zod.z.object({
  /**
   * Pipeline identifier (snake_case)
   */
  name: zod.z.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Pipeline identifier (snake_case)"),
  /**
   * Human-readable pipeline name
   */
  label: zod.z.string().optional().describe("Pipeline display name"),
  /**
   * Pipeline description
   */
  description: zod.z.string().optional().describe("Pipeline description"),
  /**
   * Data source configuration
   */
  source: ETLSourceSchema.describe("Data source"),
  /**
   * Data destination configuration
   */
  destination: ETLDestinationSchema.describe("Data destination"),
  /**
   * Transformation steps
   * Applied in order from source to destination
   */
  transformations: zod.z.array(ETLTransformationSchema).optional().describe("Transformation pipeline"),
  /**
   * Sync mode
   */
  syncMode: ETLSyncModeSchema.default("full").describe("Sync mode"),
  /**
   * Execution schedule (cron expression)
   * 
   * @example "0 2 * * *" - Daily at 2 AM
   * @example "0 *\/4 * * *" - Every 4 hours
   * @example "0 0 * * 0" - Weekly on Sunday
   */
  schedule: zod.z.string().optional().describe("Cron schedule expression"),
  /**
   * Whether pipeline is enabled
   */
  enabled: zod.z.boolean().default(true).describe("Pipeline enabled status"),
  /**
   * Retry configuration for failed runs
   */
  retry: zod.z.object({
    maxAttempts: zod.z.number().int().min(0).default(3).describe("Max retry attempts"),
    backoffMs: zod.z.number().int().min(0).default(6e4).describe("Backoff in milliseconds")
  }).optional().describe("Retry configuration"),
  /**
   * Notification configuration
   */
  notifications: zod.z.object({
    onSuccess: zod.z.array(zod.z.string()).optional().describe("Email addresses for success notifications"),
    onFailure: zod.z.array(zod.z.string()).optional().describe("Email addresses for failure notifications")
  }).optional().describe("Notification settings"),
  /**
   * Pipeline tags for organization
   */
  tags: zod.z.array(zod.z.string()).optional().describe("Pipeline tags"),
  /**
   * Custom metadata
   */
  metadata: zod.z.record(zod.z.string(), zod.z.unknown()).optional().describe("Custom metadata")
});
var ETLRunStatusSchema = zod.z.enum([
  "pending",
  // Queued for execution
  "running",
  // Currently executing
  "succeeded",
  // Completed successfully
  "failed",
  // Failed with errors
  "cancelled",
  // Manually cancelled
  "timeout"
  // Timed out
]);
var ETLPipelineRunSchema = zod.z.object({
  /**
   * Run ID
   */
  id: zod.z.string().describe("Run identifier"),
  /**
   * Pipeline name
   */
  pipelineName: zod.z.string().describe("Pipeline name"),
  /**
   * Run status
   */
  status: ETLRunStatusSchema.describe("Run status"),
  /**
   * Start timestamp
   */
  startedAt: zod.z.string().datetime().describe("Start time"),
  /**
   * End timestamp
   */
  completedAt: zod.z.string().datetime().optional().describe("Completion time"),
  /**
   * Duration in milliseconds
   */
  durationMs: zod.z.number().optional().describe("Duration in ms"),
  /**
   * Statistics
   */
  stats: zod.z.object({
    recordsRead: zod.z.number().int().default(0).describe("Records extracted"),
    recordsWritten: zod.z.number().int().default(0).describe("Records loaded"),
    recordsErrored: zod.z.number().int().default(0).describe("Records with errors"),
    bytesProcessed: zod.z.number().int().default(0).describe("Bytes processed")
  }).optional().describe("Run statistics"),
  /**
   * Error information
   */
  error: zod.z.object({
    message: zod.z.string().describe("Error message"),
    code: zod.z.string().optional().describe("Error code"),
    details: zod.z.unknown().optional().describe("Error details")
  }).optional().describe("Error information"),
  /**
   * Execution logs
   */
  logs: zod.z.array(zod.z.string()).optional().describe("Execution logs")
});
var ETL = {
  /**
   * Create a simple database-to-database pipeline
   */
  databaseSync: (params) => ({
    name: params.name,
    source: {
      type: "database",
      config: { table: params.sourceTable }
    },
    destination: {
      type: "database",
      config: { table: params.destTable },
      writeMode: "upsert"
    },
    syncMode: "incremental",
    schedule: params.schedule,
    enabled: true
  }),
  /**
   * Create an API to database pipeline
   */
  apiToDatabase: (params) => ({
    name: params.name,
    source: {
      type: "api",
      connector: params.apiConnector,
      config: {}
    },
    destination: {
      type: "database",
      config: { table: params.destTable },
      writeMode: "append"
    },
    syncMode: "full",
    schedule: params.schedule,
    enabled: true
  })
};
var ConnectorCategorySchema = zod.z.enum([
  "crm",
  // Customer Relationship Management
  "payment",
  // Payment processors
  "communication",
  // Email, SMS, Chat
  "storage",
  // File storage
  "analytics",
  // Analytics platforms
  "database",
  // Databases
  "marketing",
  // Marketing automation
  "accounting",
  // Accounting software
  "hr",
  // Human resources
  "productivity",
  // Productivity tools
  "ecommerce",
  // E-commerce platforms
  "support",
  // Customer support
  "devtools",
  // Developer tools
  "social",
  // Social media
  "other"
  // Other category
]);
var AuthenticationTypeSchema = zod.z.enum([
  "none",
  // No authentication
  "apiKey",
  // API key
  "basic",
  // Basic auth (username/password)
  "bearer",
  // Bearer token
  "oauth1",
  // OAuth 1.0
  "oauth2",
  // OAuth 2.0
  "custom"
  // Custom authentication
]);
var AuthFieldSchema = zod.z.object({
  /**
   * Field name (machine name)
   */
  name: zod.z.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Field name (snake_case)"),
  /**
   * Field label
   */
  label: zod.z.string().describe("Field label"),
  /**
   * Field type
   */
  type: zod.z.enum(["text", "password", "url", "select"]).default("text").describe("Field type"),
  /**
   * Field description
   */
  description: zod.z.string().optional().describe("Field description"),
  /**
   * Whether field is required
   */
  required: zod.z.boolean().default(true).describe("Required field"),
  /**
   * Default value
   */
  default: zod.z.string().optional().describe("Default value"),
  /**
   * Options for select fields
   */
  options: zod.z.array(zod.z.object({
    label: zod.z.string(),
    value: zod.z.string()
  })).optional().describe("Select field options"),
  /**
   * Placeholder text
   */
  placeholder: zod.z.string().optional().describe("Placeholder text")
});
var OAuth2ConfigSchema = zod.z.object({
  /**
   * Authorization URL
   */
  authorizationUrl: zod.z.string().url().describe("Authorization endpoint URL"),
  /**
   * Token URL
   */
  tokenUrl: zod.z.string().url().describe("Token endpoint URL"),
  /**
   * Scopes to request
   */
  scopes: zod.z.array(zod.z.string()).optional().describe("OAuth scopes"),
  /**
   * Client ID field name
   */
  clientIdField: zod.z.string().default("client_id").describe("Client ID field name"),
  /**
   * Client secret field name
   */
  clientSecretField: zod.z.string().default("client_secret").describe("Client secret field name")
});
var AuthenticationSchema = zod.z.object({
  /**
   * Authentication type
   */
  type: AuthenticationTypeSchema.describe("Authentication type"),
  /**
   * Authentication fields
   * Configuration fields needed for this auth type
   */
  fields: zod.z.array(AuthFieldSchema).optional().describe("Authentication fields"),
  /**
   * OAuth 2.0 configuration (when type is oauth2)
   */
  oauth2: OAuth2ConfigSchema.optional().describe("OAuth 2.0 configuration"),
  /**
   * Test authentication instructions
   */
  test: zod.z.object({
    url: zod.z.string().optional().describe("Test endpoint URL"),
    method: zod.z.enum(["GET", "POST", "PUT", "DELETE"]).default("GET").describe("HTTP method")
  }).optional().describe("Authentication test configuration")
});
var OperationTypeSchema = zod.z.enum([
  "read",
  // Read/query data
  "write",
  // Create/update data
  "delete",
  // Delete data
  "search",
  // Search operation
  "trigger",
  // Webhook/polling trigger
  "action"
  // Custom action
]);
var OperationParameterSchema = zod.z.object({
  /**
   * Parameter name
   */
  name: zod.z.string().describe("Parameter name"),
  /**
   * Parameter label
   */
  label: zod.z.string().describe("Parameter label"),
  /**
   * Parameter description
   */
  description: zod.z.string().optional().describe("Parameter description"),
  /**
   * Parameter type
   */
  type: zod.z.enum(["string", "number", "boolean", "array", "object", "date", "file"]).describe("Parameter type"),
  /**
   * Whether parameter is required
   */
  required: zod.z.boolean().default(false).describe("Required parameter"),
  /**
   * Default value
   */
  default: zod.z.unknown().optional().describe("Default value"),
  /**
   * Validation schema
   */
  validation: zod.z.record(zod.z.string(), zod.z.unknown()).optional().describe("Validation rules"),
  /**
   * Dynamic options function
   */
  dynamicOptions: zod.z.string().optional().describe("Function to load dynamic options")
});
var ConnectorOperationSchema = zod.z.object({
  /**
   * Operation identifier
   */
  id: zod.z.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Operation ID (snake_case)"),
  /**
   * Operation name
   */
  name: zod.z.string().describe("Operation name"),
  /**
   * Operation description
   */
  description: zod.z.string().optional().describe("Operation description"),
  /**
   * Operation type
   */
  type: OperationTypeSchema.describe("Operation type"),
  /**
   * Input parameters
   */
  inputSchema: zod.z.array(OperationParameterSchema).optional().describe("Input parameters"),
  /**
   * Output schema
   */
  outputSchema: zod.z.record(zod.z.string(), zod.z.unknown()).optional().describe("Output schema"),
  /**
   * Sample output for documentation
   */
  sampleOutput: zod.z.unknown().optional().describe("Sample output"),
  /**
   * Whether operation supports pagination
   */
  supportsPagination: zod.z.boolean().default(false).describe("Supports pagination"),
  /**
   * Whether operation supports filtering
   */
  supportsFiltering: zod.z.boolean().default(false).describe("Supports filtering")
});
var ConnectorTriggerSchema = zod.z.object({
  /**
   * Trigger identifier
   */
  id: zod.z.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Trigger ID (snake_case)"),
  /**
   * Trigger name
   */
  name: zod.z.string().describe("Trigger name"),
  /**
   * Trigger description
   */
  description: zod.z.string().optional().describe("Trigger description"),
  /**
   * Trigger type
   */
  type: zod.z.enum(["webhook", "polling", "stream"]).describe("Trigger mechanism"),
  /**
   * Trigger configuration
   */
  config: zod.z.record(zod.z.string(), zod.z.unknown()).optional().describe("Trigger configuration"),
  /**
   * Output schema
   */
  outputSchema: zod.z.record(zod.z.string(), zod.z.unknown()).optional().describe("Event payload schema"),
  /**
   * Polling interval (for polling triggers)
   * In milliseconds
   */
  pollingIntervalMs: zod.z.number().int().min(1e3).optional().describe("Polling interval in ms")
});
var ConnectorSchema = zod.z.object({
  /**
   * Connector identifier
   * Must be globally unique
   */
  id: zod.z.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Connector ID (snake_case)"),
  /**
   * Connector name
   */
  name: zod.z.string().describe("Connector name"),
  /**
   * Connector description
   */
  description: zod.z.string().optional().describe("Connector description"),
  /**
   * Connector version (semver)
   */
  version: zod.z.string().optional().describe("Connector version"),
  /**
   * Connector icon URL or name
   */
  icon: zod.z.string().optional().describe("Connector icon"),
  /**
   * Connector category
   */
  category: ConnectorCategorySchema.describe("Connector category"),
  /**
   * Base URL for API calls
   */
  baseUrl: zod.z.string().url().optional().describe("API base URL"),
  /**
   * Authentication configuration
   */
  authentication: AuthenticationSchema.describe("Authentication config"),
  /**
   * Available operations
   */
  operations: zod.z.array(ConnectorOperationSchema).optional().describe("Connector operations"),
  /**
   * Available triggers
   */
  triggers: zod.z.array(ConnectorTriggerSchema).optional().describe("Connector triggers"),
  /**
   * Rate limiting information
   */
  rateLimit: zod.z.object({
    requestsPerSecond: zod.z.number().optional().describe("Max requests per second"),
    requestsPerMinute: zod.z.number().optional().describe("Max requests per minute"),
    requestsPerHour: zod.z.number().optional().describe("Max requests per hour")
  }).optional().describe("Rate limiting"),
  /**
   * Connector author
   */
  author: zod.z.string().optional().describe("Connector author"),
  /**
   * Documentation URL
   */
  documentation: zod.z.string().url().optional().describe("Documentation URL"),
  /**
   * Homepage URL
   */
  homepage: zod.z.string().url().optional().describe("Homepage URL"),
  /**
   * License
   */
  license: zod.z.string().optional().describe("License (SPDX identifier)"),
  /**
   * Tags for discovery
   */
  tags: zod.z.array(zod.z.string()).optional().describe("Connector tags"),
  /**
   * Whether connector is verified/certified
   */
  verified: zod.z.boolean().default(false).describe("Verified connector"),
  /**
   * Custom metadata
   */
  metadata: zod.z.record(zod.z.string(), zod.z.unknown()).optional().describe("Custom metadata")
});
var ConnectorInstanceSchema = zod.z.object({
  /**
   * Instance ID
   */
  id: zod.z.string().describe("Instance ID"),
  /**
   * Connector ID this instance uses
   */
  connectorId: zod.z.string().describe("Connector ID"),
  /**
   * Instance name
   */
  name: zod.z.string().describe("Instance name"),
  /**
   * Instance description
   */
  description: zod.z.string().optional().describe("Instance description"),
  /**
   * Authentication credentials (encrypted)
   */
  credentials: zod.z.record(zod.z.string(), zod.z.unknown()).describe("Encrypted credentials"),
  /**
   * Additional configuration
   */
  config: zod.z.record(zod.z.string(), zod.z.unknown()).optional().describe("Additional config"),
  /**
   * Whether instance is active
   */
  active: zod.z.boolean().default(true).describe("Instance active status"),
  /**
   * Created timestamp
   */
  createdAt: zod.z.string().datetime().optional().describe("Creation time"),
  /**
   * Last tested timestamp
   */
  lastTestedAt: zod.z.string().datetime().optional().describe("Last test time"),
  /**
   * Test status
   */
  testStatus: zod.z.enum(["unknown", "success", "failed"]).default("unknown").describe("Connection test status")
});
var Connector = {
  /**
   * Create a basic API key connector
   */
  apiKey: (params) => ({
    id: params.id,
    name: params.name,
    category: params.category,
    baseUrl: params.baseUrl,
    authentication: {
      type: "apiKey",
      fields: [
        {
          name: "api_key",
          label: "API Key",
          type: "password",
          required: true
        }
      ]
    },
    verified: false
  }),
  /**
   * Create an OAuth 2.0 connector
   */
  oauth2: (params) => ({
    id: params.id,
    name: params.name,
    category: params.category,
    baseUrl: params.baseUrl,
    authentication: {
      type: "oauth2",
      oauth2: {
        authorizationUrl: params.authUrl,
        tokenUrl: params.tokenUrl,
        clientIdField: "client_id",
        clientSecretField: "client_secret",
        scopes: params.scopes
      }
    },
    verified: false
  })
};
var TransformTypeSchema = zod.z.discriminatedUnion("type", [
  zod.z.object({
    type: zod.z.literal("constant"),
    value: zod.z.unknown().describe("Constant value to use")
  }).describe("Set a constant value"),
  zod.z.object({
    type: zod.z.literal("cast"),
    targetType: zod.z.enum(["string", "number", "boolean", "date"]).describe("Target data type")
  }).describe("Cast to a specific data type"),
  zod.z.object({
    type: zod.z.literal("lookup"),
    table: zod.z.string().describe("Lookup table name"),
    keyField: zod.z.string().describe("Field to match on"),
    valueField: zod.z.string().describe("Field to retrieve")
  }).describe("Lookup value from another table"),
  zod.z.object({
    type: zod.z.literal("javascript"),
    expression: zod.z.string().describe('JavaScript expression (e.g., "value.toUpperCase()")')
  }).describe("Custom JavaScript transformation"),
  zod.z.object({
    type: zod.z.literal("map"),
    mappings: zod.z.record(zod.z.string(), zod.z.unknown()).describe('Value mappings (e.g., {"Active": "active"})')
  }).describe("Map values using a dictionary")
]);
var FieldMappingSchema = zod.z.object({
  /**
   * Source field name
   */
  source: zod.z.string().describe("Source field name"),
  /**
   * Target field name (should be snake_case for ObjectStack)
   */
  target: zod.z.string().describe("Target field name"),
  /**
   * Transformation to apply
   */
  transform: TransformTypeSchema.optional().describe("Transformation to apply"),
  /**
   * Default value if source is null/undefined
   */
  defaultValue: zod.z.unknown().optional().describe("Default if source is null/undefined")
});

// src/automation/sync.zod.ts
var SyncDirectionSchema = zod.z.enum([
  "push",
  // ObjectStack -> External (one-way)
  "pull",
  // External -> ObjectStack (one-way)
  "bidirectional"
  // Both directions
]);
var SyncModeSchema = zod.z.enum([
  "full",
  // Full refresh every time
  "incremental",
  // Only sync changed records
  "realtime"
  // Real-time streaming sync
]);
var ConflictResolutionSchema = zod.z.enum([
  "source_wins",
  // Source system always wins
  "destination_wins",
  // Destination system always wins
  "latest_wins",
  // Most recently modified wins
  "manual",
  // Flag for manual resolution
  "merge"
  // Smart merge (custom logic)
]);
var DataSourceConfigSchema = zod.z.object({
  /**
   * Source object name
   * For ObjectStack objects
   */
  object: zod.z.string().optional().describe("ObjectStack object name"),
  /**
   * Filter conditions
   * Only sync records matching these filters
   */
  filters: zod.z.unknown().optional().describe("Filter conditions"),
  /**
   * Fields to include
   * If not specified, all fields are synced
   */
  fields: zod.z.array(zod.z.string()).optional().describe("Fields to sync"),
  /**
   * External connector instance ID
   * For external data sources
   */
  connectorInstanceId: zod.z.string().optional().describe("Connector instance ID"),
  /**
   * External resource identifier
   * e.g., Salesforce object name, database table, API endpoint
   */
  externalResource: zod.z.string().optional().describe("External resource ID")
});
var DataDestinationConfigSchema = zod.z.object({
  /**
   * Destination object name
   * For ObjectStack objects
   */
  object: zod.z.string().optional().describe("ObjectStack object name"),
  /**
   * Connector instance ID
   * For external destinations
   */
  connectorInstanceId: zod.z.string().optional().describe("Connector instance ID"),
  /**
   * Operation to perform
   */
  operation: zod.z.enum([
    "insert",
    // Create new records only
    "update",
    // Update existing records only
    "upsert",
    // Insert or update based on key
    "delete",
    // Delete records
    "sync"
    // Full synchronization
  ]).describe("Sync operation"),
  /**
   * Field mappings
   * Maps source fields to destination fields
   */
  mapping: zod.z.union([
    zod.z.record(zod.z.string(), zod.z.string()),
    // Simple mapping: { sourceField: 'destField' }
    zod.z.array(FieldMappingSchema)
    // Advanced mapping with transformations
  ]).optional().describe("Field mappings"),
  /**
   * External resource identifier
   */
  externalResource: zod.z.string().optional().describe("External resource ID"),
  /**
   * Match key for upsert operations
   * Fields to use for matching existing records
   */
  matchKey: zod.z.array(zod.z.string()).optional().describe("Match key fields")
});
var DataSyncConfigSchema = zod.z.object({
  /**
   * Sync configuration name (snake_case)
   */
  name: zod.z.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Sync configuration name (snake_case)"),
  /**
   * Human-readable label
   */
  label: zod.z.string().optional().describe("Sync display name"),
  /**
   * Description
   */
  description: zod.z.string().optional().describe("Sync description"),
  /**
   * Source configuration
   */
  source: DataSourceConfigSchema.describe("Data source"),
  /**
   * Destination configuration
   */
  destination: DataDestinationConfigSchema.describe("Data destination"),
  /**
   * Sync direction
   */
  direction: SyncDirectionSchema.default("push").describe("Sync direction"),
  /**
   * Sync mode
   */
  syncMode: SyncModeSchema.default("incremental").describe("Sync mode"),
  /**
   * Conflict resolution strategy
   */
  conflictResolution: ConflictResolutionSchema.default("latest_wins").describe("Conflict resolution"),
  /**
   * Execution schedule (cron expression)
   * For scheduled syncs
   * 
   * @example "0 * * * *" - Hourly
   * @example "*\/15 * * * *" - Every 15 minutes
   */
  schedule: zod.z.string().optional().describe("Cron schedule"),
  /**
   * Whether sync is enabled
   */
  enabled: zod.z.boolean().default(true).describe("Sync enabled"),
  /**
   * Change tracking field
   * Field to track when records were last modified
   * Used for incremental sync
   * 
   * @example "updated_at", "modified_date"
   */
  changeTrackingField: zod.z.string().optional().describe("Field for change tracking"),
  /**
   * Batch size
   * Number of records to process per batch
   */
  batchSize: zod.z.number().int().min(1).max(1e4).default(100).describe("Batch size for processing"),
  /**
   * Retry configuration
   */
  retry: zod.z.object({
    maxAttempts: zod.z.number().int().min(0).default(3).describe("Max retries"),
    backoffMs: zod.z.number().int().min(0).default(3e4).describe("Backoff duration")
  }).optional().describe("Retry configuration"),
  /**
   * Pre-sync validation rules
   */
  validation: zod.z.object({
    required: zod.z.array(zod.z.string()).optional().describe("Required fields"),
    unique: zod.z.array(zod.z.string()).optional().describe("Unique constraint fields"),
    custom: zod.z.array(zod.z.object({
      name: zod.z.string(),
      condition: zod.z.string().describe("Validation condition"),
      message: zod.z.string().describe("Error message")
    })).optional().describe("Custom validation rules")
  }).optional().describe("Validation rules"),
  /**
   * Error handling configuration
   */
  errorHandling: zod.z.object({
    onValidationError: zod.z.enum(["skip", "fail", "log"]).default("skip"),
    onSyncError: zod.z.enum(["skip", "fail", "retry"]).default("retry"),
    notifyOnError: zod.z.array(zod.z.string()).optional().describe("Email notifications")
  }).optional().describe("Error handling"),
  /**
   * Performance optimization
   */
  optimization: zod.z.object({
    parallelBatches: zod.z.boolean().default(false).describe("Process batches in parallel"),
    cacheEnabled: zod.z.boolean().default(true).describe("Enable caching"),
    compressionEnabled: zod.z.boolean().default(false).describe("Enable compression")
  }).optional().describe("Performance optimization"),
  /**
   * Audit and logging
   */
  audit: zod.z.object({
    logLevel: zod.z.enum(["none", "error", "warn", "info", "debug"]).default("info"),
    retainLogsForDays: zod.z.number().int().min(1).default(30),
    trackChanges: zod.z.boolean().default(true).describe("Track all changes")
  }).optional().describe("Audit configuration"),
  /**
   * Tags for organization
   */
  tags: zod.z.array(zod.z.string()).optional().describe("Sync tags"),
  /**
   * Custom metadata
   */
  metadata: zod.z.record(zod.z.string(), zod.z.unknown()).optional().describe("Custom metadata")
});
var SyncExecutionStatusSchema = zod.z.enum([
  "pending",
  // Queued
  "running",
  // Currently executing
  "completed",
  // Successfully completed
  "partial",
  // Completed with some errors
  "failed",
  // Failed
  "cancelled"
  // Manually cancelled
]);
var SyncExecutionResultSchema = zod.z.object({
  /**
   * Execution ID
   */
  id: zod.z.string().describe("Execution ID"),
  /**
   * Sync configuration name
   */
  syncName: zod.z.string().describe("Sync name"),
  /**
   * Execution status
   */
  status: SyncExecutionStatusSchema.describe("Execution status"),
  /**
   * Start timestamp
   */
  startedAt: zod.z.string().datetime().describe("Start time"),
  /**
   * End timestamp
   */
  completedAt: zod.z.string().datetime().optional().describe("Completion time"),
  /**
   * Duration in milliseconds
   */
  durationMs: zod.z.number().optional().describe("Duration in ms"),
  /**
   * Statistics
   */
  stats: zod.z.object({
    recordsProcessed: zod.z.number().int().default(0).describe("Total records processed"),
    recordsInserted: zod.z.number().int().default(0).describe("Records inserted"),
    recordsUpdated: zod.z.number().int().default(0).describe("Records updated"),
    recordsDeleted: zod.z.number().int().default(0).describe("Records deleted"),
    recordsSkipped: zod.z.number().int().default(0).describe("Records skipped"),
    recordsErrored: zod.z.number().int().default(0).describe("Records with errors"),
    conflictsDetected: zod.z.number().int().default(0).describe("Conflicts detected"),
    conflictsResolved: zod.z.number().int().default(0).describe("Conflicts resolved")
  }).optional().describe("Execution statistics"),
  /**
   * Errors encountered
   */
  errors: zod.z.array(zod.z.object({
    recordId: zod.z.string().optional().describe("Record ID"),
    field: zod.z.string().optional().describe("Field name"),
    message: zod.z.string().describe("Error message"),
    code: zod.z.string().optional().describe("Error code")
  })).optional().describe("Errors"),
  /**
   * Execution logs
   */
  logs: zod.z.array(zod.z.string()).optional().describe("Execution logs")
});
var Sync = {
  /**
   * Create a simple object-to-object sync
   */
  objectSync: (params) => ({
    name: params.name,
    source: {
      object: params.sourceObject
    },
    destination: {
      object: params.destObject,
      operation: "upsert",
      mapping: params.mapping
    },
    direction: "push",
    syncMode: "incremental",
    conflictResolution: "latest_wins",
    batchSize: 100,
    schedule: params.schedule,
    enabled: true
  }),
  /**
   * Create a connector sync
   */
  connectorSync: (params) => ({
    name: params.name,
    source: {
      object: params.sourceObject
    },
    destination: {
      connectorInstanceId: params.connectorInstanceId,
      externalResource: params.externalResource,
      operation: "upsert",
      mapping: params.mapping
    },
    direction: "push",
    syncMode: "incremental",
    conflictResolution: "latest_wins",
    batchSize: 100,
    schedule: params.schedule,
    enabled: true
  }),
  /**
   * Create a bidirectional sync
   */
  bidirectionalSync: (params) => ({
    name: params.name,
    source: {
      object: params.object
    },
    destination: {
      connectorInstanceId: params.connectorInstanceId,
      externalResource: params.externalResource,
      operation: "sync",
      mapping: params.mapping
    },
    direction: "bidirectional",
    syncMode: "incremental",
    conflictResolution: "latest_wins",
    batchSize: 100,
    schedule: params.schedule,
    enabled: true
  })
};
var ActionRefSchema = zod.z.union([
  zod.z.string().describe("Action Name"),
  zod.z.object({
    type: zod.z.string(),
    // e.g., 'xstate.assign', 'log', 'email'
    params: zod.z.record(zod.z.string(), zod.z.unknown()).optional()
  })
]);
var GuardRefSchema = zod.z.union([
  zod.z.string().describe('Guard Name (e.g., "isManager", "amountGT1000")'),
  zod.z.object({
    type: zod.z.string(),
    params: zod.z.record(zod.z.string(), zod.z.unknown()).optional()
  })
]);
var TransitionSchema = zod.z.object({
  target: zod.z.string().optional().describe("Target State ID"),
  cond: GuardRefSchema.optional().describe("Condition (Guard) required to take this path"),
  actions: zod.z.array(ActionRefSchema).optional().describe("Actions to execute during transition"),
  description: zod.z.string().optional().describe("Human readable description of this rule")
});
var EventSchema = zod.z.object({
  type: zod.z.string().describe('Event Type (e.g. "APPROVE", "REJECT", "Submit")'),
  // Payload validation schema could go here if we want deep validation
  schema: zod.z.record(zod.z.string(), zod.z.unknown()).optional().describe("Expected event payload structure")
});
var StateNodeSchema = zod.z.lazy(() => zod.z.object({
  /** Type of state */
  type: zod.z.enum(["atomic", "compound", "parallel", "final", "history"]).default("atomic"),
  /** Entry/Exit Actions */
  entry: zod.z.array(ActionRefSchema).optional().describe("Actions to run when entering this state"),
  exit: zod.z.array(ActionRefSchema).optional().describe("Actions to run when leaving this state"),
  /** Transitions (Events) */
  on: zod.z.record(zod.z.string(), zod.z.union([
    zod.z.string(),
    // Shorthand target
    TransitionSchema,
    zod.z.array(TransitionSchema)
  ])).optional().describe("Map of Event Type -> Transition Definition"),
  /** Always Transitions (Eventless) */
  always: zod.z.array(TransitionSchema).optional(),
  /** Nesting (Hierarchical States) */
  initial: zod.z.string().optional().describe("Initial child state (if compound)"),
  states: zod.z.record(zod.z.string(), StateNodeSchema).optional(),
  /** Metadata for UI/AI */
  meta: zod.z.object({
    label: zod.z.string().optional(),
    description: zod.z.string().optional(),
    color: zod.z.string().optional(),
    // For UI diagrams
    // Instructions for AI Agent when in this state
    aiInstructions: zod.z.string().optional().describe("Specific instructions for AI when in this state")
  }).optional()
}));
var StateMachineSchema = zod.z.object({
  id: SnakeCaseIdentifierSchema.describe("Unique Machine ID"),
  description: zod.z.string().optional(),
  /** Context (Memory) Schema */
  contextSchema: zod.z.record(zod.z.string(), zod.z.unknown()).optional().describe("Zod Schema for the machine context/memory"),
  /** Initial State */
  initial: zod.z.string().describe("Initial State ID"),
  /** State Definitions */
  states: zod.z.record(zod.z.string(), StateNodeSchema).describe("State Nodes"),
  /** Global Listeners */
  on: zod.z.record(zod.z.string(), zod.z.union([zod.z.string(), TransitionSchema, zod.z.array(TransitionSchema)])).optional()
});

exports.ActionRefSchema = ActionRefSchema;
exports.ApprovalActionSchema = ApprovalActionSchema;
exports.ApprovalActionType = ApprovalActionType;
exports.ApprovalProcess = ApprovalProcess;
exports.ApprovalProcessSchema = ApprovalProcessSchema;
exports.ApprovalStepSchema = ApprovalStepSchema;
exports.ApproverType = ApproverType;
exports.AuthFieldSchema = AuthFieldSchema;
exports.AuthenticationSchema = AuthenticationSchema;
exports.AuthenticationTypeSchema = AuthenticationTypeSchema;
exports.ConflictResolutionSchema = ConflictResolutionSchema;
exports.Connector = Connector;
exports.ConnectorActionRefSchema = ConnectorActionRefSchema;
exports.ConnectorCategorySchema = ConnectorCategorySchema;
exports.ConnectorInstanceSchema = ConnectorInstanceSchema;
exports.ConnectorOperationSchema = ConnectorOperationSchema;
exports.ConnectorSchema = ConnectorSchema;
exports.ConnectorTriggerSchema = ConnectorTriggerSchema;
exports.CustomScriptActionSchema = CustomScriptActionSchema;
exports.DataDestinationConfigSchema = DataDestinationConfigSchema;
exports.DataSourceConfigSchema = DataSourceConfigSchema;
exports.DataSyncConfigSchema = DataSyncConfigSchema;
exports.ETL = ETL;
exports.ETLDestinationSchema = ETLDestinationSchema;
exports.ETLEndpointTypeSchema = ETLEndpointTypeSchema;
exports.ETLPipelineRunSchema = ETLPipelineRunSchema;
exports.ETLPipelineSchema = ETLPipelineSchema;
exports.ETLRunStatusSchema = ETLRunStatusSchema;
exports.ETLSourceSchema = ETLSourceSchema;
exports.ETLSyncModeSchema = ETLSyncModeSchema;
exports.ETLTransformationSchema = ETLTransformationSchema;
exports.ETLTransformationTypeSchema = ETLTransformationTypeSchema;
exports.EmailAlertActionSchema = EmailAlertActionSchema;
exports.EventSchema = EventSchema;
exports.FieldUpdateActionSchema = FieldUpdateActionSchema;
exports.FlowEdgeSchema = FlowEdgeSchema;
exports.FlowNodeAction = FlowNodeAction;
exports.FlowNodeSchema = FlowNodeSchema;
exports.FlowSchema = FlowSchema;
exports.FlowVariableSchema = FlowVariableSchema;
exports.GuardRefSchema = GuardRefSchema;
exports.HttpCallActionSchema = HttpCallActionSchema;
exports.OAuth2ConfigSchema = OAuth2ConfigSchema;
exports.OperationParameterSchema = OperationParameterSchema;
exports.OperationTypeSchema = OperationTypeSchema;
exports.PushNotificationActionSchema = PushNotificationActionSchema;
exports.StateMachineSchema = StateMachineSchema;
exports.StateNodeSchema = StateNodeSchema;
exports.Sync = Sync;
exports.SyncDirectionSchema = SyncDirectionSchema;
exports.SyncExecutionResultSchema = SyncExecutionResultSchema;
exports.SyncExecutionStatusSchema = SyncExecutionStatusSchema;
exports.SyncModeSchema = SyncModeSchema;
exports.TaskCreationActionSchema = TaskCreationActionSchema;
exports.TimeTriggerSchema = TimeTriggerSchema;
exports.TransitionSchema = TransitionSchema;
exports.WebhookReceiverSchema = WebhookReceiverSchema;
exports.WebhookSchema = WebhookSchema;
exports.WebhookTriggerType = WebhookTriggerType;
exports.WorkflowActionSchema = WorkflowActionSchema;
exports.WorkflowRuleSchema = WorkflowRuleSchema;
exports.WorkflowTriggerType = WorkflowTriggerType;
exports.defineFlow = defineFlow;
//# sourceMappingURL=index.js.map
//# sourceMappingURL=index.js.map