next-workflow-builder 0.7.5 → 0.7.7

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.
@@ -1 +1 @@
1
- import{a as N,e as I}from"./chunk-CI7FTYZR.js";import"./chunk-WT4BSMUD.js";import"./chunk-VUDOAZ3W.js";import"./chunk-3YVRTDK2.js";import{b as O}from"./chunk-IEOZJAW2.js";import"./chunk-6UXAINJQ.js";import"./chunk-BNX2SV7E.js";import{i as k}from"./chunk-KFTXS23Q.js";import{k as h,w as A}from"./chunk-QRG4O4PE.js";import{a as m,i as c,j as l,k as f,l as g,o as s}from"./chunk-5J6TNMJG.js";import{WebStandardStreamableHTTPServerTransport as W}from"@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js";import{withMcpAuth as _}from"better-auth/plugins";import{McpServer as E}from"@modelcontextprotocol/sdk/server/mcp.js";import{and as y,desc as v,eq as a,inArray as J}from"drizzle-orm";import{z as r}from"zod";function T(d,i){d.registerTool("list_workflows",{description:"List the authenticated user's workflows",inputSchema:{limit:r.number().optional(),offset:r.number().optional()}},async({limit:e,offset:t})=>{let o=await s.select().from(c).where(a(c.userId,i)).orderBy(v(c.updatedAt)).limit(e??50).offset(t??0);return{content:[{type:"text",text:JSON.stringify(o.map(n=>({...n,createdAt:n.createdAt.toISOString(),updatedAt:n.updatedAt.toISOString()})))}]}}),d.registerTool("get_workflow",{description:"Get a workflow by ID",inputSchema:{workflowId:r.string()}},async({workflowId:e})=>{let t=await s.query.workflows.findFirst({where:y(a(c.id,e),a(c.userId,i))});return t?{content:[{type:"text",text:JSON.stringify({...t,createdAt:t.createdAt.toISOString(),updatedAt:t.updatedAt.toISOString()})}]}:{content:[{type:"text",text:JSON.stringify({error:"Workflow not found"})}]}}),d.registerTool("create_workflow",{description:"Create a new workflow",inputSchema:{name:r.string(),description:r.string().optional(),nodes:r.array(r.record(r.string(),r.unknown())),edges:r.array(r.record(r.string(),r.unknown()))}},async({name:e,description:t,nodes:o,edges:n})=>{if(!(await k(o,i)).valid)return{content:[{type:"text",text:JSON.stringify({error:"Invalid integration references"})}]};let x=m(),[u]=await s.insert(c).values({id:x,name:e,description:t,nodes:o,edges:n,userId:i}).returning();return{content:[{type:"text",text:JSON.stringify({...u,createdAt:u.createdAt.toISOString(),updatedAt:u.updatedAt.toISOString()})}]}}),d.registerTool("update_workflow",{description:"Update an existing workflow",inputSchema:{workflowId:r.string(),name:r.string().optional(),description:r.string().optional(),nodes:r.array(r.record(r.string(),r.unknown())).optional(),edges:r.array(r.record(r.string(),r.unknown())).optional()}},async({workflowId:e,name:t,description:o,nodes:n,edges:w})=>{if(!await s.query.workflows.findFirst({where:y(a(c.id,e),a(c.userId,i))}))return{content:[{type:"text",text:JSON.stringify({error:"Workflow not found"})}]};if(n&&!(await k(n,i)).valid)return{content:[{type:"text",text:JSON.stringify({error:"Invalid integration references"})}]};let u={updatedAt:new Date};t!==void 0&&(u.name=t),o!==void 0&&(u.description=o),n!==void 0&&(u.nodes=n),w!==void 0&&(u.edges=w);let[p]=await s.update(c).set(u).where(a(c.id,e)).returning();return{content:[{type:"text",text:JSON.stringify({...p,createdAt:p.createdAt.toISOString(),updatedAt:p.updatedAt.toISOString()})}]}}),d.registerTool("delete_workflow",{description:"Delete a workflow",inputSchema:{workflowId:r.string()}},async({workflowId:e})=>{if(!await s.query.workflows.findFirst({where:y(a(c.id,e),a(c.userId,i))}))return{content:[{type:"text",text:JSON.stringify({error:"Workflow not found"})}]};let n=(await s.query.workflowExecutions.findMany({where:a(f.workflowId,e),columns:{id:!0}})).map(w=>w.id);return n.length>0&&(await s.delete(g).where(J(g.executionId,n)),await s.delete(f).where(a(f.workflowId,e))),await s.delete(c).where(a(c.id,e)),{content:[{type:"text",text:JSON.stringify({success:!0})}]}}),d.registerTool("duplicate_workflow",{description:"Duplicate a workflow",inputSchema:{workflowId:r.string()}},async({workflowId:e})=>{let t=await s.query.workflows.findFirst({where:y(a(c.id,e),a(c.userId,i))});if(!t)return{content:[{type:"text",text:JSON.stringify({error:"Workflow not found"})}]};let o=t.nodes,n=o.map(p=>({...p,id:m()})),w=new Map(o.map((p,S)=>[p.id,n[S].id])),x=t.edges.map(p=>({...p,id:m(),source:w.get(p.source)||p.source,target:w.get(p.target)||p.target})),[u]=await s.insert(c).values({id:m(),name:`${t.name} (Copy)`,description:t.description,nodes:n,edges:x,userId:i,visibility:"private"}).returning();return{content:[{type:"text",text:JSON.stringify({...u,createdAt:u.createdAt.toISOString(),updatedAt:u.updatedAt.toISOString()})}]}}),d.registerTool("execute_workflow",{description:"Execute a workflow",inputSchema:{workflowId:r.string(),input:r.record(r.string(),r.unknown()).optional()}},async({workflowId:e,input:t})=>{let o=await s.query.workflows.findFirst({where:y(a(c.id,e),a(c.userId,i))});if(!o)return{content:[{type:"text",text:JSON.stringify({error:"Workflow not found"})}]};if(!(await k(o.nodes,i)).valid)return{content:[{type:"text",text:JSON.stringify({error:"Invalid integration references"})}]};let[w]=await s.insert(f).values({workflowId:e,userId:i,status:"running",input:t??{}}).returning();return I(w.id,e,o.nodes,o.edges,t??{}),{content:[{type:"text",text:JSON.stringify({executionId:w.id,status:"running"})}]}}),d.registerTool("get_execution_status",{description:"Get execution status and logs",inputSchema:{executionId:r.string()}},async({executionId:e})=>{let t=await s.query.workflowExecutions.findFirst({where:a(f.id,e),with:{workflow:!0}});if(!t||t.workflow.userId!==i)return{content:[{type:"text",text:JSON.stringify({error:"Execution not found"})}]};let o=await s.query.workflowExecutionLogs.findMany({where:a(g.executionId,e),orderBy:[v(g.timestamp)]});return{content:[{type:"text",text:JSON.stringify({status:t.status,input:t.input,output:t.output,error:t.error,startedAt:t.startedAt.toISOString(),completedAt:t.completedAt?.toISOString(),logs:o.map(n=>({nodeId:n.nodeId,nodeName:n.nodeName,nodeType:n.nodeType,status:n.status,input:n.input,output:n.output,error:n.error}))})}]}}),d.registerTool("cancel_execution",{description:"Cancel a running workflow execution",inputSchema:{executionId:r.string()}},async({executionId:e})=>{let t=await s.query.workflowExecutions.findFirst({where:a(f.id,e),with:{workflow:!0}});if(!t||t.workflow.userId!==i)return{content:[{type:"text",text:JSON.stringify({error:"Execution not found"})}]};if(t.status!=="running"&&t.status!=="pending")return{content:[{type:"text",text:JSON.stringify({error:"Execution is not running",status:t.status})}]};await s.update(f).set({status:"cancelled",completedAt:new Date,duration:String(Date.now()-new Date(t.startedAt).getTime())}).where(a(f.id,e));let o=await s.query.workflowExecutionLogs.findMany({where:y(a(g.executionId,e),J(g.status,["pending","running"]))});for(let n of o)await s.update(g).set({status:"error",error:"Cancelled",completedAt:new Date}).where(a(g.id,n.id));return{content:[{type:"text",text:JSON.stringify({success:!0,status:"cancelled"})}]}}),d.registerTool("list_available_actions",{description:"List all available plugin actions with their config fields"},async()=>{let t=h().map(o=>({id:o.id,label:o.label,description:o.description,category:o.category,integration:o.integration,configFields:A(o.configFields).map(n=>({key:n.key,label:n.label,type:n.type,required:n.required,placeholder:n.placeholder}))}));return{content:[{type:"text",text:JSON.stringify(t)}]}}),d.registerTool("list_integrations",{description:"List the authenticated user's connected integrations"},async()=>{let e=await s.select({id:l.id,name:l.name,type:l.type,isManaged:l.isManaged,createdAt:l.createdAt,updatedAt:l.updatedAt}).from(l).where(a(l.userId,i));return{content:[{type:"text",text:JSON.stringify(e.map(t=>({...t,createdAt:t.createdAt.toISOString(),updatedAt:t.updatedAt.toISOString()})))}]}})}function L(d){let i=new E({name:"workflow-builder",version:"1.0.0"});return T(i,d),i}async function M(d,i){let e=L(i),t=new W({sessionIdGenerator:void 0});return await e.connect(t),await t.handleRequest(d)}async function V(d){if(d.method==="POST"){if(process.env.NWB_ANONYMOUS_AUTH!=="false"){let i=await N(d);if(i)return M(d,i.id)}return _(O,async(i,e)=>M(i,e.userId))(d)}return new Response("Method not allowed",{status:405})}export{V as handleMcpRequest};
1
+ import{a as N,e as I}from"./chunk-2V446QDJ.js";import"./chunk-H2FP5MBV.js";import"./chunk-VUDOAZ3W.js";import"./chunk-3YVRTDK2.js";import{b as O}from"./chunk-IEOZJAW2.js";import"./chunk-6UXAINJQ.js";import"./chunk-BNX2SV7E.js";import{i as k}from"./chunk-KFTXS23Q.js";import{k as h,w as A}from"./chunk-QRG4O4PE.js";import{a as m,i as c,j as l,k as f,l as g,o as s}from"./chunk-5J6TNMJG.js";import{WebStandardStreamableHTTPServerTransport as W}from"@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js";import{withMcpAuth as _}from"better-auth/plugins";import{McpServer as E}from"@modelcontextprotocol/sdk/server/mcp.js";import{and as y,desc as v,eq as a,inArray as J}from"drizzle-orm";import{z as r}from"zod";function T(d,i){d.registerTool("list_workflows",{description:"List the authenticated user's workflows",inputSchema:{limit:r.number().optional(),offset:r.number().optional()}},async({limit:e,offset:t})=>{let o=await s.select().from(c).where(a(c.userId,i)).orderBy(v(c.updatedAt)).limit(e??50).offset(t??0);return{content:[{type:"text",text:JSON.stringify(o.map(n=>({...n,createdAt:n.createdAt.toISOString(),updatedAt:n.updatedAt.toISOString()})))}]}}),d.registerTool("get_workflow",{description:"Get a workflow by ID",inputSchema:{workflowId:r.string()}},async({workflowId:e})=>{let t=await s.query.workflows.findFirst({where:y(a(c.id,e),a(c.userId,i))});return t?{content:[{type:"text",text:JSON.stringify({...t,createdAt:t.createdAt.toISOString(),updatedAt:t.updatedAt.toISOString()})}]}:{content:[{type:"text",text:JSON.stringify({error:"Workflow not found"})}]}}),d.registerTool("create_workflow",{description:"Create a new workflow",inputSchema:{name:r.string(),description:r.string().optional(),nodes:r.array(r.record(r.string(),r.unknown())),edges:r.array(r.record(r.string(),r.unknown()))}},async({name:e,description:t,nodes:o,edges:n})=>{if(!(await k(o,i)).valid)return{content:[{type:"text",text:JSON.stringify({error:"Invalid integration references"})}]};let x=m(),[u]=await s.insert(c).values({id:x,name:e,description:t,nodes:o,edges:n,userId:i}).returning();return{content:[{type:"text",text:JSON.stringify({...u,createdAt:u.createdAt.toISOString(),updatedAt:u.updatedAt.toISOString()})}]}}),d.registerTool("update_workflow",{description:"Update an existing workflow",inputSchema:{workflowId:r.string(),name:r.string().optional(),description:r.string().optional(),nodes:r.array(r.record(r.string(),r.unknown())).optional(),edges:r.array(r.record(r.string(),r.unknown())).optional()}},async({workflowId:e,name:t,description:o,nodes:n,edges:w})=>{if(!await s.query.workflows.findFirst({where:y(a(c.id,e),a(c.userId,i))}))return{content:[{type:"text",text:JSON.stringify({error:"Workflow not found"})}]};if(n&&!(await k(n,i)).valid)return{content:[{type:"text",text:JSON.stringify({error:"Invalid integration references"})}]};let u={updatedAt:new Date};t!==void 0&&(u.name=t),o!==void 0&&(u.description=o),n!==void 0&&(u.nodes=n),w!==void 0&&(u.edges=w);let[p]=await s.update(c).set(u).where(a(c.id,e)).returning();return{content:[{type:"text",text:JSON.stringify({...p,createdAt:p.createdAt.toISOString(),updatedAt:p.updatedAt.toISOString()})}]}}),d.registerTool("delete_workflow",{description:"Delete a workflow",inputSchema:{workflowId:r.string()}},async({workflowId:e})=>{if(!await s.query.workflows.findFirst({where:y(a(c.id,e),a(c.userId,i))}))return{content:[{type:"text",text:JSON.stringify({error:"Workflow not found"})}]};let n=(await s.query.workflowExecutions.findMany({where:a(f.workflowId,e),columns:{id:!0}})).map(w=>w.id);return n.length>0&&(await s.delete(g).where(J(g.executionId,n)),await s.delete(f).where(a(f.workflowId,e))),await s.delete(c).where(a(c.id,e)),{content:[{type:"text",text:JSON.stringify({success:!0})}]}}),d.registerTool("duplicate_workflow",{description:"Duplicate a workflow",inputSchema:{workflowId:r.string()}},async({workflowId:e})=>{let t=await s.query.workflows.findFirst({where:y(a(c.id,e),a(c.userId,i))});if(!t)return{content:[{type:"text",text:JSON.stringify({error:"Workflow not found"})}]};let o=t.nodes,n=o.map(p=>({...p,id:m()})),w=new Map(o.map((p,S)=>[p.id,n[S].id])),x=t.edges.map(p=>({...p,id:m(),source:w.get(p.source)||p.source,target:w.get(p.target)||p.target})),[u]=await s.insert(c).values({id:m(),name:`${t.name} (Copy)`,description:t.description,nodes:n,edges:x,userId:i,visibility:"private"}).returning();return{content:[{type:"text",text:JSON.stringify({...u,createdAt:u.createdAt.toISOString(),updatedAt:u.updatedAt.toISOString()})}]}}),d.registerTool("execute_workflow",{description:"Execute a workflow",inputSchema:{workflowId:r.string(),input:r.record(r.string(),r.unknown()).optional()}},async({workflowId:e,input:t})=>{let o=await s.query.workflows.findFirst({where:y(a(c.id,e),a(c.userId,i))});if(!o)return{content:[{type:"text",text:JSON.stringify({error:"Workflow not found"})}]};if(!(await k(o.nodes,i)).valid)return{content:[{type:"text",text:JSON.stringify({error:"Invalid integration references"})}]};let[w]=await s.insert(f).values({workflowId:e,userId:i,status:"running",input:t??{}}).returning();return I(w.id,e,o.nodes,o.edges,t??{}),{content:[{type:"text",text:JSON.stringify({executionId:w.id,status:"running"})}]}}),d.registerTool("get_execution_status",{description:"Get execution status and logs",inputSchema:{executionId:r.string()}},async({executionId:e})=>{let t=await s.query.workflowExecutions.findFirst({where:a(f.id,e),with:{workflow:!0}});if(!t||t.workflow.userId!==i)return{content:[{type:"text",text:JSON.stringify({error:"Execution not found"})}]};let o=await s.query.workflowExecutionLogs.findMany({where:a(g.executionId,e),orderBy:[v(g.timestamp)]});return{content:[{type:"text",text:JSON.stringify({status:t.status,input:t.input,output:t.output,error:t.error,startedAt:t.startedAt.toISOString(),completedAt:t.completedAt?.toISOString(),logs:o.map(n=>({nodeId:n.nodeId,nodeName:n.nodeName,nodeType:n.nodeType,status:n.status,input:n.input,output:n.output,error:n.error}))})}]}}),d.registerTool("cancel_execution",{description:"Cancel a running workflow execution",inputSchema:{executionId:r.string()}},async({executionId:e})=>{let t=await s.query.workflowExecutions.findFirst({where:a(f.id,e),with:{workflow:!0}});if(!t||t.workflow.userId!==i)return{content:[{type:"text",text:JSON.stringify({error:"Execution not found"})}]};if(t.status!=="running"&&t.status!=="pending")return{content:[{type:"text",text:JSON.stringify({error:"Execution is not running",status:t.status})}]};await s.update(f).set({status:"cancelled",completedAt:new Date,duration:String(Date.now()-new Date(t.startedAt).getTime())}).where(a(f.id,e));let o=await s.query.workflowExecutionLogs.findMany({where:y(a(g.executionId,e),J(g.status,["pending","running"]))});for(let n of o)await s.update(g).set({status:"error",error:"Cancelled",completedAt:new Date}).where(a(g.id,n.id));return{content:[{type:"text",text:JSON.stringify({success:!0,status:"cancelled"})}]}}),d.registerTool("list_available_actions",{description:"List all available plugin actions with their config fields"},async()=>{let t=h().map(o=>({id:o.id,label:o.label,description:o.description,category:o.category,integration:o.integration,configFields:A(o.configFields).map(n=>({key:n.key,label:n.label,type:n.type,required:n.required,placeholder:n.placeholder}))}));return{content:[{type:"text",text:JSON.stringify(t)}]}}),d.registerTool("list_integrations",{description:"List the authenticated user's connected integrations"},async()=>{let e=await s.select({id:l.id,name:l.name,type:l.type,isManaged:l.isManaged,createdAt:l.createdAt,updatedAt:l.updatedAt}).from(l).where(a(l.userId,i));return{content:[{type:"text",text:JSON.stringify(e.map(t=>({...t,createdAt:t.createdAt.toISOString(),updatedAt:t.updatedAt.toISOString()})))}]}})}function L(d){let i=new E({name:"workflow-builder",version:"1.0.0"});return T(i,d),i}async function M(d,i){let e=L(i),t=new W({sessionIdGenerator:void 0});return await e.connect(t),await t.handleRequest(d)}async function V(d){if(d.method==="POST"){if(process.env.NWB_ANONYMOUS_AUTH!=="false"){let i=await N(d);if(i)return M(d,i.id)}return _(O,async(i,e)=>M(i,e.userId))(d)}return new Response("Method not allowed",{status:405})}export{V as handleMcpRequest};
@@ -0,0 +1 @@
1
+ import"./chunk-R5GS6TJS.js";import"./chunk-CYVALTSI.js";import"./chunk-IEOZJAW2.js";import"./chunk-6UXAINJQ.js";import"./chunk-BNX2SV7E.js";import"./chunk-PRVESNIO.js";import"./chunk-KFTXS23Q.js";import"./chunk-QRG4O4PE.js";import"./chunk-7WFHHPX4.js";import{q as f}from"./chunk-5J6TNMJG.js";import"server-only";function d(e,n){if(e&&typeof e=="object")return e[n]}function h(e){let n=Number(e.inputCount)||2,r=[];for(let u=1;u<=n;u++){let s=e[`input${u}`];r.push(Array.isArray(s)?s:[])}return r}function p(e){let n=e.flat();return{merged:n,totalItems:n.length}}function y(e,n){let r=Math.max(...e.map(c=>c.length)),u=n!=="discard",s=[];for(let c=0;c<r;c++){if(!u&&e.some(o=>o[c]===void 0))continue;let i={};for(let o=0;o<e.length;o++){let g=e[o][c];g&&typeof g=="object"?Object.assign(i,g):i[`input${o+1}`]=g??null}s.push(i)}return{merged:s,totalItems:s.length}}function k(e,n,r){if(e.length<2)return{merged:e[0]||[],totalItems:e[0]?.length||0};let u=e[0];for(let s=1;s<e.length;s++){let c=e[s],i=new Map;for(let t of c){let l=d(t,n);i.has(l)||i.set(l,[]),i.get(l).push(t)}let o=[],g=new Set;for(let t of u){let l=d(t,n),m=i.get(l);if(m&&m.length>0){g.add(l);for(let a of m)o.push({...typeof t=="object"?t:{},...typeof a=="object"?a:{}})}else(r==="leftOuter"||r==="fullOuter")&&o.push({...typeof t=="object"?t:{}})}if(r==="rightOuter"||r==="fullOuter")for(let t of c){let l=d(t,n);g.has(l)||o.push({...typeof t=="object"?t:{}})}u=o}return{merged:u,totalItems:u.length}}function w(e){let n=h(e);switch(e.mode||"append"){case"append":return p(n);case"combineByPosition":return y(n,e.unmatchedHandling||"useNull");case"combineByFields":return k(n,e.matchField1||"id",e.joinType||"inner");default:return p(n)}}async function M(e){"use step";return f(e,()=>Promise.resolve(w(e)))}M.maxRetries=0;export{M as mergeStep};
@@ -1 +1 @@
1
- import{a as w}from"./chunk-WT4BSMUD.js";import"./chunk-3YVRTDK2.js";import"./chunk-R5GS6TJS.js";import"./chunk-CYVALTSI.js";import"./chunk-IEOZJAW2.js";import"./chunk-6UXAINJQ.js";import"./chunk-BNX2SV7E.js";import"./chunk-PRVESNIO.js";import"./chunk-KFTXS23Q.js";import"./chunk-QRG4O4PE.js";import"./chunk-7WFHHPX4.js";import{a as c,i,k as l,o as f,q as p}from"./chunk-5J6TNMJG.js";import"server-only";import{eq as d}from"drizzle-orm";async function k(t){let{workflowId:r,input:e}=t;if(!r)return{success:!1,error:"No workflow selected"};let[o]=await f.select().from(i).where(d(i.id,r)).limit(1);if(!o)return{success:!1,error:`Workflow "${r}" not found`};let s={};if(e&&e.trim())try{s=JSON.parse(e)}catch{return{success:!1,error:`Invalid JSON input: ${e}`}}let u=c();await f.insert(l).values({id:u,workflowId:r,userId:o.userId,status:"running",input:s});let n=await w({nodes:o.nodes,edges:o.edges,triggerInput:s,executionId:u,workflowId:r});if(n.success){let a=Object.values(n.outputs||{}).at(-1)?.data;return{success:!0,executionId:u,output:a}}return{success:!1,error:n.error||"Sub-workflow execution failed"}}async function m(t){"use step";return p(t,()=>k(t))}m.maxRetries=0;export{m as runWorkflowStep};
1
+ import{a as w}from"./chunk-H2FP5MBV.js";import"./chunk-3YVRTDK2.js";import"./chunk-R5GS6TJS.js";import"./chunk-CYVALTSI.js";import"./chunk-IEOZJAW2.js";import"./chunk-6UXAINJQ.js";import"./chunk-BNX2SV7E.js";import"./chunk-PRVESNIO.js";import"./chunk-KFTXS23Q.js";import"./chunk-QRG4O4PE.js";import"./chunk-7WFHHPX4.js";import{a as c,i,k as l,o as f,q as p}from"./chunk-5J6TNMJG.js";import"server-only";import{eq as d}from"drizzle-orm";async function k(t){let{workflowId:r,input:e}=t;if(!r)return{success:!1,error:"No workflow selected"};let[o]=await f.select().from(i).where(d(i.id,r)).limit(1);if(!o)return{success:!1,error:`Workflow "${r}" not found`};let s={};if(e&&e.trim())try{s=JSON.parse(e)}catch{return{success:!1,error:`Invalid JSON input: ${e}`}}let u=c();await f.insert(l).values({id:u,workflowId:r,userId:o.userId,status:"running",input:s});let n=await w({nodes:o.nodes,edges:o.edges,triggerInput:s,executionId:u,workflowId:r});if(n.success){let a=Object.values(n.outputs||{}).at(-1)?.data;return{success:!0,executionId:u,output:a}}return{success:!1,error:n.error||"Sub-workflow execution failed"}}async function m(t){"use step";return p(t,()=>k(t))}m.maxRetries=0;export{m as runWorkflowStep};
@@ -1 +1 @@
1
- import{a as d}from"./chunk-WT4BSMUD.js";import"./chunk-3YVRTDK2.js";import"./chunk-R5GS6TJS.js";import"./chunk-CYVALTSI.js";import"./chunk-IEOZJAW2.js";import"./chunk-6UXAINJQ.js";import"./chunk-BNX2SV7E.js";import"./chunk-PRVESNIO.js";import"./chunk-KFTXS23Q.js";import"./chunk-QRG4O4PE.js";import"./chunk-7WFHHPX4.js";import{a,i as c,k as w,o as i,q as p}from"./chunk-5J6TNMJG.js";import"server-only";import{eq as g}from"drizzle-orm";function R(e){if(!e||!e.trim())return[];try{let t=JSON.parse(e);if(Array.isArray(t))return t.filter(Boolean)}catch{}return e.split(",").map(t=>t.trim()).filter(Boolean)}async function W(e){let t=R(e.workflowIds),f=e.continueOnFailure==="true";if(t.length===0)return{success:!1,error:"No workflows selected"};let u={};if(e.input&&e.input.trim())try{u=JSON.parse(e.input)}catch{return{success:!1,error:`Invalid JSON input: ${e.input}`}}let o=[];for(let r of t){let[s]=await i.select().from(c).where(g(c.id,r)).limit(1);if(!s){let I={workflowId:r,workflowName:"Unknown",executionId:"",success:!1,error:`Workflow "${r}" not found`};if(o.push(I),!f)break;continue}let l=a();await i.insert(w).values({id:l,workflowId:r,userId:s.userId,status:"running",input:u});let n=await d({nodes:s.nodes,edges:s.edges,triggerInput:u,executionId:l,workflowId:r}),k=Object.values(n.outputs||{}).at(-1)?.data,m={workflowId:r,workflowName:s.name,executionId:l,success:n.success,output:k,error:n.error};if(o.push(m),!n.success&&!f)break}return{success:!0,results:o,succeeded:o.filter(r=>r.success).length,failed:o.filter(r=>!r.success).length,total:t.length}}async function S(e){"use step";return p(e,()=>W(e))}S.maxRetries=0;export{S as runWorkflowsInSequenceStep};
1
+ import{a as d}from"./chunk-H2FP5MBV.js";import"./chunk-3YVRTDK2.js";import"./chunk-R5GS6TJS.js";import"./chunk-CYVALTSI.js";import"./chunk-IEOZJAW2.js";import"./chunk-6UXAINJQ.js";import"./chunk-BNX2SV7E.js";import"./chunk-PRVESNIO.js";import"./chunk-KFTXS23Q.js";import"./chunk-QRG4O4PE.js";import"./chunk-7WFHHPX4.js";import{a,i as c,k as w,o as i,q as p}from"./chunk-5J6TNMJG.js";import"server-only";import{eq as g}from"drizzle-orm";function R(e){if(!e||!e.trim())return[];try{let t=JSON.parse(e);if(Array.isArray(t))return t.filter(Boolean)}catch{}return e.split(",").map(t=>t.trim()).filter(Boolean)}async function W(e){let t=R(e.workflowIds),f=e.continueOnFailure==="true";if(t.length===0)return{success:!1,error:"No workflows selected"};let u={};if(e.input&&e.input.trim())try{u=JSON.parse(e.input)}catch{return{success:!1,error:`Invalid JSON input: ${e.input}`}}let o=[];for(let r of t){let[s]=await i.select().from(c).where(g(c.id,r)).limit(1);if(!s){let I={workflowId:r,workflowName:"Unknown",executionId:"",success:!1,error:`Workflow "${r}" not found`};if(o.push(I),!f)break;continue}let l=a();await i.insert(w).values({id:l,workflowId:r,userId:s.userId,status:"running",input:u});let n=await d({nodes:s.nodes,edges:s.edges,triggerInput:u,executionId:l,workflowId:r}),k=Object.values(n.outputs||{}).at(-1)?.data,m={workflowId:r,workflowName:s.name,executionId:l,success:n.success,output:k,error:n.error};if(o.push(m),!n.success&&!f)break}return{success:!0,results:o,succeeded:o.filter(r=>r.success).length,failed:o.filter(r=>!r.success).length,total:t.length}}async function S(e){"use step";return p(e,()=>W(e))}S.maxRetries=0;export{S as runWorkflowsInSequenceStep};
@@ -1,21 +1,21 @@
1
- import{a as h,b as $,c as Te,d as Fe,e as H,f as ve,g as Ue,h as se,i as Ce,j as Oe,k as Me,l as ae}from"../../chunk-CI7FTYZR.js";import"../../chunk-WT4BSMUD.js";import{a as Ee,b as Ie,c as Re}from"../../chunk-NI6U7PHC.js";import{a as re,b as he,c as ke,d as ye,e as je,f as xe,g as J,h as G}from"../../chunk-VUDOAZ3W.js";import"../../chunk-3YVRTDK2.js";import{b as M}from"../../chunk-IEOZJAW2.js";import"../../chunk-6UXAINJQ.js";import{j as Ae,k as Pe,n as be}from"../../chunk-BNX2SV7E.js";import{c as Ne,d as ne,f as We,g as $e,h as Se,i as K}from"../../chunk-KFTXS23Q.js";import{m as me}from"../../chunk-QRG4O4PE.js";import{a as _,b as V,d as oe,i as p,k as x,l as N,m as A,o as c}from"../../chunk-5J6TNMJG.js";import{NextResponse as ee}from"next/server";import{and as Pt,eq as ie}from"drizzle-orm";import{NextResponse as S}from"next/server";import{createHash as bt}from"crypto";async function De(r){try{let t=await h(r);if(!t)return S.json({error:"Unauthorized"},{status:401});let e=await c.query.apiKeys.findMany({where:ie(A.userId,t.id),columns:{id:!0,name:!0,keyPrefix:!0,createdAt:!0,lastUsedAt:!0},orderBy:(o,{desc:n})=>[n(o.createdAt)]});return S.json(e)}catch(t){return console.error("Failed to list API keys:",t),S.json({error:"Failed to list API keys"},{status:500})}}async function Ge(r){try{let t=await h(r);if(!t)return S.json({error:"Unauthorized"},{status:401});if(t.name==="Anonymous"||t.email?.startsWith("temp-"))return S.json({error:"Anonymous users cannot create API keys"},{status:403});let n=(await r.json().catch(()=>({}))).name||null,{randomBytes:u}=await import("crypto"),d=`wfb_${u(24).toString("base64url")}`,g=bt("sha256").update(d).digest("hex"),I=d.slice(0,11),[R]=await c.insert(A).values({userId:t.id,name:n,keyHash:g,keyPrefix:I}).returning({id:A.id,name:A.name,keyPrefix:A.keyPrefix,createdAt:A.createdAt});return S.json({...R,key:d})}catch(t){return console.error("Failed to create API key:",t),S.json({error:"Failed to create API key"},{status:500})}}async function _e(r,t){try{let e=await h(r);return e?(await c.delete(A).where(Pt(ie(A.id,t),ie(A.userId,e.id))).returning({id:A.id})).length===0?S.json({error:"API key not found"},{status:404}):S.json({success:!0}):S.json({error:"Unauthorized"},{status:401})}catch(e){return console.error("Failed to delete API key:",e),S.json({error:"Failed to delete API key"},{status:500})}}import{toNextJsHandler as Nt}from"better-auth/next-js";var{GET:Wt,POST:$t}=Nt(M);async function ue(r,t){let e="/api/auth/"+t.slice(1).join("/"),o=new URL(r.url),n=`${o.origin}${e}${o.search}`,u=Fe(r,n),l=r.method==="GET"?await Wt(u):await $t(u);return l.status>=500&&!await l.clone().text()?new Response(JSON.stringify({debug:"500 with empty body from better-auth",path:e}),{status:500,headers:{"Content-Type":"application/json"}}):l}import{eq as St}from"drizzle-orm";import{NextResponse as X}from"next/server";async function ze(r,t){try{if(r.headers.get("authorization")!==`Bearer ${process.env.CRON_SECRET}`)return X.json({error:"Unauthorized"},{status:401});let o=await c.query.workflows.findFirst({where:St(p.id,t)});if(!o)return X.json({error:"Workflow not found"},{status:404});let[n]=await c.insert(x).values({workflowId:t,userId:o.userId,status:"running",input:{}}).returning();return await H(n.id,t,o.nodes,o.edges,{}),X.json({success:!0,workflowId:t,executionId:n.id,message:"Workflow execution completed"})}catch(e){return console.error("[Cron] Scheduled workflow execution error:",e),X.json({error:"Execution failed",message:e instanceof Error?e.message:"Unknown error"},{status:500})}}import{oAuthDiscoveryMetadata as Tt,oAuthProtectedResourceMetadata as Ft}from"better-auth/plugins";var de=Tt(M),ce=Ft(M);import{NextResponse as y}from"next/server";async function Le(r){try{let t=await h(r);if(!t)return y.json({error:"Unauthorized"},{status:401});let{searchParams:e}=new URL(r.url),o=e.get("type"),n=await Ne(t.id,o||void 0);return y.json(n.map(u=>({id:u.id,name:u.name,type:u.type,isManaged:u.isManaged??!1,createdAt:u.createdAt.toISOString(),updatedAt:u.updatedAt.toISOString()})))}catch(t){return console.error("Failed to get integrations:",t),y.json({error:"Failed to get integrations",details:t instanceof Error?t.message:"Unknown error"},{status:500})}}async function qe(r){try{let t=await h(r);if(!t)return y.json({error:"Unauthorized"},{status:401});let e=await r.json();if(!(e.type&&e.config))return y.json({error:"Type and config are required"},{status:400});let o=await We(t.id,e.name||"",e.type,e.config);return y.json({id:o.id,name:o.name,type:o.type,createdAt:o.createdAt.toISOString(),updatedAt:o.updatedAt.toISOString()})}catch(t){return console.error("Failed to create integration:",t),y.json({error:"Failed to create integration",details:t instanceof Error?t.message:"Unknown error"},{status:500})}}async function Ke(r,t){try{let e=await h(r);if(!e)return y.json({error:"Unauthorized"},{status:401});let o=await ne(t,e.id);return o?y.json({id:o.id,name:o.name,type:o.type,config:o.config,createdAt:o.createdAt.toISOString(),updatedAt:o.updatedAt.toISOString()}):y.json({error:"Integration not found"},{status:404})}catch(e){return console.error("Failed to get integration:",e),y.json({error:"Failed to get integration",details:e instanceof Error?e.message:"Unknown error"},{status:500})}}async function He(r,t){try{let e=await h(r);if(!e)return y.json({error:"Unauthorized"},{status:401});let o=await r.json(),n=await $e(t,e.id,o);return n?y.json({id:n.id,name:n.name,type:n.type,config:n.config,createdAt:n.createdAt.toISOString(),updatedAt:n.updatedAt.toISOString()}):y.json({error:"Integration not found"},{status:404})}catch(e){return console.error("Failed to update integration:",e),y.json({error:"Failed to update integration",details:e instanceof Error?e.message:"Unknown error"},{status:500})}}async function Be(r,t){try{let e=await h(r);return e?await Se(t,e.id)?y.json({success:!0}):y.json({error:"Integration not found"},{status:404}):y.json({error:"Unauthorized"},{status:401})}catch(e){return console.error("Failed to delete integration:",e),y.json({error:"Failed to delete integration",details:e instanceof Error?e.message:"Unknown error"},{status:500})}}async function Ye(r,t){try{let e=await h(r);if(!e)return y.json({error:"Unauthorized"},{status:401});let o=await ne(t,e.id);return o?o.type==="database"?y.json({status:"success",message:"Integration exists"}):y.json({status:"success",message:"Integration exists"}):y.json({error:"Integration not found"},{status:404})}catch(e){return console.error("Failed to test integration:",e),y.json({status:"error",message:e instanceof Error?e.message:"Failed to test connection"},{status:500})}}async function Je(r){try{if(!await h(r))return y.json({error:"Unauthorized"},{status:401});let e=await r.json();return e.type&&e.config?y.json({status:"success",message:"Credentials accepted"}):y.json({error:"Type and config are required"},{status:400})}catch(t){return console.error("Failed to test credentials:",t),y.json({status:"error",message:t instanceof Error?t.message:"Failed to test connection"},{status:500})}}import{eq as Q}from"drizzle-orm";import{NextResponse as D}from"next/server";async function Ve(r){try{let t=await h(r);if(!t)return D.json({error:"Unauthorized"},{status:401});let e=await c.query.users.findFirst({where:Q(V.id,t.id),columns:{id:!0,name:!0,email:!0,image:!0,isAnonymous:!0}});if(!e)return D.json({error:"User not found"},{status:404});let o=await c.query.accounts.findFirst({where:Q(oe.userId,t.id),columns:{providerId:!0}});return D.json({...e,providerId:o?.providerId??null})}catch(t){return console.error("Failed to get user:",t),D.json({error:t instanceof Error?t.message:"Failed to get user"},{status:500})}}async function Xe(r){try{let t=await h(r);if(!t)return D.json({error:"Unauthorized"},{status:401});let e=await c.query.accounts.findFirst({where:Q(oe.userId,t.id),columns:{providerId:!0}});if(e&&["vercel","github","google"].includes(e.providerId))return D.json({error:"Cannot update profile for OAuth users"},{status:403});let n=await r.json(),u={};return n.name!==void 0&&(u.name=n.name),n.email!==void 0&&(u.email=n.email),await c.update(V).set(u).where(Q(V.id,t.id)),D.json({success:!0})}catch(t){return console.error("Failed to update user:",t),D.json({error:t instanceof Error?t.message:"Failed to update user"},{status:500})}}import{and as v,desc as Z,eq as f,inArray as fe}from"drizzle-orm";import{NextResponse as a}from"next/server";import{createHash as zt}from"crypto";import"server-only";var vt={"Database Query":Ie.codeGenerator,"HTTP Request":Re.codeGenerator,Condition:Ee.codeGenerator},Ut=/export\s+(?:async\s+)?function\s+\w+\s*\([^)]*\)\s*(?::\s*[^{]+)?\s*\{([\s\S]*)\}/;function Ct(r){let t=vt[r];if(!t){let e=me(r);e?.codegenTemplate&&(t=e.codegenTemplate)}if(!t)return null;try{let e=t.match(Ut);return e?e[1].trim():null}catch{return null}}function Ot(r,t){let e=r.substring(1),o=e.indexOf(":");if(o===-1)return t;let n=e.substring(0,o),u=e.substring(o+1),l=u.indexOf("."),d=l!==-1?u.substring(l+1):"",g=n.replace(/[^a-zA-Z0-9]/g,"_");if(!d)return`\${outputs?.['${g}']?.data}`;let I=d.split(".").map(R=>{let b=R.match(re);return b?`?.${b[1]}?.[${b[2]}]`:`?.${R}`}).join("");return`\${outputs?.['${g}']?.data${I}}`}function Mt(r){let t=r.substring(1);if(!(t.includes(".")||t.includes("[")))return`\${outputs?.['${t.replace(/[^a-zA-Z0-9]/g,"_")}']?.data}`;let e=t.split("."),n=e[0].replace(/[^a-zA-Z0-9]/g,"_"),u=e.slice(1).join(".");if(!u)return`\${outputs?.['${n}']?.data}`;let l=u.split(".").map(d=>{let g=d.match(re);return g?`?.${g[1]}?.[${g[2]}]`:`?.${d}`}).join("");return`\${outputs?.['${n}']?.data${l}}`}function m(r){if(!r||typeof r!="string")return r;let t=/\{\{([^}]+)\}\}/g;return r.replace(t,(e,o)=>{let n=o.trim();return n.startsWith("@")?Ot(n,e):n.startsWith("$")?Mt(n):e})}function Dt(r){let t=he(r),e=r.at(-1);return e&&t.add(e.id),t}function Gt(r){let t=new Map,e=new Map;for(let o of r)if(o.data.type==="action"){let u=(o.data.config||{}).actionType,l=o.data.label||u||"UnnamedStep",d=J(l),g=t.get(d)||0;t.set(d,g+1);let I=g>0?`${d}${g+1}`:d;e.set(o.id,I)}return e}function _t(r,t,e){let o=[];for(let n of r)if(n.data.type==="action"){let u=t.get(n.id);o.push(e(n,u))}return o}function Qe(r,t,e){let o=new Set,n=[],u=new Map(t.map(s=>[s.id,s])),l=ke(e),d=ye(t,e),g=Dt(t);o.add("import { sleep, FatalError } from 'workflow';");function I(s){return o.add("import { Resend } from 'resend';"),["fromEmail: process.env.RESEND_FROM_EMAIL || 'noreply@example.com'",`emailTo: \`${m(s.emailTo||"user@example.com")}\``,`emailSubject: \`${m(s.emailSubject||"Notification")}\``,`emailBody: \`${m(s.emailBody||"No content")}\``,"apiKey: process.env.RESEND_API_KEY!"]}function R(s){return o.add("import { WebClient } from '@slack/web-api';"),[`slackChannel: \`${m(s.slackChannel||"#general")}\``,`slackMessage: \`${m(s.slackMessage||"No message")}\``,"apiKey: process.env.SLACK_API_KEY!"]}function b(s){o.add("import { LinearClient } from '@linear/sdk';");let i=[`ticketTitle: \`${m(s.ticketTitle||"New Issue")}\``,`ticketDescription: \`${m(s.ticketDescription||"")}\``,"apiKey: process.env.LINEAR_API_KEY!"];return s.teamId&&i.push(`teamId: "${s.teamId}"`),i}function z(s){o.add("import { generateText } from 'ai';");let i=s.aiModel||"meta/llama-4-scout",k;if(i.includes("/"))k=i;else{let w;i.startsWith("gpt-")||i.startsWith("o1-")?w="openai":i.startsWith("claude-")?w="anthropic":w="openai",k=`${w}/${i}`}return[`model: "${k}"`,`prompt: \`${m(s.aiPrompt||"")}\``,"apiKey: process.env.OPENAI_API_KEY!"]}function L(s){return o.add("import { experimental_generateImage as generateImage } from 'ai';"),[`model: "${s.imageModel||"google/imagen-4.0-generate"}"`,`prompt: \`${m(s.imagePrompt||"")}\``,'size: "1024x1024"',"providerOptions: { openai: { apiKey: process.env.AI_GATEWAY_API_KEY! } }"]}function q(s){return[`query: \`${m(s.dbQuery||"SELECT 1")}\``]}function E(s){let i=[`url: "${s.endpoint||"https://api.example.com/endpoint"}"`,`method: "${s.httpMethod||"POST"}"`,`headers: ${s.httpHeaders||"{}"}`];return s.httpBody&&i.push(`body: ${s.httpBody}`),i}function U(s){return[`condition: ${m(s.condition||"true")}`]}function C(s,i){o.add("import FirecrawlApp from '@mendable/firecrawl-js';");let k=s==="Search"?"search":"scrape",w=i.formats?JSON.stringify(i.formats):"['markdown']",j=[`mode: '${k}'`,"apiKey: process.env.FIRECRAWL_API_KEY!",`formats: ${w}`];return i.url&&j.push(`url: \`${m(i.url||"")}\``),i.query&&j.push(`query: \`${m(i.query||"")}\``),i.limit&&j.push(`limit: ${i.limit}`),j}function pe(s){o.add("import { createClient } from 'v0-sdk';");let i=[`message: \`${m(s.message||"")}\``,"apiKey: process.env.V0_API_KEY!"];return s.system&&i.push(`system: \`${m(s.system||"")}\``),i}function te(s){return o.add("import { createClient } from 'v0-sdk';"),[`chatId: \`${m(s.chatId||"")}\``,`message: \`${m(s.message||"")}\``,"apiKey: process.env.V0_API_KEY!"]}function mt(s){return[`userId: \`${m(s.userId||"")}\``]}function ht(s){let i=[`emailAddress: \`${m(s.emailAddress||"")}\``];return s.password&&i.push(`password: \`${m(s.password)}\``),s.firstName&&i.push(`firstName: \`${m(s.firstName)}\``),s.lastName&&i.push(`lastName: \`${m(s.lastName)}\``),s.publicMetadata&&i.push(`publicMetadata: \`${m(s.publicMetadata)}\``),s.privateMetadata&&i.push(`privateMetadata: \`${m(s.privateMetadata)}\``),i}function kt(s){let i=[`userId: \`${m(s.userId||"")}\``];return s.firstName&&i.push(`firstName: \`${m(s.firstName)}\``),s.lastName&&i.push(`lastName: \`${m(s.lastName)}\``),s.publicMetadata&&i.push(`publicMetadata: \`${m(s.publicMetadata)}\``),s.privateMetadata&&i.push(`privateMetadata: \`${m(s.privateMetadata)}\``),i}function yt(s){return[`userId: \`${m(s.userId||"")}\``]}function jt(s,i){let w={"Send Email":()=>I(i),"Send Slack Message":()=>R(i),"Create Ticket":()=>b(i),"Generate Text":()=>z(i),"Generate Image":()=>L(i),"Database Query":()=>q(i),"HTTP Request":()=>E(i),Condition:()=>U(i),Scrape:()=>C(s,i),Search:()=>C(s,i),"Create Chat":()=>pe(i),"Send Message":()=>te(i),"Get User":()=>mt(i),"Create User":()=>ht(i),"Update User":()=>kt(i),"Delete User":()=>yt(i)}[s];return w?w():[]}function xt(s,i){let k=s.data.config||{},w=k.actionType,j=s.data.label||w||"UnnamedStep",F=i||J(j),P=Ct(w),W;return P&&s.data.type==="action"?W=` // Call step function with constructed input
1
+ import{a as m,b as W,c as Fe,d as ve,e as H,f as Ce,g as Ue,h as ae,i as _e,j as Oe,k as Me,l as ie}from"../../chunk-2V446QDJ.js";import"../../chunk-H2FP5MBV.js";import{a as Re,b as Ie,c as Ae}from"../../chunk-NI6U7PHC.js";import{a as oe,b as ke,c as ye,d as xe,e as je,f as Ee,g as X,h as D}from"../../chunk-VUDOAZ3W.js";import"../../chunk-3YVRTDK2.js";import{b as O}from"../../chunk-IEOZJAW2.js";import"../../chunk-6UXAINJQ.js";import{j as be,k as $e,n as Ne}from"../../chunk-BNX2SV7E.js";import{c as Pe,d as se,f as We,g as Se,h as Te,i as B}from"../../chunk-KFTXS23Q.js";import{m as he}from"../../chunk-QRG4O4PE.js";import{a as G,b as Q,d as ne,i as l,k as y,l as N,m as A,o as c}from"../../chunk-5J6TNMJG.js";import{NextResponse as te}from"next/server";import{and as Nt,eq as ue}from"drizzle-orm";import{NextResponse as S}from"next/server";import{createHash as Pt}from"crypto";async function De(r){try{let t=await m(r);if(!t)return S.json({error:"Unauthorized"},{status:401});let e=await c.query.apiKeys.findMany({where:ue(A.userId,t.id),columns:{id:!0,name:!0,keyPrefix:!0,createdAt:!0,lastUsedAt:!0},orderBy:(o,{desc:n})=>[n(o.createdAt)]});return S.json(e)}catch(t){return console.error("Failed to list API keys:",t),S.json({error:"Failed to list API keys"},{status:500})}}async function Ge(r){try{let t=await m(r);if(!t)return S.json({error:"Unauthorized"},{status:401});if(t.name==="Anonymous"||t.email?.startsWith("temp-"))return S.json({error:"Anonymous users cannot create API keys"},{status:403});let n=(await r.json().catch(()=>({}))).name||null,{randomBytes:u}=await import("crypto"),d=`wfb_${u(24).toString("base64url")}`,g=Pt("sha256").update(d).digest("hex"),R=d.slice(0,11),[I]=await c.insert(A).values({userId:t.id,name:n,keyHash:g,keyPrefix:R}).returning({id:A.id,name:A.name,keyPrefix:A.keyPrefix,createdAt:A.createdAt});return S.json({...I,key:d})}catch(t){return console.error("Failed to create API key:",t),S.json({error:"Failed to create API key"},{status:500})}}async function ze(r,t){try{let e=await m(r);return e?(await c.delete(A).where(Nt(ue(A.id,t),ue(A.userId,e.id))).returning({id:A.id})).length===0?S.json({error:"API key not found"},{status:404}):S.json({success:!0}):S.json({error:"Unauthorized"},{status:401})}catch(e){return console.error("Failed to delete API key:",e),S.json({error:"Failed to delete API key"},{status:500})}}import{toNextJsHandler as Wt}from"better-auth/next-js";var{GET:St,POST:Tt}=Wt(O);async function de(r,t){let e="/api/auth/"+t.slice(1).join("/"),o=new URL(r.url),n=`${o.origin}${e}${o.search}`,u=ve(r,n),f=r.method==="GET"?await St(u):await Tt(u);return f.status>=500&&!await f.clone().text()?new Response(JSON.stringify({debug:"500 with empty body from better-auth",path:e}),{status:500,headers:{"Content-Type":"application/json"}}):f}import{eq as Ft}from"drizzle-orm";import{NextResponse as Z}from"next/server";async function Le(r,t){try{if(r.headers.get("authorization")!==`Bearer ${process.env.CRON_SECRET}`)return Z.json({error:"Unauthorized"},{status:401});let o=await c.query.workflows.findFirst({where:Ft(l.id,t)});if(!o)return Z.json({error:"Workflow not found"},{status:404});let[n]=await c.insert(y).values({workflowId:t,userId:o.userId,status:"running",input:{}}).returning();return await H(n.id,t,o.nodes,o.edges,{}),Z.json({success:!0,workflowId:t,executionId:n.id,message:"Workflow execution completed"})}catch(e){return console.error("[Cron] Scheduled workflow execution error:",e),Z.json({error:"Execution failed",message:e instanceof Error?e.message:"Unknown error"},{status:500})}}import{oAuthDiscoveryMetadata as vt,oAuthProtectedResourceMetadata as Ct}from"better-auth/plugins";var ce=vt(O),le=Ct(O);import{NextResponse as x}from"next/server";async function qe(r){try{let t=await m(r);if(!t)return x.json({error:"Unauthorized"},{status:401});let{searchParams:e}=new URL(r.url),o=e.get("type"),n=await Pe(t.id,o||void 0);return x.json(n.map(u=>({id:u.id,name:u.name,type:u.type,isManaged:u.isManaged??!1,createdAt:u.createdAt.toISOString(),updatedAt:u.updatedAt.toISOString()})))}catch(t){return console.error("Failed to get integrations:",t),x.json({error:"Failed to get integrations",details:t instanceof Error?t.message:"Unknown error"},{status:500})}}async function Ke(r){try{let t=await m(r);if(!t)return x.json({error:"Unauthorized"},{status:401});let e=await r.json();if(!(e.type&&e.config))return x.json({error:"Type and config are required"},{status:400});let o=await We(t.id,e.name||"",e.type,e.config);return x.json({id:o.id,name:o.name,type:o.type,createdAt:o.createdAt.toISOString(),updatedAt:o.updatedAt.toISOString()})}catch(t){return console.error("Failed to create integration:",t),x.json({error:"Failed to create integration",details:t instanceof Error?t.message:"Unknown error"},{status:500})}}async function Be(r,t){try{let e=await m(r);if(!e)return x.json({error:"Unauthorized"},{status:401});let o=await se(t,e.id);return o?x.json({id:o.id,name:o.name,type:o.type,config:o.config,createdAt:o.createdAt.toISOString(),updatedAt:o.updatedAt.toISOString()}):x.json({error:"Integration not found"},{status:404})}catch(e){return console.error("Failed to get integration:",e),x.json({error:"Failed to get integration",details:e instanceof Error?e.message:"Unknown error"},{status:500})}}async function He(r,t){try{let e=await m(r);if(!e)return x.json({error:"Unauthorized"},{status:401});let o=await r.json(),n=await Se(t,e.id,o);return n?x.json({id:n.id,name:n.name,type:n.type,config:n.config,createdAt:n.createdAt.toISOString(),updatedAt:n.updatedAt.toISOString()}):x.json({error:"Integration not found"},{status:404})}catch(e){return console.error("Failed to update integration:",e),x.json({error:"Failed to update integration",details:e instanceof Error?e.message:"Unknown error"},{status:500})}}async function Ye(r,t){try{let e=await m(r);return e?await Te(t,e.id)?x.json({success:!0}):x.json({error:"Integration not found"},{status:404}):x.json({error:"Unauthorized"},{status:401})}catch(e){return console.error("Failed to delete integration:",e),x.json({error:"Failed to delete integration",details:e instanceof Error?e.message:"Unknown error"},{status:500})}}async function Je(r,t){try{let e=await m(r);if(!e)return x.json({error:"Unauthorized"},{status:401});let o=await se(t,e.id);return o?o.type==="database"?x.json({status:"success",message:"Integration exists"}):x.json({status:"success",message:"Integration exists"}):x.json({error:"Integration not found"},{status:404})}catch(e){return console.error("Failed to test integration:",e),x.json({status:"error",message:e instanceof Error?e.message:"Failed to test connection"},{status:500})}}async function Ve(r){try{if(!await m(r))return x.json({error:"Unauthorized"},{status:401});let e=await r.json();return e.type&&e.config?x.json({status:"success",message:"Credentials accepted"}):x.json({error:"Type and config are required"},{status:400})}catch(t){return console.error("Failed to test credentials:",t),x.json({status:"error",message:t instanceof Error?t.message:"Failed to test connection"},{status:500})}}import{eq as ee}from"drizzle-orm";import{NextResponse as M}from"next/server";async function Xe(r){try{let t=await m(r);if(!t)return M.json({error:"Unauthorized"},{status:401});let e=await c.query.users.findFirst({where:ee(Q.id,t.id),columns:{id:!0,name:!0,email:!0,image:!0,isAnonymous:!0}});if(!e)return M.json({error:"User not found"},{status:404});let o=await c.query.accounts.findFirst({where:ee(ne.userId,t.id),columns:{providerId:!0}});return M.json({...e,providerId:o?.providerId??null})}catch(t){return console.error("Failed to get user:",t),M.json({error:t instanceof Error?t.message:"Failed to get user"},{status:500})}}async function Qe(r){try{let t=await m(r);if(!t)return M.json({error:"Unauthorized"},{status:401});let e=await c.query.accounts.findFirst({where:ee(ne.userId,t.id),columns:{providerId:!0}});if(e&&["vercel","github","google"].includes(e.providerId))return M.json({error:"Cannot update profile for OAuth users"},{status:403});let n=await r.json(),u={};return n.name!==void 0&&(u.name=n.name),n.email!==void 0&&(u.email=n.email),await c.update(Q).set(u).where(ee(Q.id,t.id)),M.json({success:!0})}catch(t){return console.error("Failed to update user:",t),M.json({error:t instanceof Error?t.message:"Failed to update user"},{status:500})}}import{and as F,count as qt,desc as Y,eq as p,inArray as pe,sql as z}from"drizzle-orm";import{NextResponse as a}from"next/server";import{createHash as Kt}from"crypto";import"server-only";var Ut={"Database Query":Ie.codeGenerator,"HTTP Request":Ae.codeGenerator,Condition:Re.codeGenerator},_t=/export\s+(?:async\s+)?function\s+\w+\s*\([^)]*\)\s*(?::\s*[^{]+)?\s*\{([\s\S]*)\}/;function Ot(r){let t=Ut[r];if(!t){let e=he(r);e?.codegenTemplate&&(t=e.codegenTemplate)}if(!t)return null;try{let e=t.match(_t);return e?e[1].trim():null}catch{return null}}function Mt(r,t){let e=r.substring(1),o=e.indexOf(":");if(o===-1)return t;let n=e.substring(0,o),u=e.substring(o+1),f=u.indexOf("."),d=f!==-1?u.substring(f+1):"",g=n.replace(/[^a-zA-Z0-9]/g,"_");if(!d)return`\${outputs?.['${g}']?.data}`;let R=d.split(".").map(I=>{let $=I.match(oe);return $?`?.${$[1]}?.[${$[2]}]`:`?.${I}`}).join("");return`\${outputs?.['${g}']?.data${R}}`}function Dt(r){let t=r.substring(1);if(!(t.includes(".")||t.includes("[")))return`\${outputs?.['${t.replace(/[^a-zA-Z0-9]/g,"_")}']?.data}`;let e=t.split("."),n=e[0].replace(/[^a-zA-Z0-9]/g,"_"),u=e.slice(1).join(".");if(!u)return`\${outputs?.['${n}']?.data}`;let f=u.split(".").map(d=>{let g=d.match(oe);return g?`?.${g[1]}?.[${g[2]}]`:`?.${d}`}).join("");return`\${outputs?.['${n}']?.data${f}}`}function h(r){if(!r||typeof r!="string")return r;let t=/\{\{([^}]+)\}\}/g;return r.replace(t,(e,o)=>{let n=o.trim();return n.startsWith("@")?Mt(n,e):n.startsWith("$")?Dt(n):e})}function Gt(r){let t=ke(r),e=r.at(-1);return e&&t.add(e.id),t}function zt(r){let t=new Map,e=new Map;for(let o of r)if(o.data.type==="action"){let u=(o.data.config||{}).actionType,f=o.data.label||u||"UnnamedStep",d=X(f),g=t.get(d)||0;t.set(d,g+1);let R=g>0?`${d}${g+1}`:d;e.set(o.id,R)}return e}function Lt(r,t,e){let o=[];for(let n of r)if(n.data.type==="action"){let u=t.get(n.id);o.push(e(n,u))}return o}function Ze(r,t,e){let o=new Set,n=[],u=new Map(t.map(s=>[s.id,s])),f=ye(e),d=xe(t,e),g=Gt(t);o.add("import { sleep, FatalError } from 'workflow';");function R(s){return o.add("import { Resend } from 'resend';"),["fromEmail: process.env.RESEND_FROM_EMAIL || 'noreply@example.com'",`emailTo: \`${h(s.emailTo||"user@example.com")}\``,`emailSubject: \`${h(s.emailSubject||"Notification")}\``,`emailBody: \`${h(s.emailBody||"No content")}\``,"apiKey: process.env.RESEND_API_KEY!"]}function I(s){return o.add("import { WebClient } from '@slack/web-api';"),[`slackChannel: \`${h(s.slackChannel||"#general")}\``,`slackMessage: \`${h(s.slackMessage||"No message")}\``,"apiKey: process.env.SLACK_API_KEY!"]}function $(s){o.add("import { LinearClient } from '@linear/sdk';");let i=[`ticketTitle: \`${h(s.ticketTitle||"New Issue")}\``,`ticketDescription: \`${h(s.ticketDescription||"")}\``,"apiKey: process.env.LINEAR_API_KEY!"];return s.teamId&&i.push(`teamId: "${s.teamId}"`),i}function L(s){o.add("import { generateText } from 'ai';");let i=s.aiModel||"meta/llama-4-scout",k;if(i.includes("/"))k=i;else{let w;i.startsWith("gpt-")||i.startsWith("o1-")?w="openai":i.startsWith("claude-")?w="anthropic":w="openai",k=`${w}/${i}`}return[`model: "${k}"`,`prompt: \`${h(s.aiPrompt||"")}\``,"apiKey: process.env.OPENAI_API_KEY!"]}function q(s){return o.add("import { experimental_generateImage as generateImage } from 'ai';"),[`model: "${s.imageModel||"google/imagen-4.0-generate"}"`,`prompt: \`${h(s.imagePrompt||"")}\``,'size: "1024x1024"',"providerOptions: { openai: { apiKey: process.env.AI_GATEWAY_API_KEY! } }"]}function K(s){return[`query: \`${h(s.dbQuery||"SELECT 1")}\``]}function E(s){let i=[`url: "${s.endpoint||"https://api.example.com/endpoint"}"`,`method: "${s.httpMethod||"POST"}"`,`headers: ${s.httpHeaders||"{}"}`];return s.httpBody&&i.push(`body: ${s.httpBody}`),i}function C(s){return[`condition: ${h(s.condition||"true")}`]}function U(s,i){o.add("import FirecrawlApp from '@mendable/firecrawl-js';");let k=s==="Search"?"search":"scrape",w=i.formats?JSON.stringify(i.formats):"['markdown']",j=[`mode: '${k}'`,"apiKey: process.env.FIRECRAWL_API_KEY!",`formats: ${w}`];return i.url&&j.push(`url: \`${h(i.url||"")}\``),i.query&&j.push(`query: \`${h(i.query||"")}\``),i.limit&&j.push(`limit: ${i.limit}`),j}function we(s){o.add("import { createClient } from 'v0-sdk';");let i=[`message: \`${h(s.message||"")}\``,"apiKey: process.env.V0_API_KEY!"];return s.system&&i.push(`system: \`${h(s.system||"")}\``),i}function re(s){return o.add("import { createClient } from 'v0-sdk';"),[`chatId: \`${h(s.chatId||"")}\``,`message: \`${h(s.message||"")}\``,"apiKey: process.env.V0_API_KEY!"]}function kt(s){return[`userId: \`${h(s.userId||"")}\``]}function yt(s){let i=[`emailAddress: \`${h(s.emailAddress||"")}\``];return s.password&&i.push(`password: \`${h(s.password)}\``),s.firstName&&i.push(`firstName: \`${h(s.firstName)}\``),s.lastName&&i.push(`lastName: \`${h(s.lastName)}\``),s.publicMetadata&&i.push(`publicMetadata: \`${h(s.publicMetadata)}\``),s.privateMetadata&&i.push(`privateMetadata: \`${h(s.privateMetadata)}\``),i}function xt(s){let i=[`userId: \`${h(s.userId||"")}\``];return s.firstName&&i.push(`firstName: \`${h(s.firstName)}\``),s.lastName&&i.push(`lastName: \`${h(s.lastName)}\``),s.publicMetadata&&i.push(`publicMetadata: \`${h(s.publicMetadata)}\``),s.privateMetadata&&i.push(`privateMetadata: \`${h(s.privateMetadata)}\``),i}function jt(s){return[`userId: \`${h(s.userId||"")}\``]}function Et(s,i){let w={"Send Email":()=>R(i),"Send Slack Message":()=>I(i),"Create Ticket":()=>$(i),"Generate Text":()=>L(i),"Generate Image":()=>q(i),"Database Query":()=>K(i),"HTTP Request":()=>E(i),Condition:()=>C(i),Scrape:()=>U(s,i),Search:()=>U(s,i),"Create Chat":()=>we(i),"Send Message":()=>re(i),"Get User":()=>kt(i),"Create User":()=>yt(i),"Update User":()=>xt(i),"Delete User":()=>jt(i)}[s];return w?w():[]}function Rt(s,i){let k=s.data.config||{},w=k.actionType,j=s.data.label||w||"UnnamedStep",v=i||X(j),b=Ot(w),P;return b&&s.data.type==="action"?P=` // Call step function with constructed input
2
2
  const stepInput = {
3
- ${jt(w,k).join(`,
3
+ ${Et(w,k).join(`,
4
4
  `)}
5
5
  };
6
6
 
7
7
  // Execute step implementation
8
- ${P}`:W=" return { success: true };",`async function ${F}(input: Record<string, unknown> & { outputs?: Record<string, { label: string; data: unknown }> }) {
8
+ ${b}`:P=" return { success: true };",`async function ${v}(input: Record<string, unknown> & { outputs?: Record<string, { label: string; data: unknown }> }) {
9
9
  "use step";
10
10
 
11
- ${W}
12
- }`}let we=Gt(t);n.push(..._t(t,we,xt));function Et(s,i,k){if(!g.has(s))return[`${k}// Trigger (outputs not used)`];let w=`result_${G(s)}`;return[`${k}// Triggered`,`${k}let ${w} = input;`,`${k}outputs['${G(s)}'] = { label: '${i}', data: ${w} };`]}function It(s,i,k,w){let j=i.actionType,F=k||j||"UnnamedStep",P=we.get(s)||J(F),W=[`${w}// ${F}`];if(g.has(s)){let ge=`result_${G(s)}`;W.push(`${w}const ${ge} = await ${P}({ ...input, outputs });`),W.push(`${w}outputs['${G(s)}'] = { label: '${F}', data: ${ge} };`)}else W.push(`${w}await ${P}({ ...input, outputs });`);return W}function Rt(s,i,k,w){let j=i.data.config?.condition||"true",F=m(j),P=l.get(s)||[],W=`conditionValue_${G(s)}`,T=[];return P.length>0&&(T.push(`${k}// ${i.data.label}`),T.push(`${k}const ${W} = \`${je(F)}\`;`),T.push(`${k}if (${W}) {`),P[0]&&T.push(...Y(P[0],`${k} `,w)),P[1]&&(T.push(`${k}} else {`),T.push(...Y(P[1],`${k} `,w))),T.push(`${k}}`)),T}function Y(s,i=" ",k=new Set){if(k.has(s))return[];k.add(s);let w=u.get(s);if(!w)return[];let j=[];switch(w.data.type){case"trigger":j.push(...Et(s,w.data.label,i));break;case"action":{if(w.data.config?.actionType==="Condition")return j.push(...Rt(s,w,i,k)),j;j.push(...It(s,w.data.config||{},w.data.label,i));break}default:j.push(`${i}// Unknown node type: ${w.data.type}`);break}let F=l.get(s)||[];for(let P of F)j.push(...Y(P,i,k));return j}let O=[];if(d.length===0)O.push(' return { error: "No trigger nodes" };');else{O.push(" // Track outputs from each node for template processing"),O.push(" const outputs: Record<string, { label: string; data: unknown }> = {};"),O.push("");for(let i of d)O.push(...Y(i.id));let s=t.at(-1);if(s){let i=`result_${G(s.id)}`;O.push(""),O.push(` return ${i};`)}}let At=`export async function ${xe(r)}() {
11
+ ${P}
12
+ }`}let ge=zt(t);n.push(...Lt(t,ge,Rt));function It(s,i,k){if(!g.has(s))return[`${k}// Trigger (outputs not used)`];let w=`result_${D(s)}`;return[`${k}// Triggered`,`${k}let ${w} = input;`,`${k}outputs['${D(s)}'] = { label: '${i}', data: ${w} };`]}function At(s,i,k,w){let j=i.actionType,v=k||j||"UnnamedStep",b=ge.get(s)||X(v),P=[`${w}// ${v}`];if(g.has(s)){let me=`result_${D(s)}`;P.push(`${w}const ${me} = await ${b}({ ...input, outputs });`),P.push(`${w}outputs['${D(s)}'] = { label: '${v}', data: ${me} };`)}else P.push(`${w}await ${b}({ ...input, outputs });`);return P}function bt(s,i,k,w){let j=i.data.config?.condition||"true",v=h(j),b=f.get(s)||[],P=`conditionValue_${D(s)}`,T=[];return b.length>0&&(T.push(`${k}// ${i.data.label}`),T.push(`${k}const ${P} = \`${je(v)}\`;`),T.push(`${k}if (${P}) {`),b[0]&&T.push(...V(b[0],`${k} `,w)),b[1]&&(T.push(`${k}} else {`),T.push(...V(b[1],`${k} `,w))),T.push(`${k}}`)),T}function V(s,i=" ",k=new Set){if(k.has(s))return[];k.add(s);let w=u.get(s);if(!w)return[];let j=[];switch(w.data.type){case"trigger":j.push(...It(s,w.data.label,i));break;case"action":{if(w.data.config?.actionType==="Condition")return j.push(...bt(s,w,i,k)),j;j.push(...At(s,w.data.config||{},w.data.label,i));break}default:j.push(`${i}// Unknown node type: ${w.data.type}`);break}let v=f.get(s)||[];for(let b of v)j.push(...V(b,i,k));return j}let _=[];if(d.length===0)_.push(' return { error: "No trigger nodes" };');else{_.push(" // Track outputs from each node for template processing"),_.push(" const outputs: Record<string, { label: string; data: unknown }> = {};"),_.push("");for(let i of d)_.push(...V(i.id));let s=t.at(-1);if(s){let i=`result_${D(s.id)}`;_.push(""),_.push(` return ${i};`)}}let $t=`export async function ${Ee(r)}() {
13
13
  "use workflow";
14
14
 
15
15
  // Input from workflow trigger - replace with your trigger data
16
16
  const input: Record<string, unknown> = {};
17
17
 
18
- ${O.join(`
18
+ ${_.join(`
19
19
  `)}
20
20
  }`;return`${Array.from(o).join(`
21
21
  `)}
@@ -24,14 +24,14 @@ ${n.join(`
24
24
 
25
25
  `)}
26
26
 
27
- ${At}
28
- `}async function Ze(r,t){try{let e=await h(r);if(!e)return a.json({error:"Unauthorized"},{status:401});let o=await c.query.workflows.findFirst({where:f(p.id,t)});if(!o)return a.json({error:"Workflow not found"},{status:404});if(o.userId!==e.id)return a.json({error:"Forbidden"},{status:403});if(!(await K(o.nodes,e.id)).valid)return a.json({error:"Workflow contains invalid integration references"},{status:403});let l=(await r.json().catch(()=>({}))).input||{},[d]=await c.insert(x).values({workflowId:t,userId:e.id,status:"running",input:l}).returning();return H(d.id,t,o.nodes,o.edges,l),a.json({executionId:d.id,status:"running"})}catch(e){return console.error("Failed to start workflow execution:",e),a.json({error:e instanceof Error?e.message:"Failed to execute workflow"},{status:500})}}async function et(r,t){try{let e=await h(r),o=await c.query.workflows.findFirst({where:f(p.id,t)});if(!o)return a.json({error:"Workflow not found"},{status:404});let n=e?.id===o.userId;return!n&&o.visibility!=="public"?a.json({error:"Workflow not found"},{status:404}):a.json({...o,nodes:n?o.nodes:Ue(o.nodes),createdAt:o.createdAt.toISOString(),updatedAt:o.updatedAt.toISOString(),isOwner:n})}catch(e){return console.error("Failed to get workflow:",e),a.json({error:e instanceof Error?e.message:"Failed to get workflow"},{status:500})}}async function tt(r){try{let t=await h(r);if(!t)return a.json([],{status:200});let e=await c.select().from(p).where(f(p.userId,t.id)).orderBy(Z(p.updatedAt));return a.json(e.map(o=>({...o,createdAt:o.createdAt.toISOString(),updatedAt:o.updatedAt.toISOString()})))}catch(t){return console.error("Failed to get workflows:",t),a.json({error:t instanceof Error?t.message:"Failed to get workflows"},{status:500})}}async function rt(r){try{let t=await h(r);if(!t)return a.json({error:"Unauthorized"},{status:401});let e=await r.json();if(!(e.name&&e.nodes&&e.edges))return a.json({error:"Name, nodes, and edges are required"},{status:400});if(!(await K(e.nodes,t.id)).valid)return a.json({error:"Invalid integration references in workflow"},{status:403});let n=e.nodes;n.length===0&&(n=[{id:_(),type:"trigger",position:{x:0,y:0},data:{label:"",description:"",type:"trigger",config:{triggerType:"Manual"},status:"idle"}}]);let u=e.name;e.name==="Untitled Workflow"&&(u=`Untitled ${(await c.query.workflows.findMany({where:f(p.userId,t.id)})).length+1}`);let l=_(),[d]=await c.insert(p).values({id:l,name:u,description:e.description,nodes:n,edges:e.edges,userId:t.id}).returning();return a.json({...d,createdAt:d.createdAt.toISOString(),updatedAt:d.updatedAt.toISOString()})}catch(t){return console.error("Failed to create workflow:",t),a.json({error:t instanceof Error?t.message:"Failed to create workflow"},{status:500})}}var le="~~__CURRENT__~~";async function ot(r){try{let t=await h(r);if(!t)return a.json({error:"Unauthorized"},{status:401});let[e]=await c.select().from(p).where(v(f(p.name,le),f(p.userId,t.id))).orderBy(Z(p.updatedAt)).limit(1);return e?a.json({id:e.id,nodes:e.nodes,edges:e.edges}):a.json({nodes:[],edges:[]})}catch(t){return console.error("Failed to get current workflow:",t),a.json({error:t instanceof Error?t.message:"Failed to get current workflow"},{status:500})}}async function nt(r){try{let t=await h(r);if(!t)return a.json({error:"Unauthorized"},{status:401});let e=await r.json(),{nodes:o,edges:n}=e;if(!(o&&n))return a.json({error:"Nodes and edges are required"},{status:400});let[u]=await c.select().from(p).where(v(f(p.name,le),f(p.userId,t.id))).limit(1);if(u){let[g]=await c.update(p).set({nodes:o,edges:n,updatedAt:new Date}).where(f(p.id,u.id)).returning();return a.json({id:g.id,nodes:g.nodes,edges:g.edges})}let l=_(),[d]=await c.insert(p).values({id:l,name:le,description:"Auto-saved current workflow",nodes:o,edges:n,userId:t.id}).returning();return a.json({id:d.id,nodes:d.nodes,edges:d.edges})}catch(t){return console.error("Failed to save current workflow:",t),a.json({error:t instanceof Error?t.message:"Failed to save current workflow"},{status:500})}}async function st(r,t){try{let e=await h(r);if(!e)return a.json({error:"Unauthorized"},{status:401});let o=await c.query.workflowExecutions.findFirst({where:f(x.id,t),with:{workflow:!0}});if(!o)return a.json({error:"Execution not found"},{status:404});if(o.workflow.userId!==e.id)return a.json({error:"Forbidden"},{status:403});let u=(await c.query.workflowExecutionLogs.findMany({where:f(N.executionId,t)})).map(l=>({nodeId:l.nodeId,status:l.status}));return a.json({status:o.status,nodeStatuses:u})}catch(e){return console.error("Failed to get execution status:",e),a.json({error:e instanceof Error?e.message:"Failed to get execution status"},{status:500})}}async function at(r,t){try{let e=await h(r);if(!e)return a.json({error:"Unauthorized"},{status:401});let o=await c.query.workflowExecutions.findFirst({where:f(x.id,t),with:{workflow:!0}});if(!o)return a.json({error:"Execution not found"},{status:404});if(o.workflow.userId!==e.id)return a.json({error:"Forbidden"},{status:403});let n=await c.query.workflowExecutionLogs.findMany({where:f(N.executionId,t),orderBy:[Z(N.timestamp)]});return a.json({execution:o,logs:n})}catch(e){return console.error("Failed to get execution logs:",e),a.json({error:e instanceof Error?e.message:"Failed to get execution logs"},{status:500})}}async function it(r,t){try{let e=await h(r);if(!e)return a.json({error:"Unauthorized"},{status:401});if(!await c.query.workflows.findFirst({where:v(f(p.id,t),f(p.userId,e.id))}))return a.json({error:"Workflow not found"},{status:404});let n=await r.json();if(Array.isArray(n.nodes)&&!(await K(n.nodes,e.id)).valid)return a.json({error:"Invalid integration references in workflow"},{status:403});if(n.visibility!==void 0&&n.visibility!=="private"&&n.visibility!=="public")return a.json({error:"Invalid visibility value. Must be 'private' or 'public'"},{status:400});let u=ve(n),[l]=await c.update(p).set(u).where(f(p.id,t)).returning();return l?a.json({...l,createdAt:l.createdAt.toISOString(),updatedAt:l.updatedAt.toISOString(),isOwner:!0}):a.json({error:"Workflow not found"},{status:404})}catch(e){return console.error("Failed to update workflow:",e),a.json({error:e instanceof Error?e.message:"Failed to update workflow"},{status:500})}}async function ut(r,t){try{let e=await h(r);if(!e)return a.json({error:"Unauthorized"},{status:401});if(!await c.query.workflows.findFirst({where:v(f(p.id,t),f(p.userId,e.id))}))return a.json({error:"Workflow not found"},{status:404});let u=(await c.query.workflowExecutions.findMany({where:f(x.workflowId,t),columns:{id:!0}})).map(l=>l.id);return u.length>0&&(await c.delete(N).where(fe(N.executionId,u)),await c.delete(x).where(f(x.workflowId,t))),await c.delete(p).where(f(p.id,t)),a.json({success:!0})}catch(e){return console.error("Failed to delete workflow:",e),a.json({error:e instanceof Error?e.message:"Failed to delete workflow"},{status:500})}}async function dt(r,t){try{let e=await h(r);if(!e)return a.json({error:"Unauthorized"},{status:401});let o=await c.query.workflows.findFirst({where:f(p.id,t)});if(!o)return a.json({error:"Workflow not found"},{status:404});if(!(e.id===o.userId)&&o.visibility!=="public")return a.json({error:"Workflow not found"},{status:404});let u=o.nodes,l=u.map(E=>{let U={...E,id:_()};if(U.data){let C={...U.data};if(C.config){let{integrationId:pe,...te}=C.config;C.config=te}C.status="idle",U.data=C}return U}),d=new Map(u.map((E,U)=>[E.id,l[U].id])),g=o.edges.map(E=>({...E,id:_(),source:d.get(E.source)||E.source,target:d.get(E.target)||E.target})),I=await c.query.workflows.findMany({where:f(p.userId,e.id)}),R=`${o.name} (Copy)`,b=R,z=new Set(I.map(E=>E.name));if(z.has(b)){let E=2;for(;z.has(`${R} ${E}`);)E++;b=`${R} ${E}`}let L=_(),[q]=await c.insert(p).values({id:L,name:b,description:o.description,nodes:l,edges:g,userId:e.id,visibility:"private"}).returning();return a.json({...q,createdAt:q.createdAt.toISOString(),updatedAt:q.updatedAt.toISOString(),isOwner:!0})}catch(e){return console.error("Failed to duplicate workflow:",e),a.json({error:e instanceof Error?e.message:"Failed to duplicate workflow"},{status:500})}}async function ct(r,t){try{let e=await h(r);if(!e)return a.json({error:"Unauthorized"},{status:401});if(!await c.query.workflows.findFirst({where:v(f(p.id,t),f(p.userId,e.id))}))return a.json({error:"Workflow not found"},{status:404});let n=await c.query.workflowExecutions.findMany({where:f(x.workflowId,t),orderBy:[Z(x.startedAt)],limit:50});return a.json(n)}catch(e){return console.error("Failed to get executions:",e),a.json({error:e instanceof Error?e.message:"Failed to get executions"},{status:500})}}async function lt(r,t){try{let e=await h(r);if(!e)return a.json({error:"Unauthorized"},{status:401});let o=await c.query.workflowExecutions.findFirst({where:f(x.id,t),with:{workflow:!0}});if(!o)return a.json({error:"Execution not found"},{status:404});if(o.workflow.userId!==e.id)return a.json({error:"Forbidden"},{status:403});if(o.status!=="running"&&o.status!=="pending")return a.json({error:"Execution is not running",status:o.status},{status:409});await c.update(x).set({status:"cancelled",completedAt:new Date,duration:String(Date.now()-new Date(o.startedAt).getTime())}).where(f(x.id,t));let n=await c.query.workflowExecutionLogs.findMany({where:v(f(N.executionId,t),fe(N.status,["pending","running"]))});for(let u of n)await c.update(N).set({status:"error",error:"Cancelled",completedAt:new Date}).where(f(N.id,u.id));return a.json({success:!0,status:"cancelled"})}catch(e){return console.error("Failed to cancel execution:",e),a.json({error:e instanceof Error?e.message:"Failed to cancel execution"},{status:500})}}async function ft(r,t){try{let e=await h(r);if(!e)return a.json({error:"Unauthorized"},{status:401});if(!await c.query.workflows.findFirst({where:v(f(p.id,t),f(p.userId,e.id))}))return a.json({error:"Workflow not found"},{status:404});let u=(await c.query.workflowExecutions.findMany({where:f(x.workflowId,t),columns:{id:!0}})).map(l=>l.id);return u.length>0&&(await c.delete(N).where(fe(N.executionId,u)),await c.delete(x).where(f(x.workflowId,t))),a.json({success:!0,deletedCount:u.length})}catch(e){return console.error("Failed to delete executions:",e),a.json({error:e instanceof Error?e.message:"Failed to delete executions"},{status:500})}}async function pt(r,t){try{let e=await c.query.workflows.findFirst({where:f(p.id,t)});if(!e)return a.json({error:"Workflow not found"},{status:404,headers:$});let o=r.headers.get("Authorization");if(!o)return a.json({error:"Missing Authorization header"},{status:401,headers:$});let n=o.startsWith("Bearer ")?o.slice(7):o;if(!n?.startsWith("wfb_"))return a.json({error:"Invalid API key format"},{status:401,headers:$});let u=zt("sha256").update(n).digest("hex"),l=await c.query.apiKeys.findFirst({where:f(A.keyHash,u)});if(!l||l.userId!==e.userId)return a.json({error:"Invalid API key or insufficient permissions"},{status:401,headers:$});c.update(A).set({lastUsedAt:new Date}).where(f(A.id,l.id)).catch(()=>{});let d=e.nodes.find(b=>b.data.type==="trigger");if(!d||d.data.config?.triggerType!=="Webhook")return a.json({error:"This workflow is not configured for webhook triggers"},{status:400,headers:$});if(!(await K(e.nodes,e.userId)).valid)return a.json({error:"Workflow contains invalid integration references"},{status:403,headers:$});let I=await r.json().catch(()=>({})),[R]=await c.insert(x).values({workflowId:t,userId:e.userId,status:"running",input:I}).returning();return H(R.id,t,e.nodes,e.edges,I),a.json({executionId:R.id,status:"running"},{headers:$})}catch(e){return console.error("Failed to start webhook execution:",e),a.json({error:e instanceof Error?e.message:"Failed to execute workflow"},{status:500,headers:$})}}async function wt(r,t){try{let e=await M.api.getSession({headers:r.headers});if(!e?.user)return a.json({error:"Unauthorized"},{status:401});let o=await c.query.workflows.findFirst({where:v(f(p.id,t),f(p.userId,e.user.id))});if(!o)return a.json({error:"Workflow not found"},{status:404});let n=Qe(o.name,o.nodes,o.edges);return a.json({code:n,workflowName:o.name})}catch(e){return console.error("Failed to get workflow code:",e),a.json({error:e instanceof Error?e.message:"Failed to get workflow code"},{status:500})}}async function gt(r,t){try{let e=await M.api.getSession({headers:r.headers});if(!e?.user)return a.json({error:"Unauthorized"},{status:401});let o=await c.query.workflows.findFirst({where:v(f(p.id,t),f(p.userId,e.user.id))});if(!o)return a.json({error:"Workflow not found"},{status:404});let n=await se(Ae),u=await se(Pe),l={};for(let[b,z]of Object.entries(u)){let L=z.match(be);L&&(l[`lib/steps/${b}`]=L[1])}let d=Ce({name:o.name,nodes:o.nodes,edges:o.edges}),g={...n,...l,...d},I=JSON.parse(g["package.json"]);I.dependencies={...I.dependencies,workflow:"4.0.1-beta.7",...Oe(o.nodes)},g["package.json"]=JSON.stringify(I,null,2),g["next.config.ts"]=`import { withWorkflow } from 'workflow/next';
27
+ ${$t}
28
+ `}async function et(r,t){try{let e=await m(r);if(!e)return a.json({error:"Unauthorized"},{status:401});let o=await c.query.workflows.findFirst({where:p(l.id,t)});if(!o)return a.json({error:"Workflow not found"},{status:404});if(o.userId!==e.id)return a.json({error:"Forbidden"},{status:403});if(!(await B(o.nodes,e.id)).valid)return a.json({error:"Workflow contains invalid integration references"},{status:403});let f=(await r.json().catch(()=>({}))).input||{},[d]=await c.insert(y).values({workflowId:t,userId:e.id,status:"running",input:f}).returning();return H(d.id,t,o.nodes,o.edges,f),a.json({executionId:d.id,status:"running"})}catch(e){return console.error("Failed to start workflow execution:",e),a.json({error:e instanceof Error?e.message:"Failed to execute workflow"},{status:500})}}async function tt(r,t){try{let e=await m(r),o=await c.query.workflows.findFirst({where:p(l.id,t)});if(!o)return a.json({error:"Workflow not found"},{status:404});let n=e?.id===o.userId;return!n&&o.visibility!=="public"?a.json({error:"Workflow not found"},{status:404}):a.json({...o,nodes:n?o.nodes:Ue(o.nodes),createdAt:o.createdAt.toISOString(),updatedAt:o.updatedAt.toISOString(),isOwner:n})}catch(e){return console.error("Failed to get workflow:",e),a.json({error:e instanceof Error?e.message:"Failed to get workflow"},{status:500})}}async function rt(r){try{let t=await m(r);if(!t)return a.json([],{status:200});let e=await c.select().from(l).where(p(l.userId,t.id)).orderBy(Y(l.updatedAt));return a.json(e.map(o=>({...o,createdAt:o.createdAt.toISOString(),updatedAt:o.updatedAt.toISOString()})))}catch(t){return console.error("Failed to get workflows:",t),a.json({error:t instanceof Error?t.message:"Failed to get workflows"},{status:500})}}async function ot(r){try{let t=await m(r);if(!t)return a.json({error:"Unauthorized"},{status:401});let e=await r.json();if(!(e.name&&e.nodes&&e.edges))return a.json({error:"Name, nodes, and edges are required"},{status:400});if(!(await B(e.nodes,t.id)).valid)return a.json({error:"Invalid integration references in workflow"},{status:403});let n=e.nodes;n.length===0&&(n=[{id:G(),type:"trigger",position:{x:0,y:0},data:{label:"",description:"",type:"trigger",config:{triggerType:"Manual"},status:"idle"}}]);let u=e.name;e.name==="Untitled Workflow"&&(u=`Untitled ${(await c.query.workflows.findMany({where:p(l.userId,t.id)})).length+1}`);let f=G(),[d]=await c.insert(l).values({id:f,name:u,description:e.description,nodes:n,edges:e.edges,userId:t.id}).returning();return a.json({...d,createdAt:d.createdAt.toISOString(),updatedAt:d.updatedAt.toISOString()})}catch(t){return console.error("Failed to create workflow:",t),a.json({error:t instanceof Error?t.message:"Failed to create workflow"},{status:500})}}var fe="~~__CURRENT__~~";async function nt(r){try{let t=await m(r);if(!t)return a.json({error:"Unauthorized"},{status:401});let[e]=await c.select().from(l).where(F(p(l.name,fe),p(l.userId,t.id))).orderBy(Y(l.updatedAt)).limit(1);return e?a.json({id:e.id,nodes:e.nodes,edges:e.edges}):a.json({nodes:[],edges:[]})}catch(t){return console.error("Failed to get current workflow:",t),a.json({error:t instanceof Error?t.message:"Failed to get current workflow"},{status:500})}}async function st(r){try{let t=await m(r);if(!t)return a.json({error:"Unauthorized"},{status:401});let e=await r.json(),{nodes:o,edges:n}=e;if(!(o&&n))return a.json({error:"Nodes and edges are required"},{status:400});let[u]=await c.select().from(l).where(F(p(l.name,fe),p(l.userId,t.id))).limit(1);if(u){let[g]=await c.update(l).set({nodes:o,edges:n,updatedAt:new Date}).where(p(l.id,u.id)).returning();return a.json({id:g.id,nodes:g.nodes,edges:g.edges})}let f=G(),[d]=await c.insert(l).values({id:f,name:fe,description:"Auto-saved current workflow",nodes:o,edges:n,userId:t.id}).returning();return a.json({id:d.id,nodes:d.nodes,edges:d.edges})}catch(t){return console.error("Failed to save current workflow:",t),a.json({error:t instanceof Error?t.message:"Failed to save current workflow"},{status:500})}}async function at(r,t){try{let e=await m(r);if(!e)return a.json({error:"Unauthorized"},{status:401});let o=await c.query.workflowExecutions.findFirst({where:p(y.id,t),with:{workflow:!0}});if(!o)return a.json({error:"Execution not found"},{status:404});if(o.workflow.userId!==e.id)return a.json({error:"Forbidden"},{status:403});let u=(await c.query.workflowExecutionLogs.findMany({where:p(N.executionId,t)})).map(f=>({nodeId:f.nodeId,status:f.status}));return a.json({status:o.status,nodeStatuses:u})}catch(e){return console.error("Failed to get execution status:",e),a.json({error:e instanceof Error?e.message:"Failed to get execution status"},{status:500})}}async function it(r,t){try{let e=await m(r);if(!e)return a.json({error:"Unauthorized"},{status:401});let o=await c.query.workflowExecutions.findFirst({where:p(y.id,t),with:{workflow:!0}});if(!o)return a.json({error:"Execution not found"},{status:404});if(o.workflow.userId!==e.id)return a.json({error:"Forbidden"},{status:403});let n=await c.query.workflowExecutionLogs.findMany({where:p(N.executionId,t),orderBy:[Y(N.timestamp)]});return a.json({execution:o,logs:n})}catch(e){return console.error("Failed to get execution logs:",e),a.json({error:e instanceof Error?e.message:"Failed to get execution logs"},{status:500})}}async function ut(r,t){try{let e=await m(r);if(!e)return a.json({error:"Unauthorized"},{status:401});if(!await c.query.workflows.findFirst({where:F(p(l.id,t),p(l.userId,e.id))}))return a.json({error:"Workflow not found"},{status:404});let n=await r.json();if(Array.isArray(n.nodes)&&!(await B(n.nodes,e.id)).valid)return a.json({error:"Invalid integration references in workflow"},{status:403});if(n.visibility!==void 0&&n.visibility!=="private"&&n.visibility!=="public")return a.json({error:"Invalid visibility value. Must be 'private' or 'public'"},{status:400});let u=Ce(n),[f]=await c.update(l).set(u).where(p(l.id,t)).returning();return f?a.json({...f,createdAt:f.createdAt.toISOString(),updatedAt:f.updatedAt.toISOString(),isOwner:!0}):a.json({error:"Workflow not found"},{status:404})}catch(e){return console.error("Failed to update workflow:",e),a.json({error:e instanceof Error?e.message:"Failed to update workflow"},{status:500})}}async function dt(r,t){try{let e=await m(r);if(!e)return a.json({error:"Unauthorized"},{status:401});if(!await c.query.workflows.findFirst({where:F(p(l.id,t),p(l.userId,e.id))}))return a.json({error:"Workflow not found"},{status:404});let u=(await c.query.workflowExecutions.findMany({where:p(y.workflowId,t),columns:{id:!0}})).map(f=>f.id);return u.length>0&&(await c.delete(N).where(pe(N.executionId,u)),await c.delete(y).where(p(y.workflowId,t))),await c.delete(l).where(p(l.id,t)),a.json({success:!0})}catch(e){return console.error("Failed to delete workflow:",e),a.json({error:e instanceof Error?e.message:"Failed to delete workflow"},{status:500})}}async function ct(r,t){try{let e=await m(r);if(!e)return a.json({error:"Unauthorized"},{status:401});let o=await c.query.workflows.findFirst({where:p(l.id,t)});if(!o)return a.json({error:"Workflow not found"},{status:404});if(!(e.id===o.userId)&&o.visibility!=="public")return a.json({error:"Workflow not found"},{status:404});let u=o.nodes,f=u.map(E=>{let C={...E,id:G()};if(C.data){let U={...C.data};if(U.config){let{integrationId:we,...re}=U.config;U.config=re}U.status="idle",C.data=U}return C}),d=new Map(u.map((E,C)=>[E.id,f[C].id])),g=o.edges.map(E=>({...E,id:G(),source:d.get(E.source)||E.source,target:d.get(E.target)||E.target})),R=await c.query.workflows.findMany({where:p(l.userId,e.id)}),I=`${o.name} (Copy)`,$=I,L=new Set(R.map(E=>E.name));if(L.has($)){let E=2;for(;L.has(`${I} ${E}`);)E++;$=`${I} ${E}`}let q=G(),[K]=await c.insert(l).values({id:q,name:$,description:o.description,nodes:f,edges:g,userId:e.id,visibility:"private"}).returning();return a.json({...K,createdAt:K.createdAt.toISOString(),updatedAt:K.updatedAt.toISOString(),isOwner:!0})}catch(e){return console.error("Failed to duplicate workflow:",e),a.json({error:e instanceof Error?e.message:"Failed to duplicate workflow"},{status:500})}}async function lt(r,t){try{let e=await m(r);if(!e)return a.json({error:"Unauthorized"},{status:401});if(!await c.query.workflows.findFirst({where:F(p(l.id,t),p(l.userId,e.id))}))return a.json({error:"Workflow not found"},{status:404});let n=await c.query.workflowExecutions.findMany({where:p(y.workflowId,t),orderBy:[Y(y.startedAt)],limit:50});return a.json(n)}catch(e){return console.error("Failed to get executions:",e),a.json({error:e instanceof Error?e.message:"Failed to get executions"},{status:500})}}async function ft(r,t){try{let e=await m(r);if(!e)return a.json({error:"Unauthorized"},{status:401});let o=await c.query.workflowExecutions.findFirst({where:p(y.id,t),with:{workflow:!0}});if(!o)return a.json({error:"Execution not found"},{status:404});if(o.workflow.userId!==e.id)return a.json({error:"Forbidden"},{status:403});if(o.status!=="running"&&o.status!=="pending")return a.json({error:"Execution is not running",status:o.status},{status:409});await c.update(y).set({status:"cancelled",completedAt:new Date,duration:String(Date.now()-new Date(o.startedAt).getTime())}).where(p(y.id,t));let n=await c.query.workflowExecutionLogs.findMany({where:F(p(N.executionId,t),pe(N.status,["pending","running"]))});for(let u of n)await c.update(N).set({status:"error",error:"Cancelled",completedAt:new Date}).where(p(N.id,u.id));return a.json({success:!0,status:"cancelled"})}catch(e){return console.error("Failed to cancel execution:",e),a.json({error:e instanceof Error?e.message:"Failed to cancel execution"},{status:500})}}async function pt(r,t){try{let e=await m(r);if(!e)return a.json({error:"Unauthorized"},{status:401});if(!await c.query.workflows.findFirst({where:F(p(l.id,t),p(l.userId,e.id))}))return a.json({error:"Workflow not found"},{status:404});let u=(await c.query.workflowExecutions.findMany({where:p(y.workflowId,t),columns:{id:!0}})).map(f=>f.id);return u.length>0&&(await c.delete(N).where(pe(N.executionId,u)),await c.delete(y).where(p(y.workflowId,t))),a.json({success:!0,deletedCount:u.length})}catch(e){return console.error("Failed to delete executions:",e),a.json({error:e instanceof Error?e.message:"Failed to delete executions"},{status:500})}}async function wt(r,t){try{let e=await c.query.workflows.findFirst({where:p(l.id,t)});if(!e)return a.json({error:"Workflow not found"},{status:404,headers:W});let o=r.headers.get("Authorization");if(!o)return a.json({error:"Missing Authorization header"},{status:401,headers:W});let n=o.startsWith("Bearer ")?o.slice(7):o;if(!n?.startsWith("wfb_"))return a.json({error:"Invalid API key format"},{status:401,headers:W});let u=Kt("sha256").update(n).digest("hex"),f=await c.query.apiKeys.findFirst({where:p(A.keyHash,u)});if(!f||f.userId!==e.userId)return a.json({error:"Invalid API key or insufficient permissions"},{status:401,headers:W});c.update(A).set({lastUsedAt:new Date}).where(p(A.id,f.id)).catch(()=>{});let d=e.nodes.find($=>$.data.type==="trigger");if(!d||d.data.config?.triggerType!=="Webhook")return a.json({error:"This workflow is not configured for webhook triggers"},{status:400,headers:W});if(!(await B(e.nodes,e.userId)).valid)return a.json({error:"Workflow contains invalid integration references"},{status:403,headers:W});let R=await r.json().catch(()=>({})),[I]=await c.insert(y).values({workflowId:t,userId:e.userId,status:"running",input:R}).returning();return H(I.id,t,e.nodes,e.edges,R),a.json({executionId:I.id,status:"running"},{headers:W})}catch(e){return console.error("Failed to start webhook execution:",e),a.json({error:e instanceof Error?e.message:"Failed to execute workflow"},{status:500,headers:W})}}async function gt(r,t){try{let e=await O.api.getSession({headers:r.headers});if(!e?.user)return a.json({error:"Unauthorized"},{status:401});let o=await c.query.workflows.findFirst({where:F(p(l.id,t),p(l.userId,e.user.id))});if(!o)return a.json({error:"Workflow not found"},{status:404});let n=Ze(o.name,o.nodes,o.edges);return a.json({code:n,workflowName:o.name})}catch(e){return console.error("Failed to get workflow code:",e),a.json({error:e instanceof Error?e.message:"Failed to get workflow code"},{status:500})}}async function mt(r,t){try{let e=await O.api.getSession({headers:r.headers});if(!e?.user)return a.json({error:"Unauthorized"},{status:401});let o=await c.query.workflows.findFirst({where:F(p(l.id,t),p(l.userId,e.user.id))});if(!o)return a.json({error:"Workflow not found"},{status:404});let n=await ae(be),u=await ae($e),f={};for(let[$,L]of Object.entries(u)){let q=L.match(Ne);q&&(f[`lib/steps/${$}`]=q[1])}let d=_e({name:o.name,nodes:o.nodes,edges:o.edges}),g={...n,...f,...d},R=JSON.parse(g["package.json"]);R.dependencies={...R.dependencies,workflow:"4.0.1-beta.7",...Oe(o.nodes)},g["package.json"]=JSON.stringify(R,null,2),g["next.config.ts"]=`import { withWorkflow } from 'workflow/next';
29
29
  import type { NextConfig } from 'next';
30
30
 
31
31
  const nextConfig: NextConfig = {};
32
32
 
33
33
  export default withWorkflow(nextConfig);
34
- `;let R=JSON.parse(g["tsconfig.json"]);return R.compilerOptions.plugins=[{name:"next"},{name:"workflow"}],g["tsconfig.json"]=JSON.stringify(R,null,2),g["README.md"]=`# ${o.name}
34
+ `;let I=JSON.parse(g["tsconfig.json"]);return I.compilerOptions.plugins=[{name:"next"},{name:"workflow"}],g["tsconfig.json"]=JSON.stringify(I,null,2),g["README.md"]=`# ${o.name}
35
35
 
36
36
  This is a Next.js workflow project generated from Workflow Builder.
37
37
 
@@ -56,12 +56,12 @@ Open [http://localhost:3000](http://localhost:3000) with your browser to see the
56
56
 
57
57
  ## Workflow API
58
58
 
59
- Your workflow is available at \`/api/workflows/${ae(o.name)}\`.
59
+ Your workflow is available at \`/api/workflows/${ie(o.name)}\`.
60
60
 
61
61
  Send a POST request with a JSON body to trigger the workflow:
62
62
 
63
63
  \`\`\`bash
64
- curl -X POST http://localhost:3000/api/workflows/${ae(o.name)} \\
64
+ curl -X POST http://localhost:3000/api/workflows/${ie(o.name)} \\
65
65
  -H "Content-Type: application/json" \\
66
66
  -d '{"key": "value"}'
67
67
  \`\`\`
@@ -75,4 +75,4 @@ vercel deploy
75
75
  \`\`\`
76
76
 
77
77
  For more information, visit the [Workflow documentation](https://workflow.is).
78
- `,g[".env.example"]=Me(),a.json({success:!0,files:g})}catch(e){return console.error("Failed to prepare workflow download:",e),a.json({success:!1,error:e instanceof Error?e.message:"Failed to prepare workflow download"},{status:500})}}import"virtual:workflow-builder-plugins";async function B(r){let t=Te(r),e=r.method.toUpperCase();if(t.length===0)return ee.json({error:"Not found"},{status:404});let[o,n,u,l]=t;if(o===".well-known")return n==="oauth-authorization-server"?de(r):n==="oauth-protected-resource"?ce(r):ue(r,["auth",...t]);if(o==="auth")return ue(r,t);if(o==="mcp"){if(process.env.NWB_MCP_ENABLED!=="true")return ee.json({error:"MCP server is not enabled"},{status:404});let{handleMcpRequest:d}=await import("../../handler-67JKCHM5.js");return d(r)}if(o==="workflows"){if(n===void 0&&e==="GET")return tt(r);if(n==="create"&&e==="POST")return rt(r);if(n==="current"){if(e==="GET")return ot(r);if(e==="POST")return nt(r)}if(n==="executions"&&u){let d=u;if(l==="status"&&e==="GET")return st(r,d);if(l==="logs"&&e==="GET")return at(r,d);if(l==="cancel"&&e==="POST")return lt(r,d)}if(n&&n!=="create"&&n!=="current"&&n!=="executions"){let d=n;if(u===void 0){if(e==="GET")return et(r,d);if(e==="PATCH")return it(r,d);if(e==="DELETE")return ut(r,d)}if(u==="code"&&e==="GET")return wt(r,d);if(u==="download"&&e==="GET")return gt(r,d);if(u==="duplicate"&&e==="POST")return dt(r,d);if(u==="executions"){if(e==="GET")return ct(r,d);if(e==="DELETE")return ft(r,d)}if(u==="webhook"&&e==="POST")return pt(r,d)}}if(o==="workflow"&&n){if(u==="execute"&&e==="POST")return Ze(r,n);if(u==="cron"&&e==="GET")return ze(r,n)}if(o==="integrations"){if(n===void 0){if(e==="GET")return Le(r);if(e==="POST")return qe(r)}if(n==="test"&&u===void 0&&e==="POST")return Je(r);if(n&&n!=="test"){let d=n;if(u===void 0){if(e==="GET")return Ke(r,d);if(e==="PUT")return He(r,d);if(e==="DELETE")return Be(r,d)}if(u==="test"&&e==="POST")return Ye(r,d)}}if(o==="user"){if(e==="GET")return Ve(r);if(e==="PATCH")return Xe(r)}if(o==="api-keys"){if(n===void 0){if(e==="GET")return De(r);if(e==="POST")return Ge(r)}if(n&&u===void 0&&e==="DELETE")return _e(r,n)}return ee.json({error:"Not found"},{status:404})}async function Zr(r){return B(r)}async function eo(r){return B(r)}async function to(r){return B(r)}async function ro(r){return B(r)}async function oo(r){return B(r)}async function no(r){return ee.json({},{headers:$})}export{oo as DELETE,Zr as GET,no as OPTIONS,ro as PATCH,eo as POST,to as PUT,de as oAuthDiscoveryHandler,ce as oAuthResourceHandler};
78
+ `,g[".env.example"]=Me(),a.json({success:!0,files:g})}catch(e){return console.error("Failed to prepare workflow download:",e),a.json({success:!1,error:e instanceof Error?e.message:"Failed to prepare workflow download"},{status:500})}}async function ht(r){try{let t=await m(r);if(!t)return a.json({error:"Unauthorized"},{status:401});let o=await c.select({id:l.id,name:l.name,description:l.description,updatedAt:l.updatedAt,totalRuns:qt(y.id),successCount:z`cast(count(*) filter (where ${y.status} = 'success') as int)`.as("success_count"),errorCount:z`cast(count(*) filter (where ${y.status} = 'error') as int)`.as("error_count"),cancelledCount:z`cast(count(*) filter (where ${y.status} = 'cancelled') as int)`.as("cancelled_count"),latestRunStatus:z`max(${y.status}) filter (where ${y.startedAt} = (select max(started_at) from workflow_executions we2 where we2.workflow_id = ${l.id}))`.as("latest_run_status"),latestRunStartedAt:z`max(${y.startedAt})`.as("latest_run_started_at"),runningExecutionId:z`max(${y.id}) filter (where ${y.status} in ('running', 'pending'))`.as("running_execution_id")}).from(l).leftJoin(y,p(y.workflowId,l.id)).where(F(p(l.userId,t.id),z`${l.name} != ${"~~__CURRENT__~~"}`)).groupBy(l.id).orderBy(Y(l.updatedAt));return a.json(o.map(n=>({...n,totalRuns:Number(n.totalRuns),successCount:Number(n.successCount),errorCount:Number(n.errorCount),cancelledCount:Number(n.cancelledCount),updatedAt:n.updatedAt.toISOString(),latestRunStartedAt:n.latestRunStartedAt?new Date(n.latestRunStartedAt).toISOString():null})))}catch(t){return console.error("Failed to get dashboard workflows:",t),a.json({error:t instanceof Error?t.message:"Failed to get dashboard workflows"},{status:500})}}import"virtual:workflow-builder-plugins";async function J(r){let t=Fe(r),e=r.method.toUpperCase();if(t.length===0)return te.json({error:"Not found"},{status:404});let[o,n,u,f]=t;if(o===".well-known")return n==="oauth-authorization-server"?ce(r):n==="oauth-protected-resource"?le(r):de(r,["auth",...t]);if(o==="auth")return de(r,t);if(o==="mcp"){if(process.env.NWB_MCP_ENABLED!=="true")return te.json({error:"MCP server is not enabled"},{status:404});let{handleMcpRequest:d}=await import("../../handler-NTDXJ57T.js");return d(r)}if(o==="workflows"){if(n===void 0&&e==="GET")return rt(r);if(n==="create"&&e==="POST")return ot(r);if(n==="current"){if(e==="GET")return nt(r);if(e==="POST")return st(r)}if(n==="dashboard"&&!u&&e==="GET")return ht(r);if(n==="executions"&&u){let d=u;if(f==="status"&&e==="GET")return at(r,d);if(f==="logs"&&e==="GET")return it(r,d);if(f==="cancel"&&e==="POST")return ft(r,d)}if(n&&n!=="create"&&n!=="current"&&n!=="executions"){let d=n;if(u===void 0){if(e==="GET")return tt(r,d);if(e==="PATCH")return ut(r,d);if(e==="DELETE")return dt(r,d)}if(u==="code"&&e==="GET")return gt(r,d);if(u==="download"&&e==="GET")return mt(r,d);if(u==="duplicate"&&e==="POST")return ct(r,d);if(u==="executions"){if(e==="GET")return lt(r,d);if(e==="DELETE")return pt(r,d)}if(u==="webhook"&&e==="POST")return wt(r,d)}}if(o==="workflow"&&n){if(u==="execute"&&e==="POST")return et(r,n);if(u==="cron"&&e==="GET")return Le(r,n)}if(o==="integrations"){if(n===void 0){if(e==="GET")return qe(r);if(e==="POST")return Ke(r)}if(n==="test"&&u===void 0&&e==="POST")return Ve(r);if(n&&n!=="test"){let d=n;if(u===void 0){if(e==="GET")return Be(r,d);if(e==="PUT")return He(r,d);if(e==="DELETE")return Ye(r,d)}if(u==="test"&&e==="POST")return Je(r,d)}}if(o==="user"){if(e==="GET")return Xe(r);if(e==="PATCH")return Qe(r)}if(o==="api-keys"){if(n===void 0){if(e==="GET")return De(r);if(e==="POST")return Ge(r)}if(n&&u===void 0&&e==="DELETE")return ze(r,n)}return te.json({error:"Not found"},{status:404})}async function ro(r){return J(r)}async function oo(r){return J(r)}async function no(r){return J(r)}async function so(r){return J(r)}async function ao(r){return J(r)}async function io(r){return te.json({},{headers:W})}export{ao as DELETE,ro as GET,io as OPTIONS,so as PATCH,oo as POST,no as PUT,ce as oAuthDiscoveryHandler,le as oAuthResourceHandler};
package/dist/styles.css CHANGED
@@ -41,6 +41,7 @@
41
41
  --container-md: 28rem;
42
42
  --container-lg: 32rem;
43
43
  --container-3xl: 48rem;
44
+ --container-5xl: 64rem;
44
45
  --text-xs: 0.75rem;
45
46
  --text-xs--line-height: calc(1 / 0.75);
46
47
  --text-sm: 0.875rem;
@@ -311,6 +312,9 @@
311
312
  .top-\[calc\(0\.5rem\+1\.25rem\)\] {
312
313
  top: calc(0.5rem + 1.25rem);
313
314
  }
315
+ .-right-\[4px\] {
316
+ right: calc(4px * -1);
317
+ }
314
318
  .right-0 {
315
319
  right: calc(var(--spacing) * 0);
316
320
  }
@@ -332,6 +336,9 @@
332
336
  .bottom-full {
333
337
  bottom: 100%;
334
338
  }
339
+ .-left-\[4px\] {
340
+ left: calc(4px * -1);
341
+ }
335
342
  .left-0 {
336
343
  left: calc(var(--spacing) * 0);
337
344
  }
@@ -497,6 +504,9 @@
497
504
  .mb-6 {
498
505
  margin-bottom: calc(var(--spacing) * 6);
499
506
  }
507
+ .mb-8 {
508
+ margin-bottom: calc(var(--spacing) * 8);
509
+ }
500
510
  .mb-\[32px\] {
501
511
  margin-bottom: 32px;
502
512
  }
@@ -506,6 +516,9 @@
506
516
  .ml-1 {
507
517
  margin-left: calc(var(--spacing) * 1);
508
518
  }
519
+ .ml-1\.5 {
520
+ margin-left: calc(var(--spacing) * 1.5);
521
+ }
509
522
  .ml-4 {
510
523
  margin-left: calc(var(--spacing) * 4);
511
524
  }
@@ -753,6 +766,9 @@
753
766
  .min-h-16 {
754
767
  min-height: calc(var(--spacing) * 16);
755
768
  }
769
+ .min-h-48 {
770
+ min-height: calc(var(--spacing) * 48);
771
+ }
756
772
  .min-h-\[22px\] {
757
773
  min-height: 22px;
758
774
  }
@@ -789,6 +805,9 @@
789
805
  .w-6 {
790
806
  width: calc(var(--spacing) * 6);
791
807
  }
808
+ .w-8 {
809
+ width: calc(var(--spacing) * 8);
810
+ }
792
811
  .w-9 {
793
812
  width: calc(var(--spacing) * 9);
794
813
  }
@@ -852,6 +871,9 @@
852
871
  .max-w-3xl {
853
872
  max-width: var(--container-3xl);
854
873
  }
874
+ .max-w-5xl {
875
+ max-width: var(--container-5xl);
876
+ }
855
877
  .max-w-14 {
856
878
  max-width: calc(var(--spacing) * 14);
857
879
  }
@@ -867,6 +889,9 @@
867
889
  .max-w-\[160px\] {
868
890
  max-width: 160px;
869
891
  }
892
+ .max-w-\[200px\] {
893
+ max-width: 200px;
894
+ }
870
895
  .max-w-\[465px\] {
871
896
  max-width: 465px;
872
897
  }
@@ -1408,6 +1433,12 @@
1408
1433
  .bg-blue-600 {
1409
1434
  background-color: var(--color-blue-600);
1410
1435
  }
1436
+ .bg-blue-600\/15 {
1437
+ background-color: color-mix(in srgb, oklch(54.6% 0.245 262.881) 15%, transparent);
1438
+ @supports (color: color-mix(in lab, red, red)) {
1439
+ background-color: color-mix(in oklab, var(--color-blue-600) 15%, transparent);
1440
+ }
1441
+ }
1411
1442
  .bg-border {
1412
1443
  background-color: var(--border);
1413
1444
  }
@@ -1438,6 +1469,12 @@
1438
1469
  background-color: color-mix(in oklab, var(--color-gray-500) 50%, transparent);
1439
1470
  }
1440
1471
  }
1472
+ .bg-gray-600\/15 {
1473
+ background-color: color-mix(in srgb, oklch(44.6% 0.03 256.802) 15%, transparent);
1474
+ @supports (color: color-mix(in lab, red, red)) {
1475
+ background-color: color-mix(in oklab, var(--color-gray-600) 15%, transparent);
1476
+ }
1477
+ }
1441
1478
  .bg-green-500\/10 {
1442
1479
  background-color: color-mix(in srgb, oklch(72.3% 0.219 149.579) 10%, transparent);
1443
1480
  @supports (color: color-mix(in lab, red, red)) {
@@ -1453,6 +1490,12 @@
1453
1490
  .bg-green-600 {
1454
1491
  background-color: var(--color-green-600);
1455
1492
  }
1493
+ .bg-green-600\/15 {
1494
+ background-color: color-mix(in srgb, oklch(62.7% 0.194 149.214) 15%, transparent);
1495
+ @supports (color: color-mix(in lab, red, red)) {
1496
+ background-color: color-mix(in oklab, var(--color-green-600) 15%, transparent);
1497
+ }
1498
+ }
1456
1499
  .bg-input {
1457
1500
  background-color: var(--input);
1458
1501
  }
@@ -1531,6 +1574,12 @@
1531
1574
  .bg-red-600 {
1532
1575
  background-color: var(--color-red-600);
1533
1576
  }
1577
+ .bg-red-600\/15 {
1578
+ background-color: color-mix(in srgb, oklch(57.7% 0.245 27.325) 15%, transparent);
1579
+ @supports (color: color-mix(in lab, red, red)) {
1580
+ background-color: color-mix(in oklab, var(--color-red-600) 15%, transparent);
1581
+ }
1582
+ }
1534
1583
  .bg-secondary {
1535
1584
  background-color: var(--secondary);
1536
1585
  }
@@ -1552,6 +1601,12 @@
1552
1601
  .bg-yellow-600 {
1553
1602
  background-color: var(--color-yellow-600);
1554
1603
  }
1604
+ .bg-yellow-600\/15 {
1605
+ background-color: color-mix(in srgb, oklch(68.1% 0.162 75.834) 15%, transparent);
1606
+ @supports (color: color-mix(in lab, red, red)) {
1607
+ background-color: color-mix(in oklab, var(--color-yellow-600) 15%, transparent);
1608
+ }
1609
+ }
1555
1610
  .bg-zinc-50 {
1556
1611
  background-color: var(--color-zinc-50);
1557
1612
  }
@@ -1591,6 +1646,9 @@
1591
1646
  .p-1 {
1592
1647
  padding: calc(var(--spacing) * 1);
1593
1648
  }
1649
+ .p-1\.5 {
1650
+ padding: calc(var(--spacing) * 1.5);
1651
+ }
1594
1652
  .p-2 {
1595
1653
  padding: calc(var(--spacing) * 2);
1596
1654
  }
@@ -1627,6 +1685,9 @@
1627
1685
  .px-2 {
1628
1686
  padding-inline: calc(var(--spacing) * 2);
1629
1687
  }
1688
+ .px-2\.5 {
1689
+ padding-inline: calc(var(--spacing) * 2.5);
1690
+ }
1630
1691
  .px-3 {
1631
1692
  padding-inline: calc(var(--spacing) * 3);
1632
1693
  }
@@ -1681,12 +1742,18 @@
1681
1742
  .py-8 {
1682
1743
  padding-block: calc(var(--spacing) * 8);
1683
1744
  }
1745
+ .py-10 {
1746
+ padding-block: calc(var(--spacing) * 10);
1747
+ }
1684
1748
  .py-12 {
1685
1749
  padding-block: calc(var(--spacing) * 12);
1686
1750
  }
1687
1751
  .py-16 {
1688
1752
  padding-block: calc(var(--spacing) * 16);
1689
1753
  }
1754
+ .py-24 {
1755
+ padding-block: calc(var(--spacing) * 24);
1756
+ }
1690
1757
  .py-32 {
1691
1758
  padding-block: calc(var(--spacing) * 32);
1692
1759
  }
@@ -1777,6 +1844,9 @@
1777
1844
  font-size: var(--text-xs);
1778
1845
  line-height: var(--tw-leading, var(--text-xs--line-height));
1779
1846
  }
1847
+ .text-\[9px\] {
1848
+ font-size: 9px;
1849
+ }
1780
1850
  .text-\[10px\] {
1781
1851
  font-size: 10px;
1782
1852
  }
@@ -1919,6 +1989,9 @@
1919
1989
  color: color-mix(in oklab, var(--foreground) 70%, transparent);
1920
1990
  }
1921
1991
  }
1992
+ .text-gray-500 {
1993
+ color: var(--color-gray-500);
1994
+ }
1922
1995
  .text-gray-600 {
1923
1996
  color: var(--color-gray-600);
1924
1997
  }
@@ -2361,6 +2434,12 @@
2361
2434
  border-bottom-right-radius: calc(var(--radius) - 2px);
2362
2435
  }
2363
2436
  }
2437
+ .last\:border-b-0 {
2438
+ &:last-child {
2439
+ border-bottom-style: var(--tw-border-style);
2440
+ border-bottom-width: 0px;
2441
+ }
2442
+ }
2364
2443
  .focus-within\:ring-1 {
2365
2444
  &:focus-within {
2366
2445
  --tw-ring-shadow: var(--tw-ring-inset,) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color, currentcolor);
@@ -2466,6 +2545,16 @@
2466
2545
  }
2467
2546
  }
2468
2547
  }
2548
+ .hover\:bg-green-600\/10 {
2549
+ &:hover {
2550
+ @media (hover: hover) {
2551
+ background-color: color-mix(in srgb, oklch(62.7% 0.194 149.214) 10%, transparent);
2552
+ @supports (color: color-mix(in lab, red, red)) {
2553
+ background-color: color-mix(in oklab, var(--color-green-600) 10%, transparent);
2554
+ }
2555
+ }
2556
+ }
2557
+ }
2469
2558
  .hover\:bg-muted {
2470
2559
  &:hover {
2471
2560
  @media (hover: hover) {
@@ -2473,6 +2562,16 @@
2473
2562
  }
2474
2563
  }
2475
2564
  }
2565
+ .hover\:bg-muted\/30 {
2566
+ &:hover {
2567
+ @media (hover: hover) {
2568
+ background-color: var(--muted);
2569
+ @supports (color: color-mix(in lab, red, red)) {
2570
+ background-color: color-mix(in oklab, var(--muted) 30%, transparent);
2571
+ }
2572
+ }
2573
+ }
2574
+ }
2476
2575
  .hover\:bg-muted\/50 {
2477
2576
  &:hover {
2478
2577
  @media (hover: hover) {
@@ -2493,6 +2592,16 @@
2493
2592
  }
2494
2593
  }
2495
2594
  }
2595
+ .hover\:bg-orange-600\/10 {
2596
+ &:hover {
2597
+ @media (hover: hover) {
2598
+ background-color: color-mix(in srgb, oklch(64.6% 0.222 41.116) 10%, transparent);
2599
+ @supports (color: color-mix(in lab, red, red)) {
2600
+ background-color: color-mix(in oklab, var(--color-orange-600) 10%, transparent);
2601
+ }
2602
+ }
2603
+ }
2604
+ }
2496
2605
  .hover\:bg-primary\/90 {
2497
2606
  &:hover {
2498
2607
  @media (hover: hover) {
@@ -2503,6 +2612,16 @@
2503
2612
  }
2504
2613
  }
2505
2614
  }
2615
+ .hover\:bg-red-600\/10 {
2616
+ &:hover {
2617
+ @media (hover: hover) {
2618
+ background-color: color-mix(in srgb, oklch(57.7% 0.245 27.325) 10%, transparent);
2619
+ @supports (color: color-mix(in lab, red, red)) {
2620
+ background-color: color-mix(in oklab, var(--color-red-600) 10%, transparent);
2621
+ }
2622
+ }
2623
+ }
2624
+ }
2506
2625
  .hover\:bg-secondary\/80 {
2507
2626
  &:hover {
2508
2627
  @media (hover: hover) {
@@ -3363,6 +3482,11 @@
3363
3482
  max-width: var(--container-sm);
3364
3483
  }
3365
3484
  }
3485
+ .sm\:grid-cols-4 {
3486
+ @media (width >= 40rem) {
3487
+ grid-template-columns: repeat(4, minmax(0, 1fr));
3488
+ }
3489
+ }
3366
3490
  .sm\:flex-row {
3367
3491
  @media (width >= 40rem) {
3368
3492
  flex-direction: row;
@@ -0,0 +1 @@
1
+ import"./chunk-R5GS6TJS.js";import"./chunk-CYVALTSI.js";import"./chunk-IEOZJAW2.js";import"./chunk-6UXAINJQ.js";import"./chunk-BNX2SV7E.js";import"./chunk-PRVESNIO.js";import"./chunk-KFTXS23Q.js";import"./chunk-QRG4O4PE.js";import"./chunk-7WFHHPX4.js";import{q as i}from"./chunk-5J6TNMJG.js";import"server-only";function r(n){let s=Number(n.routeCount)||4,u=[];for(let e=0;e<s;e++){let a=n[`routeName${e}`],t=n[`routeCondition${e}`],o=n[`routeCaseValue${e}`];u.push({name:a||`Route ${e+1}`,condition:t,caseValue:o})}return u}function c(n){let s=n.mode||"rules",u=n.matchMode||"first",e=r(n),a=[];if(s==="rules"){for(let t=0;t<e.length;t++)if(e[t].condition===!0){if(u==="first")return{matchedRouteIndex:t,matchedRouteName:e[t].name,isDefault:!1};a.push({index:t,name:e[t].name})}}else{let t=String(n.switchValue??"");for(let o=0;o<e.length;o++)if(e[o].caseValue!==void 0&&String(e[o].caseValue)===t){if(u==="first")return{matchedRouteIndex:o,matchedRouteName:e[o].name,isDefault:!1};a.push({index:o,name:e[o].name})}}return a.length>0?{matchedRouteIndex:a[0].index,matchedRouteName:a.map(t=>t.name).join(", "),isDefault:!1,matchedRoutes:a}:{matchedRouteIndex:-1,matchedRouteName:"Default",isDefault:!0}}async function m(n){"use step";return i(n,()=>Promise.resolve(c(n)))}m.maxRetries=0;export{m as switchStep};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "next-workflow-builder",
3
- "version": "0.7.5",
3
+ "version": "0.7.7",
4
4
  "type": "module",
5
5
  "description": "Next.js plugin for Workflow Builder",
6
6
  "repository": "https://github.com/emulienfou/next-workflow-builder",