@xtr-dev/payload-automation 0.0.16 → 0.0.18
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/core/workflow-executor.js +6 -0
- package/dist/core/workflow-executor.js.map +1 -1
- package/dist/plugin/index.js +75 -4
- package/dist/plugin/index.js.map +1 -1
- package/dist/plugin/init-collection-hooks.js +13 -1
- package/dist/plugin/init-collection-hooks.js.map +1 -1
- package/package.json +1 -1
|
@@ -608,6 +608,12 @@ export class WorkflowExecutor {
|
|
|
608
608
|
/**
|
|
609
609
|
* Find and execute workflows triggered by a collection operation
|
|
610
610
|
*/ async executeTriggeredWorkflows(collection, operation, doc, previousDoc, req) {
|
|
611
|
+
console.log('🚨 EXECUTOR: executeTriggeredWorkflows called!');
|
|
612
|
+
console.log('🚨 EXECUTOR: Collection =', collection);
|
|
613
|
+
console.log('🚨 EXECUTOR: Operation =', operation);
|
|
614
|
+
console.log('🚨 EXECUTOR: Doc ID =', doc?.id);
|
|
615
|
+
console.log('🚨 EXECUTOR: Has payload?', !!this.payload);
|
|
616
|
+
console.log('🚨 EXECUTOR: Has logger?', !!this.logger);
|
|
611
617
|
this.logger.info({
|
|
612
618
|
collection,
|
|
613
619
|
operation,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/core/workflow-executor.ts"],"sourcesContent":["import type { Payload, PayloadRequest } from 'payload'\n\n// We need to reference the generated types dynamically since they're not available at build time\n// Using generic types and casting where necessary\nexport type PayloadWorkflow = {\n id: number\n name: string\n description?: string | null\n triggers?: Array<{\n type?: string | null\n collectionSlug?: string | null\n operation?: string | null\n condition?: string | null\n [key: string]: unknown\n }> | null\n steps?: Array<{\n step?: string | null\n name?: string | null\n input?: unknown\n dependencies?: string[] | null\n condition?: string | null\n [key: string]: unknown\n }> | null\n [key: string]: unknown\n}\n\nimport { JSONPath } from 'jsonpath-plus'\n\n// Helper type to extract workflow step data from the generated types\nexport type WorkflowStep = NonNullable<PayloadWorkflow['steps']>[0] & {\n name: string // Ensure name is always present for our execution logic\n}\n\n// Helper type to extract workflow trigger data from the generated types \nexport type WorkflowTrigger = NonNullable<PayloadWorkflow['triggers']>[0] & {\n type: string // Ensure type is always present for our execution logic\n}\n\nexport interface ExecutionContext {\n steps: Record<string, {\n error?: string\n input: unknown\n output: unknown\n state: 'failed' | 'pending' | 'running' | 'succeeded'\n }>\n trigger: {\n collection?: string\n data?: unknown\n doc?: unknown\n headers?: Record<string, string>\n operation?: string\n path?: string\n previousDoc?: unknown\n req?: PayloadRequest\n triggeredAt?: string\n type: string\n user?: {\n collection?: string\n email?: string\n id?: string\n }\n }\n}\n\nexport class WorkflowExecutor {\n constructor(\n private payload: Payload,\n private logger: Payload['logger']\n ) {}\n\n /**\n * Evaluate a step condition using JSONPath\n */\n private evaluateStepCondition(condition: string, context: ExecutionContext): boolean {\n return this.evaluateCondition(condition, context)\n }\n\n /**\n * Execute a single workflow step\n */\n private async executeStep(\n step: WorkflowStep,\n stepIndex: number,\n context: ExecutionContext,\n req: PayloadRequest,\n workflowRunId?: number | string\n ): Promise<void> {\n const stepName = step.name || 'step-' + stepIndex\n\n this.logger.info({\n hasStep: 'step' in step,\n step: JSON.stringify(step),\n stepName\n }, 'Executing step')\n\n // Check step condition if present\n if (step.condition) {\n this.logger.debug({\n condition: step.condition,\n stepName,\n availableSteps: Object.keys(context.steps),\n completedSteps: Object.entries(context.steps)\n .filter(([_, s]) => s.state === 'succeeded')\n .map(([name]) => name),\n triggerType: context.trigger?.type\n }, 'Evaluating step condition')\n\n const conditionMet = this.evaluateStepCondition(step.condition, context)\n\n if (!conditionMet) {\n this.logger.info({\n condition: step.condition,\n stepName,\n contextSnapshot: JSON.stringify({\n stepOutputs: Object.entries(context.steps).reduce((acc, [name, step]) => {\n acc[name] = { state: step.state, hasOutput: !!step.output }\n return acc\n }, {} as Record<string, any>),\n triggerData: context.trigger?.data ? 'present' : 'absent'\n })\n }, 'Step condition not met, skipping')\n\n // Mark step as completed but skipped\n context.steps[stepName] = {\n error: undefined,\n input: undefined,\n output: { reason: 'Condition not met', skipped: true },\n state: 'succeeded'\n }\n\n // Update workflow run context if needed\n if (workflowRunId) {\n await this.updateWorkflowRunContext(workflowRunId, context, req)\n }\n\n return\n }\n\n this.logger.info({\n condition: step.condition,\n stepName,\n contextSnapshot: JSON.stringify({\n stepOutputs: Object.entries(context.steps).reduce((acc, [name, step]) => {\n acc[name] = { state: step.state, hasOutput: !!step.output }\n return acc\n }, {} as Record<string, any>),\n triggerData: context.trigger?.data ? 'present' : 'absent'\n })\n }, 'Step condition met, proceeding with execution')\n }\n\n // Initialize step context\n context.steps[stepName] = {\n error: undefined,\n input: undefined,\n output: undefined,\n state: 'running'\n }\n\n // Move taskSlug declaration outside try block so it's accessible in catch\n const taskSlug = step.step // Use the 'step' field for task type\n\n try {\n // Resolve input data using JSONPath\n const resolvedInput = this.resolveStepInput(step.input as Record<string, unknown> || {}, context)\n context.steps[stepName].input = resolvedInput\n\n if (!taskSlug) {\n throw new Error(`Step ${stepName} is missing a task type`)\n }\n\n this.logger.info({\n hasInput: !!resolvedInput,\n hasReq: !!req,\n stepName,\n taskSlug\n }, 'Queueing task')\n\n const job = await this.payload.jobs.queue({\n input: resolvedInput,\n req,\n task: taskSlug\n })\n\n // Run the job immediately\n await this.payload.jobs.run({\n limit: 1,\n req\n })\n\n // Get the job result\n const completedJob = await this.payload.findByID({\n id: job.id,\n collection: 'payload-jobs',\n req\n })\n\n const taskStatus = completedJob.taskStatus?.[completedJob.taskSlug]?.[completedJob.totalTried]\n const isComplete = taskStatus?.complete === true\n const hasError = completedJob.hasError || !isComplete\n\n // Extract error information from job if available\n let errorMessage: string | undefined\n if (hasError) {\n // Try to get error from the latest log entry\n if (completedJob.log && completedJob.log.length > 0) {\n const latestLog = completedJob.log[completedJob.log.length - 1]\n errorMessage = latestLog.error?.message || latestLog.error\n }\n\n // Fallback to top-level error\n if (!errorMessage && completedJob.error) {\n errorMessage = completedJob.error.message || completedJob.error\n }\n\n // Final fallback to generic message\n if (!errorMessage) {\n errorMessage = `Task ${taskSlug} failed without detailed error information`\n }\n }\n\n const result: {\n error: string | undefined\n output: unknown\n state: 'failed' | 'succeeded'\n } = {\n error: errorMessage,\n output: taskStatus?.output || {},\n state: isComplete ? 'succeeded' : 'failed'\n }\n\n // Store the output and error\n context.steps[stepName].output = result.output\n context.steps[stepName].state = result.state\n if (result.error) {\n context.steps[stepName].error = result.error\n }\n\n this.logger.debug({context}, 'Step execution context')\n\n if (result.state !== 'succeeded') {\n throw new Error(result.error || `Step ${stepName} failed`)\n }\n\n this.logger.info({\n output: result.output,\n stepName\n }, 'Step completed')\n\n // Update workflow run with current step results if workflowRunId is provided\n if (workflowRunId) {\n await this.updateWorkflowRunContext(workflowRunId, context, req)\n }\n\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error'\n context.steps[stepName].state = 'failed'\n context.steps[stepName].error = errorMessage\n\n this.logger.error({\n error: errorMessage,\n input: context.steps[stepName].input,\n stepName,\n taskSlug\n }, 'Step execution failed')\n\n // Update workflow run with current step results if workflowRunId is provided\n if (workflowRunId) {\n try {\n await this.updateWorkflowRunContext(workflowRunId, context, req)\n } catch (updateError) {\n this.logger.error({\n error: updateError instanceof Error ? updateError.message : 'Unknown error',\n stepName\n }, 'Failed to update workflow run context after step failure')\n }\n }\n\n throw error\n }\n }\n\n /**\n * Resolve step execution order based on dependencies\n */\n private resolveExecutionOrder(steps: WorkflowStep[]): WorkflowStep[][] {\n const stepMap = new Map<string, WorkflowStep>()\n const dependencyGraph = new Map<string, string[]>()\n const indegree = new Map<string, number>()\n\n // Build the step map and dependency graph\n for (const step of steps) {\n const stepName = step.name || `step-${steps.indexOf(step)}`\n const dependencies = step.dependencies || []\n\n stepMap.set(stepName, { ...step, name: stepName, dependencies })\n dependencyGraph.set(stepName, dependencies)\n indegree.set(stepName, dependencies.length)\n }\n\n // Topological sort to determine execution batches\n const executionBatches: WorkflowStep[][] = []\n const processed = new Set<string>()\n\n while (processed.size < steps.length) {\n const currentBatch: WorkflowStep[] = []\n\n // Find all steps with no remaining dependencies\n for (const [stepName, inDegree] of indegree.entries()) {\n if (inDegree === 0 && !processed.has(stepName)) {\n const step = stepMap.get(stepName)\n if (step) {\n currentBatch.push(step)\n }\n }\n }\n\n if (currentBatch.length === 0) {\n throw new Error('Circular dependency detected in workflow steps')\n }\n\n executionBatches.push(currentBatch)\n\n // Update indegrees for next iteration\n for (const step of currentBatch) {\n processed.add(step.name)\n\n // Reduce indegree for steps that depend on completed steps\n for (const [otherStepName, dependencies] of dependencyGraph.entries()) {\n if (dependencies.includes(step.name) && !processed.has(otherStepName)) {\n indegree.set(otherStepName, (indegree.get(otherStepName) || 0) - 1)\n }\n }\n }\n }\n\n return executionBatches\n }\n\n /**\n * Resolve step input using JSONPath expressions\n */\n private resolveStepInput(config: Record<string, unknown>, context: ExecutionContext): Record<string, unknown> {\n const resolved: Record<string, unknown> = {}\n\n this.logger.debug({\n configKeys: Object.keys(config),\n contextSteps: Object.keys(context.steps),\n triggerType: context.trigger?.type\n }, 'Starting step input resolution')\n\n for (const [key, value] of Object.entries(config)) {\n if (typeof value === 'string' && value.startsWith('$')) {\n // This is a JSONPath expression\n this.logger.debug({\n key,\n jsonPath: value,\n availableSteps: Object.keys(context.steps),\n hasTriggerData: !!context.trigger?.data,\n hasTriggerDoc: !!context.trigger?.doc\n }, 'Resolving JSONPath expression')\n\n try {\n const result = JSONPath({\n json: context,\n path: value,\n wrap: false\n })\n \n this.logger.debug({\n key,\n jsonPath: value,\n result: JSON.stringify(result).substring(0, 200),\n resultType: Array.isArray(result) ? 'array' : typeof result\n }, 'JSONPath resolved successfully')\n \n resolved[key] = result\n } catch (error) {\n this.logger.warn({\n error: error instanceof Error ? error.message : 'Unknown error',\n key,\n path: value,\n contextSnapshot: JSON.stringify(context).substring(0, 500)\n }, 'Failed to resolve JSONPath')\n resolved[key] = value // Keep original value if resolution fails\n }\n } else if (typeof value === 'object' && value !== null) {\n // Recursively resolve nested objects\n this.logger.debug({\n key,\n nestedKeys: Object.keys(value as Record<string, unknown>)\n }, 'Recursively resolving nested object')\n \n resolved[key] = this.resolveStepInput(value as Record<string, unknown>, context)\n } else {\n // Keep literal values as-is\n resolved[key] = value\n }\n }\n\n this.logger.debug({\n resolvedKeys: Object.keys(resolved),\n originalKeys: Object.keys(config)\n }, 'Step input resolution completed')\n\n return resolved\n }\n\n /**\n * Safely serialize an object, handling circular references and non-serializable values\n */\n private safeSerialize(obj: unknown): unknown {\n const seen = new WeakSet()\n \n const serialize = (value: unknown): unknown => {\n if (value === null || typeof value !== 'object') {\n return value\n }\n \n if (seen.has(value as object)) {\n return '[Circular Reference]'\n }\n \n seen.add(value as object)\n \n if (Array.isArray(value)) {\n return value.map(serialize)\n }\n \n const result: Record<string, unknown> = {}\n for (const [key, val] of Object.entries(value as Record<string, unknown>)) {\n try {\n // Skip non-serializable properties that are likely internal database objects\n if (key === 'table' || key === 'schema' || key === '_' || key === '__') {\n continue\n }\n result[key] = serialize(val)\n } catch {\n // Skip properties that can't be accessed or serialized\n result[key] = '[Non-serializable]'\n }\n }\n \n return result\n }\n \n return serialize(obj)\n }\n\n /**\n * Update workflow run with current context\n */\n private async updateWorkflowRunContext(\n workflowRunId: number | string,\n context: ExecutionContext,\n req: PayloadRequest\n ): Promise<void> {\n const serializeContext = () => ({\n steps: this.safeSerialize(context.steps),\n trigger: {\n type: context.trigger.type,\n collection: context.trigger.collection,\n data: this.safeSerialize(context.trigger.data),\n doc: this.safeSerialize(context.trigger.doc),\n operation: context.trigger.operation,\n previousDoc: this.safeSerialize(context.trigger.previousDoc),\n triggeredAt: context.trigger.triggeredAt,\n user: context.trigger.req?.user\n }\n })\n\n await this.payload.update({\n id: workflowRunId,\n collection: 'workflow-runs',\n data: {\n context: serializeContext()\n },\n req\n })\n }\n\n /**\n * Evaluate a condition using JSONPath and comparison operators\n */\n public evaluateCondition(condition: string, context: ExecutionContext): boolean {\n this.logger.debug({\n condition,\n contextKeys: Object.keys(context),\n triggerType: context.trigger?.type,\n triggerData: context.trigger?.data,\n triggerDoc: context.trigger?.doc ? 'present' : 'absent'\n }, 'Starting condition evaluation')\n\n try {\n // Check if this is a comparison expression\n const comparisonMatch = condition.match(/^(.+?)\\s*(==|!=|>|<|>=|<=)\\s*(.+)$/)\n \n if (comparisonMatch) {\n const [, leftExpr, operator, rightExpr] = comparisonMatch\n \n // Evaluate left side (should be JSONPath)\n const leftValue = this.resolveJSONPathValue(leftExpr.trim(), context)\n \n // Parse right side (could be string, number, boolean, or JSONPath)\n const rightValue = this.parseConditionValue(rightExpr.trim(), context)\n \n this.logger.debug({\n condition,\n leftExpr: leftExpr.trim(),\n leftValue,\n operator,\n rightExpr: rightExpr.trim(),\n rightValue,\n leftType: typeof leftValue,\n rightType: typeof rightValue\n }, 'Evaluating comparison condition')\n \n // Perform comparison\n let result: boolean\n switch (operator) {\n case '==':\n result = leftValue === rightValue\n break\n case '!=':\n result = leftValue !== rightValue\n break\n case '>':\n result = Number(leftValue) > Number(rightValue)\n break\n case '<':\n result = Number(leftValue) < Number(rightValue)\n break\n case '>=':\n result = Number(leftValue) >= Number(rightValue)\n break\n case '<=':\n result = Number(leftValue) <= Number(rightValue)\n break\n default:\n throw new Error(`Unknown comparison operator: ${operator}`)\n }\n \n this.logger.debug({\n condition,\n result,\n leftValue,\n rightValue,\n operator\n }, 'Comparison condition evaluation completed')\n \n return result\n } else {\n // Treat as simple JSONPath boolean evaluation\n const result = JSONPath({\n json: context,\n path: condition,\n wrap: false\n })\n\n this.logger.debug({\n condition,\n result,\n resultType: Array.isArray(result) ? 'array' : typeof result,\n resultLength: Array.isArray(result) ? result.length : undefined\n }, 'JSONPath boolean evaluation result')\n\n // Handle different result types\n let finalResult: boolean\n if (Array.isArray(result)) {\n finalResult = result.length > 0 && Boolean(result[0])\n } else {\n finalResult = Boolean(result)\n }\n\n this.logger.debug({\n condition,\n finalResult,\n originalResult: result\n }, 'Boolean condition evaluation completed')\n\n return finalResult\n }\n } catch (error) {\n this.logger.warn({\n condition,\n error: error instanceof Error ? error.message : 'Unknown error',\n errorStack: error instanceof Error ? error.stack : undefined\n }, 'Failed to evaluate condition')\n\n // If condition evaluation fails, assume false\n return false\n }\n }\n \n /**\n * Resolve a JSONPath value from the context\n */\n private resolveJSONPathValue(expr: string, context: ExecutionContext): any {\n if (expr.startsWith('$')) {\n const result = JSONPath({\n json: context,\n path: expr,\n wrap: false\n })\n // Return first result if array, otherwise the result itself\n return Array.isArray(result) && result.length > 0 ? result[0] : result\n }\n return expr\n }\n \n /**\n * Parse a condition value (string literal, number, boolean, or JSONPath)\n */\n private parseConditionValue(expr: string, context: ExecutionContext): any {\n // Handle string literals\n if ((expr.startsWith('\"') && expr.endsWith('\"')) || (expr.startsWith(\"'\") && expr.endsWith(\"'\"))) {\n return expr.slice(1, -1) // Remove quotes\n }\n \n // Handle boolean literals\n if (expr === 'true') return true\n if (expr === 'false') return false\n \n // Handle number literals\n if (/^-?\\d+(\\.\\d+)?$/.test(expr)) {\n return Number(expr)\n }\n \n // Handle JSONPath expressions\n if (expr.startsWith('$')) {\n return this.resolveJSONPathValue(expr, context)\n }\n \n // Return as string if nothing else matches\n return expr\n }\n\n /**\n * Execute a workflow with the given context\n */\n async execute(workflow: PayloadWorkflow, context: ExecutionContext, req: PayloadRequest): Promise<void> {\n this.logger.info({\n workflowId: workflow.id,\n workflowName: workflow.name\n }, 'Starting workflow execution')\n\n const serializeContext = () => ({\n steps: this.safeSerialize(context.steps),\n trigger: {\n type: context.trigger.type,\n collection: context.trigger.collection,\n data: this.safeSerialize(context.trigger.data),\n doc: this.safeSerialize(context.trigger.doc),\n operation: context.trigger.operation,\n previousDoc: this.safeSerialize(context.trigger.previousDoc),\n triggeredAt: context.trigger.triggeredAt,\n user: context.trigger.req?.user\n }\n })\n\n this.logger.info({\n workflowId: workflow.id,\n workflowName: workflow.name,\n contextSummary: {\n triggerType: context.trigger.type,\n triggerCollection: context.trigger.collection,\n triggerOperation: context.trigger.operation,\n hasDoc: !!context.trigger.doc,\n userEmail: context.trigger.req?.user?.email\n }\n }, 'About to create workflow run record')\n\n // Create a workflow run record\n let workflowRun;\n try {\n workflowRun = await this.payload.create({\n collection: 'workflow-runs',\n data: {\n context: serializeContext(),\n startedAt: new Date().toISOString(),\n status: 'running',\n triggeredBy: context.trigger.req?.user?.email || 'system',\n workflow: workflow.id,\n workflowVersion: 1 // Default version since generated type doesn't have _version field\n },\n req\n })\n\n this.logger.info({\n workflowRunId: workflowRun.id,\n workflowId: workflow.id,\n workflowName: workflow.name\n }, 'Workflow run record created successfully')\n } catch (error) {\n this.logger.error({\n error: error instanceof Error ? error.message : 'Unknown error',\n errorStack: error instanceof Error ? error.stack : undefined,\n workflowId: workflow.id,\n workflowName: workflow.name\n }, 'Failed to create workflow run record')\n throw error\n }\n\n try {\n // Resolve execution order based on dependencies\n const executionBatches = this.resolveExecutionOrder(workflow.steps as WorkflowStep[] || [])\n\n this.logger.info({\n batchSizes: executionBatches.map(batch => batch.length),\n totalBatches: executionBatches.length\n }, 'Resolved step execution order')\n\n // Execute each batch in sequence, but steps within each batch in parallel\n for (let batchIndex = 0; batchIndex < executionBatches.length; batchIndex++) {\n const batch = executionBatches[batchIndex]\n\n this.logger.info({\n batchIndex,\n stepCount: batch.length,\n stepNames: batch.map(s => s.name)\n }, 'Executing batch')\n\n // Execute all steps in this batch in parallel\n const batchPromises = batch.map((step, stepIndex) =>\n this.executeStep(step, stepIndex, context, req, workflowRun.id)\n )\n\n // Wait for all steps in the current batch to complete\n await Promise.all(batchPromises)\n\n this.logger.info({\n batchIndex,\n stepCount: batch.length\n }, 'Batch completed')\n }\n\n // Update workflow run as completed\n await this.payload.update({\n id: workflowRun.id,\n collection: 'workflow-runs',\n data: {\n completedAt: new Date().toISOString(),\n context: serializeContext(),\n status: 'completed'\n },\n req\n })\n\n this.logger.info({\n runId: workflowRun.id,\n workflowId: workflow.id,\n workflowName: workflow.name\n }, 'Workflow execution completed')\n\n } catch (error) {\n // Update workflow run as failed\n await this.payload.update({\n id: workflowRun.id,\n collection: 'workflow-runs',\n data: {\n completedAt: new Date().toISOString(),\n context: serializeContext(),\n error: error instanceof Error ? error.message : 'Unknown error',\n status: 'failed'\n },\n req\n })\n\n this.logger.error({\n error: error instanceof Error ? error.message : 'Unknown error',\n runId: workflowRun.id,\n workflowId: workflow.id,\n workflowName: workflow.name\n }, 'Workflow execution failed')\n\n throw error\n }\n }\n\n /**\n * Find and execute workflows triggered by a collection operation\n */\n async executeTriggeredWorkflows(\n collection: string,\n operation: 'create' | 'delete' | 'read' | 'update',\n doc: unknown,\n previousDoc: unknown,\n req: PayloadRequest\n ): Promise<void> {\n this.logger.info({\n collection,\n operation,\n docId: (doc as any)?.id\n }, 'executeTriggeredWorkflows called')\n \n try {\n // Find workflows with matching triggers\n const workflows = await this.payload.find({\n collection: 'workflows',\n depth: 2, // Include steps and triggers\n limit: 100,\n req\n })\n \n this.logger.info({\n workflowCount: workflows.docs.length\n }, 'Found workflows to check')\n\n for (const workflow of workflows.docs) {\n // Check if this workflow has a matching trigger\n const triggers = workflow.triggers as Array<{\n collection?: string\n collectionSlug?: string\n condition?: string\n operation: string\n type: string\n }>\n \n this.logger.debug({\n workflowId: workflow.id,\n workflowName: workflow.name,\n triggerCount: triggers?.length || 0,\n triggers: triggers?.map(t => ({\n type: t.type,\n collection: t.collection,\n collectionSlug: t.collectionSlug,\n operation: t.operation\n }))\n }, 'Checking workflow triggers')\n\n const matchingTriggers = triggers?.filter(trigger =>\n trigger.type === 'collection-trigger' &&\n (trigger.collection === collection || trigger.collectionSlug === collection) &&\n trigger.operation === operation\n ) || []\n \n this.logger.info({\n workflowId: workflow.id,\n workflowName: workflow.name,\n matchingTriggerCount: matchingTriggers.length,\n targetCollection: collection,\n targetOperation: operation\n }, 'Matching triggers found')\n\n for (const trigger of matchingTriggers) {\n this.logger.info({\n workflowId: workflow.id,\n workflowName: workflow.name,\n triggerDetails: {\n type: trigger.type,\n collection: trigger.collection,\n collectionSlug: trigger.collectionSlug,\n operation: trigger.operation,\n hasCondition: !!trigger.condition\n }\n }, 'Processing matching trigger - about to execute workflow')\n\n // Create execution context for condition evaluation\n const context: ExecutionContext = {\n steps: {},\n trigger: {\n type: 'collection',\n collection,\n doc,\n operation,\n previousDoc,\n req\n }\n }\n\n // Check trigger condition if present\n if (trigger.condition) {\n this.logger.debug({\n collection,\n operation,\n condition: trigger.condition,\n docId: (doc as any)?.id,\n docFields: doc ? Object.keys(doc) : [],\n previousDocId: (previousDoc as any)?.id,\n workflowId: workflow.id,\n workflowName: workflow.name\n }, 'Evaluating collection trigger condition')\n\n const conditionMet = this.evaluateCondition(trigger.condition, context)\n\n if (!conditionMet) {\n this.logger.info({\n collection,\n condition: trigger.condition,\n operation,\n workflowId: workflow.id,\n workflowName: workflow.name,\n docSnapshot: JSON.stringify(doc).substring(0, 200)\n }, 'Trigger condition not met, skipping workflow')\n continue\n }\n\n this.logger.info({\n collection,\n condition: trigger.condition,\n operation,\n workflowId: workflow.id,\n workflowName: workflow.name,\n docSnapshot: JSON.stringify(doc).substring(0, 200)\n }, 'Trigger condition met')\n }\n\n this.logger.info({\n collection,\n operation,\n workflowId: workflow.id,\n workflowName: workflow.name\n }, 'Triggering workflow')\n\n // Execute the workflow\n await this.execute(workflow as PayloadWorkflow, context, req)\n }\n }\n } catch (error) {\n this.logger.error({ error: error instanceof Error ? error.message : 'Unknown error' }, 'Workflow execution failed')\n this.logger.error({\n collection,\n error: error instanceof Error ? error.message : 'Unknown error',\n operation\n }, 'Failed to execute triggered workflows')\n }\n }\n}\n"],"names":["JSONPath","WorkflowExecutor","payload","logger","evaluateStepCondition","condition","context","evaluateCondition","executeStep","step","stepIndex","req","workflowRunId","stepName","name","info","hasStep","JSON","stringify","debug","availableSteps","Object","keys","steps","completedSteps","entries","filter","_","s","state","map","triggerType","trigger","type","conditionMet","contextSnapshot","stepOutputs","reduce","acc","hasOutput","output","triggerData","data","error","undefined","input","reason","skipped","updateWorkflowRunContext","taskSlug","resolvedInput","resolveStepInput","Error","hasInput","hasReq","job","jobs","queue","task","run","limit","completedJob","findByID","id","collection","taskStatus","totalTried","isComplete","complete","hasError","errorMessage","log","length","latestLog","message","result","updateError","resolveExecutionOrder","stepMap","Map","dependencyGraph","indegree","indexOf","dependencies","set","executionBatches","processed","Set","size","currentBatch","inDegree","has","get","push","add","otherStepName","includes","config","resolved","configKeys","contextSteps","key","value","startsWith","jsonPath","hasTriggerData","hasTriggerDoc","doc","json","path","wrap","substring","resultType","Array","isArray","warn","nestedKeys","resolvedKeys","originalKeys","safeSerialize","obj","seen","WeakSet","serialize","val","serializeContext","operation","previousDoc","triggeredAt","user","update","contextKeys","triggerDoc","comparisonMatch","match","leftExpr","operator","rightExpr","leftValue","resolveJSONPathValue","trim","rightValue","parseConditionValue","leftType","rightType","Number","resultLength","finalResult","Boolean","originalResult","errorStack","stack","expr","endsWith","slice","test","execute","workflow","workflowId","workflowName","contextSummary","triggerCollection","triggerOperation","hasDoc","userEmail","email","workflowRun","create","startedAt","Date","toISOString","status","triggeredBy","workflowVersion","batchSizes","batch","totalBatches","batchIndex","stepCount","stepNames","batchPromises","Promise","all","completedAt","runId","executeTriggeredWorkflows","docId","workflows","find","depth","workflowCount","docs","triggers","triggerCount","t","collectionSlug","matchingTriggers","matchingTriggerCount","targetCollection","targetOperation","triggerDetails","hasCondition","docFields","previousDocId","docSnapshot"],"mappings":"AA0BA,SAASA,QAAQ,QAAQ,gBAAe;AAsCxC,OAAO,MAAMC;;;IACX,YACE,AAAQC,OAAgB,EACxB,AAAQC,MAAyB,CACjC;aAFQD,UAAAA;aACAC,SAAAA;IACP;IAEH;;GAEC,GACD,AAAQC,sBAAsBC,SAAiB,EAAEC,OAAyB,EAAW;QACnF,OAAO,IAAI,CAACC,iBAAiB,CAACF,WAAWC;IAC3C;IAEA;;GAEC,GACD,MAAcE,YACZC,IAAkB,EAClBC,SAAiB,EACjBJ,OAAyB,EACzBK,GAAm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sources":["../../src/core/workflow-executor.ts"],"sourcesContent":["import type { Payload, PayloadRequest } from 'payload'\n\n// We need to reference the generated types dynamically since they're not available at build time\n// Using generic types and casting where necessary\nexport type PayloadWorkflow = {\n id: number\n name: string\n description?: string | null\n triggers?: Array<{\n type?: string | null\n collectionSlug?: string | null\n operation?: string | null\n condition?: string | null\n [key: string]: unknown\n }> | null\n steps?: Array<{\n step?: string | null\n name?: string | null\n input?: unknown\n dependencies?: string[] | null\n condition?: string | null\n [key: string]: unknown\n }> | null\n [key: string]: unknown\n}\n\nimport { JSONPath } from 'jsonpath-plus'\n\n// Helper type to extract workflow step data from the generated types\nexport type WorkflowStep = NonNullable<PayloadWorkflow['steps']>[0] & {\n name: string // Ensure name is always present for our execution logic\n}\n\n// Helper type to extract workflow trigger data from the generated types \nexport type WorkflowTrigger = NonNullable<PayloadWorkflow['triggers']>[0] & {\n type: string // Ensure type is always present for our execution logic\n}\n\nexport interface ExecutionContext {\n steps: Record<string, {\n error?: string\n input: unknown\n output: unknown\n state: 'failed' | 'pending' | 'running' | 'succeeded'\n }>\n trigger: {\n collection?: string\n data?: unknown\n doc?: unknown\n headers?: Record<string, string>\n operation?: string\n path?: string\n previousDoc?: unknown\n req?: PayloadRequest\n triggeredAt?: string\n type: string\n user?: {\n collection?: string\n email?: string\n id?: string\n }\n }\n}\n\nexport class WorkflowExecutor {\n constructor(\n private payload: Payload,\n private logger: Payload['logger']\n ) {}\n\n /**\n * Evaluate a step condition using JSONPath\n */\n private evaluateStepCondition(condition: string, context: ExecutionContext): boolean {\n return this.evaluateCondition(condition, context)\n }\n\n /**\n * Execute a single workflow step\n */\n private async executeStep(\n step: WorkflowStep,\n stepIndex: number,\n context: ExecutionContext,\n req: PayloadRequest,\n workflowRunId?: number | string\n ): Promise<void> {\n const stepName = step.name || 'step-' + stepIndex\n\n this.logger.info({\n hasStep: 'step' in step,\n step: JSON.stringify(step),\n stepName\n }, 'Executing step')\n\n // Check step condition if present\n if (step.condition) {\n this.logger.debug({\n condition: step.condition,\n stepName,\n availableSteps: Object.keys(context.steps),\n completedSteps: Object.entries(context.steps)\n .filter(([_, s]) => s.state === 'succeeded')\n .map(([name]) => name),\n triggerType: context.trigger?.type\n }, 'Evaluating step condition')\n\n const conditionMet = this.evaluateStepCondition(step.condition, context)\n\n if (!conditionMet) {\n this.logger.info({\n condition: step.condition,\n stepName,\n contextSnapshot: JSON.stringify({\n stepOutputs: Object.entries(context.steps).reduce((acc, [name, step]) => {\n acc[name] = { state: step.state, hasOutput: !!step.output }\n return acc\n }, {} as Record<string, any>),\n triggerData: context.trigger?.data ? 'present' : 'absent'\n })\n }, 'Step condition not met, skipping')\n\n // Mark step as completed but skipped\n context.steps[stepName] = {\n error: undefined,\n input: undefined,\n output: { reason: 'Condition not met', skipped: true },\n state: 'succeeded'\n }\n\n // Update workflow run context if needed\n if (workflowRunId) {\n await this.updateWorkflowRunContext(workflowRunId, context, req)\n }\n\n return\n }\n\n this.logger.info({\n condition: step.condition,\n stepName,\n contextSnapshot: JSON.stringify({\n stepOutputs: Object.entries(context.steps).reduce((acc, [name, step]) => {\n acc[name] = { state: step.state, hasOutput: !!step.output }\n return acc\n }, {} as Record<string, any>),\n triggerData: context.trigger?.data ? 'present' : 'absent'\n })\n }, 'Step condition met, proceeding with execution')\n }\n\n // Initialize step context\n context.steps[stepName] = {\n error: undefined,\n input: undefined,\n output: undefined,\n state: 'running'\n }\n\n // Move taskSlug declaration outside try block so it's accessible in catch\n const taskSlug = step.step // Use the 'step' field for task type\n\n try {\n // Resolve input data using JSONPath\n const resolvedInput = this.resolveStepInput(step.input as Record<string, unknown> || {}, context)\n context.steps[stepName].input = resolvedInput\n\n if (!taskSlug) {\n throw new Error(`Step ${stepName} is missing a task type`)\n }\n\n this.logger.info({\n hasInput: !!resolvedInput,\n hasReq: !!req,\n stepName,\n taskSlug\n }, 'Queueing task')\n\n const job = await this.payload.jobs.queue({\n input: resolvedInput,\n req,\n task: taskSlug\n })\n\n // Run the job immediately\n await this.payload.jobs.run({\n limit: 1,\n req\n })\n\n // Get the job result\n const completedJob = await this.payload.findByID({\n id: job.id,\n collection: 'payload-jobs',\n req\n })\n\n const taskStatus = completedJob.taskStatus?.[completedJob.taskSlug]?.[completedJob.totalTried]\n const isComplete = taskStatus?.complete === true\n const hasError = completedJob.hasError || !isComplete\n\n // Extract error information from job if available\n let errorMessage: string | undefined\n if (hasError) {\n // Try to get error from the latest log entry\n if (completedJob.log && completedJob.log.length > 0) {\n const latestLog = completedJob.log[completedJob.log.length - 1]\n errorMessage = latestLog.error?.message || latestLog.error\n }\n\n // Fallback to top-level error\n if (!errorMessage && completedJob.error) {\n errorMessage = completedJob.error.message || completedJob.error\n }\n\n // Final fallback to generic message\n if (!errorMessage) {\n errorMessage = `Task ${taskSlug} failed without detailed error information`\n }\n }\n\n const result: {\n error: string | undefined\n output: unknown\n state: 'failed' | 'succeeded'\n } = {\n error: errorMessage,\n output: taskStatus?.output || {},\n state: isComplete ? 'succeeded' : 'failed'\n }\n\n // Store the output and error\n context.steps[stepName].output = result.output\n context.steps[stepName].state = result.state\n if (result.error) {\n context.steps[stepName].error = result.error\n }\n\n this.logger.debug({context}, 'Step execution context')\n\n if (result.state !== 'succeeded') {\n throw new Error(result.error || `Step ${stepName} failed`)\n }\n\n this.logger.info({\n output: result.output,\n stepName\n }, 'Step completed')\n\n // Update workflow run with current step results if workflowRunId is provided\n if (workflowRunId) {\n await this.updateWorkflowRunContext(workflowRunId, context, req)\n }\n\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error'\n context.steps[stepName].state = 'failed'\n context.steps[stepName].error = errorMessage\n\n this.logger.error({\n error: errorMessage,\n input: context.steps[stepName].input,\n stepName,\n taskSlug\n }, 'Step execution failed')\n\n // Update workflow run with current step results if workflowRunId is provided\n if (workflowRunId) {\n try {\n await this.updateWorkflowRunContext(workflowRunId, context, req)\n } catch (updateError) {\n this.logger.error({\n error: updateError instanceof Error ? updateError.message : 'Unknown error',\n stepName\n }, 'Failed to update workflow run context after step failure')\n }\n }\n\n throw error\n }\n }\n\n /**\n * Resolve step execution order based on dependencies\n */\n private resolveExecutionOrder(steps: WorkflowStep[]): WorkflowStep[][] {\n const stepMap = new Map<string, WorkflowStep>()\n const dependencyGraph = new Map<string, string[]>()\n const indegree = new Map<string, number>()\n\n // Build the step map and dependency graph\n for (const step of steps) {\n const stepName = step.name || `step-${steps.indexOf(step)}`\n const dependencies = step.dependencies || []\n\n stepMap.set(stepName, { ...step, name: stepName, dependencies })\n dependencyGraph.set(stepName, dependencies)\n indegree.set(stepName, dependencies.length)\n }\n\n // Topological sort to determine execution batches\n const executionBatches: WorkflowStep[][] = []\n const processed = new Set<string>()\n\n while (processed.size < steps.length) {\n const currentBatch: WorkflowStep[] = []\n\n // Find all steps with no remaining dependencies\n for (const [stepName, inDegree] of indegree.entries()) {\n if (inDegree === 0 && !processed.has(stepName)) {\n const step = stepMap.get(stepName)\n if (step) {\n currentBatch.push(step)\n }\n }\n }\n\n if (currentBatch.length === 0) {\n throw new Error('Circular dependency detected in workflow steps')\n }\n\n executionBatches.push(currentBatch)\n\n // Update indegrees for next iteration\n for (const step of currentBatch) {\n processed.add(step.name)\n\n // Reduce indegree for steps that depend on completed steps\n for (const [otherStepName, dependencies] of dependencyGraph.entries()) {\n if (dependencies.includes(step.name) && !processed.has(otherStepName)) {\n indegree.set(otherStepName, (indegree.get(otherStepName) || 0) - 1)\n }\n }\n }\n }\n\n return executionBatches\n }\n\n /**\n * Resolve step input using JSONPath expressions\n */\n private resolveStepInput(config: Record<string, unknown>, context: ExecutionContext): Record<string, unknown> {\n const resolved: Record<string, unknown> = {}\n\n this.logger.debug({\n configKeys: Object.keys(config),\n contextSteps: Object.keys(context.steps),\n triggerType: context.trigger?.type\n }, 'Starting step input resolution')\n\n for (const [key, value] of Object.entries(config)) {\n if (typeof value === 'string' && value.startsWith('$')) {\n // This is a JSONPath expression\n this.logger.debug({\n key,\n jsonPath: value,\n availableSteps: Object.keys(context.steps),\n hasTriggerData: !!context.trigger?.data,\n hasTriggerDoc: !!context.trigger?.doc\n }, 'Resolving JSONPath expression')\n\n try {\n const result = JSONPath({\n json: context,\n path: value,\n wrap: false\n })\n \n this.logger.debug({\n key,\n jsonPath: value,\n result: JSON.stringify(result).substring(0, 200),\n resultType: Array.isArray(result) ? 'array' : typeof result\n }, 'JSONPath resolved successfully')\n \n resolved[key] = result\n } catch (error) {\n this.logger.warn({\n error: error instanceof Error ? error.message : 'Unknown error',\n key,\n path: value,\n contextSnapshot: JSON.stringify(context).substring(0, 500)\n }, 'Failed to resolve JSONPath')\n resolved[key] = value // Keep original value if resolution fails\n }\n } else if (typeof value === 'object' && value !== null) {\n // Recursively resolve nested objects\n this.logger.debug({\n key,\n nestedKeys: Object.keys(value as Record<string, unknown>)\n }, 'Recursively resolving nested object')\n \n resolved[key] = this.resolveStepInput(value as Record<string, unknown>, context)\n } else {\n // Keep literal values as-is\n resolved[key] = value\n }\n }\n\n this.logger.debug({\n resolvedKeys: Object.keys(resolved),\n originalKeys: Object.keys(config)\n }, 'Step input resolution completed')\n\n return resolved\n }\n\n /**\n * Safely serialize an object, handling circular references and non-serializable values\n */\n private safeSerialize(obj: unknown): unknown {\n const seen = new WeakSet()\n \n const serialize = (value: unknown): unknown => {\n if (value === null || typeof value !== 'object') {\n return value\n }\n \n if (seen.has(value as object)) {\n return '[Circular Reference]'\n }\n \n seen.add(value as object)\n \n if (Array.isArray(value)) {\n return value.map(serialize)\n }\n \n const result: Record<string, unknown> = {}\n for (const [key, val] of Object.entries(value as Record<string, unknown>)) {\n try {\n // Skip non-serializable properties that are likely internal database objects\n if (key === 'table' || key === 'schema' || key === '_' || key === '__') {\n continue\n }\n result[key] = serialize(val)\n } catch {\n // Skip properties that can't be accessed or serialized\n result[key] = '[Non-serializable]'\n }\n }\n \n return result\n }\n \n return serialize(obj)\n }\n\n /**\n * Update workflow run with current context\n */\n private async updateWorkflowRunContext(\n workflowRunId: number | string,\n context: ExecutionContext,\n req: PayloadRequest\n ): Promise<void> {\n const serializeContext = () => ({\n steps: this.safeSerialize(context.steps),\n trigger: {\n type: context.trigger.type,\n collection: context.trigger.collection,\n data: this.safeSerialize(context.trigger.data),\n doc: this.safeSerialize(context.trigger.doc),\n operation: context.trigger.operation,\n previousDoc: this.safeSerialize(context.trigger.previousDoc),\n triggeredAt: context.trigger.triggeredAt,\n user: context.trigger.req?.user\n }\n })\n\n await this.payload.update({\n id: workflowRunId,\n collection: 'workflow-runs',\n data: {\n context: serializeContext()\n },\n req\n })\n }\n\n /**\n * Evaluate a condition using JSONPath and comparison operators\n */\n public evaluateCondition(condition: string, context: ExecutionContext): boolean {\n this.logger.debug({\n condition,\n contextKeys: Object.keys(context),\n triggerType: context.trigger?.type,\n triggerData: context.trigger?.data,\n triggerDoc: context.trigger?.doc ? 'present' : 'absent'\n }, 'Starting condition evaluation')\n\n try {\n // Check if this is a comparison expression\n const comparisonMatch = condition.match(/^(.+?)\\s*(==|!=|>|<|>=|<=)\\s*(.+)$/)\n \n if (comparisonMatch) {\n const [, leftExpr, operator, rightExpr] = comparisonMatch\n \n // Evaluate left side (should be JSONPath)\n const leftValue = this.resolveJSONPathValue(leftExpr.trim(), context)\n \n // Parse right side (could be string, number, boolean, or JSONPath)\n const rightValue = this.parseConditionValue(rightExpr.trim(), context)\n \n this.logger.debug({\n condition,\n leftExpr: leftExpr.trim(),\n leftValue,\n operator,\n rightExpr: rightExpr.trim(),\n rightValue,\n leftType: typeof leftValue,\n rightType: typeof rightValue\n }, 'Evaluating comparison condition')\n \n // Perform comparison\n let result: boolean\n switch (operator) {\n case '==':\n result = leftValue === rightValue\n break\n case '!=':\n result = leftValue !== rightValue\n break\n case '>':\n result = Number(leftValue) > Number(rightValue)\n break\n case '<':\n result = Number(leftValue) < Number(rightValue)\n break\n case '>=':\n result = Number(leftValue) >= Number(rightValue)\n break\n case '<=':\n result = Number(leftValue) <= Number(rightValue)\n break\n default:\n throw new Error(`Unknown comparison operator: ${operator}`)\n }\n \n this.logger.debug({\n condition,\n result,\n leftValue,\n rightValue,\n operator\n }, 'Comparison condition evaluation completed')\n \n return result\n } else {\n // Treat as simple JSONPath boolean evaluation\n const result = JSONPath({\n json: context,\n path: condition,\n wrap: false\n })\n\n this.logger.debug({\n condition,\n result,\n resultType: Array.isArray(result) ? 'array' : typeof result,\n resultLength: Array.isArray(result) ? result.length : undefined\n }, 'JSONPath boolean evaluation result')\n\n // Handle different result types\n let finalResult: boolean\n if (Array.isArray(result)) {\n finalResult = result.length > 0 && Boolean(result[0])\n } else {\n finalResult = Boolean(result)\n }\n\n this.logger.debug({\n condition,\n finalResult,\n originalResult: result\n }, 'Boolean condition evaluation completed')\n\n return finalResult\n }\n } catch (error) {\n this.logger.warn({\n condition,\n error: error instanceof Error ? error.message : 'Unknown error',\n errorStack: error instanceof Error ? error.stack : undefined\n }, 'Failed to evaluate condition')\n\n // If condition evaluation fails, assume false\n return false\n }\n }\n \n /**\n * Resolve a JSONPath value from the context\n */\n private resolveJSONPathValue(expr: string, context: ExecutionContext): any {\n if (expr.startsWith('$')) {\n const result = JSONPath({\n json: context,\n path: expr,\n wrap: false\n })\n // Return first result if array, otherwise the result itself\n return Array.isArray(result) && result.length > 0 ? result[0] : result\n }\n return expr\n }\n \n /**\n * Parse a condition value (string literal, number, boolean, or JSONPath)\n */\n private parseConditionValue(expr: string, context: ExecutionContext): any {\n // Handle string literals\n if ((expr.startsWith('\"') && expr.endsWith('\"')) || (expr.startsWith(\"'\") && expr.endsWith(\"'\"))) {\n return expr.slice(1, -1) // Remove quotes\n }\n \n // Handle boolean literals\n if (expr === 'true') return true\n if (expr === 'false') return false\n \n // Handle number literals\n if (/^-?\\d+(\\.\\d+)?$/.test(expr)) {\n return Number(expr)\n }\n \n // Handle JSONPath expressions\n if (expr.startsWith('$')) {\n return this.resolveJSONPathValue(expr, context)\n }\n \n // Return as string if nothing else matches\n return expr\n }\n\n /**\n * Execute a workflow with the given context\n */\n async execute(workflow: PayloadWorkflow, context: ExecutionContext, req: PayloadRequest): Promise<void> {\n this.logger.info({\n workflowId: workflow.id,\n workflowName: workflow.name\n }, 'Starting workflow execution')\n\n const serializeContext = () => ({\n steps: this.safeSerialize(context.steps),\n trigger: {\n type: context.trigger.type,\n collection: context.trigger.collection,\n data: this.safeSerialize(context.trigger.data),\n doc: this.safeSerialize(context.trigger.doc),\n operation: context.trigger.operation,\n previousDoc: this.safeSerialize(context.trigger.previousDoc),\n triggeredAt: context.trigger.triggeredAt,\n user: context.trigger.req?.user\n }\n })\n\n this.logger.info({\n workflowId: workflow.id,\n workflowName: workflow.name,\n contextSummary: {\n triggerType: context.trigger.type,\n triggerCollection: context.trigger.collection,\n triggerOperation: context.trigger.operation,\n hasDoc: !!context.trigger.doc,\n userEmail: context.trigger.req?.user?.email\n }\n }, 'About to create workflow run record')\n\n // Create a workflow run record\n let workflowRun;\n try {\n workflowRun = await this.payload.create({\n collection: 'workflow-runs',\n data: {\n context: serializeContext(),\n startedAt: new Date().toISOString(),\n status: 'running',\n triggeredBy: context.trigger.req?.user?.email || 'system',\n workflow: workflow.id,\n workflowVersion: 1 // Default version since generated type doesn't have _version field\n },\n req\n })\n\n this.logger.info({\n workflowRunId: workflowRun.id,\n workflowId: workflow.id,\n workflowName: workflow.name\n }, 'Workflow run record created successfully')\n } catch (error) {\n this.logger.error({\n error: error instanceof Error ? error.message : 'Unknown error',\n errorStack: error instanceof Error ? error.stack : undefined,\n workflowId: workflow.id,\n workflowName: workflow.name\n }, 'Failed to create workflow run record')\n throw error\n }\n\n try {\n // Resolve execution order based on dependencies\n const executionBatches = this.resolveExecutionOrder(workflow.steps as WorkflowStep[] || [])\n\n this.logger.info({\n batchSizes: executionBatches.map(batch => batch.length),\n totalBatches: executionBatches.length\n }, 'Resolved step execution order')\n\n // Execute each batch in sequence, but steps within each batch in parallel\n for (let batchIndex = 0; batchIndex < executionBatches.length; batchIndex++) {\n const batch = executionBatches[batchIndex]\n\n this.logger.info({\n batchIndex,\n stepCount: batch.length,\n stepNames: batch.map(s => s.name)\n }, 'Executing batch')\n\n // Execute all steps in this batch in parallel\n const batchPromises = batch.map((step, stepIndex) =>\n this.executeStep(step, stepIndex, context, req, workflowRun.id)\n )\n\n // Wait for all steps in the current batch to complete\n await Promise.all(batchPromises)\n\n this.logger.info({\n batchIndex,\n stepCount: batch.length\n }, 'Batch completed')\n }\n\n // Update workflow run as completed\n await this.payload.update({\n id: workflowRun.id,\n collection: 'workflow-runs',\n data: {\n completedAt: new Date().toISOString(),\n context: serializeContext(),\n status: 'completed'\n },\n req\n })\n\n this.logger.info({\n runId: workflowRun.id,\n workflowId: workflow.id,\n workflowName: workflow.name\n }, 'Workflow execution completed')\n\n } catch (error) {\n // Update workflow run as failed\n await this.payload.update({\n id: workflowRun.id,\n collection: 'workflow-runs',\n data: {\n completedAt: new Date().toISOString(),\n context: serializeContext(),\n error: error instanceof Error ? error.message : 'Unknown error',\n status: 'failed'\n },\n req\n })\n\n this.logger.error({\n error: error instanceof Error ? error.message : 'Unknown error',\n runId: workflowRun.id,\n workflowId: workflow.id,\n workflowName: workflow.name\n }, 'Workflow execution failed')\n\n throw error\n }\n }\n\n /**\n * Find and execute workflows triggered by a collection operation\n */\n async executeTriggeredWorkflows(\n collection: string,\n operation: 'create' | 'delete' | 'read' | 'update',\n doc: unknown,\n previousDoc: unknown,\n req: PayloadRequest\n ): Promise<void> {\n console.log('🚨 EXECUTOR: executeTriggeredWorkflows called!')\n console.log('🚨 EXECUTOR: Collection =', collection)\n console.log('🚨 EXECUTOR: Operation =', operation)\n console.log('🚨 EXECUTOR: Doc ID =', (doc as any)?.id)\n console.log('🚨 EXECUTOR: Has payload?', !!this.payload)\n console.log('🚨 EXECUTOR: Has logger?', !!this.logger)\n \n this.logger.info({\n collection,\n operation,\n docId: (doc as any)?.id\n }, 'executeTriggeredWorkflows called')\n \n try {\n // Find workflows with matching triggers\n const workflows = await this.payload.find({\n collection: 'workflows',\n depth: 2, // Include steps and triggers\n limit: 100,\n req\n })\n \n this.logger.info({\n workflowCount: workflows.docs.length\n }, 'Found workflows to check')\n\n for (const workflow of workflows.docs) {\n // Check if this workflow has a matching trigger\n const triggers = workflow.triggers as Array<{\n collection?: string\n collectionSlug?: string\n condition?: string\n operation: string\n type: string\n }>\n \n this.logger.debug({\n workflowId: workflow.id,\n workflowName: workflow.name,\n triggerCount: triggers?.length || 0,\n triggers: triggers?.map(t => ({\n type: t.type,\n collection: t.collection,\n collectionSlug: t.collectionSlug,\n operation: t.operation\n }))\n }, 'Checking workflow triggers')\n\n const matchingTriggers = triggers?.filter(trigger =>\n trigger.type === 'collection-trigger' &&\n (trigger.collection === collection || trigger.collectionSlug === collection) &&\n trigger.operation === operation\n ) || []\n \n this.logger.info({\n workflowId: workflow.id,\n workflowName: workflow.name,\n matchingTriggerCount: matchingTriggers.length,\n targetCollection: collection,\n targetOperation: operation\n }, 'Matching triggers found')\n\n for (const trigger of matchingTriggers) {\n this.logger.info({\n workflowId: workflow.id,\n workflowName: workflow.name,\n triggerDetails: {\n type: trigger.type,\n collection: trigger.collection,\n collectionSlug: trigger.collectionSlug,\n operation: trigger.operation,\n hasCondition: !!trigger.condition\n }\n }, 'Processing matching trigger - about to execute workflow')\n\n // Create execution context for condition evaluation\n const context: ExecutionContext = {\n steps: {},\n trigger: {\n type: 'collection',\n collection,\n doc,\n operation,\n previousDoc,\n req\n }\n }\n\n // Check trigger condition if present\n if (trigger.condition) {\n this.logger.debug({\n collection,\n operation,\n condition: trigger.condition,\n docId: (doc as any)?.id,\n docFields: doc ? Object.keys(doc) : [],\n previousDocId: (previousDoc as any)?.id,\n workflowId: workflow.id,\n workflowName: workflow.name\n }, 'Evaluating collection trigger condition')\n\n const conditionMet = this.evaluateCondition(trigger.condition, context)\n\n if (!conditionMet) {\n this.logger.info({\n collection,\n condition: trigger.condition,\n operation,\n workflowId: workflow.id,\n workflowName: workflow.name,\n docSnapshot: JSON.stringify(doc).substring(0, 200)\n }, 'Trigger condition not met, skipping workflow')\n continue\n }\n\n this.logger.info({\n collection,\n condition: trigger.condition,\n operation,\n workflowId: workflow.id,\n workflowName: workflow.name,\n docSnapshot: JSON.stringify(doc).substring(0, 200)\n }, 'Trigger condition met')\n }\n\n this.logger.info({\n collection,\n operation,\n workflowId: workflow.id,\n workflowName: workflow.name\n }, 'Triggering workflow')\n\n // Execute the workflow\n await this.execute(workflow as PayloadWorkflow, context, req)\n }\n }\n } catch (error) {\n this.logger.error({ error: error instanceof Error ? error.message : 'Unknown error' }, 'Workflow execution failed')\n this.logger.error({\n collection,\n error: error instanceof Error ? error.message : 'Unknown error',\n operation\n }, 'Failed to execute triggered workflows')\n }\n }\n}\n"],"names":["JSONPath","WorkflowExecutor","payload","logger","evaluateStepCondition","condition","context","evaluateCondition","executeStep","step","stepIndex","req","workflowRunId","stepName","name","info","hasStep","JSON","stringify","debug","availableSteps","Object","keys","steps","completedSteps","entries","filter","_","s","state","map","triggerType","trigger","type","conditionMet","contextSnapshot","stepOutputs","reduce","acc","hasOutput","output","triggerData","data","error","undefined","input","reason","skipped","updateWorkflowRunContext","taskSlug","resolvedInput","resolveStepInput","Error","hasInput","hasReq","job","jobs","queue","task","run","limit","completedJob","findByID","id","collection","taskStatus","totalTried","isComplete","complete","hasError","errorMessage","log","length","latestLog","message","result","updateError","resolveExecutionOrder","stepMap","Map","dependencyGraph","indegree","indexOf","dependencies","set","executionBatches","processed","Set","size","currentBatch","inDegree","has","get","push","add","otherStepName","includes","config","resolved","configKeys","contextSteps","key","value","startsWith","jsonPath","hasTriggerData","hasTriggerDoc","doc","json","path","wrap","substring","resultType","Array","isArray","warn","nestedKeys","resolvedKeys","originalKeys","safeSerialize","obj","seen","WeakSet","serialize","val","serializeContext","operation","previousDoc","triggeredAt","user","update","contextKeys","triggerDoc","comparisonMatch","match","leftExpr","operator","rightExpr","leftValue","resolveJSONPathValue","trim","rightValue","parseConditionValue","leftType","rightType","Number","resultLength","finalResult","Boolean","originalResult","errorStack","stack","expr","endsWith","slice","test","execute","workflow","workflowId","workflowName","contextSummary","triggerCollection","triggerOperation","hasDoc","userEmail","email","workflowRun","create","startedAt","Date","toISOString","status","triggeredBy","workflowVersion","batchSizes","batch","totalBatches","batchIndex","stepCount","stepNames","batchPromises","Promise","all","completedAt","runId","executeTriggeredWorkflows","console","docId","workflows","find","depth","workflowCount","docs","triggers","triggerCount","t","collectionSlug","matchingTriggers","matchingTriggerCount","targetCollection","targetOperation","triggerDetails","hasCondition","docFields","previousDocId","docSnapshot"],"mappings":"AA0BA,SAASA,QAAQ,QAAQ,gBAAe;AAsCxC,OAAO,MAAMC;;;IACX,YACE,AAAQC,OAAgB,EACxB,AAAQC,MAAyB,CACjC;aAFQD,UAAAA;aACAC,SAAAA;IACP;IAEH;;GAEC,GACD,AAAQC,sBAAsBC,SAAiB,EAAEC,OAAyB,EAAW;QACnF,OAAO,IAAI,CAACC,iBAAiB,CAACF,WAAWC;IAC3C;IAEA;;GAEC,GACD,MAAcE,YACZC,IAAkB,EAClBC,SAAiB,EACjBJ,OAAyB,EACzBK,GAAmB,EACnBC,aAA+B,EAChB;QACf,MAAMC,WAAWJ,KAAKK,IAAI,IAAI,UAAUJ;QAExC,IAAI,CAACP,MAAM,CAACY,IAAI,CAAC;YACfC,SAAS,UAAUP;YACnBA,MAAMQ,KAAKC,SAAS,CAACT;YACrBI;QACF,GAAG;QAEH,kCAAkC;QAClC,IAAIJ,KAAKJ,SAAS,EAAE;YAClB,IAAI,CAACF,MAAM,CAACgB,KAAK,CAAC;gBAChBd,WAAWI,KAAKJ,SAAS;gBACzBQ;gBACAO,gBAAgBC,OAAOC,IAAI,CAAChB,QAAQiB,KAAK;gBACzCC,gBAAgBH,OAAOI,OAAO,CAACnB,QAAQiB,KAAK,EACzCG,MAAM,CAAC,CAAC,CAACC,GAAGC,EAAE,GAAKA,EAAEC,KAAK,KAAK,aAC/BC,GAAG,CAAC,CAAC,CAAChB,KAAK,GAAKA;gBACnBiB,aAAazB,QAAQ0B,OAAO,EAAEC;YAChC,GAAG;YAEH,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C5ByH;gCACAgC,YAAYD,SAAS9F,EAAE;gCACvBgG,cAAcF,SAAS/I,IAAI;gCAC3B+L,aAAa5L,KAAKC,SAAS,CAACyF,KAAKI,SAAS,CAAC,GAAG;4BAChD,GAAG;4BACH;wBACF;wBAEA,IAAI,CAAC5G,MAAM,CAACY,IAAI,CAAC;4BACfiD;4BACA3D,WAAW2B,QAAQ3B,SAAS;4BAC5ByH;4BACAgC,YAAYD,SAAS9F,EAAE;4BACvBgG,cAAcF,SAAS/I,IAAI;4BAC3B+L,aAAa5L,KAAKC,SAAS,CAACyF,KAAKI,SAAS,CAAC,GAAG;wBAChD,GAAG;oBACL;oBAEA,IAAI,CAAC5G,MAAM,CAACY,IAAI,CAAC;wBACfiD;wBACA8D;wBACAgC,YAAYD,SAAS9F,EAAE;wBACvBgG,cAAcF,SAAS/I,IAAI;oBAC7B,GAAG;oBAEH,uBAAuB;oBACvB,MAAM,IAAI,CAAC8I,OAAO,CAACC,UAA6BvJ,SAASK;gBAC3D;YACF;QACF,EAAE,OAAOgC,OAAO;YACd,IAAI,CAACxC,MAAM,CAACwC,KAAK,CAAC;gBAAEA,OAAOA,iBAAiBS,QAAQT,MAAM+B,OAAO,GAAG;YAAgB,GAAG;YACvF,IAAI,CAACvE,MAAM,CAACwC,KAAK,CAAC;gBAChBqB;gBACArB,OAAOA,iBAAiBS,QAAQT,MAAM+B,OAAO,GAAG;gBAChDoD;YACF,GAAG;QACL;IACF;AACF"}
|
package/dist/plugin/index.js
CHANGED
|
@@ -2,13 +2,21 @@ import { createWorkflowCollection } from '../collections/Workflow.js';
|
|
|
2
2
|
import { WorkflowRunsCollection } from '../collections/WorkflowRuns.js';
|
|
3
3
|
import { WorkflowExecutor } from '../core/workflow-executor.js';
|
|
4
4
|
import { generateCronTasks, registerCronJobs } from './cron-scheduler.js';
|
|
5
|
-
import { initCollectionHooks } from "./init-collection-hooks.js";
|
|
6
5
|
import { initGlobalHooks } from "./init-global-hooks.js";
|
|
7
6
|
import { initStepTasks } from "./init-step-tasks.js";
|
|
8
7
|
import { initWebhookEndpoint } from "./init-webhook.js";
|
|
9
8
|
import { initWorkflowHooks } from './init-workflow-hooks.js';
|
|
10
9
|
import { getConfigLogger, initializeLogger } from './logger.js';
|
|
11
10
|
export { getLogger } from './logger.js';
|
|
11
|
+
// Global executor registry for config-phase hooks
|
|
12
|
+
let globalExecutor = null;
|
|
13
|
+
const setWorkflowExecutor = (executor)=>{
|
|
14
|
+
console.log('🚨 SETTING GLOBAL EXECUTOR');
|
|
15
|
+
globalExecutor = executor;
|
|
16
|
+
};
|
|
17
|
+
const getWorkflowExecutor = ()=>{
|
|
18
|
+
return globalExecutor;
|
|
19
|
+
};
|
|
12
20
|
const applyCollectionsConfig = (pluginOptions, config)=>{
|
|
13
21
|
// Add workflow collections
|
|
14
22
|
if (!config.collections) {
|
|
@@ -16,12 +24,71 @@ const applyCollectionsConfig = (pluginOptions, config)=>{
|
|
|
16
24
|
}
|
|
17
25
|
config.collections.push(createWorkflowCollection(pluginOptions), WorkflowRunsCollection);
|
|
18
26
|
};
|
|
27
|
+
const applyHooksToCollections = (pluginOptions, config)=>{
|
|
28
|
+
const configLogger = getConfigLogger();
|
|
29
|
+
if (!pluginOptions.collectionTriggers || Object.keys(pluginOptions.collectionTriggers).length === 0) {
|
|
30
|
+
configLogger.warn('No collection triggers configured - hooks will not be applied');
|
|
31
|
+
return;
|
|
32
|
+
}
|
|
33
|
+
configLogger.info('Applying hooks to collections during config phase');
|
|
34
|
+
// Apply hooks to each configured collection
|
|
35
|
+
for (const [collectionSlug, triggerConfig] of Object.entries(pluginOptions.collectionTriggers)){
|
|
36
|
+
if (!triggerConfig) {
|
|
37
|
+
continue;
|
|
38
|
+
}
|
|
39
|
+
// Find the collection in the config
|
|
40
|
+
const collectionConfig = config.collections?.find((c)=>c.slug === collectionSlug);
|
|
41
|
+
if (!collectionConfig) {
|
|
42
|
+
configLogger.warn(`Collection '${collectionSlug}' not found in config - cannot apply hooks`);
|
|
43
|
+
continue;
|
|
44
|
+
}
|
|
45
|
+
const crud = triggerConfig === true ? {
|
|
46
|
+
create: true,
|
|
47
|
+
delete: true,
|
|
48
|
+
read: true,
|
|
49
|
+
update: true
|
|
50
|
+
} : triggerConfig;
|
|
51
|
+
// Initialize hooks if they don't exist
|
|
52
|
+
if (!collectionConfig.hooks) {
|
|
53
|
+
collectionConfig.hooks = {};
|
|
54
|
+
}
|
|
55
|
+
// Apply afterChange hook for create/update operations
|
|
56
|
+
if (crud.update || crud.create) {
|
|
57
|
+
if (!collectionConfig.hooks.afterChange) {
|
|
58
|
+
collectionConfig.hooks.afterChange = [];
|
|
59
|
+
}
|
|
60
|
+
// Add our automation hook - this will be called when the executor is ready
|
|
61
|
+
collectionConfig.hooks.afterChange.push(async (change)=>{
|
|
62
|
+
console.log('🚨 CONFIG-PHASE AUTOMATION HOOK CALLED! 🚨');
|
|
63
|
+
console.log('Collection:', change.collection.slug);
|
|
64
|
+
console.log('Operation:', change.operation);
|
|
65
|
+
console.log('Doc ID:', change.doc?.id);
|
|
66
|
+
// Get the executor from global registry (set during onInit)
|
|
67
|
+
const executor = getWorkflowExecutor();
|
|
68
|
+
if (!executor) {
|
|
69
|
+
console.log('❌ No executor available yet - workflow execution skipped');
|
|
70
|
+
return;
|
|
71
|
+
}
|
|
72
|
+
console.log('✅ Executor found - executing workflows');
|
|
73
|
+
try {
|
|
74
|
+
await executor.executeTriggeredWorkflows(change.collection.slug, change.operation, change.doc, change.previousDoc, change.req);
|
|
75
|
+
console.log('🚨 executeTriggeredWorkflows completed successfully');
|
|
76
|
+
} catch (error) {
|
|
77
|
+
console.log('🚨 executeTriggeredWorkflows failed:', error);
|
|
78
|
+
}
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
configLogger.info(`Applied hooks to collection: ${collectionSlug}`);
|
|
82
|
+
}
|
|
83
|
+
};
|
|
19
84
|
export const workflowsPlugin = (pluginOptions)=>(config)=>{
|
|
20
85
|
// If the plugin is disabled, return config unchanged
|
|
21
86
|
if (pluginOptions.enabled === false) {
|
|
22
87
|
return config;
|
|
23
88
|
}
|
|
24
89
|
applyCollectionsConfig(pluginOptions, config);
|
|
90
|
+
// CRITICAL FIX: Apply hooks during config phase, not onInit
|
|
91
|
+
applyHooksToCollections(pluginOptions, config);
|
|
25
92
|
if (!config.jobs) {
|
|
26
93
|
config.jobs = {
|
|
27
94
|
tasks: []
|
|
@@ -56,10 +123,14 @@ export const workflowsPlugin = (pluginOptions)=>(config)=>{
|
|
|
56
123
|
// Log collection trigger configuration
|
|
57
124
|
logger.info(`Plugin configuration: ${Object.keys(pluginOptions.collectionTriggers || {}).length} collection triggers, ${pluginOptions.steps?.length || 0} steps`);
|
|
58
125
|
// Create workflow executor instance
|
|
126
|
+
console.log('🚨 CREATING WORKFLOW EXECUTOR INSTANCE');
|
|
59
127
|
const executor = new WorkflowExecutor(payload, logger);
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
128
|
+
console.log('🚨 EXECUTOR CREATED:', typeof executor);
|
|
129
|
+
console.log('🚨 EXECUTOR METHODS:', Object.getOwnPropertyNames(Object.getPrototypeOf(executor)));
|
|
130
|
+
// Register executor globally for config-phase hooks
|
|
131
|
+
setWorkflowExecutor(executor);
|
|
132
|
+
// Note: Collection hooks are now applied during config phase, not here
|
|
133
|
+
logger.info('Collection hooks applied during config phase - executor now available for them');
|
|
63
134
|
logger.info('Initializing global hooks...');
|
|
64
135
|
initGlobalHooks(payload, logger, executor);
|
|
65
136
|
logger.info('Initializing workflow hooks...');
|
package/dist/plugin/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/plugin/index.ts"],"sourcesContent":["import type {Config} from 'payload'\n\nimport type {WorkflowsPluginConfig} from \"./config-types.js\"\n\nimport {createWorkflowCollection} from '../collections/Workflow.js'\nimport {WorkflowRunsCollection} from '../collections/WorkflowRuns.js'\nimport {WorkflowExecutor} from '../core/workflow-executor.js'\nimport {generateCronTasks, registerCronJobs} from './cron-scheduler.js'\nimport {initCollectionHooks} from \"./init-collection-hooks.js\"\nimport {initGlobalHooks} from \"./init-global-hooks.js\"\nimport {initStepTasks} from \"./init-step-tasks.js\"\nimport {initWebhookEndpoint} from \"./init-webhook.js\"\nimport {initWorkflowHooks} from './init-workflow-hooks.js'\nimport {getConfigLogger, initializeLogger} from './logger.js'\n\nexport {getLogger} from './logger.js'\n\nconst applyCollectionsConfig = <T extends string>(pluginOptions: WorkflowsPluginConfig<T>, config: Config) => {\n // Add workflow collections\n if (!config.collections) {\n config.collections = []\n }\n\n config.collections.push(\n createWorkflowCollection(pluginOptions),\n WorkflowRunsCollection\n )\n}\n\n\nexport const workflowsPlugin =\n <TSlug extends string>(pluginOptions: WorkflowsPluginConfig<TSlug>) =>\n (config: Config): Config => {\n // If the plugin is disabled, return config unchanged\n if (pluginOptions.enabled === false) {\n return config\n }\n\n applyCollectionsConfig<TSlug>(pluginOptions, config)\n\n if (!config.jobs) {\n config.jobs = {tasks: []}\n }\n\n const configLogger = getConfigLogger()\n configLogger.info(`Configuring workflow plugin with ${Object.keys(pluginOptions.collectionTriggers || {}).length} collection triggers`)\n\n // Generate cron tasks for workflows with cron triggers\n generateCronTasks(config)\n\n for (const step of pluginOptions.steps) {\n if (!config.jobs?.tasks?.find(task => task.slug === step.slug)) {\n configLogger.debug(`Registering task: ${step.slug}`)\n config.jobs?.tasks?.push(step)\n } else {\n configLogger.debug(`Task ${step.slug} already registered, skipping`)\n }\n }\n\n // Initialize webhook endpoint\n initWebhookEndpoint(config, pluginOptions.webhookPrefix || 'webhook')\n\n // Set up onInit to register collection hooks and initialize features\n const incomingOnInit = config.onInit\n config.onInit = async (payload) => {\n configLogger.info(`onInit called - collections: ${Object.keys(payload.collections).length}`)\n \n // Execute any existing onInit functions first\n if (incomingOnInit) {\n configLogger.debug('Executing existing onInit function')\n await incomingOnInit(payload)\n }\n\n // Initialize the logger with the payload instance\n const logger = initializeLogger(payload)\n logger.info('Logger initialized with payload instance')\n\n // Log collection trigger configuration\n logger.info(`Plugin configuration: ${Object.keys(pluginOptions.collectionTriggers || {}).length} collection triggers, ${pluginOptions.steps?.length || 0} steps`)\n\n // Create workflow executor instance\n const executor = new WorkflowExecutor(payload, logger)\n\n // Initialize hooks\n logger.info('Initializing collection hooks...')\n initCollectionHooks(pluginOptions, payload, logger, executor)\n \n logger.info('Initializing global hooks...')\n initGlobalHooks(payload, logger, executor)\n \n logger.info('Initializing workflow hooks...')\n initWorkflowHooks(payload, logger)\n \n logger.info('Initializing step tasks...')\n initStepTasks(pluginOptions, payload, logger)\n\n // Register cron jobs for workflows with cron triggers\n logger.info('Registering cron jobs...')\n await registerCronJobs(payload, logger)\n\n logger.info('Plugin initialized successfully - all hooks registered')\n }\n\n return config\n }\n"],"names":["createWorkflowCollection","WorkflowRunsCollection","WorkflowExecutor","generateCronTasks","registerCronJobs","initCollectionHooks","initGlobalHooks","initStepTasks","initWebhookEndpoint","initWorkflowHooks","getConfigLogger","initializeLogger","getLogger","applyCollectionsConfig","pluginOptions","config","collections","push","workflowsPlugin","enabled","jobs","tasks","configLogger","info","Object","keys","collectionTriggers","length","step","steps","find","task","slug","debug","webhookPrefix","incomingOnInit","onInit","payload","logger","executor"],"mappings":"AAIA,SAAQA,wBAAwB,QAAO,6BAA4B;AACnE,SAAQC,sBAAsB,QAAO,iCAAgC;AACrE,SAAQC,gBAAgB,QAAO,+BAA8B;AAC7D,SAAQC,iBAAiB,EAAEC,gBAAgB,QAAO,sBAAqB;AACvE,SAAQC,mBAAmB,QAAO,6BAA4B;AAC9D,SAAQC,eAAe,QAAO,yBAAwB;AACtD,SAAQC,aAAa,QAAO,uBAAsB;AAClD,SAAQC,mBAAmB,QAAO,oBAAmB;AACrD,SAAQC,iBAAiB,QAAO,2BAA0B;AAC1D,SAAQC,eAAe,EAAEC,gBAAgB,QAAO,cAAa;AAE7D,SAAQC,SAAS,QAAO,cAAa;AAErC,MAAMC,yBAAyB,CAAmBC,eAAyCC;IACzF,2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BAAgB;gBAClBb,aAAaW,KAAK,CAAC;gBACnB,MAAME,eAAeE;YACvB;YAEA,kDAAkD;YAClD,MAAMC,SAAS3B,iBAAiB0B;YAChCC,OAAOf,IAAI,CAAC;YAEZ,uCAAuC;YACvCe,OAAOf,IAAI,CAAC,CAAC,sBAAsB,EAAEC,OAAOC,IAAI,CAACX,cAAcY,kBAAkB,IAAI,CAAC,GAAGC,MAAM,CAAC,sBAAsB,EAAEb,cAAce,KAAK,EAAEF,UAAU,EAAE,MAAM,CAAC;YAEhK,oCAAoC;YACpC,MAAMY,WAAW,IAAIrC,iBAAiBmC,SAASC;YAE/C,mBAAmB;YACnBA,OAAOf,IAAI,CAAC;YACZlB,oBAAoBS,eAAeuB,SAASC,QAAQC;YAEpDD,OAAOf,IAAI,CAAC;YACZjB,gBAAgB+B,SAASC,QAAQC;YAEjCD,OAAOf,IAAI,CAAC;YACZd,kBAAkB4B,SAASC;YAE3BA,OAAOf,IAAI,CAAC;YACZhB,cAAcO,eAAeuB,SAASC;YAEtC,sDAAsD;YACtDA,OAAOf,IAAI,CAAC;YACZ,MAAMnB,iBAAiBiC,SAASC;YAEhCA,OAAOf,IAAI,CAAC;QACd;QAEA,OAAOR;IACT,EAAC"}
|
|
1
|
+
{"version":3,"sources":["../../src/plugin/index.ts"],"sourcesContent":["import type {Config} from 'payload'\n\nimport type {WorkflowsPluginConfig, CollectionTriggerConfigCrud} from \"./config-types.js\"\n\nimport {createWorkflowCollection} from '../collections/Workflow.js'\nimport {WorkflowRunsCollection} from '../collections/WorkflowRuns.js'\nimport {WorkflowExecutor} from '../core/workflow-executor.js'\nimport {generateCronTasks, registerCronJobs} from './cron-scheduler.js'\nimport {initCollectionHooks} from \"./init-collection-hooks.js\"\nimport {initGlobalHooks} from \"./init-global-hooks.js\"\nimport {initStepTasks} from \"./init-step-tasks.js\"\nimport {initWebhookEndpoint} from \"./init-webhook.js\"\nimport {initWorkflowHooks} from './init-workflow-hooks.js'\nimport {getConfigLogger, initializeLogger} from './logger.js'\n\nexport {getLogger} from './logger.js'\n\n// Global executor registry for config-phase hooks\nlet globalExecutor: WorkflowExecutor | null = null\n\nconst setWorkflowExecutor = (executor: WorkflowExecutor) => {\n console.log('🚨 SETTING GLOBAL EXECUTOR')\n globalExecutor = executor\n}\n\nconst getWorkflowExecutor = (): WorkflowExecutor | null => {\n return globalExecutor\n}\n\nconst applyCollectionsConfig = <T extends string>(pluginOptions: WorkflowsPluginConfig<T>, config: Config) => {\n // Add workflow collections\n if (!config.collections) {\n config.collections = []\n }\n\n config.collections.push(\n createWorkflowCollection(pluginOptions),\n WorkflowRunsCollection\n )\n}\n\nconst applyHooksToCollections = <T extends string>(pluginOptions: WorkflowsPluginConfig<T>, config: Config) => {\n const configLogger = getConfigLogger()\n \n if (!pluginOptions.collectionTriggers || Object.keys(pluginOptions.collectionTriggers).length === 0) {\n configLogger.warn('No collection triggers configured - hooks will not be applied')\n return\n }\n\n configLogger.info('Applying hooks to collections during config phase')\n\n // Apply hooks to each configured collection\n for (const [collectionSlug, triggerConfig] of Object.entries(pluginOptions.collectionTriggers)) {\n if (!triggerConfig) {\n continue\n }\n\n // Find the collection in the config\n const collectionConfig = config.collections?.find(c => c.slug === collectionSlug)\n if (!collectionConfig) {\n configLogger.warn(`Collection '${collectionSlug}' not found in config - cannot apply hooks`)\n continue\n }\n\n const crud: CollectionTriggerConfigCrud = triggerConfig === true ? {\n create: true,\n delete: true,\n read: true,\n update: true,\n } : triggerConfig\n\n // Initialize hooks if they don't exist\n if (!collectionConfig.hooks) {\n collectionConfig.hooks = {}\n }\n\n // Apply afterChange hook for create/update operations\n if (crud.update || crud.create) {\n if (!collectionConfig.hooks.afterChange) {\n collectionConfig.hooks.afterChange = []\n }\n\n // Add our automation hook - this will be called when the executor is ready\n collectionConfig.hooks.afterChange.push(async (change) => {\n console.log('🚨 CONFIG-PHASE AUTOMATION HOOK CALLED! 🚨')\n console.log('Collection:', change.collection.slug)\n console.log('Operation:', change.operation)\n console.log('Doc ID:', change.doc?.id)\n\n // Get the executor from global registry (set during onInit)\n const executor = getWorkflowExecutor()\n if (!executor) {\n console.log('❌ No executor available yet - workflow execution skipped')\n return\n }\n\n console.log('✅ Executor found - executing workflows')\n \n try {\n await executor.executeTriggeredWorkflows(\n change.collection.slug,\n change.operation as 'create' | 'update',\n change.doc,\n change.previousDoc,\n change.req\n )\n console.log('🚨 executeTriggeredWorkflows completed successfully')\n } catch (error) {\n console.log('🚨 executeTriggeredWorkflows failed:', error)\n }\n })\n }\n\n configLogger.info(`Applied hooks to collection: ${collectionSlug}`)\n }\n}\n\n\nexport const workflowsPlugin =\n <TSlug extends string>(pluginOptions: WorkflowsPluginConfig<TSlug>) =>\n (config: Config): Config => {\n // If the plugin is disabled, return config unchanged\n if (pluginOptions.enabled === false) {\n return config\n }\n\n applyCollectionsConfig<TSlug>(pluginOptions, config)\n \n // CRITICAL FIX: Apply hooks during config phase, not onInit\n applyHooksToCollections<TSlug>(pluginOptions, config)\n\n if (!config.jobs) {\n config.jobs = {tasks: []}\n }\n\n const configLogger = getConfigLogger()\n configLogger.info(`Configuring workflow plugin with ${Object.keys(pluginOptions.collectionTriggers || {}).length} collection triggers`)\n\n // Generate cron tasks for workflows with cron triggers\n generateCronTasks(config)\n\n for (const step of pluginOptions.steps) {\n if (!config.jobs?.tasks?.find(task => task.slug === step.slug)) {\n configLogger.debug(`Registering task: ${step.slug}`)\n config.jobs?.tasks?.push(step)\n } else {\n configLogger.debug(`Task ${step.slug} already registered, skipping`)\n }\n }\n\n // Initialize webhook endpoint\n initWebhookEndpoint(config, pluginOptions.webhookPrefix || 'webhook')\n\n // Set up onInit to register collection hooks and initialize features\n const incomingOnInit = config.onInit\n config.onInit = async (payload) => {\n configLogger.info(`onInit called - collections: ${Object.keys(payload.collections).length}`)\n \n // Execute any existing onInit functions first\n if (incomingOnInit) {\n configLogger.debug('Executing existing onInit function')\n await incomingOnInit(payload)\n }\n\n // Initialize the logger with the payload instance\n const logger = initializeLogger(payload)\n logger.info('Logger initialized with payload instance')\n\n // Log collection trigger configuration\n logger.info(`Plugin configuration: ${Object.keys(pluginOptions.collectionTriggers || {}).length} collection triggers, ${pluginOptions.steps?.length || 0} steps`)\n\n // Create workflow executor instance\n console.log('🚨 CREATING WORKFLOW EXECUTOR INSTANCE')\n const executor = new WorkflowExecutor(payload, logger)\n console.log('🚨 EXECUTOR CREATED:', typeof executor)\n console.log('🚨 EXECUTOR METHODS:', Object.getOwnPropertyNames(Object.getPrototypeOf(executor)))\n \n // Register executor globally for config-phase hooks\n setWorkflowExecutor(executor)\n\n // Note: Collection hooks are now applied during config phase, not here\n logger.info('Collection hooks applied during config phase - executor now available for them')\n \n logger.info('Initializing global hooks...')\n initGlobalHooks(payload, logger, executor)\n \n logger.info('Initializing workflow hooks...')\n initWorkflowHooks(payload, logger)\n \n logger.info('Initializing step tasks...')\n initStepTasks(pluginOptions, payload, logger)\n\n // Register cron jobs for workflows with cron triggers\n logger.info('Registering cron jobs...')\n await registerCronJobs(payload, logger)\n\n logger.info('Plugin initialized successfully - all hooks registered')\n }\n\n return config\n }\n"],"names":["createWorkflowCollection","WorkflowRunsCollection","WorkflowExecutor","generateCronTasks","registerCronJobs","initGlobalHooks","initStepTasks","initWebhookEndpoint","initWorkflowHooks","getConfigLogger","initializeLogger","getLogger","globalExecutor","setWorkflowExecutor","executor","console","log","getWorkflowExecutor","applyCollectionsConfig","pluginOptions","config","collections","push","applyHooksToCollections","configLogger","collectionTriggers","Object","keys","length","warn","info","collectionSlug","triggerConfig","entries","collectionConfig","find","c","slug","crud","create","delete","read","update","hooks","afterChange","change","collection","operation","doc","id","executeTriggeredWorkflows","previousDoc","req","error","workflowsPlugin","enabled","jobs","tasks","step","steps","task","debug","webhookPrefix","incomingOnInit","onInit","payload","logger","getOwnPropertyNames","getPrototypeOf"],"mappings":"AAIA,SAAQA,wBAAwB,QAAO,6BAA4B;AACnE,SAAQC,sBAAsB,QAAO,iCAAgC;AACrE,SAAQC,gBAAgB,QAAO,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,IAAI,CAACR,cAAcM,kBAAkB,IAAI,CAAC,GAAGG,MAAM,CAAC,sBAAsB,EAAET,cAAcwC,KAAK,EAAE/B,UAAU,EAAE,MAAM,CAAC;YAEhK,oCAAoC;YACpCb,QAAQC,GAAG,CAAC;YACZ,MAAMF,WAAW,IAAIZ,iBAAiB+D,SAASC;YAC/CnD,QAAQC,GAAG,CAAC,wBAAwB,OAAOF;YAC3CC,QAAQC,GAAG,CAAC,wBAAwBU,OAAOyC,mBAAmB,CAACzC,OAAO0C,cAAc,CAACtD;YAErF,oDAAoD;YACpDD,oBAAoBC;YAEpB,uEAAuE;YACvEoD,OAAOpC,IAAI,CAAC;YAEZoC,OAAOpC,IAAI,CAAC;YACZzB,gBAAgB4D,SAASC,QAAQpD;YAEjCoD,OAAOpC,IAAI,CAAC;YACZtB,kBAAkByD,SAASC;YAE3BA,OAAOpC,IAAI,CAAC;YACZxB,cAAca,eAAe8C,SAASC;YAEtC,sDAAsD;YACtDA,OAAOpC,IAAI,CAAC;YACZ,MAAM1B,iBAAiB6D,SAASC;YAEhCA,OAAOpC,IAAI,CAAC;QACd;QAEA,OAAOV;IACT,EAAC"}
|
|
@@ -29,21 +29,33 @@ export function initCollectionHooks(pluginOptions, payload, logger, executor) {
|
|
|
29
29
|
collection.config.hooks.afterChange = collection.config.hooks.afterChange || [];
|
|
30
30
|
collection.config.hooks.afterChange.push(async (change)=>{
|
|
31
31
|
const operation = change.operation;
|
|
32
|
+
// AGGRESSIVE LOGGING - this should ALWAYS appear
|
|
33
|
+
console.log('🚨 AUTOMATION PLUGIN HOOK CALLED! 🚨');
|
|
34
|
+
console.log('Collection:', change.collection.slug);
|
|
35
|
+
console.log('Operation:', operation);
|
|
36
|
+
console.log('Doc ID:', change.doc?.id);
|
|
37
|
+
console.log('Has executor?', !!executor);
|
|
38
|
+
console.log('Executor type:', typeof executor);
|
|
32
39
|
logger.info({
|
|
33
40
|
slug: change.collection.slug,
|
|
34
41
|
operation,
|
|
35
42
|
docId: change.doc?.id,
|
|
36
|
-
previousDocId: change.previousDoc?.id
|
|
43
|
+
previousDocId: change.previousDoc?.id,
|
|
44
|
+
hasExecutor: !!executor,
|
|
45
|
+
executorType: typeof executor
|
|
37
46
|
}, 'AUTOMATION PLUGIN: Collection hook triggered');
|
|
38
47
|
try {
|
|
48
|
+
console.log('🚨 About to call executeTriggeredWorkflows');
|
|
39
49
|
// Execute workflows for this trigger
|
|
40
50
|
await executor.executeTriggeredWorkflows(change.collection.slug, operation, change.doc, change.previousDoc, change.req);
|
|
51
|
+
console.log('🚨 executeTriggeredWorkflows completed without error');
|
|
41
52
|
logger.info({
|
|
42
53
|
slug: change.collection.slug,
|
|
43
54
|
operation,
|
|
44
55
|
docId: change.doc?.id
|
|
45
56
|
}, 'AUTOMATION PLUGIN: executeTriggeredWorkflows completed successfully');
|
|
46
57
|
} catch (error) {
|
|
58
|
+
console.log('🚨 AUTOMATION PLUGIN ERROR:', error);
|
|
47
59
|
logger.error({
|
|
48
60
|
slug: change.collection.slug,
|
|
49
61
|
operation,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/plugin/init-collection-hooks.ts"],"sourcesContent":["import type {Payload} from \"payload\"\nimport type {Logger} from \"pino\"\n\nimport type { WorkflowExecutor } from \"../core/workflow-executor.js\"\nimport type {CollectionTriggerConfigCrud, WorkflowsPluginConfig} from \"./config-types.js\"\n\nexport function initCollectionHooks<T extends string>(pluginOptions: WorkflowsPluginConfig<T>, payload: Payload, logger: Payload['logger'], executor: WorkflowExecutor) {\n \n if (!pluginOptions.collectionTriggers || Object.keys(pluginOptions.collectionTriggers).length === 0) {\n logger.warn('No collection triggers configured in plugin options')\n return\n }\n\n logger.info({\n configuredCollections: Object.keys(pluginOptions.collectionTriggers),\n availableCollections: Object.keys(payload.collections)\n }, 'Starting collection hook registration')\n\n // Add hooks to configured collections\n for (const [collectionSlug, triggerConfig] of Object.entries(pluginOptions.collectionTriggers)) {\n if (!triggerConfig) {\n logger.debug({collectionSlug}, 'Skipping collection with falsy trigger config')\n continue\n }\n\n const collection = payload.collections[collectionSlug as T]\n const crud: CollectionTriggerConfigCrud = triggerConfig === true ? {\n create: true,\n delete: true,\n read: true,\n update: true,\n } : triggerConfig\n\n if (!collection.config.hooks) {\n collection.config.hooks = {} as typeof collection.config.hooks\n }\n\n if (crud.update || crud.create) {\n collection.config.hooks.afterChange = collection.config.hooks.afterChange || []\n collection.config.hooks.afterChange.push(async (change) => {\n const operation = change.operation as 'create' | 'update'\n logger.info({\n slug: change.collection.slug,\n operation,\n docId: change.doc?.id,\n previousDocId: change.previousDoc?.id,\n }, 'AUTOMATION PLUGIN: Collection hook triggered')\n\n try {\n // Execute workflows for this trigger\n await executor.executeTriggeredWorkflows(\n change.collection.slug,\n operation,\n change.doc,\n change.previousDoc,\n change.req\n )\n logger.info({\n slug: change.collection.slug,\n operation,\n docId: change.doc?.id\n }, 'AUTOMATION PLUGIN: executeTriggeredWorkflows completed successfully')\n } catch (error) {\n logger.error({\n slug: change.collection.slug,\n operation,\n docId: change.doc?.id,\n error: error instanceof Error ? error.message : 'Unknown error',\n stack: error instanceof Error ? error.stack : undefined\n }, 'AUTOMATION PLUGIN: executeTriggeredWorkflows failed')\n // Don't re-throw to avoid breaking other hooks\n }\n })\n }\n\n if (crud.read) {\n collection.config.hooks.afterRead = collection.config.hooks.afterRead || []\n collection.config.hooks.afterRead.push(async (change) => {\n logger.debug({\n slug: change.collection.slug,\n operation: 'read',\n }, 'Collection hook triggered')\n\n // Execute workflows for this trigger\n await executor.executeTriggeredWorkflows(\n change.collection.slug,\n 'read',\n change.doc,\n undefined,\n change.req\n )\n })\n }\n\n if (crud.delete) {\n collection.config.hooks.afterDelete = collection.config.hooks.afterDelete || []\n collection.config.hooks.afterDelete.push(async (change) => {\n logger.debug({\n slug: change.collection.slug,\n operation: 'delete',\n }, 'Collection hook triggered')\n\n // Execute workflows for this trigger\n await executor.executeTriggeredWorkflows(\n change.collection.slug,\n 'delete',\n change.doc,\n undefined,\n change.req\n )\n })\n }\n\n if (collection) {\n logger.info({\n collectionSlug,\n hooksRegistered: {\n afterChange: crud.update || crud.create,\n afterRead: crud.read,\n afterDelete: crud.delete\n }\n }, 'Collection hooks registered successfully')\n } else {\n logger.error({\n collectionSlug,\n availableCollections: Object.keys(payload.collections)\n }, 'Collection not found for trigger configuration - check collection slug spelling')\n }\n }\n}\n"],"names":["initCollectionHooks","pluginOptions","payload","logger","executor","collectionTriggers","Object","keys","length","warn","info","configuredCollections","availableCollections","collections","collectionSlug","triggerConfig","entries","debug","collection","crud","create","delete","read","update","config","hooks","afterChange","push","change","operation","
|
|
1
|
+
{"version":3,"sources":["../../src/plugin/init-collection-hooks.ts"],"sourcesContent":["import type {Payload} from \"payload\"\nimport type {Logger} from \"pino\"\n\nimport type { WorkflowExecutor } from \"../core/workflow-executor.js\"\nimport type {CollectionTriggerConfigCrud, WorkflowsPluginConfig} from \"./config-types.js\"\n\nexport function initCollectionHooks<T extends string>(pluginOptions: WorkflowsPluginConfig<T>, payload: Payload, logger: Payload['logger'], executor: WorkflowExecutor) {\n \n if (!pluginOptions.collectionTriggers || Object.keys(pluginOptions.collectionTriggers).length === 0) {\n logger.warn('No collection triggers configured in plugin options')\n return\n }\n\n logger.info({\n configuredCollections: Object.keys(pluginOptions.collectionTriggers),\n availableCollections: Object.keys(payload.collections)\n }, 'Starting collection hook registration')\n\n // Add hooks to configured collections\n for (const [collectionSlug, triggerConfig] of Object.entries(pluginOptions.collectionTriggers)) {\n if (!triggerConfig) {\n logger.debug({collectionSlug}, 'Skipping collection with falsy trigger config')\n continue\n }\n\n const collection = payload.collections[collectionSlug as T]\n const crud: CollectionTriggerConfigCrud = triggerConfig === true ? {\n create: true,\n delete: true,\n read: true,\n update: true,\n } : triggerConfig\n\n if (!collection.config.hooks) {\n collection.config.hooks = {} as typeof collection.config.hooks\n }\n\n if (crud.update || crud.create) {\n collection.config.hooks.afterChange = collection.config.hooks.afterChange || []\n collection.config.hooks.afterChange.push(async (change) => {\n const operation = change.operation as 'create' | 'update'\n \n // AGGRESSIVE LOGGING - this should ALWAYS appear\n console.log('🚨 AUTOMATION PLUGIN HOOK CALLED! 🚨')\n console.log('Collection:', change.collection.slug)\n console.log('Operation:', operation)\n console.log('Doc ID:', change.doc?.id)\n console.log('Has executor?', !!executor)\n console.log('Executor type:', typeof executor)\n \n logger.info({\n slug: change.collection.slug,\n operation,\n docId: change.doc?.id,\n previousDocId: change.previousDoc?.id,\n hasExecutor: !!executor,\n executorType: typeof executor\n }, 'AUTOMATION PLUGIN: Collection hook triggered')\n\n try {\n console.log('🚨 About to call executeTriggeredWorkflows')\n \n // Execute workflows for this trigger\n await executor.executeTriggeredWorkflows(\n change.collection.slug,\n operation,\n change.doc,\n change.previousDoc,\n change.req\n )\n \n console.log('🚨 executeTriggeredWorkflows completed without error')\n \n logger.info({\n slug: change.collection.slug,\n operation,\n docId: change.doc?.id\n }, 'AUTOMATION PLUGIN: executeTriggeredWorkflows completed successfully')\n } catch (error) {\n console.log('🚨 AUTOMATION PLUGIN ERROR:', error)\n \n logger.error({\n slug: change.collection.slug,\n operation,\n docId: change.doc?.id,\n error: error instanceof Error ? error.message : 'Unknown error',\n stack: error instanceof Error ? error.stack : undefined\n }, 'AUTOMATION PLUGIN: executeTriggeredWorkflows failed')\n // Don't re-throw to avoid breaking other hooks\n }\n })\n }\n\n if (crud.read) {\n collection.config.hooks.afterRead = collection.config.hooks.afterRead || []\n collection.config.hooks.afterRead.push(async (change) => {\n logger.debug({\n slug: change.collection.slug,\n operation: 'read',\n }, 'Collection hook triggered')\n\n // Execute workflows for this trigger\n await executor.executeTriggeredWorkflows(\n change.collection.slug,\n 'read',\n change.doc,\n undefined,\n change.req\n )\n })\n }\n\n if (crud.delete) {\n collection.config.hooks.afterDelete = collection.config.hooks.afterDelete || []\n collection.config.hooks.afterDelete.push(async (change) => {\n logger.debug({\n slug: change.collection.slug,\n operation: 'delete',\n }, 'Collection hook triggered')\n\n // Execute workflows for this trigger\n await executor.executeTriggeredWorkflows(\n change.collection.slug,\n 'delete',\n change.doc,\n undefined,\n change.req\n )\n })\n }\n\n if (collection) {\n logger.info({\n collectionSlug,\n hooksRegistered: {\n afterChange: crud.update || crud.create,\n afterRead: crud.read,\n afterDelete: crud.delete\n }\n }, 'Collection hooks registered successfully')\n } else {\n logger.error({\n collectionSlug,\n availableCollections: Object.keys(payload.collections)\n }, 'Collection not found for trigger configuration - check collection slug spelling')\n }\n }\n}\n"],"names":["initCollectionHooks","pluginOptions","payload","logger","executor","collectionTriggers","Object","keys","length","warn","info","configuredCollections","availableCollections","collections","collectionSlug","triggerConfig","entries","debug","collection","crud","create","delete","read","update","config","hooks","afterChange","push","change","operation","console","log","slug","doc","id","docId","previousDocId","previousDoc","hasExecutor","executorType","executeTriggeredWorkflows","req","error","Error","message","stack","undefined","afterRead","afterDelete","hooksRegistered"],"mappings":"AAMA,OAAO,SAASA,oBAAsCC,aAAuC,EAAEC,OAAgB,EAAEC,MAAyB,EAAEC,QAA0B;IAEpK,IAAI,CAACH,cAAcI,kBAAkB,IAAIC,OAAOC,IAAI,CAACN,cAAcI,kBAAkB,EAAEG,MAAM,KAAK,GAAG;QACnGL,OAAOM,IAAI,CAAC;QACZ;IACF;IAEAN,OAAOO,IAAI,CAAC;QACVC,uBAAuBL,OAAOC,IAAI,CAACN,cAAcI,kBAAkB;QACnEO,sBAAsBN,OAAOC,IAAI,CAACL,QAAQW,WAAW;IACvD,GAAG;IAEH,sCAAsC;IACtC,KAAK,MAAM,CAACC,gBAAgBC,cAAc,IAAIT,OAAOU,OAAO,CAACf,cAAcI,kBAAkB,EAAG;QAC9F,IAAI,CAACU,eAAe;YAClBZ,OAAOc,KAAK,CAAC;gBAACH;YAAc,GAAG;YAC/B;QACF;QAEA,MAAMI,aAAahB,QAAQW,WAAW,CAACC,eAAoB;QAC3D,MAAMK,OAAoCJ,kBAAkB,OAAO;YACjEK,QAAQ;YACRC,QAAQ;YACRC,MAAM;YACNC,QAAQ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Ed;QACF;QAEA,IAAIvB,YAAY;YACdf,OAAOO,IAAI,CAAC;gBACVI;gBACAmC,iBAAiB;oBACfvB,aAAaP,KAAKI,MAAM,IAAIJ,KAAKC,MAAM;oBACvC2B,WAAW5B,KAAKG,IAAI;oBACpB0B,aAAa7B,KAAKE,MAAM;gBAC1B;YACF,GAAG;QACL,OAAO;YACLlB,OAAOuC,KAAK,CAAC;gBACX5B;gBACAF,sBAAsBN,OAAOC,IAAI,CAACL,QAAQW,WAAW;YACvD,GAAG;QACL;IACF;AACF"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@xtr-dev/payload-automation",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.18",
|
|
4
4
|
"description": "PayloadCMS Automation Plugin - Comprehensive workflow automation system with visual workflow building, execution tracking, and step types",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|