next-workflow-builder 0.7.6 → 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.
- package/CHANGELOG.md +15 -0
- package/dist/{chunk-MG2CZJRC.js → chunk-2V446QDJ.js} +1 -1
- package/dist/chunk-H2FP5MBV.js +1 -0
- package/dist/client/index.d.ts +3 -1
- package/dist/client/index.js +19 -19
- package/dist/{handler-77P4SE7Q.js → handler-NTDXJ57T.js} +1 -1
- package/dist/{run-workflow-EAXBE7Z5.js → run-workflow-TSGBN4NF.js} +1 -1
- package/dist/{run-workflows-in-sequence-X4A77MVY.js → run-workflows-in-sequence-K5THSFDS.js} +1 -1
- package/dist/server/api/index.js +12 -12
- package/dist/styles.css +109 -0
- package/dist/switch-2LUIE5RH.js +1 -0
- package/package.json +1 -1
- package/dist/chunk-4FVH6K2Q.js +0 -1
- package/dist/switch-V4UFKFL5.js +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as N,e as I}from"./chunk-
|
|
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};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as w}from"./chunk-
|
|
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};
|
package/dist/{run-workflows-in-sequence-X4A77MVY.js → run-workflows-in-sequence-K5THSFDS.js}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as d}from"./chunk-
|
|
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};
|
package/dist/server/api/index.js
CHANGED
|
@@ -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-MG2CZJRC.js";import"../../chunk-4FVH6K2Q.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
|
-
${
|
|
3
|
+
${Et(w,k).join(`,
|
|
4
4
|
`)}
|
|
5
5
|
};
|
|
6
6
|
|
|
7
7
|
// Execute step implementation
|
|
8
|
-
${
|
|
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
|
-
${
|
|
12
|
-
}`}let
|
|
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
|
-
${
|
|
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
|
-
${
|
|
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
|
|
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/${
|
|
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/${
|
|
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
|
|
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;
|
|
@@ -503,6 +504,9 @@
|
|
|
503
504
|
.mb-6 {
|
|
504
505
|
margin-bottom: calc(var(--spacing) * 6);
|
|
505
506
|
}
|
|
507
|
+
.mb-8 {
|
|
508
|
+
margin-bottom: calc(var(--spacing) * 8);
|
|
509
|
+
}
|
|
506
510
|
.mb-\[32px\] {
|
|
507
511
|
margin-bottom: 32px;
|
|
508
512
|
}
|
|
@@ -801,6 +805,9 @@
|
|
|
801
805
|
.w-6 {
|
|
802
806
|
width: calc(var(--spacing) * 6);
|
|
803
807
|
}
|
|
808
|
+
.w-8 {
|
|
809
|
+
width: calc(var(--spacing) * 8);
|
|
810
|
+
}
|
|
804
811
|
.w-9 {
|
|
805
812
|
width: calc(var(--spacing) * 9);
|
|
806
813
|
}
|
|
@@ -864,6 +871,9 @@
|
|
|
864
871
|
.max-w-3xl {
|
|
865
872
|
max-width: var(--container-3xl);
|
|
866
873
|
}
|
|
874
|
+
.max-w-5xl {
|
|
875
|
+
max-width: var(--container-5xl);
|
|
876
|
+
}
|
|
867
877
|
.max-w-14 {
|
|
868
878
|
max-width: calc(var(--spacing) * 14);
|
|
869
879
|
}
|
|
@@ -879,6 +889,9 @@
|
|
|
879
889
|
.max-w-\[160px\] {
|
|
880
890
|
max-width: 160px;
|
|
881
891
|
}
|
|
892
|
+
.max-w-\[200px\] {
|
|
893
|
+
max-width: 200px;
|
|
894
|
+
}
|
|
882
895
|
.max-w-\[465px\] {
|
|
883
896
|
max-width: 465px;
|
|
884
897
|
}
|
|
@@ -1420,6 +1433,12 @@
|
|
|
1420
1433
|
.bg-blue-600 {
|
|
1421
1434
|
background-color: var(--color-blue-600);
|
|
1422
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
|
+
}
|
|
1423
1442
|
.bg-border {
|
|
1424
1443
|
background-color: var(--border);
|
|
1425
1444
|
}
|
|
@@ -1450,6 +1469,12 @@
|
|
|
1450
1469
|
background-color: color-mix(in oklab, var(--color-gray-500) 50%, transparent);
|
|
1451
1470
|
}
|
|
1452
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
|
+
}
|
|
1453
1478
|
.bg-green-500\/10 {
|
|
1454
1479
|
background-color: color-mix(in srgb, oklch(72.3% 0.219 149.579) 10%, transparent);
|
|
1455
1480
|
@supports (color: color-mix(in lab, red, red)) {
|
|
@@ -1465,6 +1490,12 @@
|
|
|
1465
1490
|
.bg-green-600 {
|
|
1466
1491
|
background-color: var(--color-green-600);
|
|
1467
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
|
+
}
|
|
1468
1499
|
.bg-input {
|
|
1469
1500
|
background-color: var(--input);
|
|
1470
1501
|
}
|
|
@@ -1543,6 +1574,12 @@
|
|
|
1543
1574
|
.bg-red-600 {
|
|
1544
1575
|
background-color: var(--color-red-600);
|
|
1545
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
|
+
}
|
|
1546
1583
|
.bg-secondary {
|
|
1547
1584
|
background-color: var(--secondary);
|
|
1548
1585
|
}
|
|
@@ -1564,6 +1601,12 @@
|
|
|
1564
1601
|
.bg-yellow-600 {
|
|
1565
1602
|
background-color: var(--color-yellow-600);
|
|
1566
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
|
+
}
|
|
1567
1610
|
.bg-zinc-50 {
|
|
1568
1611
|
background-color: var(--color-zinc-50);
|
|
1569
1612
|
}
|
|
@@ -1603,6 +1646,9 @@
|
|
|
1603
1646
|
.p-1 {
|
|
1604
1647
|
padding: calc(var(--spacing) * 1);
|
|
1605
1648
|
}
|
|
1649
|
+
.p-1\.5 {
|
|
1650
|
+
padding: calc(var(--spacing) * 1.5);
|
|
1651
|
+
}
|
|
1606
1652
|
.p-2 {
|
|
1607
1653
|
padding: calc(var(--spacing) * 2);
|
|
1608
1654
|
}
|
|
@@ -1639,6 +1685,9 @@
|
|
|
1639
1685
|
.px-2 {
|
|
1640
1686
|
padding-inline: calc(var(--spacing) * 2);
|
|
1641
1687
|
}
|
|
1688
|
+
.px-2\.5 {
|
|
1689
|
+
padding-inline: calc(var(--spacing) * 2.5);
|
|
1690
|
+
}
|
|
1642
1691
|
.px-3 {
|
|
1643
1692
|
padding-inline: calc(var(--spacing) * 3);
|
|
1644
1693
|
}
|
|
@@ -1693,12 +1742,18 @@
|
|
|
1693
1742
|
.py-8 {
|
|
1694
1743
|
padding-block: calc(var(--spacing) * 8);
|
|
1695
1744
|
}
|
|
1745
|
+
.py-10 {
|
|
1746
|
+
padding-block: calc(var(--spacing) * 10);
|
|
1747
|
+
}
|
|
1696
1748
|
.py-12 {
|
|
1697
1749
|
padding-block: calc(var(--spacing) * 12);
|
|
1698
1750
|
}
|
|
1699
1751
|
.py-16 {
|
|
1700
1752
|
padding-block: calc(var(--spacing) * 16);
|
|
1701
1753
|
}
|
|
1754
|
+
.py-24 {
|
|
1755
|
+
padding-block: calc(var(--spacing) * 24);
|
|
1756
|
+
}
|
|
1702
1757
|
.py-32 {
|
|
1703
1758
|
padding-block: calc(var(--spacing) * 32);
|
|
1704
1759
|
}
|
|
@@ -1934,6 +1989,9 @@
|
|
|
1934
1989
|
color: color-mix(in oklab, var(--foreground) 70%, transparent);
|
|
1935
1990
|
}
|
|
1936
1991
|
}
|
|
1992
|
+
.text-gray-500 {
|
|
1993
|
+
color: var(--color-gray-500);
|
|
1994
|
+
}
|
|
1937
1995
|
.text-gray-600 {
|
|
1938
1996
|
color: var(--color-gray-600);
|
|
1939
1997
|
}
|
|
@@ -2376,6 +2434,12 @@
|
|
|
2376
2434
|
border-bottom-right-radius: calc(var(--radius) - 2px);
|
|
2377
2435
|
}
|
|
2378
2436
|
}
|
|
2437
|
+
.last\:border-b-0 {
|
|
2438
|
+
&:last-child {
|
|
2439
|
+
border-bottom-style: var(--tw-border-style);
|
|
2440
|
+
border-bottom-width: 0px;
|
|
2441
|
+
}
|
|
2442
|
+
}
|
|
2379
2443
|
.focus-within\:ring-1 {
|
|
2380
2444
|
&:focus-within {
|
|
2381
2445
|
--tw-ring-shadow: var(--tw-ring-inset,) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color, currentcolor);
|
|
@@ -2481,6 +2545,16 @@
|
|
|
2481
2545
|
}
|
|
2482
2546
|
}
|
|
2483
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
|
+
}
|
|
2484
2558
|
.hover\:bg-muted {
|
|
2485
2559
|
&:hover {
|
|
2486
2560
|
@media (hover: hover) {
|
|
@@ -2488,6 +2562,16 @@
|
|
|
2488
2562
|
}
|
|
2489
2563
|
}
|
|
2490
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
|
+
}
|
|
2491
2575
|
.hover\:bg-muted\/50 {
|
|
2492
2576
|
&:hover {
|
|
2493
2577
|
@media (hover: hover) {
|
|
@@ -2508,6 +2592,16 @@
|
|
|
2508
2592
|
}
|
|
2509
2593
|
}
|
|
2510
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
|
+
}
|
|
2511
2605
|
.hover\:bg-primary\/90 {
|
|
2512
2606
|
&:hover {
|
|
2513
2607
|
@media (hover: hover) {
|
|
@@ -2518,6 +2612,16 @@
|
|
|
2518
2612
|
}
|
|
2519
2613
|
}
|
|
2520
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
|
+
}
|
|
2521
2625
|
.hover\:bg-secondary\/80 {
|
|
2522
2626
|
&:hover {
|
|
2523
2627
|
@media (hover: hover) {
|
|
@@ -3378,6 +3482,11 @@
|
|
|
3378
3482
|
max-width: var(--container-sm);
|
|
3379
3483
|
}
|
|
3380
3484
|
}
|
|
3485
|
+
.sm\:grid-cols-4 {
|
|
3486
|
+
@media (width >= 40rem) {
|
|
3487
|
+
grid-template-columns: repeat(4, minmax(0, 1fr));
|
|
3488
|
+
}
|
|
3489
|
+
}
|
|
3381
3490
|
.sm\:flex-row {
|
|
3382
3491
|
@media (width >= 40rem) {
|
|
3383
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
package/dist/chunk-4FVH6K2Q.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{c as L}from"./chunk-3YVRTDK2.js";import{b as V}from"./chunk-6UXAINJQ.js";import{k as z,o as q,p as B,q as H}from"./chunk-5J6TNMJG.js";import{eq as K}from"drizzle-orm";import"server-only";function Q(s){return{success:!0,data:s.triggerData}}async function A(s){"use step";return s._workflowComplete?(await B(s._workflowComplete),{success:!0,data:{}}):H(s,()=>Promise.resolve(Q(s)))}A.maxRetries=0;var _={"Database Query":{importer:()=>import("./database-query-OHFQUPLV.js"),stepFunction:"databaseQueryStep"},"HTTP Request":{importer:()=>import("./http-request-EHJHOTNA.js"),stepFunction:"httpRequestStep"},Condition:{importer:()=>import("./condition-CFAA7UDI.js"),stepFunction:"conditionStep"},Loop:{importer:()=>import("./loop-5LPVY452.js"),stepFunction:"loopStep"},Switch:{importer:()=>import("./switch-V4UFKFL5.js"),stepFunction:"switchStep"},Merge:{importer:()=>import("./merge-LQKF2JKM.js"),stepFunction:"mergeStep"},"Run Workflow":{importer:()=>import("./run-workflow-EAXBE7Z5.js"),stepFunction:"runWorkflowStep"},"Run Workflows in Sequence":{importer:()=>import("./run-workflows-in-sequence-X4A77MVY.js"),stepFunction:"runWorkflowsInSequenceStep"}};function Z(s,x){if(s===void 0||s==="")return;let c=/\{\{@([^:]+):([^}]+)\}\}/g,p=[...s.matchAll(c)];if(p.length===0)return s;function u(E,n){let l=E.replace(/[^a-zA-Z0-9]/g,"_"),d=x[l];if(!d)return;let a=n.indexOf(".");if(a===-1)return d.data;if(d.data===null||d.data===void 0)return;let i=n.substring(a+1).split("."),o=d.data,S=i[0];o&&typeof o=="object"&&"success"in o&&"data"in o&&S!=="success"&&S!=="data"&&S!=="error"&&!(S in o)&&(o=o.data);for(let k of i)if(o&&typeof o=="object")o=o[k];else return;return o}return p.length===1&&p[0][0]===s?u(p[0][1],p[0][2]):s.replace(c,(E,n,l)=>{let d=u(n,l);return d==null?"":typeof d=="object"?JSON.stringify(d):String(d)})}function Y(s,x){let c=s.dataType||"string",p=s.operator,u=s.leftValue,E=s.rightValue,n=Z(u,x),l=Z(E,x);return console.log("[Condition] Evaluating:",{dataType:c,operator:p,leftResolved:n,rightResolved:l}),{result:L(c,p,n,l),resolvedValues:{leftValue:n,rightValue:l}}}function G(s){let x=/^(.+?)\s*(===|!==|==|!=|>=|<=|>|<)\s*(.+)$/,c=s.trim().match(x);if(!c){let k=s.trim();return k!==""&&k!=="false"&&k!=="0"&&k!=="null"&&k!=="undefined"}let[,p,u,E]=c,n=p.trim(),l=E.trim(),d=k=>k.startsWith('"')&&k.endsWith('"')||k.startsWith("'")&&k.endsWith("'")?k.slice(1,-1):k,a=d(n),g=d(l),i=Number(a),o=Number(g),S=!Number.isNaN(i)&&!Number.isNaN(o)&&a!==""&&g!=="";switch(u){case"===":case"==":return a===g;case"!==":case"!=":return a!==g;case">":return S?i>o:a>g;case"<":return S?i<o:a<g;case">=":return S?i>=o:a>=g;case"<=":return S?i<=o:a<=g;default:return!1}}async function U(s){let{actionType:x,config:c,outputs:p,context:u}=s,E={...c,_context:u};if(x==="Condition"){let a=_.Condition,g=await a.importer(),{result:i,resolvedValues:o}=Y(c,p);return console.log("[Condition] Final result:",i),await g[a.stepFunction]({condition:i,dataType:c.dataType,operator:c.operator,leftValue:o.leftValue,rightValue:o.rightValue,_context:u})}if(x==="Switch"&&(c.mode||"rules")==="rules"){let g=Number(c.routeCount)||4;for(let i=0;i<g;i++){let o=`routeCondition${i}`,S=E[o];typeof S=="string"&&S.trim()!==""&&(E[o]=G(S))}}let n=_[x];if(n){let g=(await n.importer())[n.stepFunction];return await g(E)}let{getStepImporter:l}=await import("virtual:workflow-builder-step-registry"),d=l(x);if(d){let g=(await d.importer())[d.stepFunction];return g?await g(E):{success:!1,error:`Step function "${d.stepFunction}" not found in module for action "${x}". Check that the plugin exports the correct function name.`}}return{success:!1,error:`Unknown action type: "${x}". This action is not registered in the plugin system. Available system actions: ${Object.keys(_).join(", ")}.`}}function J(s,x){let c={};for(let[p,u]of Object.entries(s))if(typeof u=="string"){let E=u,n=/\{\{@([^:]+):([^}]+)\}\}/g;E=E.replace(n,(l,d,a)=>{let g=d.replace(/[^a-zA-Z0-9]/g,"_"),i=x[g];if(!i)return l;let o=a.indexOf(".");if(o===-1){let N=i.data;return N==null?"":typeof N=="object"?JSON.stringify(N):String(N)}if(i.data===null||i.data===void 0)return"";let k=a.substring(o+1).split("."),m=i.data,F=k[0];m&&typeof m=="object"&&"success"in m&&"data"in m&&F!=="success"&&F!=="data"&&F!=="error"&&!(F in m)&&(m=m.data);for(let N of k)if(m&&typeof m=="object")m=m[N];else return"";return m==null?"":typeof m=="object"?JSON.stringify(m):String(m)}),c[p]=E}else c[p]=u;return c}async function ce(s){"use workflow";console.log("[Workflow Executor] Starting workflow execution");let{nodes:x,edges:c,triggerInput:p={},executionId:u,workflowId:E}=s;console.log("[Workflow Executor] Input:",{nodeCount:x.length,edgeCount:c.length,hasExecutionId:!!u,workflowId:E||"none"});let n={},l={},d=new Map(x.map(e=>[e.id,e])),a=new Map,g=new Map,i=new Map;for(let e of c){let f=a.get(e.source)||[];f.push(e.target),a.set(e.source,f);let t=g.get(e.target)||[];if(t.push(e.source),g.set(e.target,t),e.sourceHandle){let r=`${e.source}:${e.sourceHandle}`,j=i.get(r)||[];j.push(e.target),i.set(r,j)}}let o=new Set(c.map(e=>e.target)),S=x.filter(e=>e.data.type==="trigger"&&!o.has(e.id));console.log("[Workflow Executor] Found",S.length,"trigger nodes");let{getActionLabel:k}=await import("virtual:workflow-builder-step-registry");function m(e){if(e.data.label)return e.data.label;if(e.data.type==="action"){let f=e.data.config?.actionType;if(f){let t=k(f);if(t)return t}return"Action"}return e.data.type==="trigger"?e.data.config?.triggerType||"Trigger":e.data.type}async function F(){return u?(await q.query.workflowExecutions.findFirst({where:K(z.id,u),columns:{status:!0}}))?.status==="cancelled":!1}async function N(e,f=new Set){if(console.log("[Workflow Executor] Executing node:",e),await F()){console.log("[Workflow Executor] Execution cancelled, stopping");return}if(f.has(e)){console.log("[Workflow Executor] Node already visited, skipping");return}f.add(e);let t=d.get(e);if(!t){console.log("[Workflow Executor] Node not found:",e);return}if(t.data.enabled===!1){console.log("[Workflow Executor] Skipping disabled node:",e);let r=e.replace(/[^a-zA-Z0-9]/g,"_");n[r]={label:t.data.label||e,data:null};let j=a.get(e)||[];await Promise.all(j.map(R=>N(R,f)));return}try{let r;if(t.data.type==="trigger"){console.log("[Workflow Executor] Executing trigger node");let R=t.data.config||{},P=R.triggerType,O={triggered:!0,timestamp:Date.now()};if(P==="Webhook"&&R.webhookMockRequest&&(!p||Object.keys(p).length===0))try{let W=JSON.parse(R.webhookMockRequest);O={...O,...W},console.log("[Workflow Executor] Using webhook mock request data:",W)}catch(W){console.error("[Workflow Executor] Failed to parse webhook mock request:",W)}else p&&Object.keys(p).length>0&&(O={...O,...p});let b={executionId:u,nodeId:t.id,nodeName:m(t),nodeType:t.data.type},w=await A({triggerData:O,_context:b});r={success:w.success,data:w.data}}else if(t.data.type==="action"){let R=t.data.config||{},P=R.actionType;if(console.log("[Workflow Executor] Executing action node:",P),!P){r={success:!1,error:`Action node "${t.data.label||t.id}" has no action type configured`},l[e]=r;return}let O=J(R,n),b={executionId:u,nodeId:t.id,nodeName:m(t),nodeType:P},w={};if(P==="Merge"){let I=c.filter(T=>T.target===e);for(let T of I){let $=T.source.replace(/[^a-zA-Z0-9]/g,"_"),M=n[$];if(!M?.data)continue;let y=M.data;if("success"in y&&"data"in y&&y.data&&(y=y.data),T.targetHandle){let C=Number.parseInt(T.targetHandle.replace("input-",""),10);Number.isNaN(C)||(w[`input${C+1}`]=y)}else if(typeof y=="object")for(let[C,v]of Object.entries(y))C!=="success"&&C!=="error"&&(w[C]=v)}}else{let I=g.get(e)||[];for(let T of I){let $=T.replace(/[^a-zA-Z0-9]/g,"_"),M=n[$];if(M?.data&&typeof M.data=="object"){let y=M.data;"success"in y&&"data"in y&&y.data&&typeof y.data=="object"&&(y=y.data);for(let[C,v]of Object.entries(y))C!=="success"&&C!=="error"&&(w[C]=v)}}}console.log("[Workflow Executor] Calling executeActionStep");let h=await U({actionType:P,config:{...w,...O},outputs:n,context:b});if(console.log("[Workflow Executor] Step result received:",{hasResult:!!h,resultType:typeof h}),h&&typeof h=="object"&&"success"in h&&h.success===!1){let I=h,T=typeof I.error=="string"?I.error:I.error?.message||`Step "${P}" in node "${t.data.label||t.id}" failed without a specific error message.`;console.error(`[Workflow Executor] Step "${P}" failed:`,T),r={success:!1,error:T}}else r={success:!0,data:h}}else console.log("[Workflow Executor] Unknown node type:",t.data.type),r={success:!1,error:`Unknown node type "${t.data.type}" in node "${t.data.label||t.id}". Expected "trigger" or "action".`};l[e]=r;let j=e.replace(/[^a-zA-Z0-9]/g,"_");if(n[j]={label:t.data.label||e,data:r.data},console.log("[Workflow Executor] Node execution completed:",{nodeId:e,success:r.success}),r.success){let R=t.data.type==="action"&&t.data.config?.actionType==="Condition",P=t.data.type==="action"&&t.data.config?.actionType==="Switch",O=t.data.type==="action"&&t.data.config?.actionType==="Loop";if(R){let b=r.data?.condition;console.log("[Workflow Executor] Condition node result:",b);let w=b?"condition-true":"condition-false",W=i.get(`${e}:${w}`)||[];if(W.length>0)console.log("[Workflow Executor] Condition routing via handle:",w,"executing",W.length,"next nodes"),await Promise.all(W.map(h=>N(h,f)));else if(b===!0){let h=a.get(e)||[];console.log("[Workflow Executor] Condition is true (legacy), executing",h.length,"next nodes in parallel"),await Promise.all(h.map(D=>N(D,f)))}else console.log("[Workflow Executor] Condition is false, skipping next nodes")}else if(P){let b=r.data,w=b?.matchedRouteIndex??-1,h=b?.isDefault??!0?"route-default":`route-${w}`,D=i.get(`${e}:${h}`)||[];console.log("[Workflow Executor] Switch node matched route:",h,"executing",D.length,"next nodes"),D.length>0&&await Promise.all(D.map(I=>N(I,f)))}else if(O){let b=a.get(e)||[],w=r.data;if(w&&b.length>0){let W=new Set(f),h=0;for(;;){console.log("[Workflow Executor] Loop iteration",h,"- batchIndex:",w.currentBatchIndex,"hasMore:",w.hasMore);let D=new Set(W);if(await Promise.all(b.map(C=>N(C,D))),!w.hasMore)break;if(await F()){console.log("[Workflow Executor] Loop cancelled between iterations");break}let I=w.currentBatchIndex+1,T=t.data.config||{},$=J(T,n),M={executionId:u,nodeId:t.id,nodeName:m(t),nodeType:"Loop"},y=await U({actionType:"Loop",config:{...$,currentBatchIndex:I},outputs:n,context:M});n[j]={label:t.data.label||e,data:y},l[e]={success:!0,data:y},w=y,h++}}else b.length>0&&await Promise.all(b.map(W=>N(W,f)))}else{let b=a.get(e)||[];console.log("[Workflow Executor] Executing",b.length,"next nodes in parallel"),await Promise.all(b.map(w=>N(w,f)))}}}catch(r){console.error("[Workflow Executor] Error executing node:",e,r);let R={success:!1,error:await V(r)};l[e]=R}}try{console.log("[Workflow Executor] Starting execution from trigger nodes");let e=Date.now();await Promise.all(S.map(r=>N(r.id)));let f=Object.values(l).every(r=>r.success),t=Date.now()-e;if(console.log("[Workflow Executor] Workflow execution completed:",{success:f,resultCount:Object.keys(l).length,duration:t}),u&&!await F())try{await A({triggerData:{},_workflowComplete:{executionId:u,status:f?"success":"error",output:Object.values(l).at(-1)?.data,error:Object.values(l).find(r=>!r.success)?.error,startTime:e}}),console.log("[Workflow Executor] Updated execution record")}catch(r){console.error("[Workflow Executor] Failed to update execution record:",r)}return{success:f,results:l,outputs:n}}catch(e){console.error("[Workflow Executor] Fatal error during workflow execution:",e);let f=await V(e);if(u)try{await A({triggerData:{},_workflowComplete:{executionId:u,status:"error",error:f,startTime:Date.now()}})}catch(t){console.error("[Workflow Executor] Failed to log error:",t)}return{success:!1,results:l,outputs:n,error:f}}}export{ce as a};
|
package/dist/switch-V4UFKFL5.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
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 s}from"./chunk-5J6TNMJG.js";import"server-only";function a(t){let u=Number(t.routeCount)||4,n=[];for(let e=0;e<u;e++){let o=t[`routeName${e}`],i=t[`routeCondition${e}`],r=t[`routeCaseValue${e}`];n.push({name:o||`Route ${e+1}`,condition:i,caseValue:r})}return n}function c(t){let u=t.mode||"rules",n=a(t);if(u==="rules"){for(let e=0;e<n.length;e++)if(n[e].condition===!0)return{matchedRouteIndex:e,matchedRouteName:n[e].name,isDefault:!1}}else{let e=String(t.switchValue??"");for(let o=0;o<n.length;o++)if(n[o].caseValue!==void 0&&String(n[o].caseValue)===e)return{matchedRouteIndex:o,matchedRouteName:n[o].name,isDefault:!1}}return{matchedRouteIndex:-1,matchedRouteName:"Default",isDefault:!0}}async function l(t){"use step";return s(t,()=>Promise.resolve(c(t)))}l.maxRetries=0;export{l as switchStep};
|