next-workflow-builder 0.7.3 → 0.7.5
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 +23 -0
- package/dist/{chunk-4BSNRZZU.js → chunk-CI7FTYZR.js} +2 -2
- package/dist/{chunk-5M2LRKT5.js → chunk-CYVALTSI.js} +9 -9
- package/dist/{chunk-HJKTLN6E.js → chunk-WT4BSMUD.js} +1 -1
- package/dist/client/index.d.ts +12 -2
- package/dist/client/index.js +19 -19
- package/dist/{condition-CEH7OSFJ.js → condition-CFAA7UDI.js} +1 -1
- package/dist/{handler-PF3O3IEZ.js → handler-67JKCHM5.js} +1 -1
- package/dist/{loop-E2EVYWUK.js → loop-5LPVY452.js} +1 -1
- package/dist/{merge-XFCABPCI.js → merge-HYBHX22D.js} +1 -1
- package/dist/next/index.js +1 -1
- package/dist/{run-workflow-KBAEB2FV.js → run-workflow-VFZV5YLI.js} +1 -1
- package/dist/{run-workflows-in-sequence-S44K3HKF.js → run-workflows-in-sequence-3APONBOX.js} +1 -1
- package/dist/server/api/index.js +7 -7
- package/dist/server/index.js +1 -1
- package/dist/styles.css +1 -1
- package/dist/{switch-FN4UA62F.js → switch-ZPVREROE.js} +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import"./chunk-R5GS6TJS.js";import"./chunk-
|
|
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 o}from"./chunk-5J6TNMJG.js";import"server-only";function n(t){return{condition:t.condition}}async function e(t){"use step";return o(t,()=>Promise.resolve(n(t)))}e.maxRetries=0;export{e as conditionStep};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as N,e as I}from"./chunk-
|
|
1
|
+
import{a as N,e as I}from"./chunk-CI7FTYZR.js";import"./chunk-WT4BSMUD.js";import"./chunk-VUDOAZ3W.js";import"./chunk-3YVRTDK2.js";import{b as O}from"./chunk-IEOZJAW2.js";import"./chunk-6UXAINJQ.js";import"./chunk-BNX2SV7E.js";import{i as k}from"./chunk-KFTXS23Q.js";import{k as h,w as A}from"./chunk-QRG4O4PE.js";import{a as m,i as c,j as l,k as f,l as g,o as s}from"./chunk-5J6TNMJG.js";import{WebStandardStreamableHTTPServerTransport as W}from"@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js";import{withMcpAuth as _}from"better-auth/plugins";import{McpServer as E}from"@modelcontextprotocol/sdk/server/mcp.js";import{and as y,desc as v,eq as a,inArray as J}from"drizzle-orm";import{z as r}from"zod";function T(d,i){d.registerTool("list_workflows",{description:"List the authenticated user's workflows",inputSchema:{limit:r.number().optional(),offset:r.number().optional()}},async({limit:e,offset:t})=>{let o=await s.select().from(c).where(a(c.userId,i)).orderBy(v(c.updatedAt)).limit(e??50).offset(t??0);return{content:[{type:"text",text:JSON.stringify(o.map(n=>({...n,createdAt:n.createdAt.toISOString(),updatedAt:n.updatedAt.toISOString()})))}]}}),d.registerTool("get_workflow",{description:"Get a workflow by ID",inputSchema:{workflowId:r.string()}},async({workflowId:e})=>{let t=await s.query.workflows.findFirst({where:y(a(c.id,e),a(c.userId,i))});return t?{content:[{type:"text",text:JSON.stringify({...t,createdAt:t.createdAt.toISOString(),updatedAt:t.updatedAt.toISOString()})}]}:{content:[{type:"text",text:JSON.stringify({error:"Workflow not found"})}]}}),d.registerTool("create_workflow",{description:"Create a new workflow",inputSchema:{name:r.string(),description:r.string().optional(),nodes:r.array(r.record(r.string(),r.unknown())),edges:r.array(r.record(r.string(),r.unknown()))}},async({name:e,description:t,nodes:o,edges:n})=>{if(!(await k(o,i)).valid)return{content:[{type:"text",text:JSON.stringify({error:"Invalid integration references"})}]};let x=m(),[u]=await s.insert(c).values({id:x,name:e,description:t,nodes:o,edges:n,userId:i}).returning();return{content:[{type:"text",text:JSON.stringify({...u,createdAt:u.createdAt.toISOString(),updatedAt:u.updatedAt.toISOString()})}]}}),d.registerTool("update_workflow",{description:"Update an existing workflow",inputSchema:{workflowId:r.string(),name:r.string().optional(),description:r.string().optional(),nodes:r.array(r.record(r.string(),r.unknown())).optional(),edges:r.array(r.record(r.string(),r.unknown())).optional()}},async({workflowId:e,name:t,description:o,nodes:n,edges:w})=>{if(!await s.query.workflows.findFirst({where:y(a(c.id,e),a(c.userId,i))}))return{content:[{type:"text",text:JSON.stringify({error:"Workflow not found"})}]};if(n&&!(await k(n,i)).valid)return{content:[{type:"text",text:JSON.stringify({error:"Invalid integration references"})}]};let u={updatedAt:new Date};t!==void 0&&(u.name=t),o!==void 0&&(u.description=o),n!==void 0&&(u.nodes=n),w!==void 0&&(u.edges=w);let[p]=await s.update(c).set(u).where(a(c.id,e)).returning();return{content:[{type:"text",text:JSON.stringify({...p,createdAt:p.createdAt.toISOString(),updatedAt:p.updatedAt.toISOString()})}]}}),d.registerTool("delete_workflow",{description:"Delete a workflow",inputSchema:{workflowId:r.string()}},async({workflowId:e})=>{if(!await s.query.workflows.findFirst({where:y(a(c.id,e),a(c.userId,i))}))return{content:[{type:"text",text:JSON.stringify({error:"Workflow not found"})}]};let n=(await s.query.workflowExecutions.findMany({where:a(f.workflowId,e),columns:{id:!0}})).map(w=>w.id);return n.length>0&&(await s.delete(g).where(J(g.executionId,n)),await s.delete(f).where(a(f.workflowId,e))),await s.delete(c).where(a(c.id,e)),{content:[{type:"text",text:JSON.stringify({success:!0})}]}}),d.registerTool("duplicate_workflow",{description:"Duplicate a workflow",inputSchema:{workflowId:r.string()}},async({workflowId:e})=>{let t=await s.query.workflows.findFirst({where:y(a(c.id,e),a(c.userId,i))});if(!t)return{content:[{type:"text",text:JSON.stringify({error:"Workflow not found"})}]};let o=t.nodes,n=o.map(p=>({...p,id:m()})),w=new Map(o.map((p,S)=>[p.id,n[S].id])),x=t.edges.map(p=>({...p,id:m(),source:w.get(p.source)||p.source,target:w.get(p.target)||p.target})),[u]=await s.insert(c).values({id:m(),name:`${t.name} (Copy)`,description:t.description,nodes:n,edges:x,userId:i,visibility:"private"}).returning();return{content:[{type:"text",text:JSON.stringify({...u,createdAt:u.createdAt.toISOString(),updatedAt:u.updatedAt.toISOString()})}]}}),d.registerTool("execute_workflow",{description:"Execute a workflow",inputSchema:{workflowId:r.string(),input:r.record(r.string(),r.unknown()).optional()}},async({workflowId:e,input:t})=>{let o=await s.query.workflows.findFirst({where:y(a(c.id,e),a(c.userId,i))});if(!o)return{content:[{type:"text",text:JSON.stringify({error:"Workflow not found"})}]};if(!(await k(o.nodes,i)).valid)return{content:[{type:"text",text:JSON.stringify({error:"Invalid integration references"})}]};let[w]=await s.insert(f).values({workflowId:e,userId:i,status:"running",input:t??{}}).returning();return I(w.id,e,o.nodes,o.edges,t??{}),{content:[{type:"text",text:JSON.stringify({executionId:w.id,status:"running"})}]}}),d.registerTool("get_execution_status",{description:"Get execution status and logs",inputSchema:{executionId:r.string()}},async({executionId:e})=>{let t=await s.query.workflowExecutions.findFirst({where:a(f.id,e),with:{workflow:!0}});if(!t||t.workflow.userId!==i)return{content:[{type:"text",text:JSON.stringify({error:"Execution not found"})}]};let o=await s.query.workflowExecutionLogs.findMany({where:a(g.executionId,e),orderBy:[v(g.timestamp)]});return{content:[{type:"text",text:JSON.stringify({status:t.status,input:t.input,output:t.output,error:t.error,startedAt:t.startedAt.toISOString(),completedAt:t.completedAt?.toISOString(),logs:o.map(n=>({nodeId:n.nodeId,nodeName:n.nodeName,nodeType:n.nodeType,status:n.status,input:n.input,output:n.output,error:n.error}))})}]}}),d.registerTool("cancel_execution",{description:"Cancel a running workflow execution",inputSchema:{executionId:r.string()}},async({executionId:e})=>{let t=await s.query.workflowExecutions.findFirst({where:a(f.id,e),with:{workflow:!0}});if(!t||t.workflow.userId!==i)return{content:[{type:"text",text:JSON.stringify({error:"Execution not found"})}]};if(t.status!=="running"&&t.status!=="pending")return{content:[{type:"text",text:JSON.stringify({error:"Execution is not running",status:t.status})}]};await s.update(f).set({status:"cancelled",completedAt:new Date,duration:String(Date.now()-new Date(t.startedAt).getTime())}).where(a(f.id,e));let o=await s.query.workflowExecutionLogs.findMany({where:y(a(g.executionId,e),J(g.status,["pending","running"]))});for(let n of o)await s.update(g).set({status:"error",error:"Cancelled",completedAt:new Date}).where(a(g.id,n.id));return{content:[{type:"text",text:JSON.stringify({success:!0,status:"cancelled"})}]}}),d.registerTool("list_available_actions",{description:"List all available plugin actions with their config fields"},async()=>{let t=h().map(o=>({id:o.id,label:o.label,description:o.description,category:o.category,integration:o.integration,configFields:A(o.configFields).map(n=>({key:n.key,label:n.label,type:n.type,required:n.required,placeholder:n.placeholder}))}));return{content:[{type:"text",text:JSON.stringify(t)}]}}),d.registerTool("list_integrations",{description:"List the authenticated user's connected integrations"},async()=>{let e=await s.select({id:l.id,name:l.name,type:l.type,isManaged:l.isManaged,createdAt:l.createdAt,updatedAt:l.updatedAt}).from(l).where(a(l.userId,i));return{content:[{type:"text",text:JSON.stringify(e.map(t=>({...t,createdAt:t.createdAt.toISOString(),updatedAt:t.updatedAt.toISOString()})))}]}})}function L(d){let i=new E({name:"workflow-builder",version:"1.0.0"});return T(i,d),i}async function M(d,i){let e=L(i),t=new W({sessionIdGenerator:void 0});return await e.connect(t),await t.handleRequest(d)}async function V(d){if(d.method==="POST"){if(process.env.NWB_ANONYMOUS_AUTH!=="false"){let i=await N(d);if(i)return M(d,i.id)}return _(O,async(i,e)=>M(i,e.userId))(d)}return new Response("Method not allowed",{status:405})}export{V as handleMcpRequest};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import"./chunk-R5GS6TJS.js";import"./chunk-
|
|
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 m}from"./chunk-5J6TNMJG.js";import"server-only";function h(t){let c=typeof t.items=="string"?JSON.parse(t.items):t.items,n=Array.isArray(c)?c:[],e=Math.max(1,t.batchSize||1),o=t.currentBatchIndex??0,r=n.length,a=Math.ceil(r/e),s=o*e,p=Math.min(s+e,r),u=n.slice(s,p),i=u[0];return{hasMore:o<a-1,currentBatchIndex:o,currentBatch:u,currentItem:i,currentIndex:s,totalItems:r,totalBatches:a,items:n,batchSize:e}}async function I(t){"use step";return m(t,()=>Promise.resolve(h(t)))}I.maxRetries=0;export{I as loopStep};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import"./chunk-R5GS6TJS.js";import"./chunk-
|
|
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 g}from"./chunk-5J6TNMJG.js";import"server-only";function p(e,t){if(e&&typeof e=="object")return e[t]}function m(e,t){let o=[...e,...t];return{merged:o,totalItems:o.length}}function f(e,t,o){let l=Math.max(e.length,t.length),c=o!=="discard",u=[];for(let r=0;r<l;r++){let s=e[r],n=t[r];!c&&(s===void 0||n===void 0)||u.push({...s&&typeof s=="object"?s:{input1:s??null},...n&&typeof n=="object"?n:{input2:n??null}})}return{merged:u,totalItems:u.length}}function h(e,t,o,l,c){let u=new Map;for(let n of t){let i=p(n,l);u.has(i)||u.set(i,[]),u.get(i).push(n)}let r=[],s=new Set;for(let n of e){let i=p(n,o),d=u.get(i);if(d&&d.length>0){s.add(i);for(let a of d)r.push({...typeof n=="object"?n:{},...typeof a=="object"?a:{}})}else(c==="leftOuter"||c==="fullOuter")&&r.push({...typeof n=="object"?n:{}})}if(c==="rightOuter"||c==="fullOuter")for(let n of t){let i=p(n,l);s.has(i)||r.push({...typeof n=="object"?n:{}})}return{merged:r,totalItems:r.length}}function y(e){let t=Array.isArray(e.input1)?e.input1:[],o=Array.isArray(e.input2)?e.input2:[];switch(e.mode||"append"){case"append":return m(t,o);case"combineByPosition":return f(t,o,e.unmatchedHandling||"useNull");case"combineByFields":return h(t,o,e.matchField1||"id",e.matchField2||"id",e.joinType||"inner");default:return m(t,o)}}async function w(e){"use step";return g(e,()=>Promise.resolve(y(e)))}w.maxRetries=0;export{w as mergeStep};
|
package/dist/next/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as l}from"../chunk-
|
|
1
|
+
import{a as l}from"../chunk-CYVALTSI.js";import"../chunk-BNX2SV7E.js";import"../chunk-QRG4O4PE.js";import{join as a}from"path";import{z as _}from"zod";import{z as o}from"zod";var n=o.strictObject({debug:o.boolean().optional(),authOptions:o.record(o.string(),o.unknown()).optional(),anonymousAuth:o.boolean().optional(),databaseUrl:o.string().optional(),mcp:o.strictObject({enabled:o.boolean(),loginPage:o.string().optional()}).optional()});var u="virtual:workflow-builder-plugins",p="virtual:workflow-builder-step-registry",A=(c={})=>{let{error:i,data:e}=n.safeParse(c);if(i)throw console.error("Error validating NextWorkflowBuilderConfig"),_.prettifyError(i);return e.authOptions&&(process.env.NWB_AUTH_OPTIONS=JSON.stringify(e.authOptions)),e.databaseUrl&&(process.env.NWB_DATABASE_URL=e.databaseUrl),e.anonymousAuth===!1&&(process.env.NWB_ANONYMOUS_AUTH="false"),e.mcp?.enabled&&(process.env.NWB_MCP_ENABLED="true",process.env.NWB_MCP_LOGIN_PAGE=e.mcp.loginPage||"/auth/sign-in"),l(),function(s={}){let f="./plugins/index.ts",d=a(process.cwd(),"plugins","index.ts"),N="./lib/step-registry.ts",g=a(process.cwd(),"lib","step-registry.ts"),t={};return e.authOptions&&(t.NWB_AUTH_OPTIONS=JSON.stringify(e.authOptions)),e.databaseUrl&&(t.NWB_DATABASE_URL=e.databaseUrl),e.anonymousAuth===!1&&(t.NWB_ANONYMOUS_AUTH="false"),e.mcp?.enabled&&(t.NWB_MCP_ENABLED="true",t.NWB_MCP_LOGIN_PAGE=e.mcp.loginPage||"/auth/sign-in"),{...s,...Object.keys(t).length>0?{env:{...s.env,...t}}:{},turbopack:{...s.turbopack,resolveAlias:{...s.turbopack?.resolveAlias,[u]:f,[p]:N}},webpack:(r,m)=>(r.resolve=r.resolve||{},r.resolve.alias=r.resolve.alias||{},r.resolve.alias[u]=d,r.resolve.alias[p]=g,typeof s.webpack=="function"?s.webpack(r,m):r)}}},U=A;export{U as default};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as w}from"./chunk-
|
|
1
|
+
import{a as w}from"./chunk-WT4BSMUD.js";import"./chunk-3YVRTDK2.js";import"./chunk-R5GS6TJS.js";import"./chunk-CYVALTSI.js";import"./chunk-IEOZJAW2.js";import"./chunk-6UXAINJQ.js";import"./chunk-BNX2SV7E.js";import"./chunk-PRVESNIO.js";import"./chunk-KFTXS23Q.js";import"./chunk-QRG4O4PE.js";import"./chunk-7WFHHPX4.js";import{a as c,i,k as l,o as f,q as p}from"./chunk-5J6TNMJG.js";import"server-only";import{eq as d}from"drizzle-orm";async function k(t){let{workflowId:r,input:e}=t;if(!r)return{success:!1,error:"No workflow selected"};let[o]=await f.select().from(i).where(d(i.id,r)).limit(1);if(!o)return{success:!1,error:`Workflow "${r}" not found`};let s={};if(e&&e.trim())try{s=JSON.parse(e)}catch{return{success:!1,error:`Invalid JSON input: ${e}`}}let u=c();await f.insert(l).values({id:u,workflowId:r,userId:o.userId,status:"running",input:s});let n=await w({nodes:o.nodes,edges:o.edges,triggerInput:s,executionId:u,workflowId:r});if(n.success){let a=Object.values(n.outputs||{}).at(-1)?.data;return{success:!0,executionId:u,output:a}}return{success:!1,error:n.error||"Sub-workflow execution failed"}}async function m(t){"use step";return p(t,()=>k(t))}m.maxRetries=0;export{m as runWorkflowStep};
|
package/dist/{run-workflows-in-sequence-S44K3HKF.js → run-workflows-in-sequence-3APONBOX.js}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as d}from"./chunk-
|
|
1
|
+
import{a as d}from"./chunk-WT4BSMUD.js";import"./chunk-3YVRTDK2.js";import"./chunk-R5GS6TJS.js";import"./chunk-CYVALTSI.js";import"./chunk-IEOZJAW2.js";import"./chunk-6UXAINJQ.js";import"./chunk-BNX2SV7E.js";import"./chunk-PRVESNIO.js";import"./chunk-KFTXS23Q.js";import"./chunk-QRG4O4PE.js";import"./chunk-7WFHHPX4.js";import{a,i as c,k as w,o as i,q as p}from"./chunk-5J6TNMJG.js";import"server-only";import{eq as g}from"drizzle-orm";function R(e){if(!e||!e.trim())return[];try{let t=JSON.parse(e);if(Array.isArray(t))return t.filter(Boolean)}catch{}return e.split(",").map(t=>t.trim()).filter(Boolean)}async function W(e){let t=R(e.workflowIds),f=e.continueOnFailure==="true";if(t.length===0)return{success:!1,error:"No workflows selected"};let u={};if(e.input&&e.input.trim())try{u=JSON.parse(e.input)}catch{return{success:!1,error:`Invalid JSON input: ${e.input}`}}let o=[];for(let r of t){let[s]=await i.select().from(c).where(g(c.id,r)).limit(1);if(!s){let I={workflowId:r,workflowName:"Unknown",executionId:"",success:!1,error:`Workflow "${r}" not found`};if(o.push(I),!f)break;continue}let l=a();await i.insert(w).values({id:l,workflowId:r,userId:s.userId,status:"running",input:u});let n=await d({nodes:s.nodes,edges:s.edges,triggerInput:u,executionId:l,workflowId:r}),k=Object.values(n.outputs||{}).at(-1)?.data,m={workflowId:r,workflowName:s.name,executionId:l,success:n.success,output:k,error:n.error};if(o.push(m),!n.success&&!f)break}return{success:!0,results:o,succeeded:o.filter(r=>r.success).length,failed:o.filter(r=>!r.success).length,total:t.length}}async function S(e){"use step";return p(e,()=>W(e))}S.maxRetries=0;export{S as runWorkflowsInSequenceStep};
|
package/dist/server/api/index.js
CHANGED
|
@@ -1,15 +1,15 @@
|
|
|
1
|
-
import{a as h,b as W,c as Se,d as Te,e as H,f as Fe,g as ve,h as se,i as Ue,j as Ce,k as Oe,l as ae}from"../../chunk-4BSNRZZU.js";import"../../chunk-HJKTLN6E.js";import{a as Re,b as Ae,c as Pe}from"../../chunk-NI6U7PHC.js";import{a as re,b as ye,c as je,d as xe,e as Ee,f as Ie,g as J,h as G}from"../../chunk-VUDOAZ3W.js";import"../../chunk-3YVRTDK2.js";import{b as M}from"../../chunk-IEOZJAW2.js";import{j as ge,k as me,n as he}from"../../chunk-BNX2SV7E.js";import"../../chunk-6UXAINJQ.js";import{c as be,d as ne,f as Ne,g as We,h as $e,i as K}from"../../chunk-KFTXS23Q.js";import{m as ke}from"../../chunk-QRG4O4PE.js";import{a as _,b as V,d as oe,i as f,k as R,l as T,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 $}from"next/server";import{createHash as bt}from"crypto";async function Me(r){try{let t=await h(r);if(!t)return $.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 $.json(e)}catch(t){return console.error("Failed to list API keys:",t),$.json({error:"Failed to list API keys"},{status:500})}}async function De(r){try{let t=await h(r);if(!t)return $.json({error:"Unauthorized"},{status:401});if(t.name==="Anonymous"||t.email?.startsWith("temp-"))return $.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"),E=d.slice(0,11),[I]=await c.insert(A).values({userId:t.id,name:n,keyHash:g,keyPrefix:E}).returning({id:A.id,name:A.name,keyPrefix:A.keyPrefix,createdAt:A.createdAt});return $.json({...I,key:d})}catch(t){return console.error("Failed to create API key:",t),$.json({error:"Failed to create API key"},{status:500})}}async function Ge(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?$.json({error:"API key not found"},{status:404}):$.json({success:!0}):$.json({error:"Unauthorized"},{status:401})}catch(e){return console.error("Failed to delete API key:",e),$.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=Te(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 _e(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(f.id,t)});if(!o)return X.json({error:"Workflow not found"},{status:404});let[n]=await c.insert(R).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 ze(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 be(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 Le(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 Ne(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 qe(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 Ke(r,t){try{let e=await h(r);if(!e)return y.json({error:"Unauthorized"},{status:401});let o=await r.json(),n=await We(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 He(r,t){try{let e=await h(r);return e?await $e(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 Be(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 Ye(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 Je(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 Ve(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 p,inArray as Qe}from"drizzle-orm";import{NextResponse as a}from"next/server";import{createHash as zt}from"crypto";import"server-only";var vt={"Database Query":Ae.codeGenerator,"HTTP Request":Pe.codeGenerator,Condition:Re.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=ke(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 E=d.split(".").map(I=>{let b=I.match(re);return b?`?.${b[1]}?.[${b[2]}]`:`?.${I}`}).join("");return`\${outputs?.['${g}']?.data${E}}`}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=ye(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 E=g>0?`${d}${g+1}`:d;e.set(o.id,E)}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 Xe(r,t,e){let o=new Set,n=[],u=new Map(t.map(s=>[s.id,s])),l=je(e),d=xe(t,e),g=Dt(t);o.add("import { sleep, FatalError } from 'workflow';");function E(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 I(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 x(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 fe(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":()=>E(i),"Send Slack Message":()=>I(i),"Create Ticket":()=>b(i),"Generate Text":()=>z(i),"Generate Image":()=>L(i),"Database Query":()=>q(i),"HTTP Request":()=>x(i),Condition:()=>U(i),Scrape:()=>C(s,i),Search:()=>C(s,i),"Create Chat":()=>fe(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),N;return P&&s.data.type==="action"?N=` // Call step function with constructed input
|
|
1
|
+
import{a as h,b as $,c as Te,d as Fe,e as H,f as ve,g as Ue,h as se,i as Ce,j as Oe,k as Me,l as ae}from"../../chunk-CI7FTYZR.js";import"../../chunk-WT4BSMUD.js";import{a as Ee,b as Ie,c as Re}from"../../chunk-NI6U7PHC.js";import{a as re,b as he,c as ke,d as ye,e as je,f as xe,g as J,h as G}from"../../chunk-VUDOAZ3W.js";import"../../chunk-3YVRTDK2.js";import{b as M}from"../../chunk-IEOZJAW2.js";import"../../chunk-6UXAINJQ.js";import{j as Ae,k as Pe,n as be}from"../../chunk-BNX2SV7E.js";import{c as Ne,d as ne,f as We,g as $e,h as Se,i as K}from"../../chunk-KFTXS23Q.js";import{m as me}from"../../chunk-QRG4O4PE.js";import{a as _,b as V,d as oe,i as p,k as x,l as N,m as A,o as c}from"../../chunk-5J6TNMJG.js";import{NextResponse as ee}from"next/server";import{and as Pt,eq as ie}from"drizzle-orm";import{NextResponse as S}from"next/server";import{createHash as bt}from"crypto";async function De(r){try{let t=await h(r);if(!t)return S.json({error:"Unauthorized"},{status:401});let e=await c.query.apiKeys.findMany({where:ie(A.userId,t.id),columns:{id:!0,name:!0,keyPrefix:!0,createdAt:!0,lastUsedAt:!0},orderBy:(o,{desc:n})=>[n(o.createdAt)]});return S.json(e)}catch(t){return console.error("Failed to list API keys:",t),S.json({error:"Failed to list API keys"},{status:500})}}async function Ge(r){try{let t=await h(r);if(!t)return S.json({error:"Unauthorized"},{status:401});if(t.name==="Anonymous"||t.email?.startsWith("temp-"))return S.json({error:"Anonymous users cannot create API keys"},{status:403});let n=(await r.json().catch(()=>({}))).name||null,{randomBytes:u}=await import("crypto"),d=`wfb_${u(24).toString("base64url")}`,g=bt("sha256").update(d).digest("hex"),I=d.slice(0,11),[R]=await c.insert(A).values({userId:t.id,name:n,keyHash:g,keyPrefix:I}).returning({id:A.id,name:A.name,keyPrefix:A.keyPrefix,createdAt:A.createdAt});return S.json({...R,key:d})}catch(t){return console.error("Failed to create API key:",t),S.json({error:"Failed to create API key"},{status:500})}}async function _e(r,t){try{let e=await h(r);return e?(await c.delete(A).where(Pt(ie(A.id,t),ie(A.userId,e.id))).returning({id:A.id})).length===0?S.json({error:"API key not found"},{status:404}):S.json({success:!0}):S.json({error:"Unauthorized"},{status:401})}catch(e){return console.error("Failed to delete API key:",e),S.json({error:"Failed to delete API key"},{status:500})}}import{toNextJsHandler as Nt}from"better-auth/next-js";var{GET:Wt,POST:$t}=Nt(M);async function ue(r,t){let e="/api/auth/"+t.slice(1).join("/"),o=new URL(r.url),n=`${o.origin}${e}${o.search}`,u=Fe(r,n),l=r.method==="GET"?await Wt(u):await $t(u);return l.status>=500&&!await l.clone().text()?new Response(JSON.stringify({debug:"500 with empty body from better-auth",path:e}),{status:500,headers:{"Content-Type":"application/json"}}):l}import{eq as St}from"drizzle-orm";import{NextResponse as X}from"next/server";async function ze(r,t){try{if(r.headers.get("authorization")!==`Bearer ${process.env.CRON_SECRET}`)return X.json({error:"Unauthorized"},{status:401});let o=await c.query.workflows.findFirst({where:St(p.id,t)});if(!o)return X.json({error:"Workflow not found"},{status:404});let[n]=await c.insert(x).values({workflowId:t,userId:o.userId,status:"running",input:{}}).returning();return await H(n.id,t,o.nodes,o.edges,{}),X.json({success:!0,workflowId:t,executionId:n.id,message:"Workflow execution completed"})}catch(e){return console.error("[Cron] Scheduled workflow execution error:",e),X.json({error:"Execution failed",message:e instanceof Error?e.message:"Unknown error"},{status:500})}}import{oAuthDiscoveryMetadata as Tt,oAuthProtectedResourceMetadata as Ft}from"better-auth/plugins";var de=Tt(M),ce=Ft(M);import{NextResponse as y}from"next/server";async function Le(r){try{let t=await h(r);if(!t)return y.json({error:"Unauthorized"},{status:401});let{searchParams:e}=new URL(r.url),o=e.get("type"),n=await Ne(t.id,o||void 0);return y.json(n.map(u=>({id:u.id,name:u.name,type:u.type,isManaged:u.isManaged??!1,createdAt:u.createdAt.toISOString(),updatedAt:u.updatedAt.toISOString()})))}catch(t){return console.error("Failed to get integrations:",t),y.json({error:"Failed to get integrations",details:t instanceof Error?t.message:"Unknown error"},{status:500})}}async function qe(r){try{let t=await h(r);if(!t)return y.json({error:"Unauthorized"},{status:401});let e=await r.json();if(!(e.type&&e.config))return y.json({error:"Type and config are required"},{status:400});let o=await We(t.id,e.name||"",e.type,e.config);return y.json({id:o.id,name:o.name,type:o.type,createdAt:o.createdAt.toISOString(),updatedAt:o.updatedAt.toISOString()})}catch(t){return console.error("Failed to create integration:",t),y.json({error:"Failed to create integration",details:t instanceof Error?t.message:"Unknown error"},{status:500})}}async function Ke(r,t){try{let e=await h(r);if(!e)return y.json({error:"Unauthorized"},{status:401});let o=await ne(t,e.id);return o?y.json({id:o.id,name:o.name,type:o.type,config:o.config,createdAt:o.createdAt.toISOString(),updatedAt:o.updatedAt.toISOString()}):y.json({error:"Integration not found"},{status:404})}catch(e){return console.error("Failed to get integration:",e),y.json({error:"Failed to get integration",details:e instanceof Error?e.message:"Unknown error"},{status:500})}}async function He(r,t){try{let e=await h(r);if(!e)return y.json({error:"Unauthorized"},{status:401});let o=await r.json(),n=await $e(t,e.id,o);return n?y.json({id:n.id,name:n.name,type:n.type,config:n.config,createdAt:n.createdAt.toISOString(),updatedAt:n.updatedAt.toISOString()}):y.json({error:"Integration not found"},{status:404})}catch(e){return console.error("Failed to update integration:",e),y.json({error:"Failed to update integration",details:e instanceof Error?e.message:"Unknown error"},{status:500})}}async function Be(r,t){try{let e=await h(r);return e?await Se(t,e.id)?y.json({success:!0}):y.json({error:"Integration not found"},{status:404}):y.json({error:"Unauthorized"},{status:401})}catch(e){return console.error("Failed to delete integration:",e),y.json({error:"Failed to delete integration",details:e instanceof Error?e.message:"Unknown error"},{status:500})}}async function Ye(r,t){try{let e=await h(r);if(!e)return y.json({error:"Unauthorized"},{status:401});let o=await ne(t,e.id);return o?o.type==="database"?y.json({status:"success",message:"Integration exists"}):y.json({status:"success",message:"Integration exists"}):y.json({error:"Integration not found"},{status:404})}catch(e){return console.error("Failed to test integration:",e),y.json({status:"error",message:e instanceof Error?e.message:"Failed to test connection"},{status:500})}}async function Je(r){try{if(!await h(r))return y.json({error:"Unauthorized"},{status:401});let e=await r.json();return e.type&&e.config?y.json({status:"success",message:"Credentials accepted"}):y.json({error:"Type and config are required"},{status:400})}catch(t){return console.error("Failed to test credentials:",t),y.json({status:"error",message:t instanceof Error?t.message:"Failed to test connection"},{status:500})}}import{eq as Q}from"drizzle-orm";import{NextResponse as D}from"next/server";async function Ve(r){try{let t=await h(r);if(!t)return D.json({error:"Unauthorized"},{status:401});let e=await c.query.users.findFirst({where:Q(V.id,t.id),columns:{id:!0,name:!0,email:!0,image:!0,isAnonymous:!0}});if(!e)return D.json({error:"User not found"},{status:404});let o=await c.query.accounts.findFirst({where:Q(oe.userId,t.id),columns:{providerId:!0}});return D.json({...e,providerId:o?.providerId??null})}catch(t){return console.error("Failed to get user:",t),D.json({error:t instanceof Error?t.message:"Failed to get user"},{status:500})}}async function Xe(r){try{let t=await h(r);if(!t)return D.json({error:"Unauthorized"},{status:401});let e=await c.query.accounts.findFirst({where:Q(oe.userId,t.id),columns:{providerId:!0}});if(e&&["vercel","github","google"].includes(e.providerId))return D.json({error:"Cannot update profile for OAuth users"},{status:403});let n=await r.json(),u={};return n.name!==void 0&&(u.name=n.name),n.email!==void 0&&(u.email=n.email),await c.update(V).set(u).where(Q(V.id,t.id)),D.json({success:!0})}catch(t){return console.error("Failed to update user:",t),D.json({error:t instanceof Error?t.message:"Failed to update user"},{status:500})}}import{and as v,desc as Z,eq as f,inArray as fe}from"drizzle-orm";import{NextResponse as a}from"next/server";import{createHash as zt}from"crypto";import"server-only";var vt={"Database Query":Ie.codeGenerator,"HTTP Request":Re.codeGenerator,Condition:Ee.codeGenerator},Ut=/export\s+(?:async\s+)?function\s+\w+\s*\([^)]*\)\s*(?::\s*[^{]+)?\s*\{([\s\S]*)\}/;function Ct(r){let t=vt[r];if(!t){let e=me(r);e?.codegenTemplate&&(t=e.codegenTemplate)}if(!t)return null;try{let e=t.match(Ut);return e?e[1].trim():null}catch{return null}}function Ot(r,t){let e=r.substring(1),o=e.indexOf(":");if(o===-1)return t;let n=e.substring(0,o),u=e.substring(o+1),l=u.indexOf("."),d=l!==-1?u.substring(l+1):"",g=n.replace(/[^a-zA-Z0-9]/g,"_");if(!d)return`\${outputs?.['${g}']?.data}`;let I=d.split(".").map(R=>{let b=R.match(re);return b?`?.${b[1]}?.[${b[2]}]`:`?.${R}`}).join("");return`\${outputs?.['${g}']?.data${I}}`}function Mt(r){let t=r.substring(1);if(!(t.includes(".")||t.includes("[")))return`\${outputs?.['${t.replace(/[^a-zA-Z0-9]/g,"_")}']?.data}`;let e=t.split("."),n=e[0].replace(/[^a-zA-Z0-9]/g,"_"),u=e.slice(1).join(".");if(!u)return`\${outputs?.['${n}']?.data}`;let l=u.split(".").map(d=>{let g=d.match(re);return g?`?.${g[1]}?.[${g[2]}]`:`?.${d}`}).join("");return`\${outputs?.['${n}']?.data${l}}`}function m(r){if(!r||typeof r!="string")return r;let t=/\{\{([^}]+)\}\}/g;return r.replace(t,(e,o)=>{let n=o.trim();return n.startsWith("@")?Ot(n,e):n.startsWith("$")?Mt(n):e})}function Dt(r){let t=he(r),e=r.at(-1);return e&&t.add(e.id),t}function Gt(r){let t=new Map,e=new Map;for(let o of r)if(o.data.type==="action"){let u=(o.data.config||{}).actionType,l=o.data.label||u||"UnnamedStep",d=J(l),g=t.get(d)||0;t.set(d,g+1);let I=g>0?`${d}${g+1}`:d;e.set(o.id,I)}return e}function _t(r,t,e){let o=[];for(let n of r)if(n.data.type==="action"){let u=t.get(n.id);o.push(e(n,u))}return o}function Qe(r,t,e){let o=new Set,n=[],u=new Map(t.map(s=>[s.id,s])),l=ke(e),d=ye(t,e),g=Dt(t);o.add("import { sleep, FatalError } from 'workflow';");function I(s){return o.add("import { Resend } from 'resend';"),["fromEmail: process.env.RESEND_FROM_EMAIL || 'noreply@example.com'",`emailTo: \`${m(s.emailTo||"user@example.com")}\``,`emailSubject: \`${m(s.emailSubject||"Notification")}\``,`emailBody: \`${m(s.emailBody||"No content")}\``,"apiKey: process.env.RESEND_API_KEY!"]}function R(s){return o.add("import { WebClient } from '@slack/web-api';"),[`slackChannel: \`${m(s.slackChannel||"#general")}\``,`slackMessage: \`${m(s.slackMessage||"No message")}\``,"apiKey: process.env.SLACK_API_KEY!"]}function b(s){o.add("import { LinearClient } from '@linear/sdk';");let i=[`ticketTitle: \`${m(s.ticketTitle||"New Issue")}\``,`ticketDescription: \`${m(s.ticketDescription||"")}\``,"apiKey: process.env.LINEAR_API_KEY!"];return s.teamId&&i.push(`teamId: "${s.teamId}"`),i}function z(s){o.add("import { generateText } from 'ai';");let i=s.aiModel||"meta/llama-4-scout",k;if(i.includes("/"))k=i;else{let w;i.startsWith("gpt-")||i.startsWith("o1-")?w="openai":i.startsWith("claude-")?w="anthropic":w="openai",k=`${w}/${i}`}return[`model: "${k}"`,`prompt: \`${m(s.aiPrompt||"")}\``,"apiKey: process.env.OPENAI_API_KEY!"]}function L(s){return o.add("import { experimental_generateImage as generateImage } from 'ai';"),[`model: "${s.imageModel||"google/imagen-4.0-generate"}"`,`prompt: \`${m(s.imagePrompt||"")}\``,'size: "1024x1024"',"providerOptions: { openai: { apiKey: process.env.AI_GATEWAY_API_KEY! } }"]}function q(s){return[`query: \`${m(s.dbQuery||"SELECT 1")}\``]}function E(s){let i=[`url: "${s.endpoint||"https://api.example.com/endpoint"}"`,`method: "${s.httpMethod||"POST"}"`,`headers: ${s.httpHeaders||"{}"}`];return s.httpBody&&i.push(`body: ${s.httpBody}`),i}function U(s){return[`condition: ${m(s.condition||"true")}`]}function C(s,i){o.add("import FirecrawlApp from '@mendable/firecrawl-js';");let k=s==="Search"?"search":"scrape",w=i.formats?JSON.stringify(i.formats):"['markdown']",j=[`mode: '${k}'`,"apiKey: process.env.FIRECRAWL_API_KEY!",`formats: ${w}`];return i.url&&j.push(`url: \`${m(i.url||"")}\``),i.query&&j.push(`query: \`${m(i.query||"")}\``),i.limit&&j.push(`limit: ${i.limit}`),j}function pe(s){o.add("import { createClient } from 'v0-sdk';");let i=[`message: \`${m(s.message||"")}\``,"apiKey: process.env.V0_API_KEY!"];return s.system&&i.push(`system: \`${m(s.system||"")}\``),i}function te(s){return o.add("import { createClient } from 'v0-sdk';"),[`chatId: \`${m(s.chatId||"")}\``,`message: \`${m(s.message||"")}\``,"apiKey: process.env.V0_API_KEY!"]}function mt(s){return[`userId: \`${m(s.userId||"")}\``]}function ht(s){let i=[`emailAddress: \`${m(s.emailAddress||"")}\``];return s.password&&i.push(`password: \`${m(s.password)}\``),s.firstName&&i.push(`firstName: \`${m(s.firstName)}\``),s.lastName&&i.push(`lastName: \`${m(s.lastName)}\``),s.publicMetadata&&i.push(`publicMetadata: \`${m(s.publicMetadata)}\``),s.privateMetadata&&i.push(`privateMetadata: \`${m(s.privateMetadata)}\``),i}function kt(s){let i=[`userId: \`${m(s.userId||"")}\``];return s.firstName&&i.push(`firstName: \`${m(s.firstName)}\``),s.lastName&&i.push(`lastName: \`${m(s.lastName)}\``),s.publicMetadata&&i.push(`publicMetadata: \`${m(s.publicMetadata)}\``),s.privateMetadata&&i.push(`privateMetadata: \`${m(s.privateMetadata)}\``),i}function yt(s){return[`userId: \`${m(s.userId||"")}\``]}function jt(s,i){let w={"Send Email":()=>I(i),"Send Slack Message":()=>R(i),"Create Ticket":()=>b(i),"Generate Text":()=>z(i),"Generate Image":()=>L(i),"Database Query":()=>q(i),"HTTP Request":()=>E(i),Condition:()=>U(i),Scrape:()=>C(s,i),Search:()=>C(s,i),"Create Chat":()=>pe(i),"Send Message":()=>te(i),"Get User":()=>mt(i),"Create User":()=>ht(i),"Update User":()=>kt(i),"Delete User":()=>yt(i)}[s];return w?w():[]}function xt(s,i){let k=s.data.config||{},w=k.actionType,j=s.data.label||w||"UnnamedStep",F=i||J(j),P=Ct(w),W;return P&&s.data.type==="action"?W=` // Call step function with constructed input
|
|
2
2
|
const stepInput = {
|
|
3
3
|
${jt(w,k).join(`,
|
|
4
4
|
`)}
|
|
5
5
|
};
|
|
6
6
|
|
|
7
7
|
// Execute step implementation
|
|
8
|
-
${P}`:
|
|
8
|
+
${P}`:W=" return { success: true };",`async function ${F}(input: Record<string, unknown> & { outputs?: Record<string, { label: string; data: unknown }> }) {
|
|
9
9
|
"use step";
|
|
10
10
|
|
|
11
|
-
${
|
|
12
|
-
}`}let
|
|
11
|
+
${W}
|
|
12
|
+
}`}let we=Gt(t);n.push(..._t(t,we,xt));function Et(s,i,k){if(!g.has(s))return[`${k}// Trigger (outputs not used)`];let w=`result_${G(s)}`;return[`${k}// Triggered`,`${k}let ${w} = input;`,`${k}outputs['${G(s)}'] = { label: '${i}', data: ${w} };`]}function It(s,i,k,w){let j=i.actionType,F=k||j||"UnnamedStep",P=we.get(s)||J(F),W=[`${w}// ${F}`];if(g.has(s)){let ge=`result_${G(s)}`;W.push(`${w}const ${ge} = await ${P}({ ...input, outputs });`),W.push(`${w}outputs['${G(s)}'] = { label: '${F}', data: ${ge} };`)}else W.push(`${w}await ${P}({ ...input, outputs });`);return W}function Rt(s,i,k,w){let j=i.data.config?.condition||"true",F=m(j),P=l.get(s)||[],W=`conditionValue_${G(s)}`,T=[];return P.length>0&&(T.push(`${k}// ${i.data.label}`),T.push(`${k}const ${W} = \`${je(F)}\`;`),T.push(`${k}if (${W}) {`),P[0]&&T.push(...Y(P[0],`${k} `,w)),P[1]&&(T.push(`${k}} else {`),T.push(...Y(P[1],`${k} `,w))),T.push(`${k}}`)),T}function Y(s,i=" ",k=new Set){if(k.has(s))return[];k.add(s);let w=u.get(s);if(!w)return[];let j=[];switch(w.data.type){case"trigger":j.push(...Et(s,w.data.label,i));break;case"action":{if(w.data.config?.actionType==="Condition")return j.push(...Rt(s,w,i,k)),j;j.push(...It(s,w.data.config||{},w.data.label,i));break}default:j.push(`${i}// Unknown node type: ${w.data.type}`);break}let F=l.get(s)||[];for(let P of F)j.push(...Y(P,i,k));return j}let O=[];if(d.length===0)O.push(' return { error: "No trigger nodes" };');else{O.push(" // Track outputs from each node for template processing"),O.push(" const outputs: Record<string, { label: string; data: unknown }> = {};"),O.push("");for(let i of d)O.push(...Y(i.id));let s=t.at(-1);if(s){let i=`result_${G(s.id)}`;O.push(""),O.push(` return ${i};`)}}let At=`export async function ${xe(r)}() {
|
|
13
13
|
"use workflow";
|
|
14
14
|
|
|
15
15
|
// Input from workflow trigger - replace with your trigger data
|
|
@@ -25,13 +25,13 @@ ${n.join(`
|
|
|
25
25
|
`)}
|
|
26
26
|
|
|
27
27
|
${At}
|
|
28
|
-
`}async function Ze(r,t){try{let e=await h(r);if(!e)return a.json({error:"Unauthorized"},{status:401});let o=await c.query.workflows.findFirst({where:p(f.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(R).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:p(f.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:ve(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(f).where(p(f.userId,t.id)).orderBy(Z(f.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:p(f.userId,t.id)})).length+1}`);let l=_(),[d]=await c.insert(f).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(f).where(v(p(f.name,le),p(f.userId,t.id))).orderBy(Z(f.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(f).where(v(p(f.name,le),p(f.userId,t.id))).limit(1);if(u){let[g]=await c.update(f).set({nodes:o,edges:n,updatedAt:new Date}).where(p(f.id,u.id)).returning();return a.json({id:g.id,nodes:g.nodes,edges:g.edges})}let l=_(),[d]=await c.insert(f).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:p(R.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(T.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:p(R.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(T.executionId,t),orderBy:[Z(T.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(p(f.id,t),p(f.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=Fe(n),[l]=await c.update(f).set(u).where(p(f.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);return e?await c.query.workflows.findFirst({where:v(p(f.id,t),p(f.userId,e.id))})?(await c.delete(f).where(p(f.id,t)),a.json({success:!0})):a.json({error:"Workflow not found"},{status:404}):a.json({error:"Unauthorized"},{status:401})}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:p(f.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(x=>{let U={...x,id:_()};if(U.data){let C={...U.data};if(C.config){let{integrationId:fe,...te}=C.config;C.config=te}C.status="idle",U.data=C}return U}),d=new Map(u.map((x,U)=>[x.id,l[U].id])),g=o.edges.map(x=>({...x,id:_(),source:d.get(x.source)||x.source,target:d.get(x.target)||x.target})),E=await c.query.workflows.findMany({where:p(f.userId,e.id)}),I=`${o.name} (Copy)`,b=I,z=new Set(E.map(x=>x.name));if(z.has(b)){let x=2;for(;z.has(`${I} ${x}`);)x++;b=`${I} ${x}`}let L=_(),[q]=await c.insert(f).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(p(f.id,t),p(f.userId,e.id))}))return a.json({error:"Workflow not found"},{status:404});let n=await c.query.workflowExecutions.findMany({where:p(R.workflowId,t),orderBy:[Z(R.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:p(R.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(R).set({status:"cancelled",completedAt:new Date,duration:String(Date.now()-new Date(o.startedAt).getTime())}).where(p(R.id,t));let n=await c.query.workflowExecutionLogs.findMany({where:v(p(T.executionId,t),Qe(T.status,["pending","running"]))});for(let u of n)await c.update(T).set({status:"error",error:"Cancelled",completedAt:new Date}).where(p(T.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(p(f.id,t),p(f.userId,e.id))}))return a.json({error:"Workflow not found"},{status:404});let u=(await c.query.workflowExecutions.findMany({where:p(R.workflowId,t),columns:{id:!0}})).map(l=>l.id);return u.length>0&&(await c.delete(T).where(Qe(T.executionId,u)),await c.delete(R).where(p(R.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:p(f.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=zt("sha256").update(n).digest("hex"),l=await c.query.apiKeys.findFirst({where:p(A.keyHash,u)});if(!l||l.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,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:W});if(!(await K(e.nodes,e.userId)).valid)return a.json({error:"Workflow contains invalid integration references"},{status:403,headers:W});let E=await r.json().catch(()=>({})),[I]=await c.insert(R).values({workflowId:t,userId:e.userId,status:"running",input:E}).returning();return H(I.id,t,e.nodes,e.edges,E),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 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(p(f.id,t),p(f.userId,e.user.id))});if(!o)return a.json({error:"Workflow not found"},{status:404});let n=Xe(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(p(f.id,t),p(f.userId,e.user.id))});if(!o)return a.json({error:"Workflow not found"},{status:404});let n=await se(ge),u=await se(me),l={};for(let[b,z]of Object.entries(u)){let L=z.match(he);L&&(l[`lib/steps/${b}`]=L[1])}let d=Ue({name:o.name,nodes:o.nodes,edges:o.edges}),g={...n,...l,...d},E=JSON.parse(g["package.json"]);E.dependencies={...E.dependencies,workflow:"4.0.1-beta.7",...Ce(o.nodes)},g["package.json"]=JSON.stringify(E,null,2),g["next.config.ts"]=`import { withWorkflow } from 'workflow/next';
|
|
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';
|
|
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 R=JSON.parse(g["tsconfig.json"]);return R.compilerOptions.plugins=[{name:"next"},{name:"workflow"}],g["tsconfig.json"]=JSON.stringify(R,null,2),g["README.md"]=`# ${o.name}
|
|
35
35
|
|
|
36
36
|
This is a Next.js workflow project generated from Workflow Builder.
|
|
37
37
|
|
|
@@ -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"]=
|
|
78
|
+
`,g[".env.example"]=Me(),a.json({success:!0,files:g})}catch(e){return console.error("Failed to prepare workflow download:",e),a.json({success:!1,error:e instanceof Error?e.message:"Failed to prepare workflow download"},{status:500})}}import"virtual:workflow-builder-plugins";async function B(r){let t=Te(r),e=r.method.toUpperCase();if(t.length===0)return ee.json({error:"Not found"},{status:404});let[o,n,u,l]=t;if(o===".well-known")return n==="oauth-authorization-server"?de(r):n==="oauth-protected-resource"?ce(r):ue(r,["auth",...t]);if(o==="auth")return ue(r,t);if(o==="mcp"){if(process.env.NWB_MCP_ENABLED!=="true")return ee.json({error:"MCP server is not enabled"},{status:404});let{handleMcpRequest:d}=await import("../../handler-67JKCHM5.js");return d(r)}if(o==="workflows"){if(n===void 0&&e==="GET")return tt(r);if(n==="create"&&e==="POST")return rt(r);if(n==="current"){if(e==="GET")return ot(r);if(e==="POST")return nt(r)}if(n==="executions"&&u){let d=u;if(l==="status"&&e==="GET")return st(r,d);if(l==="logs"&&e==="GET")return at(r,d);if(l==="cancel"&&e==="POST")return lt(r,d)}if(n&&n!=="create"&&n!=="current"&&n!=="executions"){let d=n;if(u===void 0){if(e==="GET")return et(r,d);if(e==="PATCH")return it(r,d);if(e==="DELETE")return ut(r,d)}if(u==="code"&&e==="GET")return wt(r,d);if(u==="download"&&e==="GET")return gt(r,d);if(u==="duplicate"&&e==="POST")return dt(r,d);if(u==="executions"){if(e==="GET")return ct(r,d);if(e==="DELETE")return ft(r,d)}if(u==="webhook"&&e==="POST")return pt(r,d)}}if(o==="workflow"&&n){if(u==="execute"&&e==="POST")return Ze(r,n);if(u==="cron"&&e==="GET")return ze(r,n)}if(o==="integrations"){if(n===void 0){if(e==="GET")return Le(r);if(e==="POST")return qe(r)}if(n==="test"&&u===void 0&&e==="POST")return Je(r);if(n&&n!=="test"){let d=n;if(u===void 0){if(e==="GET")return Ke(r,d);if(e==="PUT")return He(r,d);if(e==="DELETE")return Be(r,d)}if(u==="test"&&e==="POST")return Ye(r,d)}}if(o==="user"){if(e==="GET")return Ve(r);if(e==="PATCH")return Xe(r)}if(o==="api-keys"){if(n===void 0){if(e==="GET")return De(r);if(e==="POST")return Ge(r)}if(n&&u===void 0&&e==="DELETE")return _e(r,n)}return ee.json({error:"Not found"},{status:404})}async function Zr(r){return B(r)}async function eo(r){return B(r)}async function to(r){return B(r)}async function ro(r){return B(r)}async function oo(r){return B(r)}async function no(r){return ee.json({},{headers:$})}export{oo as DELETE,Zr as GET,no as OPTIONS,ro as PATCH,eo as POST,to as PUT,de as oAuthDiscoveryHandler,ce as oAuthResourceHandler};
|
package/dist/server/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as q}from"../chunk-R5GS6TJS.js";import{a}from"../chunk-
|
|
1
|
+
import{a as q}from"../chunk-R5GS6TJS.js";import{a as b}from"../chunk-CYVALTSI.js";import{b as t}from"../chunk-IEOZJAW2.js";import{b as a}from"../chunk-6UXAINJQ.js";import"../chunk-BNX2SV7E.js";import{a as p}from"../chunk-PRVESNIO.js";import{a as n,b as o}from"../chunk-KFTXS23Q.js";import"../chunk-QRG4O4PE.js";import{a as r}from"../chunk-7WFHHPX4.js";import{a as c,b as d,c as e,d as f,e as g,j as h,k as i,l as j,m as k,n as l,o as m,q as s}from"../chunk-5J6TNMJG.js";export{f as accounts,k as apiKeys,t as auth,m as db,o as decrypt,b as discoverPlugins,n as encrypt,p as fetchCredentials,c as generateId,q as generateWorkflowMetadata,r as getErrorMessage,a as getErrorMessageAsync,h as integrations,e as sessions,d as users,g as verifications,s as withStepLogging,j as workflowExecutionLogs,i as workflowExecutions,l as workflowExecutionsRelations};
|
package/dist/styles.css
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import"./chunk-R5GS6TJS.js";import"./chunk-
|
|
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 s(t){let u=[];for(let e=0;e<4;e++){let o=t[`routeName${e}`],n=t[`routeCondition${e}`],r=t[`routeCaseValue${e}`];u.push({name:o||`Route ${e+1}`,condition:n,caseValue:r})}return u}function a(t){let u=t.mode||"rules",e=s(t);if(u==="rules"){for(let o=0;o<e.length;o++)if(e[o].condition===!0)return{matchedRouteIndex:o,matchedRouteName:e[o].name,isDefault:!1}}else{let o=String(t.switchValue??"");for(let n=0;n<e.length;n++)if(e[n].caseValue!==void 0&&String(e[n].caseValue)===o)return{matchedRouteIndex:n,matchedRouteName:e[n].name,isDefault:!1}}return{matchedRouteIndex:-1,matchedRouteName:"Default",isDefault:!0}}async function c(t){"use step";return i(t,()=>Promise.resolve(a(t)))}c.maxRetries=0;export{c as switchStep};
|