next-workflow-builder 0.7.5 → 0.7.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,17 +1,17 @@
1
- "use client";import{a as Uo,b as Ko,c as qo}from"../chunk-NI6U7PHC.js";import{i as mr}from"../chunk-VUDOAZ3W.js";import{a as Zs,b as pr}from"../chunk-3YVRTDK2.js";import{a as x}from"../chunk-6UXAINJQ.js";import{d as Ks,h as Dt,i as qs,k as js,l as Js,m as fe,n as eo,o as Ys,p as Xs,v as Qs,w as Ca,y as _o}from"../chunk-QRG4O4PE.js";import{AuthView as xf}from"@daveyplate/better-auth-ui";import{useParams as Nf}from"next/navigation";import{useAtom as $t,useAtomValue as sf,useSetAtom as At}from"jotai";import{ChevronLeft as lf,ChevronRight as df}from"lucide-react";import cf from"next/link";import{useSearchParams as uf}from"next/navigation";import{useCallback as go,useEffect as St,useRef as Lo,useState as ls}from"react";import{toast as ds}from"sonner";var Ta=class extends Error{status;constructor(t,o){super(o),this.status=t,this.name="ApiError"}};async function ge(e,t){let o=await fetch(e,{...t,headers:{"Content-Type":"application/json",...t?.headers}});if(!o.ok){let n=await o.json().catch(()=>({error:"Unknown error"}));throw new Ta(o.status,n.error||"Request failed")}return o.json()}function Mc(e,t){e?.name&&(t.currentData.name=e.name)}function Wc(e,t){e?.description&&(t.currentData.description=e.description)}function Fc(e,t){e?.node&&(t.currentData.nodes=[...t.currentData.nodes,e.node])}function zc(e,t){e?.edge&&(t.currentData.edges=[...t.currentData.edges,e.edge])}function Bc(e,t){e?.nodeId&&(t.currentData.nodes=t.currentData.nodes.filter(o=>o.id!==e.nodeId),t.currentData.edges=t.currentData.edges.filter(o=>o.source!==e.nodeId&&o.target!==e.nodeId))}function Vc(e,t){e?.edgeId&&(t.currentData.edges=t.currentData.edges.filter(o=>o.id!==e.edgeId))}function Gc(e,t){e?.nodeId&&e.updates&&(t.currentData.nodes=t.currentData.nodes.map(o=>o.id===e.nodeId?{...o,...e.updates?.position?{position:e.updates.position}:{},...e.updates?.data?{data:{...o.data,...e.updates.data}}:{}}:o))}var Hc={setName:Mc,setDescription:Wc,addNode:Fc,addEdge:zc,removeNode:Bc,removeEdge:Vc,updateNode:Gc};function $c(e,t){if(!e?.op)return;let o=Hc[e.op];o&&o(e,t)}function _c(e,t,o){if(e.trim())try{let n=JSON.parse(e);if(n.type==="operation"&&n.operation)$c(n.operation,o),t({...o.currentData});else if(n.type==="error")throw console.error("[API Client] Error:",n.error),new Error(n.error)}catch(n){console.error("[API Client] Failed to parse JSONL line:",n)}}function Uc(e,t,o,n){n.buffer+=t.decode(e,{stream:!0});let r=n.buffer.split(`
2
- `);n.buffer=r.pop()||"";for(let s of r)_c(s,o,n)}var Kc={generate:(e,t)=>ge("/api/ai/generate",{method:"POST",body:JSON.stringify({prompt:e,existingWorkflow:t})}),generateStream:async(e,t,o)=>{let n=await fetch("/api/ai/generate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({prompt:e,existingWorkflow:o})});if(!n.ok)throw new Error(`HTTP error! status: ${n.status}`);if(!n.body)throw new Error("No response body");let r=n.body.getReader(),s=new TextDecoder,a={buffer:"",currentData:o?{nodes:o.nodes||[],edges:o.edges||[],name:o.name}:{nodes:[],edges:[]}};try{for(;;){let{done:d,value:i}=await r.read();if(d)break;Uc(i,s,t,a)}return a.currentData}finally{r.releaseLock()}}},qc={getAll:e=>ge(`/api/integrations${e?`?type=${e}`:""}`),get:e=>ge(`/api/integrations/${e}`),create:e=>ge("/api/integrations",{method:"POST",body:JSON.stringify(e)}),update:(e,t)=>ge(`/api/integrations/${e}`,{method:"PUT",body:JSON.stringify(t)}),delete:e=>ge(`/api/integrations/${e}`,{method:"DELETE"}),testConnection:e=>ge(`/api/integrations/${e}/test`,{method:"POST"}),testCredentials:e=>ge("/api/integrations/test",{method:"POST",body:JSON.stringify(e)})},jc={get:()=>ge("/api/user"),update:e=>ge("/api/user",{method:"PATCH",body:JSON.stringify(e)})},fr={getAll:()=>ge("/api/workflows"),getById:e=>ge(`/api/workflows/${e}`),create:e=>ge("/api/workflows/create",{method:"POST",body:JSON.stringify(e)}),update:(e,t)=>ge(`/api/workflows/${e}`,{method:"PATCH",body:JSON.stringify(t)}),delete:e=>ge(`/api/workflows/${e}`,{method:"DELETE"}),duplicate:e=>ge(`/api/workflows/${e}/duplicate`,{method:"POST"}),getCurrent:()=>ge("/api/workflows/current"),saveCurrent:(e,t)=>ge("/api/workflows/current",{method:"POST",body:JSON.stringify({nodes:e,edges:t})}),execute:(e,t={})=>ge(`/api/workflow/${e}/execute`,{method:"POST",body:JSON.stringify({input:t})}),triggerWebhook:(e,t={})=>ge(`/api/workflows/${e}/webhook`,{method:"POST",body:JSON.stringify(t)}),getCode:e=>ge(`/api/workflows/${e}/code`),getExecutions:e=>ge(`/api/workflows/${e}/executions`),deleteExecutions:e=>ge(`/api/workflows/${e}/executions`,{method:"DELETE"}),getExecutionLogs:e=>ge(`/api/workflows/executions/${e}/logs`),getExecutionStatus:e=>ge(`/api/workflows/executions/${e}/status`),cancelExecution:e=>ge(`/api/workflows/executions/${e}/cancel`,{method:"POST"}),download:e=>ge(`/api/workflows/${e}/download`),autoSaveCurrent:(()=>{let e=null,t=2e3;return(o,n)=>{e&&clearTimeout(e),e=setTimeout(()=>{fr.saveCurrent(o,n).catch(r=>{console.error("Auto-save failed:",r)})},t)}})(),autoSaveWorkflow:(()=>{let e=null,t=2e3;return(o,n,r=!0)=>{if(!r)return fr.update(o,n);e&&clearTimeout(e),e=setTimeout(()=>{fr.update(o,n).catch(s=>{console.error("Auto-save failed:",s)})},t)}})()},Jc={getStatus:()=>ge("/api/ai-gateway/status"),getTeams:()=>ge("/api/ai-gateway/teams"),consent:(e,t)=>ge("/api/ai-gateway/consent",{method:"POST",body:JSON.stringify({teamId:e,teamName:t})}),revokeConsent:()=>ge("/api/ai-gateway/consent",{method:"DELETE"})},q={ai:Kc,aiGateway:Jc,integration:qc,user:jc,workflow:fr};import{atom as zn}from"jotai";var ft=zn([]),gr=zn(!1),sh=zn(null),Rt=zn(0),ei=zn(e=>{let t=e(ft);return new Set(t.map(o=>o.id))});import{applyEdgeChanges as Yc,applyNodeChanges as Xc}from"@xyflow/react";import{atom as le}from"jotai";var re=le([]),ue=le([]),ke=le(null),_e=le(null),ni=le(!1),ti=le(!1),Nt=le(!1),Ue=le(null),gt=le(""),yr=le("private"),oo=le(!0),jo=le({snapToGrid:!0,edgeStyle:"smoothstep"}),Bt=le("properties"),vr=le(!1),no=le(null),hr=le(null),br=le(!1),wr=le(!1),ri=le(!1),xr=le(!1),Nr=le(new Set),to=le(null),kr=le(!1),Jo=le({}),Aa=null,Qc=1e3,Ot=le(null,async(e,t,o)=>{let n=e(Ue),r=e(re),s=e(ue);if(!n)return;let a=async()=>{try{await q.workflow.update(n,{nodes:r,edges:s}),t(nt,!1)}catch(d){console.error("Autosave failed:",d)}};o?.immediate?await a():(Aa&&clearTimeout(Aa),Aa=setTimeout(a,Qc))}),ai=le(null,(e,t,o)=>{let n=e(re),r=o.filter(l=>l.type==="remove"?n.find(u=>u.id===l.id)?.data.type!=="trigger":!0),s=Xc(r,n);t(re,s);let a=s.find(l=>l.selected);if(a){t(ke,a.id),t(_e,null);let l=e(to);l&&l!==a.id&&t(to,null)}else if(e(ke)){let l=e(ke);s.find(u=>u.id===l)||t(ke,null),t(to,null)}if(r.some(l=>l.type==="remove")){t(Ot,{immediate:!0});return}r.some(l=>l.type==="position"&&l.dragging===!1)&&t(Ot)}),si=le(null,(e,t,o)=>{let n=e(ue),r=Yc(o,n);t(ue,r);let s=r.find(d=>d.selected);if(s)t(_e,s.id),t(ke,null);else if(e(_e)){let d=e(_e);r.find(l=>l.id===d)||t(_e,null)}o.some(d=>d.type==="remove")&&t(Ot,{immediate:!0})}),Yo=le(null,(e,t,o)=>{let n=e(re),r=e(ue),s=e(ot);t(ot,[...s,{nodes:n,edges:r}]),t(zt,[]);let a=n.map(l=>({...l,selected:!1})),d={...o,selected:!0},i=[...a,d];t(re,i),t(ke,o.id),o.data.type==="action"&&!o.data.config?.actionType&&t(to,o.id),t(nt,!0),t(Ot,{immediate:!0})}),ro=le(null,(e,t,{id:o,data:n})=>{let r=e(re),a=r.find(c=>c.id===o)?.data.label,d=n.label,i=d!==void 0&&a!==d,l=r.map(c=>{if(c.id===o)return{...c,data:{...c.data,...n}};if(i&&a){let u=ii(c.data.config||{},o,a,d);if(u!==c.data.config)return{...c,data:{...c.data,config:u}}}return c});t(re,l),n.status||(t(nt,!0),t(Ot))});function ii(e,t,o,n){let r=!1,s={};for(let[a,d]of Object.entries(e))if(typeof d=="string"){let i=new RegExp(`\\{\\{@${oi(t)}:${oi(o)}(\\.[^}]+)?\\}\\}`,"g"),l=d.replace(i,(c,u)=>(r=!0,`{{@${t}:${n}${u||""}}}`));s[a]=l}else if(typeof d=="object"&&d!==null&&!Array.isArray(d)){let i=ii(d,t,o,n);i!==d&&(r=!0),s[a]=i}else s[a]=d;return r?s:e}function oi(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var ao=le(null,(e,t,o)=>{let n=e(re);if(n.find(l=>l.id===o)?.data.type==="trigger")return;let s=e(ue),a=e(ot);t(ot,[...a,{nodes:n,edges:s}]),t(zt,[]);let d=n.filter(l=>l.id!==o),i=s.filter(l=>l.source!==o&&l.target!==o);t(re,d),t(ue,i),e(ke)===o&&t(ke,null),t(nt,!0),t(Ot,{immediate:!0})}),so=le(null,(e,t,o)=>{let n=e(re),r=e(ue),s=e(ot);t(ot,[...s,{nodes:n,edges:r}]),t(zt,[]);let a=r.filter(d=>d.id!==o);t(ue,a),e(_e)===o&&t(_e,null),t(nt,!0),t(Ot,{immediate:!0})}),li=le(null,(e,t)=>{let o=e(re),n=e(ue),r=e(ot);t(ot,[...r,{nodes:o,edges:n}]),t(zt,[]);let s=o.filter(i=>i.selected&&i.data.type!=="trigger").map(i=>i.id),a=o.filter(i=>i.data.type==="trigger"?!0:!i.selected),d=n.filter(i=>!(i.selected||s.includes(i.source)||s.includes(i.target)));t(re,a),t(ue,d),t(ke,null),t(_e,null),t(nt,!0),t(Ot,{immediate:!0})}),Xo=le(null,(e,t)=>{let o=e(re),n=e(ue),r=e(ot);t(ot,[...r,{nodes:o,edges:n}]),t(zt,[]);let s=o.filter(a=>a.data.type==="trigger");t(re,s),t(ue,[]),t(ke,null),t(_e,null),t(nt,!0),t(Ot,{immediate:!0})}),uh=le(null,async(e,t)=>{try{t(ti,!0);let o=await q.workflow.getCurrent();t(re,o.nodes),t(ue,o.edges),o.id&&t(Ue,o.id)}catch(o){console.error("Failed to load workflow:",o)}finally{t(ti,!1)}}),mh=le(null,async(e,t,{name:o,description:n})=>{let r=e(re),s=e(ue);try{return await q.workflow.create({name:o,description:n,nodes:r,edges:s})}catch(a){throw console.error("Failed to save workflow:",a),a}}),Cr=le(!1),nt=le(!1),di=le(!1),ot=le([]),zt=le([]),ci=le(null,(e,t)=>{let o=e(ot);if(o.length===0)return;let n=e(re),r=e(ue),s=e(zt);t(zt,[...s,{nodes:n,edges:r}]);let a=[...o],d=a.pop();d&&(t(ot,a),t(re,d.nodes),t(ue,d.edges),t(nt,!0))}),ui=le(null,(e,t)=>{let o=e(zt);if(o.length===0)return;let n=e(re),r=e(ue),s=e(ot);t(ot,[...s,{nodes:n,edges:r}]);let a=[...o],d=a.pop();d&&(t(zt,a),t(re,d.nodes),t(ue,d.edges),t(nt,!0))}),mi=le(e=>e(ot).length>0),pi=le(e=>e(zt).length>0),Tr=le(null,(e,t)=>{let n=e(re).map(r=>({...r,data:{...r.data,status:"idle"}}));t(re,n)});import*as Ar from"react";var Sa=768;function Vt(){let[e,t]=Ar.useState(void 0);return Ar.useEffect(()=>{let o=window.matchMedia(`(max-width: ${Sa-1}px)`),n=()=>{t(window.innerWidth<Sa)};return o.addEventListener("change",n),t(window.innerWidth<Sa),()=>o.removeEventListener("change",n)},[]),!!e}import{Slot as Zc}from"radix-ui";import{cva as eu}from"class-variance-authority";import{jsx as tu}from"react/jsx-runtime";var Sr=eu("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",{variants:{variant:{default:"bg-primary text-primary-foreground hover:bg-primary/90",destructive:"bg-destructive text-white hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",outline:"border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-9 px-4 py-2 has-[>svg]:px-3",sm:"h-8 rounded-md gap-1.5 px-3 has-[>svg]:px-2.5",lg:"h-10 rounded-md px-6 has-[>svg]:px-4",icon:"size-9","icon-sm":"size-8","icon-lg":"size-10"}},defaultVariants:{variant:"default",size:"default"}});function D({className:e,variant:t,size:o,asChild:n=!1,...r}){let s=n?Zc.Slot:"button";return tu(s,{"data-slot":"button",className:x(Sr({variant:t,size:o,className:e})),...r})}var ou={"Database Query":"database"};function nu(e){return fe(e)?.integration||ou[e]}function fi(e,t,o){let n=e.data.config?.actionType;if(!n)return null;let r=nu(n);if(!r)return null;let s=e.data.config?.integrationId;if(s&&o.has(s))return null;let d=t.filter(i=>i.type===r);return d.length===1?{nodeId:e.id,newIntegrationId:d[0].id}:d.length===0&&s?{nodeId:e.id,newIntegrationId:void 0}:null}import{useAtom as po,useAtomValue as as,useSetAtom as Oo}from"jotai";import{Copy as Ml,Eraser as ss,Eye as Qp,EyeOff as Zp,FileCode as Wl,RefreshCw as Fl,Trash2 as oa}from"lucide-react";import{useCallback as ef,useEffect as zl,useMemo as tf,useRef as Bl,useState as Zn}from"react";import{toast as xn}from"sonner";import{AlertTriangleIcon as mu}from"lucide-react";import{Loader2 as ru}from"lucide-react";import{jsx as Qo,jsxs as Pa}from"react/jsx-runtime";function Ia({action:e}){return Pa(D,{disabled:e.disabled||e.loading,onClick:e.onClick,variant:e.variant??"default",children:[e.loading&&Qo(ru,{className:"mr-2 size-4 animate-spin"}),e.label]})}function gi({actions:e,className:t,children:o}){if(o)return Qo("div",{className:x("flex flex-col-reverse gap-2 p-6 pt-4 sm:flex-row sm:justify-end",t),children:o});if(!e||e.length===0)return null;let n=e.filter(i=>i.variant==="ghost"),r=e.filter(i=>i.variant==="outline"||i.variant==="secondary"),s=e.filter(i=>!i.variant||i.variant==="default"||i.variant==="destructive"),a=n.length>0,d=r.length>0||s.length>0;return Pa("div",{className:x("flex flex-col-reverse gap-2 p-6 pt-4 sm:flex-row",a&&d?"sm:justify-between":"sm:justify-end",t),children:[a&&Qo("div",{className:"flex flex-col-reverse gap-2 sm:flex-row",children:n.map(i=>Qo(Ia,{action:i},i.label))}),d&&Pa("div",{className:"flex flex-col-reverse gap-2 sm:flex-row",children:[r.map(i=>Qo(Ia,{action:i},i.label)),s.map(i=>Qo(Ia,{action:i},i.label))]})]})}import{ChevronLeftIcon as lu,XIcon as du}from"lucide-react";import{createContext as vi,useCallback as Zo,useContext as hi,useMemo as au,useRef as su,useState as iu}from"react";import{jsx as yi}from"react/jsx-runtime";var bi=vi(null),wi=vi([]);function Ea(){return`overlay-${Date.now()}-${Math.random().toString(36).slice(2,9)}`}function xi({children:e}){let[t,o]=iu([]),n=su([]);t.length>0&&(n.current=t);let r=Zo((u,f,h)=>{let k=Ea();return o([{id:k,component:u,props:f??{},options:h??{}}]),k},[]),s=Zo((u,f,h)=>{let k=Ea(),b={id:k,component:u,props:f??{},options:h??{}};return o(y=>[...y,b]),k},[]),a=Zo(()=>{o(u=>u.length<=1?(u[0]?.options.onClose?.(),[]):(u[u.length-1]?.options.onClose?.(),u.slice(0,-1)))},[]),d=Zo((u,f,h)=>{let k=Ea(),b={id:k,component:u,props:f??{},options:h??{}};return o(y=>y.length===0?[b]:(y[y.length-1]?.options.onClose?.(),[...y.slice(0,-1),b])),k},[]),i=Zo(()=>{o(u=>{for(let f of u)f.options.onClose?.();return[]})},[]),l=Zo(u=>{o(f=>{let h=f.findIndex(k=>k.id===u);if(h===-1)return f;for(let k=h;k<f.length;k++)f[k].options.onClose?.();return f.slice(0,h)})},[]),c=au(()=>({stack:t,open:r,push:s,pop:a,replace:d,closeAll:i,close:l,hasOverlays:t.length>0,depth:t.length}),[t,r,s,a,d,i,l]);return yi(bi.Provider,{value:c,children:yi(wi.Provider,{value:n.current,children:e})})}function oe(){let e=hi(bi);if(!e)throw new Error("useOverlay must be used within an OverlayProvider");return e}function Ni(e){let{stack:t}=oe(),o=hi(wi),n=t.length>0?t:o,r=n.findIndex(s=>s.id===e);return{index:r,isFirst:r===0,isLast:r===n.length-1,depth:n.length,showBackButton:r>0}}import{jsx as xo,jsxs as ki}from"react/jsx-runtime";function cu({title:e,description:t,showBackButton:o,showCloseButton:n=!0,onBack:r,onClose:s,className:a}){let{pop:d,closeAll:i}=oe(),l=o??!1,c=()=>{r?r():d()},u=()=>{s?s():i()};return ki("div",{className:x("relative flex flex-col gap-1.5 p-6 pb-0",a),children:[ki("div",{className:"flex min-h-8 items-center gap-2",children:[l&&xo(D,{"aria-label":"Go back",className:"ml-[-8px] size-8 shrink-0",onClick:c,size:"icon",variant:"ghost",children:xo(lu,{className:"size-5"})}),e&&xo("h2",{className:"flex-1 font-semibold text-lg leading-none tracking-tight",children:e}),n&&xo(D,{"aria-label":"Close",className:"absolute top-4 right-4 size-8 shrink-0 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",onClick:u,size:"icon",variant:"ghost",children:xo(du,{className:"size-4"})})]}),t&&xo("p",{className:"text-muted-foreground text-sm",children:t})]})}function en({overlayId:e,showBackButton:t,...o}){let{showBackButton:n}=Ni(e);return xo(cu,{...o,showBackButton:t??n})}import{jsx as Da,jsxs as uu}from"react/jsx-runtime";function Re({overlayId:e,title:t,description:o,actions:n,children:r,className:s}){return uu("div",{className:x("flex flex-col",s),children:[(t||o)&&Da(en,{description:o,overlayId:e,title:t}),r&&Da("div",{className:"flex-1 overflow-y-auto p-6",children:r}),Da(gi,{actions:n})]})}import{jsx as Ir,jsxs as pu}from"react/jsx-runtime";function Ie({overlayId:e,title:t="Confirm",message:o,confirmLabel:n="Confirm",cancelLabel:r="Cancel",confirmVariant:s="default",destructive:a=!1,onConfirm:d,onCancel:i}){let{pop:l}=oe();return Ir(Re,{actions:[{label:r,variant:"outline",onClick:()=>{i?.(),l()}},{label:n,variant:a?"destructive":s,onClick:async()=>{await d(),l()}}],overlayId:e,title:t,children:pu("div",{className:"flex gap-4",children:[a&&Ir("div",{className:"flex size-10 shrink-0 items-center justify-center rounded-full bg-destructive/10",children:Ir(mu,{className:"size-5 text-destructive"})}),Ir("p",{className:x("text-muted-foreground text-sm",a&&"pt-2"),children:o})]})})}import{AlertDialog as io}from"radix-ui";import{jsx as Lt,jsxs as yu}from"react/jsx-runtime";function tn({...e}){return Lt(io.Root,{"data-slot":"alert-dialog",...e})}function fu({...e}){return Lt(io.Portal,{"data-slot":"alert-dialog-portal",...e})}function gu({className:e,...t}){return Lt(io.Overlay,{"data-slot":"alert-dialog-overlay",className:x("data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",e),...t})}function on({className:e,...t}){return yu(fu,{children:[Lt(gu,{}),Lt(io.Content,{"data-slot":"alert-dialog-content",className:x("bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 sm:max-w-lg",e),...t})]})}function nn({className:e,...t}){return Lt("div",{"data-slot":"alert-dialog-header",className:x("flex flex-col gap-2 text-center sm:text-left",e),...t})}function rn({className:e,...t}){return Lt("div",{"data-slot":"alert-dialog-footer",className:x("flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",e),...t})}function an({className:e,...t}){return Lt(io.Title,{"data-slot":"alert-dialog-title",className:x("text-lg font-semibold",e),...t})}function sn({className:e,...t}){return Lt(io.Description,{"data-slot":"alert-dialog-description",className:x("text-muted-foreground text-sm",e),...t})}function ln({className:e,...t}){return Lt(io.Action,{className:x(Sr(),e),...t})}function dn({className:e,...t}){return Lt(io.Cancel,{className:x(Sr({variant:"outline"}),e),...t})}import vu from"@monaco-editor/react";import{useTheme as hu}from"next-themes";var Ci={base:"vs-dark",inherit:!0,rules:[{token:"",foreground:"ededed"},{token:"comment",foreground:"a1a1a1",fontStyle:"italic"},{token:"keyword",foreground:"ff4d8d"},{token:"keyword.operator",foreground:"ff4d8d"},{token:"string",foreground:"00ca50"},{token:"string.escape",foreground:"00ca50"},{token:"number",foreground:"ffffff"},{token:"type",foreground:"47a8ff"},{token:"type.identifier",foreground:"47a8ff"},{token:"identifier",foreground:"ededed"},{token:"parameter",foreground:"ededed"},{token:"variable",foreground:"ededed"},{token:"variable.parameter",foreground:"ededed"},{token:"function",foreground:"c472fb"},{token:"identifier.function",foreground:"c472fb"},{token:"member.function",foreground:"c472fb"},{token:"constant.language",foreground:"47a8ff"},{token:"keyword.json",foreground:"47a8ff"},{token:"variable.predefined",foreground:"ededed"},{token:"support.variable",foreground:"ededed"},{token:"support.constant",foreground:"ededed"},{token:"delimiter",foreground:"ededed"},{token:"delimiter.bracket",foreground:"ededed"},{token:"delimiter.parenthesis",foreground:"ededed"},{token:"delimiter.curly",foreground:"ededed"},{token:"delimiter.array",foreground:"ededed"},{token:"punctuation",foreground:"ededed"},{token:"operator",foreground:"ededed"},{token:"string.key.json",foreground:"47a8ff"},{token:"string.value.json",foreground:"00ca50"},{token:"number.json",foreground:"ffffff"},{token:"keyword.json",foreground:"47a8ff"}],colors:{"editor.background":"#000000","editor.foreground":"#ededed","editorLineNumber.foreground":"#444444","editorLineNumber.activeForeground":"#888888","editor.lineHighlightBackground":"#0A0A0A","editor.selectionBackground":"#264F78","editor.inactiveSelectionBackground":"#1A1A1A","editorCursor.foreground":"#FFFFFF","editorWhitespace.foreground":"#333333","editorIndentGuide.background":"#1A1A1A","editorIndentGuide.activeBackground":"#333333","editorBracketMatch.background":"#0A0A0A","editorBracketMatch.border":"#444444"}};import{jsx as bu}from"react/jsx-runtime";function yt(e){let{resolvedTheme:t}=hu();return bu(vu,{...e,onMount:(n,r)=>{r.editor.defineTheme("vercel-dark",Ci),r.editor.setTheme(t==="dark"?"vercel-dark":"light"),e.onMount&&e.onMount(n,r)},theme:t==="dark"?"vercel-dark":"light"})}import{jsx as wu}from"react/jsx-runtime";function ae({className:e,type:t,...o}){return wu("input",{type:t,"data-slot":"input",className:x("file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground bg-transparent border-input h-9 w-full min-w-0 rounded-md border px-3 py-1 text-base shadow-xs transition-[color,box-shadow] outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm","focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]","aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",e),...o})}import{Label as xu}from"radix-ui";import{jsx as Nu}from"react/jsx-runtime";function M({className:e,...t}){return Nu(xu.Root,{"data-slot":"label",className:x("flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",e),...t})}import{Tabs as Pr}from"radix-ui";import{jsx as Er}from"react/jsx-runtime";function Ra({className:e,...t}){return Er(Pr.Root,{"data-slot":"tabs",className:x("flex flex-col gap-2",e),...t})}function Oa({className:e,...t}){return Er(Pr.List,{"data-slot":"tabs-list",className:x("bg-muted text-muted-foreground inline-flex h-10 w-fit items-center justify-center rounded-lg p-[3px]",e),...t})}function No({className:e,...t}){return Er(Pr.Trigger,{"data-slot":"tabs-trigger",className:x("data-[state=active]:bg-background dark:data-[state=active]:text-foreground focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:outline-ring dark:data-[state=active]:border-input dark:data-[state=active]:bg-input/30 text-foreground dark:text-muted-foreground inline-flex h-[calc(100%-1px)] flex-1 items-center justify-center gap-1.5 rounded-sm border border-transparent px-2 py-1 text-sm font-medium whitespace-nowrap transition-[color,box-shadow] focus-visible:ring-[3px] focus-visible:outline-1 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:shadow-sm [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",e),...t})}function ko({className:e,...t}){return Er(Pr.Content,{"data-slot":"tabs-content",className:x("flex-1 outline-none",e),...t})}import{useAtomValue as dl,useSetAtom as _m}from"jotai";import{HelpCircle as Um,Plus as Km,Settings as qm}from"lucide-react";import{useEffect as jm,useMemo as $r,useState as Jm}from"react";import{Select as rt}from"radix-ui";import{CheckIcon as ku,ChevronDownIcon as Ti,ChevronUpIcon as Cu}from"lucide-react";import{jsx as Be,jsxs as La}from"react/jsx-runtime";function ve({...e}){return Be(rt.Root,{"data-slot":"select",...e})}function Ai({...e}){return Be(rt.Group,{"data-slot":"select-group",...e})}function we({...e}){return Be(rt.Value,{"data-slot":"select-value",...e})}function he({className:e,size:t="default",children:o,...n}){return La(rt.Trigger,{"data-slot":"select-trigger","data-size":t,className:x("border-input data-[placeholder]:text-muted-foreground [&_svg:not([class*='text-'])]:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive bg-transparent hover:bg-accent/50 flex w-fit items-center justify-between gap-2 rounded-md border px-3 py-2 text-sm whitespace-nowrap shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 data-[size=default]:h-9 data-[size=sm]:h-8 *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-2 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",e),...n,children:[o,Be(rt.Icon,{asChild:!0,children:Be(Ti,{className:"size-4 opacity-50"})})]})}function be({className:e,children:t,position:o="popper",align:n="center",...r}){return Be(rt.Portal,{children:La(rt.Content,{"data-slot":"select-content",className:x("bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 relative z-50 max-h-(--radix-select-content-available-height) min-w-[8rem] origin-(--radix-select-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border shadow-md",o==="popper"&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",e),position:o,align:n,...r,children:[Be(Tu,{}),Be(rt.Viewport,{className:x("p-1",o==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)] scroll-my-1"),children:t}),Be(Au,{})]})})}function Si({className:e,...t}){return Be(rt.Label,{"data-slot":"select-label",className:x("text-muted-foreground px-2 py-1.5 text-xs",e),...t})}function te({className:e,children:t,...o}){return La(rt.Item,{"data-slot":"select-item",className:x("focus:bg-accent focus:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground relative flex w-full cursor-default items-center gap-2 rounded-sm py-1.5 pr-8 pl-2 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",e),...o,children:[Be("span",{className:"absolute right-2 flex size-3.5 items-center justify-center",children:Be(rt.ItemIndicator,{children:Be(ku,{className:"size-4"})})}),Be(rt.ItemText,{children:t})]})}function Dr({className:e,...t}){return Be(rt.Separator,{"data-slot":"select-separator",className:x("bg-border pointer-events-none -mx-1 my-1 h-px",e),...t})}function Tu({className:e,...t}){return Be(rt.ScrollUpButton,{"data-slot":"select-scroll-up-button",className:x("flex cursor-default items-center justify-center py-1",e),...t,children:Be(Cu,{className:"size-4"})})}function Au({className:e,...t}){return Be(rt.ScrollDownButton,{"data-slot":"select-scroll-down-button",className:x("flex cursor-default items-center justify-center py-1",e),...t,children:Be(Ti,{className:"size-4"})})}import{useAtom as Ei}from"jotai";import{useEffect as Ma,useRef as Wa,useState as cn}from"react";import{useAtom as Ii}from"jotai";import{Check as Su}from"lucide-react";import{useEffect as Rr,useRef as Iu,useState as Pi}from"react";import{createPortal as Pu}from"react-dom";import{Fragment as Ou,jsx as Bn,jsxs as Or}from"react/jsx-runtime";var Eu=e=>{if(e.data.label)return e.data.label;if(e.data.type==="action"){let t=e.data.config?.actionType;if(t){let o=fe(t);if(o?.label)return o.label}return t||"HTTP Request"}return e.data.type==="trigger"?e.data.config?.triggerType||"Manual":"Node"},Vn=(e,t="")=>{let o=[];for(let n of e){let r=t?`${t}.${n.name}`:n.name,s=n.type==="array"?`${n.itemType}[]`:n.type,a=n.description||`${s}`;if(o.push({field:r,description:a}),n.type==="object"&&n.fields&&n.fields.length>0&&o.push(...Vn(n.fields,r)),n.type==="array"&&n.itemType==="object"&&n.fields&&n.fields.length>0){let d=`${r}[0]`;o.push(...Vn(n.fields,d))}}return o},Du=(e,...t)=>e?t.some(o=>e===o||e.endsWith(`/${o.toLowerCase().replace(/\s+/g,"-")}`)):!1,Ru=e=>{let t=e.data.config?.actionType;if(t==="HTTP Request")return[{field:"data",description:"Response data"},{field:"status",description:"HTTP status code"}];if(t==="Database Query"){let o=e.data.config?.dbSchema;if(o)try{let n=JSON.parse(o);if(n.length>0)return Vn(n)}catch{}return[{field:"rows",description:"Query result rows"},{field:"count",description:"Number of rows"}]}if(Du(t,"Generate Text","ai-gateway/generate-text")){let o=e.data.config?.aiFormat,n=e.data.config?.aiSchema;if(o==="object"&&n)try{let r=JSON.parse(n);if(r.length>0)return Vn(r,"object")}catch{}return[{field:"text",description:"Generated text"}]}if(t){let o=fe(t);if(o?.outputFields&&o.outputFields.length>0)return o.outputFields}if(e.data.type==="trigger"){let o=e.data.config?.triggerType,n=e.data.config?.webhookSchema;if(o==="Webhook"&&n)try{let r=JSON.parse(n);if(r.length>0)return Vn(r)}catch{}return[{field:"triggered",description:"Trigger status"},{field:"timestamp",description:"Trigger timestamp"},{field:"input",description:"Input data"}]}return[{field:"data",description:"Output data"}]};function Lr({isOpen:e,position:t,onSelect:o,onClose:n,currentNodeId:r,filter:s=""}){let[a]=Ii(re),[d]=Ii(ue),[i,l]=Pi(0),c=Iu(null),[u,f]=Pi(!1);Rr(()=>(f(!0),()=>f(!1)),[]);let k=(()=>{if(!r)return[];let g=new Set,C=[],I=A=>{if(g.has(A))return;g.add(A);let w=d.filter(m=>m.target===A);for(let m of w)C.push(m.source),I(m.source)};return I(r),a.filter(A=>C.includes(A.id))})(),b=[];for(let g of k){let C=Eu(g),I=Ru(g);b.push({type:"node",nodeId:g.id,nodeName:C,template:`{{@${g.id}:${C}}}`});for(let A of I)b.push({type:"field",nodeId:g.id,nodeName:C,field:A.field,description:A.description,template:`{{@${g.id}:${C}.${A.field}}}`})}let y=s?b.filter(g=>g.nodeName.toLowerCase().includes(s.toLowerCase())||g.field&&g.field.toLowerCase().includes(s.toLowerCase())):b;if(Rr(()=>{l(0)},[s]),Rr(()=>{let g=C=>{if(e)switch(C.key){case"ArrowDown":C.preventDefault(),l(I=>I<y.length-1?I+1:I);break;case"ArrowUp":C.preventDefault(),l(I=>I>0?I-1:I);break;case"Enter":C.preventDefault(),y[i]&&o(y[i].template);break;case"Escape":C.preventDefault(),n();break}};return window.addEventListener("keydown",g),()=>window.removeEventListener("keydown",g)},[e,y,i,o,n]),Rr(()=>{if(c.current){let g=c.current.children[i];g&&g.scrollIntoView({block:"nearest"})}},[i]),!e||y.length===0||!u)return null;let p={top:Math.min(t.top,window.innerHeight-300),left:Math.min(t.left,window.innerWidth-320)},v=Bn("div",{className:"fixed z-[9999] w-80 rounded-lg border bg-popover p-1 text-popover-foreground shadow-md",ref:c,style:{top:`${p.top}px`,left:`${p.left}px`},children:Bn("div",{className:"max-h-60 overflow-y-auto",children:y.map((g,C)=>Or("div",{className:x("flex cursor-pointer items-center justify-between rounded px-2 py-1.5 text-sm transition-colors",C===i?"bg-accent text-accent-foreground":"hover:bg-accent/50"),onClick:()=>o(g.template),onMouseEnter:()=>l(C),children:[Or("div",{className:"flex-1",children:[Bn("div",{className:"font-medium",children:g.type==="node"?g.nodeName:Or(Ou,{children:[Or("span",{className:"text-muted-foreground",children:[g.nodeName,"."]}),g.field]})}),g.description&&Bn("div",{className:"text-muted-foreground text-xs",children:g.description})]}),C===i&&Bn(Su,{className:"h-4 w-4"})]},`${g.nodeId}-${g.field||"root"}`))})});return Pu(v,document.body)}import{Fragment as Wu,jsx as Fa,jsxs as Fu}from"react/jsx-runtime";function Lu(e,t){let o=e.match(/\{\{@([^:]+):([^}]+)\}\}/);if(!o)return!1;let n=o[1];return t.some(r=>r.id===n)}function Mu(e,t){let o=e.match(/\{\{@([^:]+):([^}]+)\}\}/);if(!o)return e;let n=o[1],r=o[2],s=t.find(l=>l.id===n);if(!s)return r;let a=s.data.label;if(!a&&s.data.type==="action"){let l=s.data.config?.actionType;l&&(a=fe(l)?.label)}let d=r.indexOf(".");if(d===-1)return a??r;let i=r.substring(d+1);return a?`${a}.${i}`:r}function Oe({value:e="",onChange:t,placeholder:o,disabled:n,className:r,id:s}){let[a,d]=cn(!1),i=Wa(null),[l,c]=cn(e),u=Wa(!0),[f]=Ei(ke),[h]=Ei(re),[k,b]=cn(!1),[y,p]=cn({top:0,left:0}),[v,g]=cn(""),[C,I]=cn(null),A=Wa(null);Ma(()=>{e!==l&&!a&&(c(e),u.current=!0)},[e,a,l]),Ma(()=>{!a&&l&&(u.current=!0)},[h,a,l]);let w=()=>{if(!i.current)return null;let V=window.getSelection();if(!V||V.rangeCount===0)return null;let J=V.getRangeAt(0),W=J.cloneRange();W.selectNodeContents(i.current),W.setEnd(J.endContainer,J.endOffset);let K=0,T=document.createTreeWalker(i.current,NodeFilter.SHOW_TEXT|NodeFilter.SHOW_ELEMENT,null),z,N=!1;for(;(z=T.nextNode())&&!N;)if(z.nodeType===Node.TEXT_NODE)if(z===J.endContainer)K+=J.endOffset,N=!0;else{let R=(z.textContent||"").length;K+=R}else if(z.nodeType===Node.ELEMENT_NODE){let R=z,G=R.getAttribute("data-template");G&&(R.contains(J.endContainer)||R===J.endContainer?(K+=G.length,N=!0):K+=G.length)}return{offset:K}},m=V=>{if(!i.current||!V)return;let J=0,W=document.createTreeWalker(i.current,NodeFilter.SHOW_TEXT|NodeFilter.SHOW_ELEMENT,null),K,T=null,z=0;for(;K=W.nextNode();)if(K.nodeType===Node.TEXT_NODE){let N=(K.textContent||"").length;if(J+N>=V.offset){T=K,z=V.offset-J;break}J+=N}else if(K.nodeType===Node.ELEMENT_NODE){let N=K,R=N.getAttribute("data-template");if(R){if(J+R.length>=V.offset){T=N.nextSibling,z=0,!T&&N.parentNode&&(T=document.createTextNode(""),N.parentNode.appendChild(T));break}J+=R.length}}if(T){let N=document.createRange(),R=window.getSelection();try{let G=Math.min(z,T.textContent?.length||0);N.setStart(T,G),N.collapse(!0),R?.removeAllRanges(),R?.addRange(N),i.current.focus()}catch{i.current.focus()}}},S=()=>{if(!i.current||!u.current)return;let V=i.current,J=l||"",W=a?w():null;if(A.current!==null&&(W={offset:A.current},A.current=null),V.innerHTML="",!J&&!a){V.innerHTML=`<span class="text-muted-foreground pointer-events-none">${o||""}</span>`;return}let K=/\{\{@([^:]+):([^}]+)\}\}/g,T=0,z;for(;(z=K.exec(J))!==null;){let[N]=z,R=z.index;if(R>T){let de=J.slice(T,R),B=document.createTextNode(de);V.appendChild(B)}let G=document.createElement("span"),ne=Lu(N,h);G.className=ne?"inline-flex items-center gap-1 rounded bg-blue-500/10 px-1.5 py-0.5 text-blue-600 dark:text-blue-400 font-mono text-xs border border-blue-500/20 mx-0.5":"inline-flex items-center gap-1 rounded bg-red-500/10 px-1.5 py-0.5 text-red-600 dark:text-red-400 font-mono text-xs border border-red-500/20 mx-0.5",G.contentEditable="false",G.setAttribute("data-template",N),G.textContent=Mu(N,h),V.appendChild(G),T=K.lastIndex}if(T<J.length){let N=J.slice(T),R=document.createTextNode(N);V.appendChild(R)}V.innerHTML===""&&a&&(V.innerHTML="<br>"),u.current=!1,W&&requestAnimationFrame(()=>m(W))},X=()=>{if(!i.current)return"";let V="",J=document.createTreeWalker(i.current,NodeFilter.SHOW_TEXT|NodeFilter.SHOW_ELEMENT,null),W;for(;W=J.nextNode();)if(W.nodeType===Node.TEXT_NODE){let K=W.parentElement,T=!1;for(;K&&K!==i.current;){if(K.getAttribute("data-template")){T=!0;break}K=K.parentElement}T||(V+=W.textContent)}else if(W.nodeType===Node.ELEMENT_NODE){let T=W.getAttribute("data-template");T&&(V+=T)}return V},ie=()=>{let V=X();if(V===l)return;let J=(l.match(/\{\{@([^:]+):([^}]+)\}\}/g)||[]).length,W=(V.match(/\{\{@([^:]+):([^}]+)\}\}/g)||[]).length;if(W>J){c(V),t?.(V),u.current=!0,b(!1),requestAnimationFrame(()=>S());return}if(W===J&&W>0){c(V),t?.(V);let T=V.lastIndexOf("@");if(T!==-1){let z=V.slice(T+1);if(z.includes(" "))b(!1);else{if(g(z),I(T),i.current){let N=i.current.getBoundingClientRect(),R={top:N.bottom+window.scrollY+4,left:N.left+window.scrollX};p(R)}b(!0)}}else b(!1);return}if(W<J){c(V),t?.(V),u.current=!0,requestAnimationFrame(()=>S());return}c(V),t?.(V);let K=V.lastIndexOf("@");if(K!==-1){let T=V.slice(K+1);if(T.includes(" "))b(!1);else{if(g(T),I(K),i.current){let z=i.current.getBoundingClientRect(),N={top:z.bottom+window.scrollY+4,left:z.left+window.scrollX};p(N)}b(!0)}}else b(!1)},L=V=>{if(!i.current||C===null)return;let J=X(),W=J.slice(0,C),K=J.slice(C+1+v.length),T=W+V+K,z=W.length+V.length;c(T),t?.(T),u.current=!0,b(!1),I(null),A.current=z,i.current.focus()},F=()=>{d(!0),u.current=!0},$=()=>{setTimeout(()=>{document.activeElement!==i.current&&(d(!1),u.current=!0,b(!1))},200)},P=V=>{V.preventDefault();let J=V.clipboardData.getData("text/plain");document.execCommand("insertText",!1,J)};return Ma(()=>{u.current&&S()},[l,a]),Fu(Wu,{children:[Fa("div",{className:x("flex min-h-9 w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm transition-colors focus-within:outline-none focus-within:ring-1 focus-within:ring-ring",n&&"cursor-not-allowed opacity-50",r),children:Fa("div",{className:"w-full outline-none",contentEditable:!n,id:s,onBlur:$,onFocus:F,onInput:ie,onPaste:P,ref:i,role:"textbox",suppressContentEditableWarning:!0})}),Fa(Lr,{currentNodeId:f||void 0,filter:v,isOpen:k,onClose:()=>b(!1),onSelect:L,position:y})]})}import{jsx as at,jsxs as Co}from"react/jsx-runtime";function Di({config:e,onUpdateConfig:t,disabled:o}){let n=e?.dataType||"string",r=e?.operator||pr[n][0].value,s=pr[n],d=s.find(l=>l.value===r)?.unary??!1;function i(l){t("dataType",l);let c=pr[l];c?.[0]&&t("operator",c[0].value)}return Co("div",{className:"space-y-4",children:[Co("div",{className:"space-y-2",children:[at(M,{htmlFor:"leftValue",children:"Value to Test"}),at(Oe,{disabled:o,id:"leftValue",onChange:l=>t("leftValue",l),placeholder:"e.g., {{PreviousNode.status}}",value:e?.leftValue||""}),at("p",{className:"text-muted-foreground text-xs",children:"Use @ to reference previous node outputs."})]}),Co("div",{className:"space-y-2",children:[at(M,{htmlFor:"dataType",children:"Data Type"}),Co(ve,{disabled:o,onValueChange:i,value:n,children:[at(he,{id:"dataType",children:at(we,{placeholder:"Select data type"})}),at(be,{children:Zs.map(l=>at(te,{value:l.value,children:l.label},l.value))})]})]}),Co("div",{className:"space-y-2",children:[at(M,{htmlFor:"operator",children:"Operator"}),Co(ve,{disabled:o,onValueChange:l=>t("operator",l),value:r,children:[at(he,{id:"operator",children:at(we,{placeholder:"Select operator"})}),at(be,{children:s.map(l=>at(te,{value:l.value,children:l.label},l.value))})]})]}),!d&&Co("div",{className:"space-y-2",children:[at(M,{htmlFor:"rightValue",children:"Compare Value"}),at(Oe,{disabled:o,id:"rightValue",onChange:l=>t("rightValue",l),placeholder:"e.g., 200 or {{OtherNode.field}}",value:e?.rightValue||""})]})]})}import{Plus as zu,Trash2 as Bu}from"lucide-react";import{nanoid as Vu}from"nanoid";import{jsx as Ce,jsxs as ct}from"react/jsx-runtime";function lo({schema:e,onChange:t,disabled:o,level:n=0}){let r=()=>{t([...e,{id:Vu(),name:"",type:"string"}])},s=(c,u)=>{let f={...c};return u!=="array"&&(f.itemType=void 0),u!=="object"&&(f.fields=void 0),u==="array"&&!f.itemType&&(f.itemType="string"),u==="object"&&!f.fields&&(f.fields=[]),f},a=(c,u)=>{let f=[...e];f[c]={...f[c],...u},u.type&&(f[c]=s(f[c],u.type)),t(f)},d=c=>{t(e.filter((u,f)=>f!==c))},i=(c,u)=>{let f=[...e];f[c].fields=u,t(f)},l=n>0?"ml-4 border-l-2 border-muted pl-4":"";return ct("div",{className:`space-y-3 ${l}`,children:[e.map((c,u)=>{let f=c.id||`field-${n}-${u}`;return ct("div",{className:"space-y-2 rounded-md border p-3",children:[ct("div",{className:"flex gap-2",children:[ct("div",{className:"flex-1 space-y-2",children:[Ce(M,{className:"ml-1",htmlFor:`field-name-${n}-${u}`,children:"Property Name"}),Ce(ae,{disabled:o,id:`field-name-${n}-${u}`,onChange:h=>a(u,{name:h.target.value}),placeholder:"propertyName",value:c.name})]}),ct("div",{className:"flex-1 space-y-2",children:[Ce(M,{className:"ml-1",htmlFor:`field-type-${n}-${u}`,children:"Type"}),ct(ve,{disabled:o,onValueChange:h=>a(u,{type:h}),value:c.type,children:[Ce(he,{className:"w-full",id:`field-type-${n}-${u}`,children:Ce(we,{})}),ct(be,{children:[Ce(te,{value:"string",children:"String"}),Ce(te,{value:"number",children:"Number"}),Ce(te,{value:"boolean",children:"Boolean"}),Ce(te,{value:"array",children:"Array"}),Ce(te,{value:"object",children:"Object"})]})]})]}),Ce("div",{className:"flex items-end",children:Ce(D,{disabled:o,onClick:()=>d(u),size:"icon",variant:"ghost",children:Ce(Bu,{className:"h-4 w-4"})})})]}),c.type==="array"&&ct("div",{className:"space-y-2",children:[Ce(M,{className:"ml-1",htmlFor:`field-item-type-${n}-${u}`,children:"Array Item Type"}),ct(ve,{disabled:o,onValueChange:h=>a(u,{itemType:h}),value:c.itemType||"string",children:[Ce(he,{className:"w-full",id:`field-item-type-${n}-${u}`,children:Ce(we,{})}),ct(be,{children:[Ce(te,{value:"string",children:"String"}),Ce(te,{value:"number",children:"Number"}),Ce(te,{value:"boolean",children:"Boolean"}),Ce(te,{value:"object",children:"Object"})]})]})]}),c.type==="object"&&ct("div",{className:"mt-2",children:[Ce(M,{className:"mb-2 block",children:"Object Properties"}),Ce(lo,{disabled:o,level:n+1,onChange:h=>i(u,h),schema:c.fields||[]})]}),c.type==="array"&&c.itemType==="object"&&ct("div",{className:"mt-2",children:[Ce(M,{className:"mb-2 block",children:"Array Item Properties"}),Ce(lo,{disabled:o,level:n+1,onChange:h=>i(u,h),schema:c.fields||[]})]}),ct("div",{className:"space-y-2",children:[Ce(M,{className:"ml-1",htmlFor:`field-desc-${n}-${u}`,children:"Description (optional)"}),Ce(ae,{disabled:o,id:`field-desc-${n}-${u}`,onChange:h=>a(u,{description:h.target.value}),placeholder:"Description for the AI",value:c.description||""})]})]},f)}),ct(D,{className:"w-full",disabled:o,onClick:r,type:"button",variant:"outline",children:[Ce(zu,{className:"size-4"}),"Add Property"]})]})}import{Fragment as Gu,jsx as un,jsxs as za}from"react/jsx-runtime";function Ri({config:e,onUpdateConfig:t,disabled:o}){return za(Gu,{children:[za("div",{className:"space-y-2",children:[un(M,{htmlFor:"dbQuery",children:"SQL Query"}),un("div",{className:"overflow-hidden rounded-md border",children:un(yt,{defaultLanguage:"sql",height:"150px",onChange:n=>t("dbQuery",n||""),options:{minimap:{enabled:!1},lineNumbers:"on",scrollBeyondLastLine:!1,fontSize:12,readOnly:o,wordWrap:"off"},value:e?.dbQuery||""})}),un("p",{className:"text-muted-foreground text-xs",children:"The DATABASE_URL from your project integrations will be used to execute this query."})]}),za("div",{className:"space-y-2",children:[un(M,{children:"Schema (Optional)"}),un(lo,{disabled:o,onChange:n=>t("dbSchema",JSON.stringify(n)),schema:e?.dbSchema?JSON.parse(e.dbSchema):[]})]})]})}import{Fragment as Hu,jsx as Ke,jsxs as To}from"react/jsx-runtime";function Oi({config:e,onUpdateConfig:t,disabled:o}){return To(Hu,{children:[To("div",{className:"space-y-2",children:[Ke(M,{htmlFor:"httpMethod",children:"HTTP Method"}),To(ve,{disabled:o,onValueChange:n=>t("httpMethod",n),value:e?.httpMethod||"POST",children:[Ke(he,{className:"w-full",id:"httpMethod",children:Ke(we,{placeholder:"Select method"})}),To(be,{children:[Ke(te,{value:"GET",children:"GET"}),Ke(te,{value:"POST",children:"POST"}),Ke(te,{value:"PUT",children:"PUT"}),Ke(te,{value:"PATCH",children:"PATCH"}),Ke(te,{value:"DELETE",children:"DELETE"})]})]})]}),To("div",{className:"space-y-2",children:[Ke(M,{htmlFor:"endpoint",children:"URL"}),Ke(Oe,{disabled:o,id:"endpoint",onChange:n=>t("endpoint",n),placeholder:"https://api.example.com/endpoint or {{NodeName.url}}",value:e?.endpoint||""})]}),To("div",{className:"space-y-2",children:[Ke(M,{htmlFor:"httpHeaders",children:"Headers (JSON)"}),Ke("div",{className:"overflow-hidden rounded-md border",children:Ke(yt,{defaultLanguage:"json",height:"100px",onChange:n=>t("httpHeaders",n||"{}"),options:{minimap:{enabled:!1},lineNumbers:"off",scrollBeyondLastLine:!1,fontSize:12,readOnly:o,wordWrap:"off"},value:e?.httpHeaders||"{}"})})]}),To("div",{className:"space-y-2",children:[Ke(M,{htmlFor:"httpBody",children:"Body (JSON)"}),Ke("div",{className:`overflow-hidden rounded-md border ${e?.httpMethod==="GET"?"opacity-50":""}`,children:Ke(yt,{defaultLanguage:"json",height:"120px",onChange:n=>t("httpBody",n||"{}"),options:{minimap:{enabled:!1},lineNumbers:"off",scrollBeyondLastLine:!1,fontSize:12,readOnly:e?.httpMethod==="GET"||o,domReadOnly:e?.httpMethod==="GET"||o,wordWrap:"off"},value:e?.httpBody||"{}"})}),e?.httpMethod==="GET"&&Ke("p",{className:"text-muted-foreground text-xs",children:"Body is disabled for GET requests"})]})]})}import{jsx as mn,jsxs as Ba}from"react/jsx-runtime";function Li({config:e,onUpdateConfig:t,disabled:o}){return Ba("div",{className:"space-y-4",children:[Ba("div",{className:"space-y-2",children:[mn(M,{htmlFor:"items",children:"Items to Iterate"}),mn(Oe,{disabled:o,id:"items",onChange:n=>t("items",n),placeholder:"e.g., {{PreviousNode.rows}}, {{DatabaseQuery.results}}",value:e?.items||""}),mn("p",{className:"text-muted-foreground text-xs",children:"Reference an array from a previous node. Use @ to reference outputs."})]}),Ba("div",{className:"space-y-2",children:[mn(M,{htmlFor:"batchSize",children:"Batch Size (optional)"}),mn(Oe,{disabled:o,id:"batchSize",onChange:n=>t("batchSize",n),placeholder:"1",value:e?.batchSize||""}),mn("p",{className:"text-muted-foreground text-xs",children:"Number of items per batch. Default is 1 (process one item at a time)."})]})]})}import{Fragment as $u,jsx as ye,jsxs as Xe}from"react/jsx-runtime";function Mi({config:e,onUpdateConfig:t,disabled:o}){let n=e?.mode||"append";return Xe("div",{className:"space-y-4",children:[Xe("div",{className:"space-y-2",children:[ye(M,{htmlFor:"mode",children:"Mode"}),Xe(ve,{disabled:o,onValueChange:r=>t("mode",r),value:n,children:[ye(he,{id:"mode",children:ye(we,{placeholder:"Select mode"})}),Xe(be,{children:[ye(te,{value:"append",children:"Append"}),ye(te,{value:"combineByPosition",children:"Combine by Position"}),ye(te,{value:"combineByFields",children:"Combine by Fields"})]})]}),Xe("p",{className:"text-muted-foreground text-xs",children:[n==="append"&&"Concatenate both lists into one.",n==="combineByPosition"&&"Merge items at the same index from both inputs.",n==="combineByFields"&&"Match and merge items based on a common field."]})]}),Xe("div",{className:"space-y-2",children:[ye(M,{htmlFor:"input1",children:"Input 1"}),ye(Oe,{disabled:o,id:"input1",onChange:r=>t("input1",r),placeholder:"e.g., {{PreviousNode.rows}}",value:e?.input1||""}),ye("p",{className:"text-muted-foreground text-xs",children:"First array to merge. Use @ to reference outputs from previous nodes."})]}),Xe("div",{className:"space-y-2",children:[ye(M,{htmlFor:"input2",children:"Input 2"}),ye(Oe,{disabled:o,id:"input2",onChange:r=>t("input2",r),placeholder:"e.g., {{AnotherNode.results}}",value:e?.input2||""}),ye("p",{className:"text-muted-foreground text-xs",children:"Second array to merge. Use @ to reference outputs from previous nodes."})]}),n==="combineByPosition"&&Xe("div",{className:"space-y-2",children:[ye(M,{htmlFor:"unmatchedHandling",children:"When arrays have different lengths"}),Xe(ve,{disabled:o,onValueChange:r=>t("unmatchedHandling",r),value:e?.unmatchedHandling||"useNull",children:[ye(he,{id:"unmatchedHandling",children:ye(we,{})}),Xe(be,{children:[ye(te,{value:"useNull",children:"Fill with null"}),ye(te,{value:"discard",children:"Discard extra items"})]})]})]}),n==="combineByFields"&&Xe($u,{children:[Xe("div",{className:"space-y-2",children:[ye(M,{htmlFor:"matchField1",children:"Match Field (Input 1)"}),ye(Oe,{disabled:o,id:"matchField1",onChange:r=>t("matchField1",r),placeholder:"e.g., id",value:e?.matchField1||""}),ye("p",{className:"text-muted-foreground text-xs",children:"Field name in Input 1 to match on."})]}),Xe("div",{className:"space-y-2",children:[ye(M,{htmlFor:"matchField2",children:"Match Field (Input 2)"}),ye(Oe,{disabled:o,id:"matchField2",onChange:r=>t("matchField2",r),placeholder:"e.g., id",value:e?.matchField2||""}),ye("p",{className:"text-muted-foreground text-xs",children:"Field name in Input 2 to match on."})]}),Xe("div",{className:"space-y-2",children:[ye(M,{htmlFor:"joinType",children:"Join Type"}),Xe(ve,{disabled:o,onValueChange:r=>t("joinType",r),value:e?.joinType||"inner",children:[ye(he,{id:"joinType",children:ye(we,{})}),Xe(be,{children:[ye(te,{value:"inner",children:"Inner Join"}),ye(te,{value:"leftOuter",children:"Left Outer Join"}),ye(te,{value:"rightOuter",children:"Right Outer Join"}),ye(te,{value:"fullOuter",children:"Full Outer Join"})]})]}),ye("p",{className:"text-muted-foreground text-xs",children:"Inner keeps only matches. Left/Right keeps all items from that input. Full keeps everything."})]})]})]})}import{Loader2 as _u}from"lucide-react";import{useEffect as Uu,useState as Wi}from"react";import{jsx as Gt,jsxs as Gn}from"react/jsx-runtime";function Fi({config:e,onUpdateConfig:t,disabled:o}){let[n,r]=Wi([]),[s,a]=Wi(!0);Uu(()=>{async function i(){try{let l=await fetch("/api/workflow-builder/workflows");if(l.ok){let c=await l.json();r((c.workflows||c||[]).map(u=>({id:u.id,name:u.name})))}}catch{}finally{a(!1)}}i()},[]);let d=e?.workflowId||"";return Gn("div",{className:"space-y-4",children:[Gn("div",{className:"space-y-2",children:[Gt(M,{htmlFor:"workflowId",children:"Workflow"}),s?Gn("div",{className:"flex items-center gap-2 rounded-md border px-3 py-2 text-muted-foreground text-sm",children:[Gt(_u,{className:"size-4 animate-spin"}),"Loading workflows..."]}):Gn(ve,{disabled:o||n.length===0,onValueChange:i=>t("workflowId",i),value:d||void 0,children:[Gt(he,{className:"w-full",id:"workflowId",children:Gt(we,{placeholder:n.length===0?"No workflows found":"Select a workflow"})}),Gt(be,{children:n.map(i=>Gt(te,{value:i.id,children:i.name},i.id))})]}),Gt("p",{className:"text-muted-foreground text-xs",children:"The workflow to execute. It will run inline and wait for completion."})]}),Gn("div",{className:"space-y-2",children:[Gt(M,{htmlFor:"input",children:"Input (optional JSON)"}),Gt(Oe,{disabled:o,id:"input",onChange:i=>t("input",i),placeholder:'{"key": "value"} or {{PreviousNode.field}}',value:e?.input||""}),Gt("p",{className:"text-muted-foreground text-xs",children:"Optional JSON passed as trigger input to the sub-workflow."})]})]})}import{ArrowDown as Ku,ArrowUp as qu,Loader2 as ju,Plus as Ju,Trash2 as Yu}from"lucide-react";import{useEffect as Xu,useState as zi}from"react";import{jsx as Le,jsxs as kt}from"react/jsx-runtime";function Bi({config:e,onUpdateConfig:t,disabled:o}){let[n,r]=zi([]),[s,a]=zi(!0);Xu(()=>{async function p(){try{let v=await fetch("/api/workflow-builder/workflows");if(v.ok){let g=await v.json();r((g.workflows||g||[]).map(C=>({id:C.id,name:C.name})))}}catch{}finally{a(!1)}}p()},[]);let d=e?.workflowIds||"[]",i=[];try{let p=JSON.parse(d);Array.isArray(p)&&(i=p)}catch{i=d.split(",").map(p=>p.trim()).filter(Boolean)}let l=p=>{t("workflowIds",JSON.stringify(p))},c=p=>{p&&!i.includes(p)&&l([...i,p])},u=p=>{let v=[...i];v.splice(p,1),l(v)},f=p=>{if(p===0)return;let v=[...i];[v[p-1],v[p]]=[v[p],v[p-1]],l(v)},h=p=>{if(p===i.length-1)return;let v=[...i];[v[p],v[p+1]]=[v[p+1],v[p]],l(v)},k=p=>n.find(v=>v.id===p)?.name||p,b=n.filter(p=>!i.includes(p.id)),y=e?.continueOnFailure||"false";return kt("div",{className:"space-y-4",children:[kt("div",{className:"space-y-2",children:[Le(M,{children:"Workflows (executed in order)"}),s?kt("div",{className:"flex items-center gap-2 rounded-md border px-3 py-2 text-muted-foreground text-sm",children:[Le(ju,{className:"size-4 animate-spin"}),"Loading workflows..."]}):kt("div",{className:"space-y-1",children:[i.map((p,v)=>kt("div",{className:"flex items-center gap-1 rounded-md border bg-muted/30 px-2 py-1.5 text-sm",children:[kt("span",{className:"w-5 shrink-0 text-center text-muted-foreground text-xs",children:[v+1,"."]}),Le("span",{className:"min-w-0 flex-1 truncate",children:k(p)}),Le(D,{className:"size-6",disabled:o||v===0,onClick:()=>f(v),size:"icon",variant:"ghost",children:Le(qu,{className:"size-3"})}),Le(D,{className:"size-6",disabled:o||v===i.length-1,onClick:()=>h(v),size:"icon",variant:"ghost",children:Le(Ku,{className:"size-3"})}),Le(D,{className:"size-6 text-destructive hover:text-destructive",disabled:o,onClick:()=>u(v),size:"icon",variant:"ghost",children:Le(Yu,{className:"size-3"})})]},`${p}-${v}`)),b.length>0&&kt(ve,{disabled:o,onValueChange:c,value:"",children:[Le(he,{className:x("w-full",i.length>0&&"border-dashed"),children:kt("div",{className:"flex items-center gap-1.5 text-muted-foreground",children:[Le(Ju,{className:"size-3.5"}),Le("span",{children:"Add workflow..."})]})}),Le(be,{children:b.map(p=>Le(te,{value:p.id,children:p.name},p.id))})]}),!s&&n.length===0&&Le("p",{className:"text-muted-foreground text-xs",children:"No workflows found."})]})]}),kt("div",{className:"space-y-2",children:[Le(M,{htmlFor:"continueOnFailure",children:"On failure"}),kt(ve,{disabled:o,onValueChange:p=>t("continueOnFailure",p),value:y,children:[Le(he,{className:"w-full",id:"continueOnFailure",children:Le(we,{})}),kt(be,{children:[Le(te,{value:"false",children:"Stop sequence"}),Le(te,{value:"true",children:"Continue with next workflow"})]})]})]}),kt("div",{className:"space-y-2",children:[Le(M,{htmlFor:"sequenceInput",children:"Input (optional JSON, passed to all workflows)"}),Le(Oe,{disabled:o,id:"sequenceInput",onChange:p=>t("input",p),placeholder:'{"key": "value"} or {{PreviousNode.field}}',value:e?.input||""}),Le("p",{className:"text-muted-foreground text-xs",children:"Optional JSON passed as trigger input to every workflow in the sequence."})]})]})}import{jsx as st,jsxs as Mt}from"react/jsx-runtime";function Vi({config:e,onUpdateConfig:t,disabled:o}){let n=e?.mode||"rules";return Mt("div",{className:"space-y-4",children:[Mt("div",{className:"space-y-2",children:[st(M,{htmlFor:"mode",children:"Mode"}),Mt(ve,{disabled:o,onValueChange:r=>t("mode",r),value:n,children:[st(he,{id:"mode",children:st(we,{placeholder:"Select mode"})}),Mt(be,{children:[st(te,{value:"rules",children:"Rules"}),st(te,{value:"expression",children:"Expression"})]})]}),Mt("p",{className:"text-muted-foreground text-xs",children:[n==="rules"&&"Each route has a condition. The first route whose condition is true wins.",n==="expression"&&"Compare a value against each route's case value. First match wins."]})]}),n==="expression"&&Mt("div",{className:"space-y-2",children:[st(M,{htmlFor:"switchValue",children:"Value to Switch On"}),st(Oe,{disabled:o,id:"switchValue",onChange:r=>t("switchValue",r),placeholder:"e.g., {{PreviousNode.statusCode}}",value:e?.switchValue||""}),st("p",{className:"text-muted-foreground text-xs",children:"The value to compare against each route's case value. Use @ to reference previous node outputs."})]}),[0,1,2,3].map(r=>Mt("div",{className:"space-y-3 rounded-md border p-3",children:[Mt("p",{className:"font-medium text-sm",children:["Route ",r+1]}),Mt("div",{className:"space-y-2",children:[st(M,{htmlFor:`routeName${r}`,children:"Name (optional)"}),st(ae,{disabled:o,id:`routeName${r}`,onChange:s=>t(`routeName${r}`,s.target.value),placeholder:`Route ${r+1}`,value:e?.[`routeName${r}`]||""})]}),n==="rules"&&Mt("div",{className:"space-y-2",children:[st(M,{htmlFor:`routeCondition${r}`,children:"Condition"}),st(Oe,{disabled:o,id:`routeCondition${r}`,onChange:s=>t(`routeCondition${r}`,s),placeholder:"e.g., {{PreviousNode.status}} === 200",value:e?.[`routeCondition${r}`]||""})]}),n==="expression"&&Mt("div",{className:"space-y-2",children:[st(M,{htmlFor:`routeCaseValue${r}`,children:"Case Value"}),st(Oe,{disabled:o,id:`routeCaseValue${r}`,onChange:s=>t(`routeCaseValue${r}`,s),placeholder:`e.g., ${r===0?"200":r===1?"404":r===2?"500":"default"}`,value:e?.[`routeCaseValue${r}`]||""})]})]},r)),st("p",{className:"text-muted-foreground text-xs",children:'Routes are evaluated in order. The first matching route wins. If no route matches, the result falls back to "Default".'})]})}import{atom as Mr}from"jotai";var Wr=Mr(null),Gi=Mr([]),Hi=Mr(!1),Gw=Mr(!1);import{useAtomValue as qi,useSetAtom as Va}from"jotai";import{Search as nm}from"lucide-react";import{useCallback as rm,useMemo as am,useState as pn}from"react";import{toast as So}from"sonner";import{atom as Hn,useSetAtom as Qu}from"jotai";import*as _i from"react";var $i=null;var Ao=Hn(null),Fr=Hn([]),zr=Hn(!1),Ui=Hn(!1),Kt=Hn(null);function Ki(){let e=Qu(Kt);_i.useEffect(()=>{$i&&e($i)},[e])}import{Database as Zu,HelpCircle as em}from"lucide-react";import{jsx as $n}from"react/jsx-runtime";function tm({className:e}){return $n("svg",{className:e,fill:"currentColor",height:"12",viewBox:"0 0 1155 1000",width:"12",xmlns:"http://www.w3.org/2000/svg",children:$n("path",{d:"m577.3 0 577.4 1000H0z"})})}var om={database:Zu,vercel:tm};function Wt({integration:e,className:t="h-3 w-3"}){let o=om[e];if(o)return $n(o,{className:x("text-foreground",t)});let n=Dt(e);if(n?.icon){let r=n.icon;return $n(r,{className:x("text-foreground",t)})}return $n(em,{className:x("text-foreground",t)})}import{jsx as Ge,jsxs as vt}from"react/jsx-runtime";var sm=["database"],im={database:"Database"},lm={database:"Connect to PostgreSQL databases"},dm=()=>[...Xs(),...sm],Ga=e=>eo()[e]||im[e]||e,cm=e=>Ys()[e]||lm[e]||"";function Ji({overlayId:e,onSuccess:t}){let{push:o,closeAll:n}=oe(),[r,s]=pn(""),a=Vt(),d=qi(Kt),i=qi(Ao),l=Va(Ao),c=Va(Fr),u=Va(zr),f=dm(),h=am(()=>{if(!r.trim())return f;let y=r.toLowerCase();return f.filter(p=>Ga(p).toLowerCase().includes(y))},[f,r]),k=rm(()=>{d&&o(d.ConsentOverlay,{onConsent:y=>{t?.(y),n()}})},[d,o,n,t]),b=y=>{let p=d?.integrationType===y;if(p&&i?.enabled&&i?.isVercelUser){k();return}if(p&&i===null){d.api.getStatus().then(g=>{l(g),g?.enabled&&g?.isVercelUser?(u(!0),d.api.getTeams().then(C=>{c(C.teams)}).finally(()=>{u(!1),k()})):o(co,{type:y,onSuccess:t})});return}o(co,{type:y,onSuccess:t})};return vt(Re,{overlayId:e,title:"Add Connection",children:[Ge("p",{className:"-mt-2 mb-4 text-muted-foreground text-sm",children:"Select a service to connect"}),vt("div",{className:"space-y-3",children:[vt("div",{className:"relative",children:[Ge(nm,{className:"absolute top-1/2 left-3 size-4 -translate-y-1/2 text-muted-foreground"}),Ge(ae,{autoFocus:!a,className:"pl-9",onChange:y=>s(y.target.value),placeholder:"Search services...",value:r})]}),Ge("div",{className:"max-h-[300px] space-y-1 overflow-y-auto",children:h.length===0?Ge("p",{className:"py-4 text-center text-muted-foreground text-sm",children:"No services found"}):h.map(y=>{let p=cm(y);return vt("button",{className:"flex w-full items-center gap-3 rounded-md px-3 py-2 text-left text-sm transition-colors hover:bg-muted/50",onClick:()=>b(y),type:"button",children:[Ge(Wt,{className:"size-5 shrink-0",integration:y==="ai-gateway"?"vercel":y}),vt("span",{className:"min-w-0 flex-1 truncate",children:[Ge("span",{className:"font-medium",children:Ga(y)}),p&&vt("span",{className:"text-muted-foreground text-xs",children:[" ","- ",p]})]})]},y)})})]})]})}function ji({fieldId:e,label:t,configKey:o,placeholder:n,helpText:r,helpLink:s,value:a,onChange:d}){return vt("div",{className:"space-y-2",children:[Ge(M,{htmlFor:e,children:t}),Ge(ae,{className:"flex-1",id:e,onChange:i=>d(o,i.target.value),placeholder:n,type:"password",value:a}),(r||s)&&vt("p",{className:"text-muted-foreground text-xs",children:[r,s&&Ge("a",{className:"underline hover:text-foreground",href:s.url,rel:"noopener noreferrer",target:"_blank",children:s.text})]})]})}function co({overlayId:e,type:t,onSuccess:o}){let{push:n,closeAll:r}=oe(),[s,a]=pn(!1),[d,i]=pn(!1),[l,c]=pn(null),[u,f]=pn(""),[h,k]=pn({}),b=(A,w)=>{k(m=>({...m,[A]:w}))},y=async()=>{try{a(!0);let A=await q.integration.create({name:u.trim(),type:t,config:h});So.success("Connection created"),o?.(A.id),r()}catch(A){console.error("Failed to save integration:",A),So.error("Failed to save connection")}finally{a(!1)}},p=async()=>{if(!Object.values(h).some(w=>w&&w.length>0)){So.error("Please enter credentials");return}try{a(!0),c(null);let w=await q.integration.testCredentials({type:t,config:h});if(w.status==="error"){n(Ie,{title:"Connection Test Failed",message:`The test failed: ${w.message}
1
+ "use client";import{a as Yo,b as Xo,c as Qo}from"../chunk-NI6U7PHC.js";import{i as vr}from"../chunk-VUDOAZ3W.js";import{a as ii,b as hr}from"../chunk-3YVRTDK2.js";import{a as N}from"../chunk-6UXAINJQ.js";import{d as ei,h as Mt,i as ti,k as oi,l as ni,m as ye,n as no,o as ri,p as ai,v as si,w as Ea,y as Jo}from"../chunk-QRG4O4PE.js";import{Check as cu,Clock as di,Loader2 as uu,Play as mu,Square as ci,Trash2 as pu,X as fu}from"lucide-react";import gu from"next/link";import{useCallback as yu,useEffect as li,useState as Ra}from"react";var Da=class extends Error{status;constructor(t,o){super(o),this.status=t,this.name="ApiError"}};async function ve(e,t){let o=await fetch(e,{...t,headers:{"Content-Type":"application/json",...t?.headers}});if(!o.ok){let n=await o.json().catch(()=>({error:"Unknown error"}));throw new Da(o.status,n.error||"Request failed")}return o.json()}function qc(e,t){e?.name&&(t.currentData.name=e.name)}function jc(e,t){e?.description&&(t.currentData.description=e.description)}function Jc(e,t){e?.node&&(t.currentData.nodes=[...t.currentData.nodes,e.node])}function Yc(e,t){e?.edge&&(t.currentData.edges=[...t.currentData.edges,e.edge])}function Xc(e,t){e?.nodeId&&(t.currentData.nodes=t.currentData.nodes.filter(o=>o.id!==e.nodeId),t.currentData.edges=t.currentData.edges.filter(o=>o.source!==e.nodeId&&o.target!==e.nodeId))}function Qc(e,t){e?.edgeId&&(t.currentData.edges=t.currentData.edges.filter(o=>o.id!==e.edgeId))}function Zc(e,t){e?.nodeId&&e.updates&&(t.currentData.nodes=t.currentData.nodes.map(o=>o.id===e.nodeId?{...o,...e.updates?.position?{position:e.updates.position}:{},...e.updates?.data?{data:{...o.data,...e.updates.data}}:{}}:o))}var eu={setName:qc,setDescription:jc,addNode:Jc,addEdge:Yc,removeNode:Xc,removeEdge:Qc,updateNode:Zc};function tu(e,t){if(!e?.op)return;let o=eu[e.op];o&&o(e,t)}function ou(e,t,o){if(e.trim())try{let n=JSON.parse(e);if(n.type==="operation"&&n.operation)tu(n.operation,o),t({...o.currentData});else if(n.type==="error")throw console.error("[API Client] Error:",n.error),new Error(n.error)}catch(n){console.error("[API Client] Failed to parse JSONL line:",n)}}function nu(e,t,o,n){n.buffer+=t.decode(e,{stream:!0});let r=n.buffer.split(`
2
+ `);n.buffer=r.pop()||"";for(let s of r)ou(s,o,n)}var ru={generate:(e,t)=>ve("/api/ai/generate",{method:"POST",body:JSON.stringify({prompt:e,existingWorkflow:t})}),generateStream:async(e,t,o)=>{let n=await fetch("/api/ai/generate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({prompt:e,existingWorkflow:o})});if(!n.ok)throw new Error(`HTTP error! status: ${n.status}`);if(!n.body)throw new Error("No response body");let r=n.body.getReader(),s=new TextDecoder,a={buffer:"",currentData:o?{nodes:o.nodes||[],edges:o.edges||[],name:o.name}:{nodes:[],edges:[]}};try{for(;;){let{done:d,value:i}=await r.read();if(d)break;nu(i,s,t,a)}return a.currentData}finally{r.releaseLock()}}},au={getAll:e=>ve(`/api/integrations${e?`?type=${e}`:""}`),get:e=>ve(`/api/integrations/${e}`),create:e=>ve("/api/integrations",{method:"POST",body:JSON.stringify(e)}),update:(e,t)=>ve(`/api/integrations/${e}`,{method:"PUT",body:JSON.stringify(t)}),delete:e=>ve(`/api/integrations/${e}`,{method:"DELETE"}),testConnection:e=>ve(`/api/integrations/${e}/test`,{method:"POST"}),testCredentials:e=>ve("/api/integrations/test",{method:"POST",body:JSON.stringify(e)})},su={get:()=>ve("/api/user"),update:e=>ve("/api/user",{method:"PATCH",body:JSON.stringify(e)})},br={getDashboardWorkflows:()=>ve("/api/workflows/dashboard"),getAll:()=>ve("/api/workflows"),getById:e=>ve(`/api/workflows/${e}`),create:e=>ve("/api/workflows/create",{method:"POST",body:JSON.stringify(e)}),update:(e,t)=>ve(`/api/workflows/${e}`,{method:"PATCH",body:JSON.stringify(t)}),delete:e=>ve(`/api/workflows/${e}`,{method:"DELETE"}),duplicate:e=>ve(`/api/workflows/${e}/duplicate`,{method:"POST"}),getCurrent:()=>ve("/api/workflows/current"),saveCurrent:(e,t)=>ve("/api/workflows/current",{method:"POST",body:JSON.stringify({nodes:e,edges:t})}),execute:(e,t={})=>ve(`/api/workflow/${e}/execute`,{method:"POST",body:JSON.stringify({input:t})}),triggerWebhook:(e,t={})=>ve(`/api/workflows/${e}/webhook`,{method:"POST",body:JSON.stringify(t)}),getCode:e=>ve(`/api/workflows/${e}/code`),getExecutions:e=>ve(`/api/workflows/${e}/executions`),deleteExecutions:e=>ve(`/api/workflows/${e}/executions`,{method:"DELETE"}),getExecutionLogs:e=>ve(`/api/workflows/executions/${e}/logs`),getExecutionStatus:e=>ve(`/api/workflows/executions/${e}/status`),cancelExecution:e=>ve(`/api/workflows/executions/${e}/cancel`,{method:"POST"}),download:e=>ve(`/api/workflows/${e}/download`),autoSaveCurrent:(()=>{let e=null,t=2e3;return(o,n)=>{e&&clearTimeout(e),e=setTimeout(()=>{br.saveCurrent(o,n).catch(r=>{console.error("Auto-save failed:",r)})},t)}})(),autoSaveWorkflow:(()=>{let e=null,t=2e3;return(o,n,r=!0)=>{if(!r)return br.update(o,n);e&&clearTimeout(e),e=setTimeout(()=>{br.update(o,n).catch(s=>{console.error("Auto-save failed:",s)})},t)}})()},iu={getStatus:()=>ve("/api/ai-gateway/status"),getTeams:()=>ve("/api/ai-gateway/teams"),consent:(e,t)=>ve("/api/ai-gateway/consent",{method:"POST",body:JSON.stringify({teamId:e,teamName:t})}),revokeConsent:()=>ve("/api/ai-gateway/consent",{method:"DELETE"})},U={ai:ru,aiGateway:iu,integration:au,user:su,workflow:br};function Zo(e,t){return`${e} ${t}${e===1?"":"s"} ago`}function wr(e){let t=new Date,o=new Date(e),n=Math.floor((t.getTime()-o.getTime())/1e3);if(n<60)return"just now";let r=Math.floor(n/60);if(r<60)return Zo(r,"min");let s=Math.floor(r/60);if(s<24)return Zo(s,"hour");let a=Math.floor(s/24);if(a<7)return Zo(a,"day");let d=Math.floor(a/7);if(d<4)return Zo(d,"week");let i=Math.floor(a/30);if(i<12)return Zo(i,"month");let l=Math.floor(a/365);return Zo(l,"year")}import{Loader2Icon as lu}from"lucide-react";import{jsx as du}from"react/jsx-runtime";function pt({className:e,...t}){let{ref:o,...n}=t;return du(lu,{role:"status","aria-label":"Loading",className:N("size-4 animate-spin",e),...n})}import{jsx as se,jsxs as ft}from"react/jsx-runtime";function vu({status:e}){let t={success:{class:"bg-green-600/15 text-green-600",icon:se(cu,{className:"h-3 w-3"}),label:"Success"},error:{class:"bg-red-600/15 text-red-600",icon:se(fu,{className:"h-3 w-3"}),label:"Error"},running:{class:"bg-blue-600/15 text-blue-600",icon:se(uu,{className:"h-3 w-3 animate-spin"}),label:"Running"},cancelled:{class:"bg-gray-600/15 text-gray-500",icon:se(ci,{className:"h-3 w-3"}),label:"Cancelled"},pending:{class:"bg-yellow-600/15 text-yellow-600",icon:se(di,{className:"h-3 w-3"}),label:"Pending"}},o=t[e]||t.pending;return ft("span",{className:N("inline-flex items-center gap-1.5 rounded-full px-2.5 py-0.5 text-xs font-medium",o.class),children:[o.icon,o.label]})}function Oa(){let[e,t]=Ra([]),[o,n]=Ra(!0),[r,s]=Ra({}),a=yu(async(y=!0)=>{try{y&&n(!0);let v=await U.workflow.getDashboardWorkflows();t(v)}catch(v){console.error("Failed to load workflows:",v)}finally{y&&n(!1)}},[]);li(()=>{a()},[a]),li(()=>{let y=setInterval(()=>a(!1),5e3);return()=>clearInterval(y)},[a]);let d=async y=>{s(v=>({...v,[y]:!0}));try{await U.workflow.execute(y),await a(!1)}catch(v){console.error("Failed to execute workflow:",v)}finally{s(v=>({...v,[y]:!1}))}},i=async(y,v)=>{s(p=>({...p,[v]:!0}));try{await U.workflow.cancelExecution(y),await a(!1)}catch(p){console.error("Failed to cancel execution:",p)}finally{s(p=>({...p,[v]:!1}))}},l=async(y,v)=>{if(confirm(`Delete "${v}"? This will also delete all its executions.`)){s(p=>({...p,[y]:!0}));try{await U.workflow.delete(y),t(p=>p.filter(m=>m.id!==y))}catch(p){console.error("Failed to delete workflow:",p)}finally{s(p=>({...p,[y]:!1}))}}},c=e.length,u=e.reduce((y,v)=>y+v.totalRuns,0),g=e.reduce((y,v)=>y+v.successCount,0),b=e.reduce((y,v)=>y+v.errorCount,0);return o?se("div",{className:"flex items-center justify-center py-24",children:se(pt,{})}):ft("div",{className:"pointer-events-auto mx-auto max-w-5xl px-6 py-10",children:[se("h1",{className:"mb-6 text-2xl font-bold",children:"Dashboard"}),ft("div",{className:"mb-8 grid grid-cols-2 gap-4 sm:grid-cols-4",children:[ft("div",{className:"rounded-lg border bg-card p-4",children:[se("div",{className:"text-sm text-muted-foreground",children:"Workflows"}),se("div",{className:"mt-1 text-2xl font-semibold",children:c})]}),ft("div",{className:"rounded-lg border bg-card p-4",children:[se("div",{className:"text-sm text-muted-foreground",children:"Total Runs"}),se("div",{className:"mt-1 text-2xl font-semibold",children:u})]}),ft("div",{className:"rounded-lg border bg-card p-4",children:[se("div",{className:"text-sm text-muted-foreground",children:"Successful"}),se("div",{className:"mt-1 text-2xl font-semibold text-green-600",children:g})]}),ft("div",{className:"rounded-lg border bg-card p-4",children:[se("div",{className:"text-sm text-muted-foreground",children:"Failed"}),se("div",{className:"mt-1 text-2xl font-semibold text-red-600",children:b})]})]}),e.length===0?ft("div",{className:"flex flex-col items-center justify-center rounded-lg border border-dashed py-16",children:[se(di,{className:"mb-3 h-8 w-8 text-muted-foreground"}),se("div",{className:"font-medium text-sm",children:"No workflows yet"}),se("div",{className:"mt-1 text-muted-foreground text-xs",children:"Create a workflow to get started"})]}):se("div",{className:"overflow-hidden rounded-lg border",children:ft("table",{className:"w-full",children:[se("thead",{children:ft("tr",{className:"border-b bg-muted/50 text-left text-xs font-medium text-muted-foreground",children:[se("th",{className:"px-4 py-3",children:"Workflow"}),se("th",{className:"px-4 py-3",children:"Runs"}),se("th",{className:"px-4 py-3",children:"Success"}),se("th",{className:"px-4 py-3",children:"Error"}),se("th",{className:"px-4 py-3",children:"Stopped"}),se("th",{className:"px-4 py-3",children:"Latest Run"}),se("th",{className:"px-4 py-3 text-right",children:"Actions"})]})}),se("tbody",{children:e.map(y=>ft("tr",{className:"border-b last:border-b-0 transition-colors hover:bg-muted/30",children:[ft("td",{className:"px-4 py-3",children:[se(gu,{className:"font-medium text-sm hover:underline",href:`/workflows/${y.id}`,children:y.name}),y.description&&se("div",{className:"mt-0.5 text-xs text-muted-foreground truncate max-w-[200px]",children:y.description})]}),se("td",{className:"px-4 py-3 text-sm tabular-nums",children:y.totalRuns}),se("td",{className:"px-4 py-3 text-sm tabular-nums text-green-600",children:y.successCount}),se("td",{className:"px-4 py-3 text-sm tabular-nums text-red-600",children:y.errorCount}),se("td",{className:"px-4 py-3 text-sm tabular-nums text-gray-500",children:y.cancelledCount}),se("td",{className:"px-4 py-3",children:y.latestRunStatus?ft("div",{className:"flex items-center gap-2",children:[se(vu,{status:y.latestRunStatus}),se("span",{className:"text-xs text-muted-foreground",children:y.latestRunStartedAt&&wr(y.latestRunStartedAt)})]}):se("span",{className:"text-xs text-muted-foreground",children:"-"})}),se("td",{className:"px-4 py-3 text-right",children:ft("div",{className:"inline-flex items-center gap-1",children:[y.runningExecutionId?se("button",{type:"button",className:"rounded p-1.5 text-orange-600 hover:bg-orange-600/10 disabled:opacity-50",title:"Stop running execution",disabled:r[y.id],onClick:()=>i(y.runningExecutionId,y.id),children:se(ci,{className:"h-3.5 w-3.5"})}):se("button",{type:"button",className:"rounded p-1.5 text-green-600 hover:bg-green-600/10 disabled:opacity-50",title:"Execute workflow",disabled:r[y.id],onClick:()=>d(y.id),children:se(mu,{className:"h-3.5 w-3.5"})}),se("button",{type:"button",className:"rounded p-1.5 text-red-600 hover:bg-red-600/10 disabled:opacity-50",title:"Delete workflow",disabled:r[y.id],onClick:()=>l(y.id,y.name),children:se(pu,{className:"h-3.5 w-3.5"})})]})})]},y.id))})]})})]})}import{AuthView as $f}from"@daveyplate/better-auth-ui";import{useParams as _f}from"next/navigation";import{useAtom as qt,useAtomValue as Pf,useSetAtom as Pt}from"jotai";import{ChevronLeft as Ef,ChevronRight as Df}from"lucide-react";import Rf from"next/link";import{useSearchParams as Of}from"next/navigation";import{useCallback as ho,useEffect as Et,useRef as Bo,useState as ys}from"react";import{toast as vs}from"sonner";import{atom as $n}from"jotai";var bt=$n([]),xr=$n(!1),Hh=$n(null),Wt=$n(0),ui=$n(e=>{let t=e(bt);return new Set(t.map(o=>o.id))});import{applyEdgeChanges as hu,applyNodeChanges as bu}from"@xyflow/react";import{atom as le}from"jotai";var re=le([]),ue=le([]),Te=le(null),Ue=le(null),fi=le(!1),mi=le(!1),St=le(!1),Ke=le(null),wt=le(""),Nr=le("private"),ao=le(!0),en=le({snapToGrid:!0,edgeStyle:"smoothstep"}),$t=le("properties"),kr=le(!1),so=le(null),Cr=le(null),Tr=le(!1),Sr=le(!1),gi=le(!1),Ar=le(!1),Ir=le(new Set),ro=le(null),Pr=le(!1),tn=le({}),La=null,wu=1e3,Ft=le(null,async(e,t,o)=>{let n=e(Ke),r=e(re),s=e(ue);if(!n)return;let a=async()=>{try{await U.workflow.update(n,{nodes:r,edges:s}),t(st,!1)}catch(d){console.error("Autosave failed:",d)}};o?.immediate?await a():(La&&clearTimeout(La),La=setTimeout(a,wu))}),yi=le(null,(e,t,o)=>{let n=e(re),r=o.filter(l=>l.type==="remove"?n.find(u=>u.id===l.id)?.data.type!=="trigger":!0),s=bu(r,n);t(re,s);let a=s.find(l=>l.selected);if(a){t(Te,a.id),t(Ue,null);let l=e(ro);l&&l!==a.id&&t(ro,null)}else if(e(Te)){let l=e(Te);s.find(u=>u.id===l)||t(Te,null),t(ro,null)}if(r.some(l=>l.type==="remove")){t(Ft,{immediate:!0});return}r.some(l=>l.type==="position"&&l.dragging===!1)&&t(Ft)}),vi=le(null,(e,t,o)=>{let n=e(ue),r=hu(o,n);t(ue,r);let s=r.find(d=>d.selected);if(s)t(Ue,s.id),t(Te,null);else if(e(Ue)){let d=e(Ue);r.find(l=>l.id===d)||t(Ue,null)}o.some(d=>d.type==="remove")&&t(Ft,{immediate:!0})}),on=le(null,(e,t,o)=>{let n=e(re),r=e(ue),s=e(at);t(at,[...s,{nodes:n,edges:r}]),t(Gt,[]);let a=n.map(l=>({...l,selected:!1})),d={...o,selected:!0},i=[...a,d];t(re,i),t(Te,o.id),o.data.type==="action"&&!o.data.config?.actionType&&t(ro,o.id),t(st,!0),t(Ft,{immediate:!0})}),io=le(null,(e,t,{id:o,data:n})=>{let r=e(re),a=r.find(c=>c.id===o)?.data.label,d=n.label,i=d!==void 0&&a!==d,l=r.map(c=>{if(c.id===o)return{...c,data:{...c.data,...n}};if(i&&a){let u=hi(c.data.config||{},o,a,d);if(u!==c.data.config)return{...c,data:{...c.data,config:u}}}return c});t(re,l),n.status||(t(st,!0),t(Ft))});function hi(e,t,o,n){let r=!1,s={};for(let[a,d]of Object.entries(e))if(typeof d=="string"){let i=new RegExp(`\\{\\{@${pi(t)}:${pi(o)}(\\.[^}]+)?\\}\\}`,"g"),l=d.replace(i,(c,u)=>(r=!0,`{{@${t}:${n}${u||""}}}`));s[a]=l}else if(typeof d=="object"&&d!==null&&!Array.isArray(d)){let i=hi(d,t,o,n);i!==d&&(r=!0),s[a]=i}else s[a]=d;return r?s:e}function pi(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var lo=le(null,(e,t,o)=>{let n=e(re);if(n.find(l=>l.id===o)?.data.type==="trigger")return;let s=e(ue),a=e(at);t(at,[...a,{nodes:n,edges:s}]),t(Gt,[]);let d=n.filter(l=>l.id!==o),i=s.filter(l=>l.source!==o&&l.target!==o);t(re,d),t(ue,i),e(Te)===o&&t(Te,null),t(st,!0),t(Ft,{immediate:!0})}),co=le(null,(e,t,o)=>{let n=e(re),r=e(ue),s=e(at);t(at,[...s,{nodes:n,edges:r}]),t(Gt,[]);let a=r.filter(d=>d.id!==o);t(ue,a),e(Ue)===o&&t(Ue,null),t(st,!0),t(Ft,{immediate:!0})}),bi=le(null,(e,t)=>{let o=e(re),n=e(ue),r=e(at);t(at,[...r,{nodes:o,edges:n}]),t(Gt,[]);let s=o.filter(i=>i.selected&&i.data.type!=="trigger").map(i=>i.id),a=o.filter(i=>i.data.type==="trigger"?!0:!i.selected),d=n.filter(i=>!(i.selected||s.includes(i.source)||s.includes(i.target)));t(re,a),t(ue,d),t(Te,null),t(Ue,null),t(st,!0),t(Ft,{immediate:!0})}),nn=le(null,(e,t)=>{let o=e(re),n=e(ue),r=e(at);t(at,[...r,{nodes:o,edges:n}]),t(Gt,[]);let s=o.filter(a=>a.data.type==="trigger");t(re,s),t(ue,[]),t(Te,null),t(Ue,null),t(st,!0),t(Ft,{immediate:!0})}),Kh=le(null,async(e,t)=>{try{t(mi,!0);let o=await U.workflow.getCurrent();t(re,o.nodes),t(ue,o.edges),o.id&&t(Ke,o.id)}catch(o){console.error("Failed to load workflow:",o)}finally{t(mi,!1)}}),qh=le(null,async(e,t,{name:o,description:n})=>{let r=e(re),s=e(ue);try{return await U.workflow.create({name:o,description:n,nodes:r,edges:s})}catch(a){throw console.error("Failed to save workflow:",a),a}}),Er=le(!1),st=le(!1),wi=le(!1),at=le([]),Gt=le([]),xi=le(null,(e,t)=>{let o=e(at);if(o.length===0)return;let n=e(re),r=e(ue),s=e(Gt);t(Gt,[...s,{nodes:n,edges:r}]);let a=[...o],d=a.pop();d&&(t(at,a),t(re,d.nodes),t(ue,d.edges),t(st,!0))}),Ni=le(null,(e,t)=>{let o=e(Gt);if(o.length===0)return;let n=e(re),r=e(ue),s=e(at);t(at,[...s,{nodes:n,edges:r}]);let a=[...o],d=a.pop();d&&(t(Gt,a),t(re,d.nodes),t(ue,d.edges),t(st,!0))}),ki=le(e=>e(at).length>0),Ci=le(e=>e(Gt).length>0),Dr=le(null,(e,t)=>{let n=e(re).map(r=>({...r,data:{...r.data,status:"idle"}}));t(re,n)});import*as Rr from"react";var Ma=768;function _t(){let[e,t]=Rr.useState(void 0);return Rr.useEffect(()=>{let o=window.matchMedia(`(max-width: ${Ma-1}px)`),n=()=>{t(window.innerWidth<Ma)};return o.addEventListener("change",n),t(window.innerWidth<Ma),()=>o.removeEventListener("change",n)},[]),!!e}import{Slot as xu}from"radix-ui";import{cva as Nu}from"class-variance-authority";import{jsx as ku}from"react/jsx-runtime";var Or=Nu("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",{variants:{variant:{default:"bg-primary text-primary-foreground hover:bg-primary/90",destructive:"bg-destructive text-white hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",outline:"border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-9 px-4 py-2 has-[>svg]:px-3",sm:"h-8 rounded-md gap-1.5 px-3 has-[>svg]:px-2.5",lg:"h-10 rounded-md px-6 has-[>svg]:px-4",icon:"size-9","icon-sm":"size-8","icon-lg":"size-10"}},defaultVariants:{variant:"default",size:"default"}});function E({className:e,variant:t,size:o,asChild:n=!1,...r}){let s=n?xu.Slot:"button";return ku(s,{"data-slot":"button",className:N(Or({variant:t,size:o,className:e})),...r})}var Cu={"Database Query":"database"};function Tu(e){return ye(e)?.integration||Cu[e]}function Ti(e,t,o){let n=e.data.config?.actionType;if(!n)return null;let r=Tu(n);if(!r)return null;let s=e.data.config?.integrationId;if(s&&o.has(s))return null;let d=t.filter(i=>i.type===r);return d.length===1?{nodeId:e.id,newIntegrationId:d[0].id}:d.length===0&&s?{nodeId:e.id,newIntegrationId:void 0}:null}import{useAtom as yo,useAtomValue as ps,useSetAtom as zo}from"jotai";import{Copy as ql,Eraser as fs,Eye as xf,EyeOff as Nf,FileCode as jl,RefreshCw as Jl,Trash2 as sa}from"lucide-react";import{useCallback as kf,useEffect as Yl,useMemo as Cf,useRef as Xl,useState as rr}from"react";import{toast as In}from"sonner";import{AlertTriangleIcon as Lu}from"lucide-react";import{Loader2 as Su}from"lucide-react";import{jsx as rn,jsxs as Fa}from"react/jsx-runtime";function Wa({action:e}){return Fa(E,{disabled:e.disabled||e.loading,onClick:e.onClick,variant:e.variant??"default",children:[e.loading&&rn(Su,{className:"mr-2 size-4 animate-spin"}),e.label]})}function Si({actions:e,className:t,children:o}){if(o)return rn("div",{className:N("flex flex-col-reverse gap-2 p-6 pt-4 sm:flex-row sm:justify-end",t),children:o});if(!e||e.length===0)return null;let n=e.filter(i=>i.variant==="ghost"),r=e.filter(i=>i.variant==="outline"||i.variant==="secondary"),s=e.filter(i=>!i.variant||i.variant==="default"||i.variant==="destructive"),a=n.length>0,d=r.length>0||s.length>0;return Fa("div",{className:N("flex flex-col-reverse gap-2 p-6 pt-4 sm:flex-row",a&&d?"sm:justify-between":"sm:justify-end",t),children:[a&&rn("div",{className:"flex flex-col-reverse gap-2 sm:flex-row",children:n.map(i=>rn(Wa,{action:i},i.label))}),d&&Fa("div",{className:"flex flex-col-reverse gap-2 sm:flex-row",children:[r.map(i=>rn(Wa,{action:i},i.label)),s.map(i=>rn(Wa,{action:i},i.label))]})]})}import{ChevronLeftIcon as Eu,XIcon as Du}from"lucide-react";import{createContext as Ii,useCallback as an,useContext as Pi,useMemo as Au,useRef as Iu,useState as Pu}from"react";import{jsx as Ai}from"react/jsx-runtime";var Ei=Ii(null),Di=Ii([]);function za(){return`overlay-${Date.now()}-${Math.random().toString(36).slice(2,9)}`}function Ri({children:e}){let[t,o]=Pu([]),n=Iu([]);t.length>0&&(n.current=t);let r=an((u,g,b)=>{let y=za();return o([{id:y,component:u,props:g??{},options:b??{}}]),y},[]),s=an((u,g,b)=>{let y=za(),v={id:y,component:u,props:g??{},options:b??{}};return o(p=>[...p,v]),y},[]),a=an(()=>{o(u=>u.length<=1?(u[0]?.options.onClose?.(),[]):(u[u.length-1]?.options.onClose?.(),u.slice(0,-1)))},[]),d=an((u,g,b)=>{let y=za(),v={id:y,component:u,props:g??{},options:b??{}};return o(p=>p.length===0?[v]:(p[p.length-1]?.options.onClose?.(),[...p.slice(0,-1),v])),y},[]),i=an(()=>{o(u=>{for(let g of u)g.options.onClose?.();return[]})},[]),l=an(u=>{o(g=>{let b=g.findIndex(y=>y.id===u);if(b===-1)return g;for(let y=b;y<g.length;y++)g[y].options.onClose?.();return g.slice(0,b)})},[]),c=Au(()=>({stack:t,open:r,push:s,pop:a,replace:d,closeAll:i,close:l,hasOverlays:t.length>0,depth:t.length}),[t,r,s,a,d,i,l]);return Ai(Ei.Provider,{value:c,children:Ai(Di.Provider,{value:n.current,children:e})})}function oe(){let e=Pi(Ei);if(!e)throw new Error("useOverlay must be used within an OverlayProvider");return e}function Oi(e){let{stack:t}=oe(),o=Pi(Di),n=t.length>0?t:o,r=n.findIndex(s=>s.id===e);return{index:r,isFirst:r===0,isLast:r===n.length-1,depth:n.length,showBackButton:r>0}}import{jsx as So,jsxs as Li}from"react/jsx-runtime";function Ru({title:e,description:t,showBackButton:o,showCloseButton:n=!0,onBack:r,onClose:s,className:a}){let{pop:d,closeAll:i}=oe(),l=o??!1,c=()=>{r?r():d()},u=()=>{s?s():i()};return Li("div",{className:N("relative flex flex-col gap-1.5 p-6 pb-0",a),children:[Li("div",{className:"flex min-h-8 items-center gap-2",children:[l&&So(E,{"aria-label":"Go back",className:"ml-[-8px] size-8 shrink-0",onClick:c,size:"icon",variant:"ghost",children:So(Eu,{className:"size-5"})}),e&&So("h2",{className:"flex-1 font-semibold text-lg leading-none tracking-tight",children:e}),n&&So(E,{"aria-label":"Close",className:"absolute top-4 right-4 size-8 shrink-0 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",onClick:u,size:"icon",variant:"ghost",children:So(Du,{className:"size-4"})})]}),t&&So("p",{className:"text-muted-foreground text-sm",children:t})]})}function sn({overlayId:e,showBackButton:t,...o}){let{showBackButton:n}=Oi(e);return So(Ru,{...o,showBackButton:t??n})}import{jsx as Ba,jsxs as Ou}from"react/jsx-runtime";function Oe({overlayId:e,title:t,description:o,actions:n,children:r,className:s}){return Ou("div",{className:N("flex flex-col",s),children:[(t||o)&&Ba(sn,{description:o,overlayId:e,title:t}),r&&Ba("div",{className:"flex-1 overflow-y-auto p-6",children:r}),Ba(Si,{actions:n})]})}import{jsx as Lr,jsxs as Mu}from"react/jsx-runtime";function Ee({overlayId:e,title:t="Confirm",message:o,confirmLabel:n="Confirm",cancelLabel:r="Cancel",confirmVariant:s="default",destructive:a=!1,onConfirm:d,onCancel:i}){let{pop:l}=oe();return Lr(Oe,{actions:[{label:r,variant:"outline",onClick:()=>{i?.(),l()}},{label:n,variant:a?"destructive":s,onClick:async()=>{await d(),l()}}],overlayId:e,title:t,children:Mu("div",{className:"flex gap-4",children:[a&&Lr("div",{className:"flex size-10 shrink-0 items-center justify-center rounded-full bg-destructive/10",children:Lr(Lu,{className:"size-5 text-destructive"})}),Lr("p",{className:N("text-muted-foreground text-sm",a&&"pt-2"),children:o})]})})}import{AlertDialog as uo}from"radix-ui";import{jsx as zt,jsxs as zu}from"react/jsx-runtime";function ln({...e}){return zt(uo.Root,{"data-slot":"alert-dialog",...e})}function Wu({...e}){return zt(uo.Portal,{"data-slot":"alert-dialog-portal",...e})}function Fu({className:e,...t}){return zt(uo.Overlay,{"data-slot":"alert-dialog-overlay",className:N("data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",e),...t})}function dn({className:e,...t}){return zu(Wu,{children:[zt(Fu,{}),zt(uo.Content,{"data-slot":"alert-dialog-content",className:N("bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 sm:max-w-lg",e),...t})]})}function cn({className:e,...t}){return zt("div",{"data-slot":"alert-dialog-header",className:N("flex flex-col gap-2 text-center sm:text-left",e),...t})}function un({className:e,...t}){return zt("div",{"data-slot":"alert-dialog-footer",className:N("flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",e),...t})}function mn({className:e,...t}){return zt(uo.Title,{"data-slot":"alert-dialog-title",className:N("text-lg font-semibold",e),...t})}function pn({className:e,...t}){return zt(uo.Description,{"data-slot":"alert-dialog-description",className:N("text-muted-foreground text-sm",e),...t})}function fn({className:e,...t}){return zt(uo.Action,{className:N(Or(),e),...t})}function gn({className:e,...t}){return zt(uo.Cancel,{className:N(Or({variant:"outline"}),e),...t})}import Bu from"@monaco-editor/react";import{useTheme as Vu}from"next-themes";var Mi={base:"vs-dark",inherit:!0,rules:[{token:"",foreground:"ededed"},{token:"comment",foreground:"a1a1a1",fontStyle:"italic"},{token:"keyword",foreground:"ff4d8d"},{token:"keyword.operator",foreground:"ff4d8d"},{token:"string",foreground:"00ca50"},{token:"string.escape",foreground:"00ca50"},{token:"number",foreground:"ffffff"},{token:"type",foreground:"47a8ff"},{token:"type.identifier",foreground:"47a8ff"},{token:"identifier",foreground:"ededed"},{token:"parameter",foreground:"ededed"},{token:"variable",foreground:"ededed"},{token:"variable.parameter",foreground:"ededed"},{token:"function",foreground:"c472fb"},{token:"identifier.function",foreground:"c472fb"},{token:"member.function",foreground:"c472fb"},{token:"constant.language",foreground:"47a8ff"},{token:"keyword.json",foreground:"47a8ff"},{token:"variable.predefined",foreground:"ededed"},{token:"support.variable",foreground:"ededed"},{token:"support.constant",foreground:"ededed"},{token:"delimiter",foreground:"ededed"},{token:"delimiter.bracket",foreground:"ededed"},{token:"delimiter.parenthesis",foreground:"ededed"},{token:"delimiter.curly",foreground:"ededed"},{token:"delimiter.array",foreground:"ededed"},{token:"punctuation",foreground:"ededed"},{token:"operator",foreground:"ededed"},{token:"string.key.json",foreground:"47a8ff"},{token:"string.value.json",foreground:"00ca50"},{token:"number.json",foreground:"ffffff"},{token:"keyword.json",foreground:"47a8ff"}],colors:{"editor.background":"#000000","editor.foreground":"#ededed","editorLineNumber.foreground":"#444444","editorLineNumber.activeForeground":"#888888","editor.lineHighlightBackground":"#0A0A0A","editor.selectionBackground":"#264F78","editor.inactiveSelectionBackground":"#1A1A1A","editorCursor.foreground":"#FFFFFF","editorWhitespace.foreground":"#333333","editorIndentGuide.background":"#1A1A1A","editorIndentGuide.activeBackground":"#333333","editorBracketMatch.background":"#0A0A0A","editorBracketMatch.border":"#444444"}};import{jsx as Hu}from"react/jsx-runtime";function xt(e){let{resolvedTheme:t}=Vu();return Hu(Bu,{...e,onMount:(n,r)=>{r.editor.defineTheme("vercel-dark",Mi),r.editor.setTheme(t==="dark"?"vercel-dark":"light"),e.onMount&&e.onMount(n,r)},theme:t==="dark"?"vercel-dark":"light"})}import{jsx as Gu}from"react/jsx-runtime";function ae({className:e,type:t,...o}){return Gu("input",{type:t,"data-slot":"input",className:N("file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground bg-transparent border-input h-9 w-full min-w-0 rounded-md border px-3 py-1 text-base shadow-xs transition-[color,box-shadow] outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm","focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]","aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",e),...o})}import{Label as $u}from"radix-ui";import{jsx as _u}from"react/jsx-runtime";function L({className:e,...t}){return _u($u.Root,{"data-slot":"label",className:N("flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",e),...t})}import{Tabs as Mr}from"radix-ui";import{jsx as Wr}from"react/jsx-runtime";function Va({className:e,...t}){return Wr(Mr.Root,{"data-slot":"tabs",className:N("flex flex-col gap-2",e),...t})}function Ha({className:e,...t}){return Wr(Mr.List,{"data-slot":"tabs-list",className:N("bg-muted text-muted-foreground inline-flex h-10 w-fit items-center justify-center rounded-lg p-[3px]",e),...t})}function Ao({className:e,...t}){return Wr(Mr.Trigger,{"data-slot":"tabs-trigger",className:N("data-[state=active]:bg-background dark:data-[state=active]:text-foreground focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:outline-ring dark:data-[state=active]:border-input dark:data-[state=active]:bg-input/30 text-foreground dark:text-muted-foreground inline-flex h-[calc(100%-1px)] flex-1 items-center justify-center gap-1.5 rounded-sm border border-transparent px-2 py-1 text-sm font-medium whitespace-nowrap transition-[color,box-shadow] focus-visible:ring-[3px] focus-visible:outline-1 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:shadow-sm [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",e),...t})}function Io({className:e,...t}){return Wr(Mr.Content,{"data-slot":"tabs-content",className:N("flex-1 outline-none",e),...t})}import{useAtomValue as Nl,useSetAtom as fp}from"jotai";import{HelpCircle as gp,Plus as yp,Settings as vp}from"lucide-react";import{useEffect as hp,useMemo as Jr,useState as bp}from"react";import{Select as it}from"radix-ui";import{CheckIcon as Uu,ChevronDownIcon as Wi,ChevronUpIcon as Ku}from"lucide-react";import{jsx as He,jsxs as Ga}from"react/jsx-runtime";function he({...e}){return He(it.Root,{"data-slot":"select",...e})}function Fi({...e}){return He(it.Group,{"data-slot":"select-group",...e})}function xe({...e}){return He(it.Value,{"data-slot":"select-value",...e})}function be({className:e,size:t="default",children:o,...n}){return Ga(it.Trigger,{"data-slot":"select-trigger","data-size":t,className:N("border-input data-[placeholder]:text-muted-foreground [&_svg:not([class*='text-'])]:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive bg-transparent hover:bg-accent/50 flex w-fit items-center justify-between gap-2 rounded-md border px-3 py-2 text-sm whitespace-nowrap shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 data-[size=default]:h-9 data-[size=sm]:h-8 *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-2 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",e),...n,children:[o,He(it.Icon,{asChild:!0,children:He(Wi,{className:"size-4 opacity-50"})})]})}function we({className:e,children:t,position:o="popper",align:n="center",...r}){return He(it.Portal,{children:Ga(it.Content,{"data-slot":"select-content",className:N("bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 relative z-50 max-h-(--radix-select-content-available-height) min-w-[8rem] origin-(--radix-select-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border shadow-md",o==="popper"&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",e),position:o,align:n,...r,children:[He(qu,{}),He(it.Viewport,{className:N("p-1",o==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)] scroll-my-1"),children:t}),He(ju,{})]})})}function zi({className:e,...t}){return He(it.Label,{"data-slot":"select-label",className:N("text-muted-foreground px-2 py-1.5 text-xs",e),...t})}function Q({className:e,children:t,...o}){return Ga(it.Item,{"data-slot":"select-item",className:N("focus:bg-accent focus:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground relative flex w-full cursor-default items-center gap-2 rounded-sm py-1.5 pr-8 pl-2 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",e),...o,children:[He("span",{className:"absolute right-2 flex size-3.5 items-center justify-center",children:He(it.ItemIndicator,{children:He(Uu,{className:"size-4"})})}),He(it.ItemText,{children:t})]})}function Fr({className:e,...t}){return He(it.Separator,{"data-slot":"select-separator",className:N("bg-border pointer-events-none -mx-1 my-1 h-px",e),...t})}function qu({className:e,...t}){return He(it.ScrollUpButton,{"data-slot":"select-scroll-up-button",className:N("flex cursor-default items-center justify-center py-1",e),...t,children:He(Ku,{className:"size-4"})})}function ju({className:e,...t}){return He(it.ScrollDownButton,{"data-slot":"select-scroll-down-button",className:N("flex cursor-default items-center justify-center py-1",e),...t,children:He(Wi,{className:"size-4"})})}import{useAtom as Hi}from"jotai";import{useEffect as $a,useRef as _a,useState as yn}from"react";import{useAtom as Bi}from"jotai";import{Check as Ju}from"lucide-react";import{useEffect as zr,useRef as Yu,useState as Vi}from"react";import{createPortal as Xu}from"react-dom";import{Fragment as tm,jsx as _n,jsxs as Br}from"react/jsx-runtime";var Qu=e=>{if(e.data.label)return e.data.label;if(e.data.type==="action"){let t=e.data.config?.actionType;if(t){let o=ye(t);if(o?.label)return o.label}return t||"HTTP Request"}return e.data.type==="trigger"?e.data.config?.triggerType||"Manual":"Node"},Un=(e,t="")=>{let o=[];for(let n of e){let r=t?`${t}.${n.name}`:n.name,s=n.type==="array"?`${n.itemType}[]`:n.type==="enum"?`enum<${(n.enumValues||[]).join(" | ")||n.enumItemType||"string"}>`:n.type,a=n.description||`${s}`;if(o.push({field:r,description:a}),n.type==="object"&&n.fields&&n.fields.length>0&&o.push(...Un(n.fields,r)),n.type==="array"&&n.itemType==="object"&&n.fields&&n.fields.length>0){let d=`${r}[0]`;o.push(...Un(n.fields,d))}}return o},Zu=(e,...t)=>e?t.some(o=>e===o||e.endsWith(`/${o.toLowerCase().replace(/\s+/g,"-")}`)):!1,em=e=>{let t=e.data.config?.actionType;if(t==="HTTP Request")return[{field:"data",description:"Response data"},{field:"status",description:"HTTP status code"}];if(t==="Database Query"){let o=e.data.config?.dbSchema;if(o)try{let n=JSON.parse(o);if(n.length>0)return Un(n)}catch{}return[{field:"rows",description:"Query result rows"},{field:"count",description:"Number of rows"}]}if(Zu(t,"Generate Text","ai-gateway/generate-text")){let o=e.data.config?.aiFormat,n=e.data.config?.aiSchema;if(o==="object"&&n)try{let r=JSON.parse(n);if(r.length>0)return Un(r,"object")}catch{}return[{field:"text",description:"Generated text"}]}if(t){let o=ye(t);if(o?.outputFields&&o.outputFields.length>0)return o.outputFields}if(e.data.type==="trigger"){let o=e.data.config?.triggerType,n=e.data.config?.webhookSchema;if(o==="Webhook"&&n)try{let r=JSON.parse(n);if(r.length>0)return Un(r)}catch{}return[{field:"triggered",description:"Trigger status"},{field:"timestamp",description:"Trigger timestamp"},{field:"input",description:"Input data"}]}return[{field:"data",description:"Output data"}]};function Vr({isOpen:e,position:t,onSelect:o,onClose:n,currentNodeId:r,filter:s=""}){let[a]=Bi(re),[d]=Bi(ue),[i,l]=Vi(0),c=Yu(null),[u,g]=Vi(!1);zr(()=>(g(!0),()=>g(!1)),[]);let y=(()=>{if(!r)return[];let h=new Set,S=[],D=I=>{if(h.has(I))return;h.add(I);let k=d.filter(f=>f.target===I);for(let f of k)S.push(f.source),D(f.source)};return D(r),a.filter(I=>S.includes(I.id))})(),v=[];for(let h of y){let S=Qu(h),D=em(h);v.push({type:"node",nodeId:h.id,nodeName:S,template:`{{@${h.id}:${S}}}`});for(let I of D)v.push({type:"field",nodeId:h.id,nodeName:S,field:I.field,description:I.description,template:`{{@${h.id}:${S}.${I.field}}}`})}let p=s?v.filter(h=>h.nodeName.toLowerCase().includes(s.toLowerCase())||h.field&&h.field.toLowerCase().includes(s.toLowerCase())):v;if(zr(()=>{l(0)},[s]),zr(()=>{let h=S=>{if(e)switch(S.key){case"ArrowDown":S.preventDefault(),l(D=>D<p.length-1?D+1:D);break;case"ArrowUp":S.preventDefault(),l(D=>D>0?D-1:D);break;case"Enter":S.preventDefault(),p[i]&&o(p[i].template);break;case"Escape":S.preventDefault(),n();break}};return window.addEventListener("keydown",h),()=>window.removeEventListener("keydown",h)},[e,p,i,o,n]),zr(()=>{if(c.current){let h=c.current.children[i];h&&h.scrollIntoView({block:"nearest"})}},[i]),!e||p.length===0||!u)return null;let m={top:Math.min(t.top,window.innerHeight-300),left:Math.min(t.left,window.innerWidth-320)},w=_n("div",{className:"fixed z-[9999] w-80 rounded-lg border bg-popover p-1 text-popover-foreground shadow-md",ref:c,style:{top:`${m.top}px`,left:`${m.left}px`},children:_n("div",{className:"max-h-60 overflow-y-auto",children:p.map((h,S)=>Br("div",{className:N("flex cursor-pointer items-center justify-between rounded px-2 py-1.5 text-sm transition-colors",S===i?"bg-accent text-accent-foreground":"hover:bg-accent/50"),onClick:()=>o(h.template),onMouseEnter:()=>l(S),children:[Br("div",{className:"flex-1",children:[_n("div",{className:"font-medium",children:h.type==="node"?h.nodeName:Br(tm,{children:[Br("span",{className:"text-muted-foreground",children:[h.nodeName,"."]}),h.field]})}),h.description&&_n("div",{className:"text-muted-foreground text-xs",children:h.description})]}),S===i&&_n(Ju,{className:"h-4 w-4"})]},`${h.nodeId}-${h.field||"root"}`))})});return Xu(w,document.body)}import{Fragment as rm,jsx as Ua,jsxs as am}from"react/jsx-runtime";function om(e,t){let o=e.match(/\{\{@([^:]+):([^}]+)\}\}/);if(!o)return!1;let n=o[1];return t.some(r=>r.id===n)}function nm(e,t){let o=e.match(/\{\{@([^:]+):([^}]+)\}\}/);if(!o)return e;let n=o[1],r=o[2],s=t.find(l=>l.id===n);if(!s)return r;let a=s.data.label;if(!a&&s.data.type==="action"){let l=s.data.config?.actionType;l&&(a=ye(l)?.label)}let d=r.indexOf(".");if(d===-1)return a??r;let i=r.substring(d+1);return a?`${a}.${i}`:r}function We({value:e="",onChange:t,placeholder:o,disabled:n,className:r,id:s}){let[a,d]=yn(!1),i=_a(null),[l,c]=yn(e),u=_a(!0),[g]=Hi(Te),[b]=Hi(re),[y,v]=yn(!1),[p,m]=yn({top:0,left:0}),[w,h]=yn(""),[S,D]=yn(null),I=_a(null);$a(()=>{e!==l&&!a&&(c(e),u.current=!0)},[e,a,l]),$a(()=>{!a&&l&&(u.current=!0)},[b,a,l]);let k=()=>{if(!i.current)return null;let H=window.getSelection();if(!H||H.rangeCount===0)return null;let X=H.getRangeAt(0),z=X.cloneRange();z.selectNodeContents(i.current),z.setEnd(X.endContainer,X.endOffset);let j=0,A=document.createTreeWalker(i.current,NodeFilter.SHOW_TEXT|NodeFilter.SHOW_ELEMENT,null),B,C=!1;for(;(B=A.nextNode())&&!C;)if(B.nodeType===Node.TEXT_NODE)if(B===X.endContainer)j+=X.endOffset,C=!0;else{let R=(B.textContent||"").length;j+=R}else if(B.nodeType===Node.ELEMENT_NODE){let R=B,_=R.getAttribute("data-template");_&&(R.contains(X.endContainer)||R===X.endContainer?(j+=_.length,C=!0):j+=_.length)}return{offset:j}},f=H=>{if(!i.current||!H)return;let X=0,z=document.createTreeWalker(i.current,NodeFilter.SHOW_TEXT|NodeFilter.SHOW_ELEMENT,null),j,A=null,B=0;for(;j=z.nextNode();)if(j.nodeType===Node.TEXT_NODE){let C=(j.textContent||"").length;if(X+C>=H.offset){A=j,B=H.offset-X;break}X+=C}else if(j.nodeType===Node.ELEMENT_NODE){let C=j,R=C.getAttribute("data-template");if(R){if(X+R.length>=H.offset){A=C.nextSibling,B=0,!A&&C.parentNode&&(A=document.createTextNode(""),C.parentNode.appendChild(A));break}X+=R.length}}if(A){let C=document.createRange(),R=window.getSelection();try{let _=Math.min(B,A.textContent?.length||0);C.setStart(A,_),C.collapse(!0),R?.removeAllRanges(),R?.addRange(C),i.current.focus()}catch{i.current.focus()}}},x=()=>{if(!i.current||!u.current)return;let H=i.current,X=l||"",z=a?k():null;if(I.current!==null&&(z={offset:I.current},I.current=null),H.innerHTML="",!X&&!a){H.innerHTML=`<span class="text-muted-foreground pointer-events-none">${o||""}</span>`;return}let j=/\{\{@([^:]+):([^}]+)\}\}/g,A=0,B;for(;(B=j.exec(X))!==null;){let[C]=B,R=B.index;if(R>A){let de=X.slice(A,R),V=document.createTextNode(de);H.appendChild(V)}let _=document.createElement("span"),ne=om(C,b);_.className=ne?"inline-flex items-center gap-1 rounded bg-blue-500/10 px-1.5 py-0.5 text-blue-600 dark:text-blue-400 font-mono text-xs border border-blue-500/20 mx-0.5":"inline-flex items-center gap-1 rounded bg-red-500/10 px-1.5 py-0.5 text-red-600 dark:text-red-400 font-mono text-xs border border-red-500/20 mx-0.5",_.contentEditable="false",_.setAttribute("data-template",C),_.textContent=nm(C,b),H.appendChild(_),A=j.lastIndex}if(A<X.length){let C=X.slice(A),R=document.createTextNode(C);H.appendChild(R)}H.innerHTML===""&&a&&(H.innerHTML="<br>"),u.current=!1,z&&requestAnimationFrame(()=>f(z))},G=()=>{if(!i.current)return"";let H="",X=document.createTreeWalker(i.current,NodeFilter.SHOW_TEXT|NodeFilter.SHOW_ELEMENT,null),z;for(;z=X.nextNode();)if(z.nodeType===Node.TEXT_NODE){let j=z.parentElement,A=!1;for(;j&&j!==i.current;){if(j.getAttribute("data-template")){A=!0;break}j=j.parentElement}A||(H+=z.textContent)}else if(z.nodeType===Node.ELEMENT_NODE){let A=z.getAttribute("data-template");A&&(H+=A)}return H},te=()=>{let H=G();if(H===l)return;let X=(l.match(/\{\{@([^:]+):([^}]+)\}\}/g)||[]).length,z=(H.match(/\{\{@([^:]+):([^}]+)\}\}/g)||[]).length;if(z>X){c(H),t?.(H),u.current=!0,v(!1),requestAnimationFrame(()=>x());return}if(z===X&&z>0){c(H),t?.(H);let A=H.lastIndexOf("@");if(A!==-1){let B=H.slice(A+1);if(B.includes(" "))v(!1);else{if(h(B),D(A),i.current){let C=i.current.getBoundingClientRect(),R={top:C.bottom+window.scrollY+4,left:C.left+window.scrollX};m(R)}v(!0)}}else v(!1);return}if(z<X){c(H),t?.(H),u.current=!0,requestAnimationFrame(()=>x());return}c(H),t?.(H);let j=H.lastIndexOf("@");if(j!==-1){let A=H.slice(j+1);if(A.includes(" "))v(!1);else{if(h(A),D(j),i.current){let B=i.current.getBoundingClientRect(),C={top:B.bottom+window.scrollY+4,left:B.left+window.scrollX};m(C)}v(!0)}}else v(!1)},O=H=>{if(!i.current||S===null)return;let X=G(),z=X.slice(0,S),j=X.slice(S+1+w.length),A=z+H+j,B=z.length+H.length;c(A),t?.(A),u.current=!0,v(!1),D(null),I.current=B,i.current.focus()},W=()=>{d(!0),u.current=!0},$=()=>{setTimeout(()=>{document.activeElement!==i.current&&(d(!1),u.current=!0,v(!1))},200)},T=H=>{H.preventDefault();let X=H.clipboardData.getData("text/plain");document.execCommand("insertText",!1,X)};return $a(()=>{u.current&&x()},[l,a]),am(rm,{children:[Ua("div",{className:N("flex min-h-9 w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm transition-colors focus-within:outline-none focus-within:ring-1 focus-within:ring-ring",n&&"cursor-not-allowed opacity-50",r),children:Ua("div",{className:"w-full outline-none",contentEditable:!n,id:s,onBlur:$,onFocus:W,onInput:te,onPaste:T,ref:i,role:"textbox",suppressContentEditableWarning:!0})}),Ua(Vr,{currentNodeId:g||void 0,filter:w,isOpen:y,onClose:()=>v(!1),onSelect:O,position:p})]})}import{jsx as lt,jsxs as Po}from"react/jsx-runtime";function Gi({config:e,onUpdateConfig:t,onUpdateMultipleConfig:o,disabled:n}){let r=e?.dataType||"string",s=e?.operator||hr[r][0].value,a=hr[r],i=a.find(c=>c.value===s)?.unary??!1;function l(c){let g=hr[c]?.[0]?.value??"";o?o({dataType:c,operator:g}):(t("dataType",c),g&&t("operator",g))}return Po("div",{className:"space-y-4",children:[Po("div",{className:"space-y-2",children:[lt(L,{htmlFor:"leftValue",children:"Value to Test"}),lt(We,{disabled:n,id:"leftValue",onChange:c=>t("leftValue",c),placeholder:"e.g., {{PreviousNode.status}}",value:e?.leftValue||""}),lt("p",{className:"text-muted-foreground text-xs",children:"Use @ to reference previous node outputs."})]}),Po("div",{className:"space-y-2",children:[lt(L,{htmlFor:"dataType",children:"Data Type"}),Po(he,{disabled:n,onValueChange:l,value:r,children:[lt(be,{id:"dataType",children:lt(xe,{placeholder:"Select data type"})}),lt(we,{children:ii.map(c=>lt(Q,{value:c.value,children:c.label},c.value))})]})]}),Po("div",{className:"space-y-2",children:[lt(L,{htmlFor:"operator",children:"Operator"}),Po(he,{disabled:n,onValueChange:c=>t("operator",c),value:s,children:[lt(be,{id:"operator",children:lt(xe,{placeholder:"Select operator"})}),lt(we,{children:a.map(c=>lt(Q,{value:c.value,children:c.label},c.value))})]})]}),!i&&Po("div",{className:"space-y-2",children:[lt(L,{htmlFor:"rightValue",children:"Compare Value"}),lt(We,{disabled:n,id:"rightValue",onChange:c=>t("rightValue",c),placeholder:"e.g., 200 or {{OtherNode.field}}",value:e?.rightValue||""})]})]})}import{Plus as $i,Trash2 as _i}from"lucide-react";import{nanoid as sm}from"nanoid";import{jsx as ce,jsxs as Fe}from"react/jsx-runtime";function mo({schema:e,onChange:t,disabled:o,level:n=0}){let r=()=>{t([...e,{id:sm(),name:"",type:"string"}])},s=(c,u)=>{let g={...c};return u!=="array"&&(g.itemType=void 0),u!=="object"&&(g.fields=void 0),u!=="enum"&&(g.enumValues=void 0,g.enumItemType=void 0),u==="array"&&!g.itemType&&(g.itemType="string"),u==="object"&&!g.fields&&(g.fields=[]),u==="enum"&&!g.enumValues&&(g.enumValues=[],g.enumItemType="string"),g},a=(c,u)=>{let g=[...e];g[c]={...g[c],...u},u.type&&(g[c]=s(g[c],u.type)),t(g)},d=c=>{t(e.filter((u,g)=>g!==c))},i=(c,u)=>{let g=[...e];g[c].fields=u,t(g)},l=n>0?"ml-4 border-l-2 border-muted pl-4":"";return Fe("div",{className:`space-y-3 ${l}`,children:[e.map((c,u)=>{let g=c.id||`field-${n}-${u}`;return Fe("div",{className:"space-y-2 rounded-md border p-3",children:[Fe("div",{className:"flex gap-2",children:[Fe("div",{className:"flex-1 space-y-2",children:[ce(L,{className:"ml-1",htmlFor:`field-name-${n}-${u}`,children:"Property Name"}),ce(ae,{disabled:o,id:`field-name-${n}-${u}`,onChange:b=>a(u,{name:b.target.value}),placeholder:"propertyName",value:c.name})]}),Fe("div",{className:"flex-1 space-y-2",children:[ce(L,{className:"ml-1",htmlFor:`field-type-${n}-${u}`,children:"Type"}),Fe(he,{disabled:o,onValueChange:b=>a(u,{type:b}),value:c.type,children:[ce(be,{className:"w-full",id:`field-type-${n}-${u}`,children:ce(xe,{})}),Fe(we,{children:[ce(Q,{value:"string",children:"String"}),ce(Q,{value:"number",children:"Number"}),ce(Q,{value:"boolean",children:"Boolean"}),ce(Q,{value:"enum",children:"Enum"}),ce(Q,{value:"array",children:"Array"}),ce(Q,{value:"object",children:"Object"})]})]})]}),ce("div",{className:"flex items-end",children:ce(E,{disabled:o,onClick:()=>d(u),size:"icon",variant:"ghost",children:ce(_i,{className:"h-4 w-4"})})})]}),c.type==="array"&&Fe("div",{className:"space-y-2",children:[ce(L,{className:"ml-1",htmlFor:`field-item-type-${n}-${u}`,children:"Array Item Type"}),Fe(he,{disabled:o,onValueChange:b=>a(u,{itemType:b}),value:c.itemType||"string",children:[ce(be,{className:"w-full",id:`field-item-type-${n}-${u}`,children:ce(xe,{})}),Fe(we,{children:[ce(Q,{value:"string",children:"String"}),ce(Q,{value:"number",children:"Number"}),ce(Q,{value:"boolean",children:"Boolean"}),ce(Q,{value:"object",children:"Object"})]})]})]}),c.type==="enum"&&Fe("div",{className:"space-y-3",children:[Fe("div",{className:"space-y-2",children:[ce(L,{className:"ml-1",htmlFor:`field-enum-type-${n}-${u}`,children:"Value Type"}),Fe(he,{disabled:o,onValueChange:b=>a(u,{enumItemType:b}),value:c.enumItemType||"string",children:[ce(be,{className:"w-full",id:`field-enum-type-${n}-${u}`,children:ce(xe,{})}),Fe(we,{children:[ce(Q,{value:"string",children:"String"}),ce(Q,{value:"number",children:"Number"}),ce(Q,{value:"boolean",children:"Boolean"})]})]})]}),Fe("div",{className:"space-y-2",children:[ce(L,{className:"ml-1",children:"Allowed Values"}),(c.enumValues||[]).map((b,y)=>Fe("div",{className:"flex gap-2",children:[ce(ae,{disabled:o,onChange:v=>{let p=[...c.enumValues||[]];p[y]=v.target.value,a(u,{enumValues:p})},placeholder:c.enumItemType==="boolean"?"true or false":c.enumItemType==="number"?"e.g. 42":"e.g. active",value:b}),ce(E,{disabled:o,onClick:()=>{let v=(c.enumValues||[]).filter((p,m)=>m!==y);a(u,{enumValues:v})},size:"icon",variant:"ghost",children:ce(_i,{className:"h-4 w-4"})})]},y)),Fe(E,{className:"w-full",disabled:o,onClick:()=>{let b=[...c.enumValues||[],""];a(u,{enumValues:b})},type:"button",variant:"outline",children:[ce($i,{className:"size-4"}),"Add Value"]})]})]}),c.type==="object"&&Fe("div",{className:"mt-2",children:[ce(L,{className:"mb-2 block",children:"Object Properties"}),ce(mo,{disabled:o,level:n+1,onChange:b=>i(u,b),schema:c.fields||[]})]}),c.type==="array"&&c.itemType==="object"&&Fe("div",{className:"mt-2",children:[ce(L,{className:"mb-2 block",children:"Array Item Properties"}),ce(mo,{disabled:o,level:n+1,onChange:b=>i(u,b),schema:c.fields||[]})]}),Fe("div",{className:"space-y-2",children:[ce(L,{className:"ml-1",htmlFor:`field-desc-${n}-${u}`,children:"Description (optional)"}),ce(ae,{disabled:o,id:`field-desc-${n}-${u}`,onChange:b=>a(u,{description:b.target.value}),placeholder:"Description for the AI",value:c.description||""})]})]},g)}),Fe(E,{className:"w-full",disabled:o,onClick:r,type:"button",variant:"outline",children:[ce($i,{className:"size-4"}),"Add Property"]})]})}import{Fragment as im,jsx as vn,jsxs as Ka}from"react/jsx-runtime";function Ui({config:e,onUpdateConfig:t,disabled:o}){return Ka(im,{children:[Ka("div",{className:"space-y-2",children:[vn(L,{htmlFor:"dbQuery",children:"SQL Query"}),vn("div",{className:"overflow-hidden rounded-md border",children:vn(xt,{defaultLanguage:"sql",height:"150px",onChange:n=>t("dbQuery",n||""),options:{minimap:{enabled:!1},lineNumbers:"on",scrollBeyondLastLine:!1,fontSize:12,readOnly:o,wordWrap:"off"},value:e?.dbQuery||""})}),vn("p",{className:"text-muted-foreground text-xs",children:"The DATABASE_URL from your project integrations will be used to execute this query."})]}),Ka("div",{className:"space-y-2",children:[vn(L,{children:"Schema (Optional)"}),vn(mo,{disabled:o,onChange:n=>t("dbSchema",JSON.stringify(n)),schema:e?.dbSchema?JSON.parse(e.dbSchema):[]})]})]})}import{Fragment as lm,jsx as qe,jsxs as Eo}from"react/jsx-runtime";function Ki({config:e,onUpdateConfig:t,disabled:o}){return Eo(lm,{children:[Eo("div",{className:"space-y-2",children:[qe(L,{htmlFor:"httpMethod",children:"HTTP Method"}),Eo(he,{disabled:o,onValueChange:n=>t("httpMethod",n),value:e?.httpMethod||"POST",children:[qe(be,{className:"w-full",id:"httpMethod",children:qe(xe,{placeholder:"Select method"})}),Eo(we,{children:[qe(Q,{value:"GET",children:"GET"}),qe(Q,{value:"POST",children:"POST"}),qe(Q,{value:"PUT",children:"PUT"}),qe(Q,{value:"PATCH",children:"PATCH"}),qe(Q,{value:"DELETE",children:"DELETE"})]})]})]}),Eo("div",{className:"space-y-2",children:[qe(L,{htmlFor:"endpoint",children:"URL"}),qe(We,{disabled:o,id:"endpoint",onChange:n=>t("endpoint",n),placeholder:"https://api.example.com/endpoint or {{NodeName.url}}",value:e?.endpoint||""})]}),Eo("div",{className:"space-y-2",children:[qe(L,{htmlFor:"httpHeaders",children:"Headers (JSON)"}),qe("div",{className:"overflow-hidden rounded-md border",children:qe(xt,{defaultLanguage:"json",height:"100px",onChange:n=>t("httpHeaders",n||"{}"),options:{minimap:{enabled:!1},lineNumbers:"off",scrollBeyondLastLine:!1,fontSize:12,readOnly:o,wordWrap:"off"},value:e?.httpHeaders||"{}"})})]}),Eo("div",{className:"space-y-2",children:[qe(L,{htmlFor:"httpBody",children:"Body (JSON)"}),qe("div",{className:`overflow-hidden rounded-md border ${e?.httpMethod==="GET"?"opacity-50":""}`,children:qe(xt,{defaultLanguage:"json",height:"120px",onChange:n=>t("httpBody",n||"{}"),options:{minimap:{enabled:!1},lineNumbers:"off",scrollBeyondLastLine:!1,fontSize:12,readOnly:e?.httpMethod==="GET"||o,domReadOnly:e?.httpMethod==="GET"||o,wordWrap:"off"},value:e?.httpBody||"{}"})}),e?.httpMethod==="GET"&&qe("p",{className:"text-muted-foreground text-xs",children:"Body is disabled for GET requests"})]})]})}import{jsx as hn,jsxs as qa}from"react/jsx-runtime";function qi({config:e,onUpdateConfig:t,disabled:o}){return qa("div",{className:"space-y-4",children:[qa("div",{className:"space-y-2",children:[hn(L,{htmlFor:"items",children:"Items to Iterate"}),hn(We,{disabled:o,id:"items",onChange:n=>t("items",n),placeholder:"e.g., {{PreviousNode.rows}}, {{DatabaseQuery.results}}",value:e?.items||""}),hn("p",{className:"text-muted-foreground text-xs",children:"Reference an array from a previous node. Use @ to reference outputs."})]}),qa("div",{className:"space-y-2",children:[hn(L,{htmlFor:"batchSize",children:"Batch Size (optional)"}),hn(We,{disabled:o,id:"batchSize",onChange:n=>t("batchSize",n),placeholder:"1",value:e?.batchSize||""}),hn("p",{className:"text-muted-foreground text-xs",children:"Number of items per batch. Default is 1 (process one item at a time)."})]})]})}import{Minus as dm,Plus as cm}from"lucide-react";import{Fragment as um,jsx as Se,jsxs as je}from"react/jsx-runtime";function ji({config:e,onUpdateConfig:t,disabled:o}){let n=e?.mode||"append",r=Number(e?.inputCount)||2,s=()=>{t("inputCount",String(r+1))},a=()=>{if(r<=2)return;t(`input${r}`,""),t("inputCount",String(r-1))};return je("div",{className:"space-y-4",children:[je("div",{className:"space-y-2",children:[Se(L,{htmlFor:"mode",children:"Mode"}),je(he,{disabled:o,onValueChange:d=>t("mode",d),value:n,children:[Se(be,{id:"mode",children:Se(xe,{placeholder:"Select mode"})}),je(we,{children:[Se(Q,{value:"append",children:"Append"}),Se(Q,{value:"combineByPosition",children:"Combine by Position"}),Se(Q,{value:"combineByFields",children:"Combine by Fields"})]})]}),je("p",{className:"text-muted-foreground text-xs",children:[n==="append"&&"Concatenate all lists into one.",n==="combineByPosition"&&"Merge items at the same index from all inputs.",n==="combineByFields"&&"Match and merge items based on a common field."]})]}),Array.from({length:r},(d,i)=>je("div",{className:"space-y-2",children:[je(L,{htmlFor:`input${i+1}`,children:["Input ",i+1]}),Se(We,{disabled:o,id:`input${i+1}`,onChange:l=>t(`input${i+1}`,l),placeholder:"e.g., {{Node.rows}}",value:e?.[`input${i+1}`]||""}),i===0&&Se("p",{className:"text-muted-foreground text-xs",children:"Use @ to reference outputs from previous nodes."})]},i)),je("div",{className:"flex gap-2",children:[je(E,{className:"flex-1",disabled:o,onClick:s,type:"button",variant:"outline",children:[Se(cm,{className:"mr-2 size-4"}),"Add Input"]}),Se(E,{disabled:o||r<=2,onClick:a,type:"button",variant:"outline",children:Se(dm,{className:"size-4"})})]}),n==="combineByPosition"&&je("div",{className:"space-y-2",children:[Se(L,{htmlFor:"unmatchedHandling",children:"When arrays have different lengths"}),je(he,{disabled:o,onValueChange:d=>t("unmatchedHandling",d),value:e?.unmatchedHandling||"useNull",children:[Se(be,{id:"unmatchedHandling",children:Se(xe,{})}),je(we,{children:[Se(Q,{value:"useNull",children:"Fill with null"}),Se(Q,{value:"discard",children:"Discard extra items"})]})]})]}),n==="combineByFields"&&je(um,{children:[je("div",{className:"space-y-2",children:[Se(L,{htmlFor:"matchField",children:"Match Field"}),Se(We,{disabled:o,id:"matchField",onChange:d=>t("matchField1",d),placeholder:"e.g., id",value:e?.matchField1||""}),Se("p",{className:"text-muted-foreground text-xs",children:"Field name to match items on across all inputs."})]}),je("div",{className:"space-y-2",children:[Se(L,{htmlFor:"joinType",children:"Join Type"}),je(he,{disabled:o,onValueChange:d=>t("joinType",d),value:e?.joinType||"inner",children:[Se(be,{id:"joinType",children:Se(xe,{})}),je(we,{children:[Se(Q,{value:"inner",children:"Inner Join"}),Se(Q,{value:"leftOuter",children:"Left Outer Join"}),Se(Q,{value:"rightOuter",children:"Right Outer Join"}),Se(Q,{value:"fullOuter",children:"Full Outer Join"})]})]}),Se("p",{className:"text-muted-foreground text-xs",children:"Inner keeps only matches. Left/Right keeps all items from that input. Full keeps everything."})]})]})]})}import{Loader2 as mm}from"lucide-react";import{useEffect as pm,useState as Ji}from"react";import{jsx as Ut,jsxs as Kn}from"react/jsx-runtime";function Yi({config:e,onUpdateConfig:t,disabled:o}){let[n,r]=Ji([]),[s,a]=Ji(!0);pm(()=>{async function i(){try{let l=await fetch("/api/workflow-builder/workflows");if(l.ok){let c=await l.json();r((c.workflows||c||[]).map(u=>({id:u.id,name:u.name})))}}catch{}finally{a(!1)}}i()},[]);let d=e?.workflowId||"";return Kn("div",{className:"space-y-4",children:[Kn("div",{className:"space-y-2",children:[Ut(L,{htmlFor:"workflowId",children:"Workflow"}),s?Kn("div",{className:"flex items-center gap-2 rounded-md border px-3 py-2 text-muted-foreground text-sm",children:[Ut(mm,{className:"size-4 animate-spin"}),"Loading workflows..."]}):Kn(he,{disabled:o||n.length===0,onValueChange:i=>t("workflowId",i),value:d||void 0,children:[Ut(be,{className:"w-full",id:"workflowId",children:Ut(xe,{placeholder:n.length===0?"No workflows found":"Select a workflow"})}),Ut(we,{children:n.map(i=>Ut(Q,{value:i.id,children:i.name},i.id))})]}),Ut("p",{className:"text-muted-foreground text-xs",children:"The workflow to execute. It will run inline and wait for completion."})]}),Kn("div",{className:"space-y-2",children:[Ut(L,{htmlFor:"input",children:"Input (optional JSON)"}),Ut(We,{disabled:o,id:"input",onChange:i=>t("input",i),placeholder:'{"key": "value"} or {{PreviousNode.field}}',value:e?.input||""}),Ut("p",{className:"text-muted-foreground text-xs",children:"Optional JSON passed as trigger input to the sub-workflow."})]})]})}import{ArrowDown as fm,ArrowUp as gm,Loader2 as ym,Plus as vm,Trash2 as hm}from"lucide-react";import{useEffect as bm,useState as Xi}from"react";import{jsx as Le,jsxs as At}from"react/jsx-runtime";function Qi({config:e,onUpdateConfig:t,disabled:o}){let[n,r]=Xi([]),[s,a]=Xi(!0);bm(()=>{async function m(){try{let w=await fetch("/api/workflow-builder/workflows");if(w.ok){let h=await w.json();r((h.workflows||h||[]).map(S=>({id:S.id,name:S.name})))}}catch{}finally{a(!1)}}m()},[]);let d=e?.workflowIds||"[]",i=[];try{let m=JSON.parse(d);Array.isArray(m)&&(i=m)}catch{i=d.split(",").map(m=>m.trim()).filter(Boolean)}let l=m=>{t("workflowIds",JSON.stringify(m))},c=m=>{m&&!i.includes(m)&&l([...i,m])},u=m=>{let w=[...i];w.splice(m,1),l(w)},g=m=>{if(m===0)return;let w=[...i];[w[m-1],w[m]]=[w[m],w[m-1]],l(w)},b=m=>{if(m===i.length-1)return;let w=[...i];[w[m],w[m+1]]=[w[m+1],w[m]],l(w)},y=m=>n.find(w=>w.id===m)?.name||m,v=n.filter(m=>!i.includes(m.id)),p=e?.continueOnFailure||"false";return At("div",{className:"space-y-4",children:[At("div",{className:"space-y-2",children:[Le(L,{children:"Workflows (executed in order)"}),s?At("div",{className:"flex items-center gap-2 rounded-md border px-3 py-2 text-muted-foreground text-sm",children:[Le(ym,{className:"size-4 animate-spin"}),"Loading workflows..."]}):At("div",{className:"space-y-1",children:[i.map((m,w)=>At("div",{className:"flex items-center gap-1 rounded-md border bg-muted/30 px-2 py-1.5 text-sm",children:[At("span",{className:"w-5 shrink-0 text-center text-muted-foreground text-xs",children:[w+1,"."]}),Le("span",{className:"min-w-0 flex-1 truncate",children:y(m)}),Le(E,{className:"size-6",disabled:o||w===0,onClick:()=>g(w),size:"icon",variant:"ghost",children:Le(gm,{className:"size-3"})}),Le(E,{className:"size-6",disabled:o||w===i.length-1,onClick:()=>b(w),size:"icon",variant:"ghost",children:Le(fm,{className:"size-3"})}),Le(E,{className:"size-6 text-destructive hover:text-destructive",disabled:o,onClick:()=>u(w),size:"icon",variant:"ghost",children:Le(hm,{className:"size-3"})})]},`${m}-${w}`)),v.length>0&&At(he,{disabled:o,onValueChange:c,value:"",children:[Le(be,{className:N("w-full",i.length>0&&"border-dashed"),children:At("div",{className:"flex items-center gap-1.5 text-muted-foreground",children:[Le(vm,{className:"size-3.5"}),Le("span",{children:"Add workflow..."})]})}),Le(we,{children:v.map(m=>Le(Q,{value:m.id,children:m.name},m.id))})]}),!s&&n.length===0&&Le("p",{className:"text-muted-foreground text-xs",children:"No workflows found."})]})]}),At("div",{className:"space-y-2",children:[Le(L,{htmlFor:"continueOnFailure",children:"On failure"}),At(he,{disabled:o,onValueChange:m=>t("continueOnFailure",m),value:p,children:[Le(be,{className:"w-full",id:"continueOnFailure",children:Le(xe,{})}),At(we,{children:[Le(Q,{value:"false",children:"Stop sequence"}),Le(Q,{value:"true",children:"Continue with next workflow"})]})]})]}),At("div",{className:"space-y-2",children:[Le(L,{htmlFor:"sequenceInput",children:"Input (optional JSON, passed to all workflows)"}),Le(We,{disabled:o,id:"sequenceInput",onChange:m=>t("input",m),placeholder:'{"key": "value"} or {{PreviousNode.field}}',value:e?.input||""}),Le("p",{className:"text-muted-foreground text-xs",children:"Optional JSON passed as trigger input to every workflow in the sequence."})]})]})}import{Minus as wm,Plus as xm}from"lucide-react";import{jsx as Me,jsxs as Je}from"react/jsx-runtime";function Zi({config:e,onUpdateConfig:t,disabled:o}){let n=e?.mode||"rules",r=e?.matchMode||"first",s=Number(e?.routeCount)||4,a=()=>{t("routeCount",String(s+1))},d=()=>{if(s<=1)return;let i=s-1;t(`routeName${i}`,""),t(`routeCondition${i}`,""),t(`routeCaseValue${i}`,""),t("routeCount",String(s-1))};return Je("div",{className:"space-y-4",children:[Je("div",{className:"space-y-2",children:[Me(L,{htmlFor:"mode",children:"Mode"}),Je(he,{disabled:o,onValueChange:i=>t("mode",i),value:n,children:[Me(be,{id:"mode",children:Me(xe,{placeholder:"Select mode"})}),Je(we,{children:[Me(Q,{value:"rules",children:"Rules"}),Me(Q,{value:"expression",children:"Expression"})]})]}),Je("p",{className:"text-muted-foreground text-xs",children:[n==="rules"&&"Each route has a condition that is evaluated.",n==="expression"&&"Compare a value against each route's case value."]})]}),Je("div",{className:"space-y-2",children:[Me(L,{htmlFor:"matchMode",children:"Match"}),Je(he,{disabled:o,onValueChange:i=>t("matchMode",i),value:r,children:[Me(be,{id:"matchMode",children:Me(xe,{placeholder:"Select match mode"})}),Je(we,{children:[Me(Q,{value:"first",children:"First match"}),Me(Q,{value:"all",children:"All matches"})]})]}),Je("p",{className:"text-muted-foreground text-xs",children:[r==="first"&&"Stop at the first matching route.",r==="all"&&"Execute all routes whose condition is true."]})]}),n==="expression"&&Je("div",{className:"space-y-2",children:[Me(L,{htmlFor:"switchValue",children:"Value to Switch On"}),Me(We,{disabled:o,id:"switchValue",onChange:i=>t("switchValue",i),placeholder:"e.g., {{PreviousNode.statusCode}}",value:e?.switchValue||""}),Me("p",{className:"text-muted-foreground text-xs",children:"The value to compare against each route's case value. Use @ to reference previous node outputs."})]}),Array.from({length:s},(i,l)=>Je("div",{className:"space-y-3 rounded-md border p-3",children:[Je("p",{className:"font-medium text-sm",children:["Route ",l+1]}),Je("div",{className:"space-y-2",children:[Me(L,{htmlFor:`routeName${l}`,children:"Name (optional)"}),Me(ae,{disabled:o,id:`routeName${l}`,onChange:c=>t(`routeName${l}`,c.target.value),placeholder:`Route ${l+1}`,value:e?.[`routeName${l}`]||""})]}),n==="rules"&&Je("div",{className:"space-y-2",children:[Me(L,{htmlFor:`routeCondition${l}`,children:"Condition"}),Me(We,{disabled:o,id:`routeCondition${l}`,onChange:c=>t(`routeCondition${l}`,c),placeholder:"e.g., {{PreviousNode.status}} === 200",value:e?.[`routeCondition${l}`]||""})]}),n==="expression"&&Je("div",{className:"space-y-2",children:[Me(L,{htmlFor:`routeCaseValue${l}`,children:"Case Value"}),Me(We,{disabled:o,id:`routeCaseValue${l}`,onChange:c=>t(`routeCaseValue${l}`,c),placeholder:`e.g., ${l===0?"200":l===1?"404":"500"}`,value:e?.[`routeCaseValue${l}`]||""})]})]},l)),Je("div",{className:"flex gap-2",children:[Je(E,{className:"flex-1",disabled:o,onClick:a,type:"button",variant:"outline",children:[Me(xm,{className:"mr-2 size-4"}),"Add Route"]}),Me(E,{disabled:o||s<=1,onClick:d,type:"button",variant:"outline",children:Me(wm,{className:"size-4"})})]}),Me("p",{className:"text-muted-foreground text-xs",children:'Routes are evaluated in order. If no route matches, the result falls back to "Default".'})]})}import{atom as Hr}from"jotai";var Gr=Hr(null),el=Hr([]),tl=Hr(!1),Sx=Hr(!1);import{useAtomValue as sl,useSetAtom as ja}from"jotai";import{Search as Am}from"lucide-react";import{useCallback as Im,useMemo as Pm,useState as bn}from"react";import{toast as Ro}from"sonner";import{atom as qn,useSetAtom as Nm}from"jotai";import*as nl from"react";var ol=null;var Do=qn(null),$r=qn([]),_r=qn(!1),rl=qn(!1),Yt=qn(null);function al(){let e=Nm(Yt);nl.useEffect(()=>{ol&&e(ol)},[e])}import{Database as km,HelpCircle as Cm}from"lucide-react";import{jsx as jn}from"react/jsx-runtime";function Tm({className:e}){return jn("svg",{className:e,fill:"currentColor",height:"12",viewBox:"0 0 1155 1000",width:"12",xmlns:"http://www.w3.org/2000/svg",children:jn("path",{d:"m577.3 0 577.4 1000H0z"})})}var Sm={database:km,vercel:Tm};function Bt({integration:e,className:t="h-3 w-3"}){let o=Sm[e];if(o)return jn(o,{className:N("text-foreground",t)});let n=Mt(e);if(n?.icon){let r=n.icon;return jn(r,{className:N("text-foreground",t)})}return jn(Cm,{className:N("text-foreground",t)})}import{jsx as $e,jsxs as Nt}from"react/jsx-runtime";var Em=["database"],Dm={database:"Database"},Rm={database:"Connect to PostgreSQL databases"},Om=()=>[...ai(),...Em],Ja=e=>no()[e]||Dm[e]||e,Lm=e=>ri()[e]||Rm[e]||"";function ll({overlayId:e,onSuccess:t}){let{push:o,closeAll:n}=oe(),[r,s]=bn(""),a=_t(),d=sl(Yt),i=sl(Do),l=ja(Do),c=ja($r),u=ja(_r),g=Om(),b=Pm(()=>{if(!r.trim())return g;let p=r.toLowerCase();return g.filter(m=>Ja(m).toLowerCase().includes(p))},[g,r]),y=Im(()=>{d&&o(d.ConsentOverlay,{onConsent:p=>{t?.(p),n()}})},[d,o,n,t]),v=p=>{let m=d?.integrationType===p;if(m&&i?.enabled&&i?.isVercelUser){y();return}if(m&&i===null){d.api.getStatus().then(h=>{l(h),h?.enabled&&h?.isVercelUser?(u(!0),d.api.getTeams().then(S=>{c(S.teams)}).finally(()=>{u(!1),y()})):o(po,{type:p,onSuccess:t})});return}o(po,{type:p,onSuccess:t})};return Nt(Oe,{overlayId:e,title:"Add Connection",children:[$e("p",{className:"-mt-2 mb-4 text-muted-foreground text-sm",children:"Select a service to connect"}),Nt("div",{className:"space-y-3",children:[Nt("div",{className:"relative",children:[$e(Am,{className:"absolute top-1/2 left-3 size-4 -translate-y-1/2 text-muted-foreground"}),$e(ae,{autoFocus:!a,className:"pl-9",onChange:p=>s(p.target.value),placeholder:"Search services...",value:r})]}),$e("div",{className:"max-h-[300px] space-y-1 overflow-y-auto",children:b.length===0?$e("p",{className:"py-4 text-center text-muted-foreground text-sm",children:"No services found"}):b.map(p=>{let m=Lm(p);return Nt("button",{className:"flex w-full items-center gap-3 rounded-md px-3 py-2 text-left text-sm transition-colors hover:bg-muted/50",onClick:()=>v(p),type:"button",children:[$e(Bt,{className:"size-5 shrink-0",integration:p==="ai-gateway"?"vercel":p}),Nt("span",{className:"min-w-0 flex-1 truncate",children:[$e("span",{className:"font-medium",children:Ja(p)}),m&&Nt("span",{className:"text-muted-foreground text-xs",children:[" ","- ",m]})]})]},p)})})]})]})}function il({fieldId:e,label:t,configKey:o,placeholder:n,helpText:r,helpLink:s,value:a,onChange:d}){return Nt("div",{className:"space-y-2",children:[$e(L,{htmlFor:e,children:t}),$e(ae,{className:"flex-1",id:e,onChange:i=>d(o,i.target.value),placeholder:n,type:"password",value:a}),(r||s)&&Nt("p",{className:"text-muted-foreground text-xs",children:[r,s&&$e("a",{className:"underline hover:text-foreground",href:s.url,rel:"noopener noreferrer",target:"_blank",children:s.text})]})]})}function po({overlayId:e,type:t,onSuccess:o}){let{push:n,closeAll:r}=oe(),[s,a]=bn(!1),[d,i]=bn(!1),[l,c]=bn(null),[u,g]=bn(""),[b,y]=bn({}),v=(I,k)=>{y(f=>({...f,[I]:k}))},p=async()=>{try{a(!0);let I=await U.integration.create({name:u.trim(),type:t,config:b});Ro.success("Connection created"),o?.(I.id),r()}catch(I){console.error("Failed to save integration:",I),Ro.error("Failed to save connection")}finally{a(!1)}},m=async()=>{if(!Object.values(b).some(k=>k&&k.length>0)){Ro.error("Please enter credentials");return}try{a(!0),c(null);let k=await U.integration.testCredentials({type:t,config:b});if(k.status==="error"){n(Ee,{title:"Connection Test Failed",message:`The test failed: ${k.message}
3
3
 
4
- Do you want to save anyway?`,confirmLabel:"Save Anyway",onConfirm:async()=>{await y()}}),a(!1);return}await y()}catch(w){let m=w instanceof Error?w.message:"Failed to test connection";n(Ie,{title:"Connection Test Failed",message:`${m}
4
+ Do you want to save anyway?`,confirmLabel:"Save Anyway",onConfirm:async()=>{await p()}}),a(!1);return}await p()}catch(k){let f=k instanceof Error?k.message:"Failed to test connection";n(Ee,{title:"Connection Test Failed",message:`${f}
5
5
 
6
- Do you want to save anyway?`,confirmLabel:"Save Anyway",onConfirm:async()=>{await y()}}),a(!1)}},v=async()=>{if(!Object.values(h).some(w=>w&&w.length>0)){So.error("Please enter credentials first");return}try{i(!0),c(null);let w=await q.integration.testCredentials({type:t,config:h});c(w),w.status==="success"?So.success(w.message||"Connection successful"):So.error(w.message||"Connection failed")}catch(w){let m=w instanceof Error?w.message:"Connection test failed";c({status:"error",message:m}),So.error(m)}finally{i(!1)}},C=Dt(t)?.formFields,I=()=>t==="database"?Ge(ji,{configKey:"url",fieldId:"url",helpText:"Connection string in the format: postgresql://user:password@host:port/database",label:"Database URL",onChange:b,placeholder:"postgresql://user:password@host:port/database",value:h.url||""}):C?C.map(A=>A.type==="password"?Ge(ji,{configKey:A.configKey,fieldId:A.id,helpLink:A.helpLink,helpText:A.helpText,label:A.label,onChange:b,placeholder:A.placeholder,value:h[A.configKey]||""},A.id):vt("div",{className:"space-y-2",children:[Ge(M,{htmlFor:A.id,children:A.label}),Ge(ae,{id:A.id,onChange:w=>b(A.configKey,w.target.value),placeholder:A.placeholder,type:A.type,value:h[A.configKey]||""}),(A.helpText||A.helpLink)&&vt("p",{className:"text-muted-foreground text-xs",children:[A.helpText,A.helpLink&&Ge("a",{className:"underline hover:text-foreground",href:A.helpLink.url,rel:"noopener noreferrer",target:"_blank",children:A.helpLink.text})]})]},A.id)):null;return vt(Re,{actions:[{label:"Test",variant:"outline",onClick:v,loading:d,disabled:s},{label:"Create",onClick:p,loading:s}],overlayId:e,title:`Add ${Ga(t)}`,children:[Ge("p",{className:"-mt-2 mb-4 text-muted-foreground text-sm",children:"Enter your credentials"}),vt("div",{className:"space-y-4",children:[I(),vt("div",{className:"space-y-2",children:[Ge(M,{htmlFor:"name",children:"Label (Optional)"}),Ge(ae,{id:"name",onChange:A=>f(A.target.value),placeholder:"e.g. Production, Personal, Work",value:u})]})]})]})}import{useAtomValue as Yi,useSetAtom as um}from"jotai";import{Loader2 as mm,Sparkles as pm,X as fm}from"lucide-react";import{useCallback as Br,useEffect as gm,useState as Ha}from"react";import{jsx as qe,jsxs as uo}from"react/jsx-runtime";function Xi({overlayId:e,onConsent:t,onManualEntry:o,onDecline:n}){let{pop:r}=oe(),s=um(Wr),[a,d]=Ha(!1),[i,l]=Ha(null),[c,u]=Ha(""),f=Yi(Gi),h=Yi(Hi);gm(()=>{f.length>0&&!c&&u(f[0].id)},[f,c]);let k=Br(g=>{d(!1),t?.(g),r()},[t,r]),b=Br(async()=>{if(!c){l("Please select a team");return}let C=f.find(I=>I.id===c)?.name||"AI Gateway";d(!0),l(null);try{let I=await q.aiGateway.consent(c,C);if(!I.success)throw new Error(I.error||"Failed to set up AI Gateway");let A=I.managedIntegrationId||"";s(w=>w?{...w,hasManagedKey:I.hasManagedKey,managedIntegrationId:A}:null),k(A)}catch(I){l(I instanceof Error?I.message:"An error occurred"),d(!1)}},[c,f,s,k]),y=Br(()=>{n?.(),r()},[n,r]),p=Br(()=>{o?.()},[o]),v=[...o?[{label:"Enter manually",variant:"ghost",onClick:p,disabled:a}]:[],{label:"Cancel",variant:"outline",onClick:y,disabled:a},{label:a?"Setting up...":"Agree & Connect",variant:"default",onClick:b,disabled:a||h&&f.length===0||!c,loading:a}];return qe(Re,{actions:v,description:"Connect your Vercel account to use your own AI Gateway balance",overlayId:e,title:"Use Your AI Gateway Credits",children:uo("div",{className:"space-y-4",children:[uo("div",{className:"flex items-start gap-3",children:[qe("div",{className:"flex size-10 shrink-0 items-center justify-center rounded-full bg-primary/10",children:qe(pm,{className:"size-5 text-primary"})}),qe("p",{className:"pt-2 text-muted-foreground text-sm",children:"This will create an API key on your Vercel account that uses your AI Gateway credits for AI operations in workflows."})]}),uo("div",{className:"space-y-2",children:[qe(M,{htmlFor:"team-select",children:"Vercel Team"}),h&&f.length===0?uo("div",{className:"flex h-10 items-center gap-2 rounded-md border px-3 text-muted-foreground text-sm",children:[qe(mm,{className:"size-4 animate-spin"}),"Loading teams..."]}):uo(ve,{disabled:a,onValueChange:u,value:c,children:[qe(he,{id:"team-select",children:qe(we,{placeholder:"Select a team"})}),qe(be,{children:f.map((g,C)=>uo("div",{children:[qe(te,{value:g.id,children:uo("div",{className:"flex items-center gap-2",children:[g.avatar?qe("img",{alt:"",className:"size-4 rounded-full bg-white",src:g.avatar}):qe("div",{className:"size-4 rounded-full bg-white"}),qe("span",{children:g.name}),g.isPersonal&&qe("span",{className:"text-muted-foreground text-xs",children:"(Personal)"})]})}),g.isPersonal&&C<f.length-1&&qe(Dr,{})]},g.id))})]})]}),i&&uo("div",{className:"flex items-start gap-3 rounded-md border border-red-500/30 bg-red-500/10 p-3",children:[qe(fm,{className:"mt-0.5 size-4 shrink-0 text-red-500"}),qe("p",{className:"text-red-700 text-sm dark:text-red-400",children:i})]})]})})}import{useAtom as Hr,useAtomValue as el,useSetAtom as tl}from"jotai";import{AlertTriangle as km,Check as Ua,Circle as ol,Pencil as Ka,Plus as Cm,Settings as Tm}from"lucide-react";import{useCallback as _n,useEffect as fn,useMemo as Am,useRef as Sm,useState as nl}from"react";import{useAtomValue as vm}from"jotai";import{Check as hm,Pencil as bm,X as wm}from"lucide-react";import{useState as mo}from"react";import{toast as Io}from"sonner";import*as Vr from"@radix-ui/react-checkbox";import{CheckIcon as ym}from"lucide-react";import{jsx as $a}from"react/jsx-runtime";function Qi({className:e,...t}){return $a(Vr.Root,{"data-slot":"checkbox",className:x("peer border-input dark:bg-input/30 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground dark:data-[state=checked]:bg-primary data-[state=checked]:border-primary focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive size-4 shrink-0 rounded-[4px] border shadow-xs transition-shadow outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",e),...t,children:$a(Vr.Indicator,{"data-slot":"checkbox-indicator",className:"grid place-content-center text-current transition-none",children:$a(ym,{className:"size-3.5"})})})}import{jsx as Fe,jsxs as ut}from"react/jsx-runtime";var xm={database:"Database"},Nm=e=>eo()[e]||xm[e]||e;function Zi({fieldId:e,label:t,configKey:o,placeholder:n,helpText:r,helpLink:s,value:a,onChange:d}){let[i,l]=mo(!1),c=Vt(),u=a.length>0;return i||u?ut("div",{className:"space-y-2",children:[Fe(M,{htmlFor:e,children:t}),ut("div",{className:"flex items-center gap-2",children:[Fe(ae,{autoFocus:i&&!c,className:"flex-1",id:e,onChange:f=>d(o,f.target.value),placeholder:n,type:"password",value:a}),(i||u)&&Fe(D,{onClick:()=>{d(o,""),l(!1)},size:"icon",type:"button",variant:"ghost",children:Fe(wm,{className:"size-4"})})]}),(r||s)&&ut("p",{className:"text-muted-foreground text-xs",children:[r,s&&Fe("a",{className:"underline hover:text-foreground",href:s.url,rel:"noopener noreferrer",target:"_blank",children:s.text})]})]}):ut("div",{className:"space-y-2",children:[Fe(M,{htmlFor:e,children:t}),ut("div",{className:"flex items-center gap-2",children:[ut("div",{className:"flex h-9 flex-1 items-center gap-2 rounded-md border bg-muted/30 px-3",children:[Fe(hm,{className:"size-4 text-green-600"}),Fe("span",{className:"text-muted-foreground text-sm",children:"Configured"})]}),ut(D,{onClick:()=>l(!0),type:"button",variant:"outline",children:[Fe(bm,{className:"mr-1.5 size-3"}),"Change"]})]})]})}function Gr({overlayId:e,integration:t,onSuccess:o,onDelete:n}){let{push:r,closeAll:s}=oe(),[a,d]=mo(!1),[i,l]=mo(!1),[c,u]=mo(null),[f,h]=mo(t.name),[k,b]=mo({}),y=(m,S)=>{b(X=>({...X,[m]:S}))},p=async()=>{try{d(!0);let m=Object.values(k).some(S=>S&&S.length>0);await q.integration.update(t.id,{name:f.trim(),...m?{config:k}:{}}),Io.success("Connection updated"),o?.(),s()}catch(m){console.error("Failed to update integration:",m),Io.error("Failed to update connection")}finally{d(!1)}},v=async()=>{if(!Object.values(k).some(S=>S&&S.length>0)){await p();return}try{d(!0),u(null);let S=await q.integration.testCredentials({type:t.type,config:k});if(S.status==="error"){r(Ie,{title:"Connection Test Failed",message:`The test failed: ${S.message}
6
+ Do you want to save anyway?`,confirmLabel:"Save Anyway",onConfirm:async()=>{await p()}}),a(!1)}},w=async()=>{if(!Object.values(b).some(k=>k&&k.length>0)){Ro.error("Please enter credentials first");return}try{i(!0),c(null);let k=await U.integration.testCredentials({type:t,config:b});c(k),k.status==="success"?Ro.success(k.message||"Connection successful"):Ro.error(k.message||"Connection failed")}catch(k){let f=k instanceof Error?k.message:"Connection test failed";c({status:"error",message:f}),Ro.error(f)}finally{i(!1)}},S=Mt(t)?.formFields,D=()=>t==="database"?$e(il,{configKey:"url",fieldId:"url",helpText:"Connection string in the format: postgresql://user:password@host:port/database",label:"Database URL",onChange:v,placeholder:"postgresql://user:password@host:port/database",value:b.url||""}):S?S.map(I=>I.type==="password"?$e(il,{configKey:I.configKey,fieldId:I.id,helpLink:I.helpLink,helpText:I.helpText,label:I.label,onChange:v,placeholder:I.placeholder,value:b[I.configKey]||""},I.id):Nt("div",{className:"space-y-2",children:[$e(L,{htmlFor:I.id,children:I.label}),$e(ae,{id:I.id,onChange:k=>v(I.configKey,k.target.value),placeholder:I.placeholder,type:I.type,value:b[I.configKey]||""}),(I.helpText||I.helpLink)&&Nt("p",{className:"text-muted-foreground text-xs",children:[I.helpText,I.helpLink&&$e("a",{className:"underline hover:text-foreground",href:I.helpLink.url,rel:"noopener noreferrer",target:"_blank",children:I.helpLink.text})]})]},I.id)):null;return Nt(Oe,{actions:[{label:"Test",variant:"outline",onClick:w,loading:d,disabled:s},{label:"Create",onClick:m,loading:s}],overlayId:e,title:`Add ${Ja(t)}`,children:[$e("p",{className:"-mt-2 mb-4 text-muted-foreground text-sm",children:"Enter your credentials"}),Nt("div",{className:"space-y-4",children:[D(),Nt("div",{className:"space-y-2",children:[$e(L,{htmlFor:"name",children:"Label (Optional)"}),$e(ae,{id:"name",onChange:I=>g(I.target.value),placeholder:"e.g. Production, Personal, Work",value:u})]})]})]})}import{useAtomValue as dl,useSetAtom as Mm}from"jotai";import{Loader2 as Wm,Sparkles as Fm,X as zm}from"lucide-react";import{useCallback as Ur,useEffect as Bm,useState as Ya}from"react";import{jsx as Ye,jsxs as fo}from"react/jsx-runtime";function cl({overlayId:e,onConsent:t,onManualEntry:o,onDecline:n}){let{pop:r}=oe(),s=Mm(Gr),[a,d]=Ya(!1),[i,l]=Ya(null),[c,u]=Ya(""),g=dl(el),b=dl(tl);Bm(()=>{g.length>0&&!c&&u(g[0].id)},[g,c]);let y=Ur(h=>{d(!1),t?.(h),r()},[t,r]),v=Ur(async()=>{if(!c){l("Please select a team");return}let S=g.find(D=>D.id===c)?.name||"AI Gateway";d(!0),l(null);try{let D=await U.aiGateway.consent(c,S);if(!D.success)throw new Error(D.error||"Failed to set up AI Gateway");let I=D.managedIntegrationId||"";s(k=>k?{...k,hasManagedKey:D.hasManagedKey,managedIntegrationId:I}:null),y(I)}catch(D){l(D instanceof Error?D.message:"An error occurred"),d(!1)}},[c,g,s,y]),p=Ur(()=>{n?.(),r()},[n,r]),m=Ur(()=>{o?.()},[o]),w=[...o?[{label:"Enter manually",variant:"ghost",onClick:m,disabled:a}]:[],{label:"Cancel",variant:"outline",onClick:p,disabled:a},{label:a?"Setting up...":"Agree & Connect",variant:"default",onClick:v,disabled:a||b&&g.length===0||!c,loading:a}];return Ye(Oe,{actions:w,description:"Connect your Vercel account to use your own AI Gateway balance",overlayId:e,title:"Use Your AI Gateway Credits",children:fo("div",{className:"space-y-4",children:[fo("div",{className:"flex items-start gap-3",children:[Ye("div",{className:"flex size-10 shrink-0 items-center justify-center rounded-full bg-primary/10",children:Ye(Fm,{className:"size-5 text-primary"})}),Ye("p",{className:"pt-2 text-muted-foreground text-sm",children:"This will create an API key on your Vercel account that uses your AI Gateway credits for AI operations in workflows."})]}),fo("div",{className:"space-y-2",children:[Ye(L,{htmlFor:"team-select",children:"Vercel Team"}),b&&g.length===0?fo("div",{className:"flex h-10 items-center gap-2 rounded-md border px-3 text-muted-foreground text-sm",children:[Ye(Wm,{className:"size-4 animate-spin"}),"Loading teams..."]}):fo(he,{disabled:a,onValueChange:u,value:c,children:[Ye(be,{id:"team-select",children:Ye(xe,{placeholder:"Select a team"})}),Ye(we,{children:g.map((h,S)=>fo("div",{children:[Ye(Q,{value:h.id,children:fo("div",{className:"flex items-center gap-2",children:[h.avatar?Ye("img",{alt:"",className:"size-4 rounded-full bg-white",src:h.avatar}):Ye("div",{className:"size-4 rounded-full bg-white"}),Ye("span",{children:h.name}),h.isPersonal&&Ye("span",{className:"text-muted-foreground text-xs",children:"(Personal)"})]})}),h.isPersonal&&S<g.length-1&&Ye(Fr,{})]},h.id))})]})]}),i&&fo("div",{className:"flex items-start gap-3 rounded-md border border-red-500/30 bg-red-500/10 p-3",children:[Ye(zm,{className:"mt-0.5 size-4 shrink-0 text-red-500"}),Ye("p",{className:"text-red-700 text-sm dark:text-red-400",children:i})]})]})})}import{useAtom as jr,useAtomValue as pl,useSetAtom as fl}from"jotai";import{AlertTriangle as qm,Check as Za,Circle as gl,Pencil as es,Plus as jm,Settings as Jm}from"lucide-react";import{useCallback as Jn,useEffect as wn,useMemo as Ym,useRef as Xm,useState as yl}from"react";import{useAtomValue as Hm}from"jotai";import{Check as Gm,Pencil as $m,X as _m}from"lucide-react";import{useState as go}from"react";import{toast as Oo}from"sonner";import*as Kr from"@radix-ui/react-checkbox";import{CheckIcon as Vm}from"lucide-react";import{jsx as Xa}from"react/jsx-runtime";function ul({className:e,...t}){return Xa(Kr.Root,{"data-slot":"checkbox",className:N("peer border-input dark:bg-input/30 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground dark:data-[state=checked]:bg-primary data-[state=checked]:border-primary focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive size-4 shrink-0 rounded-[4px] border shadow-xs transition-shadow outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",e),...t,children:Xa(Kr.Indicator,{"data-slot":"checkbox-indicator",className:"grid place-content-center text-current transition-none",children:Xa(Vm,{className:"size-3.5"})})})}import{jsx as Be,jsxs as gt}from"react/jsx-runtime";var Um={database:"Database"},Km=e=>no()[e]||Um[e]||e;function ml({fieldId:e,label:t,configKey:o,placeholder:n,helpText:r,helpLink:s,value:a,onChange:d}){let[i,l]=go(!1),c=_t(),u=a.length>0;return i||u?gt("div",{className:"space-y-2",children:[Be(L,{htmlFor:e,children:t}),gt("div",{className:"flex items-center gap-2",children:[Be(ae,{autoFocus:i&&!c,className:"flex-1",id:e,onChange:g=>d(o,g.target.value),placeholder:n,type:"password",value:a}),(i||u)&&Be(E,{onClick:()=>{d(o,""),l(!1)},size:"icon",type:"button",variant:"ghost",children:Be(_m,{className:"size-4"})})]}),(r||s)&&gt("p",{className:"text-muted-foreground text-xs",children:[r,s&&Be("a",{className:"underline hover:text-foreground",href:s.url,rel:"noopener noreferrer",target:"_blank",children:s.text})]})]}):gt("div",{className:"space-y-2",children:[Be(L,{htmlFor:e,children:t}),gt("div",{className:"flex items-center gap-2",children:[gt("div",{className:"flex h-9 flex-1 items-center gap-2 rounded-md border bg-muted/30 px-3",children:[Be(Gm,{className:"size-4 text-green-600"}),Be("span",{className:"text-muted-foreground text-sm",children:"Configured"})]}),gt(E,{onClick:()=>l(!0),type:"button",variant:"outline",children:[Be($m,{className:"mr-1.5 size-3"}),"Change"]})]})]})}function qr({overlayId:e,integration:t,onSuccess:o,onDelete:n}){let{push:r,closeAll:s}=oe(),[a,d]=go(!1),[i,l]=go(!1),[c,u]=go(null),[g,b]=go(t.name),[y,v]=go({}),p=(f,x)=>{v(G=>({...G,[f]:x}))},m=async()=>{try{d(!0);let f=Object.values(y).some(x=>x&&x.length>0);await U.integration.update(t.id,{name:g.trim(),...f?{config:y}:{}}),Oo.success("Connection updated"),o?.(),s()}catch(f){console.error("Failed to update integration:",f),Oo.error("Failed to update connection")}finally{d(!1)}},w=async()=>{if(!Object.values(y).some(x=>x&&x.length>0)){await m();return}try{d(!0),u(null);let x=await U.integration.testCredentials({type:t.type,config:y});if(x.status==="error"){r(Ee,{title:"Connection Test Failed",message:`The test failed: ${x.message}
7
7
 
8
- Do you want to save anyway?`,confirmLabel:"Save Anyway",onConfirm:async()=>{await p()}}),d(!1);return}await p()}catch(S){let X=S instanceof Error?S.message:"Failed to test connection";r(Ie,{title:"Connection Test Failed",message:`${X}
8
+ Do you want to save anyway?`,confirmLabel:"Save Anyway",onConfirm:async()=>{await m()}}),d(!1);return}await m()}catch(x){let G=x instanceof Error?x.message:"Failed to test connection";r(Ee,{title:"Connection Test Failed",message:`${G}
9
9
 
10
- Do you want to save anyway?`,confirmLabel:"Save Anyway",onConfirm:async()=>{await p()}}),d(!1)}},g=async()=>{let m=Object.values(k).some(S=>S&&S.length>0);try{l(!0),u(null);let S;m?S=await q.integration.testCredentials({type:t.type,config:k}):S=await q.integration.testConnection(t.id),u(S),S.status==="success"?Io.success(S.message||"Connection successful"):Io.error(S.message||"Connection failed")}catch(S){let X=S instanceof Error?S.message:"Connection test failed";u({status:"error",message:X}),Io.error(X)}finally{l(!1)}},C=()=>{r(_a,{integration:t,onSuccess:()=>{n?.(),s()}})},A=Dt(t.type)?.formFields,w=()=>t.type==="database"?Fe(Zi,{configKey:"url",fieldId:"url",helpText:"Connection string in the format: postgresql://user:password@host:port/database",label:"Database URL",onChange:y,placeholder:"postgresql://user:password@host:port/database",value:k.url||""}):A?A.map(m=>m.type==="password"?Fe(Zi,{configKey:m.configKey,fieldId:m.id,helpLink:m.helpLink,helpText:m.helpText,label:m.label,onChange:y,placeholder:m.placeholder,value:k[m.configKey]||""},m.id):ut("div",{className:"space-y-2",children:[Fe(M,{htmlFor:m.id,children:m.label}),Fe(ae,{id:m.id,onChange:S=>y(m.configKey,S.target.value),placeholder:m.placeholder,type:m.type,value:k[m.configKey]||""}),(m.helpText||m.helpLink)&&ut("p",{className:"text-muted-foreground text-xs",children:[m.helpText,m.helpLink&&Fe("a",{className:"underline hover:text-foreground",href:m.helpLink.url,rel:"noopener noreferrer",target:"_blank",children:m.helpLink.text})]})]},m.id)):null;return ut(Re,{actions:[{label:"Delete",variant:"ghost",onClick:C,disabled:a||i},{label:"Test",variant:"outline",onClick:g,loading:i,disabled:a},{label:"Update",onClick:v,loading:a}],overlayId:e,title:`Edit ${Nm(t.type)}`,children:[Fe("p",{className:"-mt-2 mb-4 text-muted-foreground text-sm",children:"Update your connection credentials"}),ut("div",{className:"space-y-4",children:[w(),ut("div",{className:"space-y-2",children:[Fe(M,{htmlFor:"name",children:"Label (Optional)"}),Fe(ae,{id:"name",onChange:m=>h(m.target.value),placeholder:"e.g. Production, Personal, Work",value:f})]})]})]})}function _a({overlayId:e,integration:t,onSuccess:o}){let{pop:n}=oe(),r=vm(Kt),[s,a]=mo(!1),[d,i]=mo(!0);return ut(Re,{actions:[{label:"Cancel",variant:"outline",onClick:n},{label:"Delete",variant:"destructive",onClick:async()=>{try{a(!0),t.isManaged&&d&&r?await r.api.revokeConsent():await q.integration.delete(t.id),Io.success("Connection deleted"),o?.()}catch(c){console.error("Failed to delete integration:",c),Io.error("Failed to delete connection"),a(!1)}},loading:s}],overlayId:e,title:"Delete Connection",children:[Fe("p",{className:"text-muted-foreground text-sm",children:"Are you sure you want to delete this connection? Workflows using it will fail until a new one is configured."}),t.isManaged&&ut("div",{className:"mt-4 flex items-center gap-2",children:[Fe(Qi,{checked:d,id:"revoke-key",onCheckedChange:c=>i(c)}),Fe(M,{className:"cursor-pointer font-normal",htmlFor:"revoke-key",children:"Revoke API key from Vercel"})]})]})}import{Fragment as qa,jsx as Se,jsxs as Ht}from"react/jsx-runtime";function rl({integrationType:e,value:t,onChange:o,onOpenSettings:n,disabled:r,onAddConnection:s}){let{push:a}=oe(),[d,i]=Hr(ft),l=el(Rt),c=tl(Rt),u=Sm(l),[f,h]=nl(!1),k=el(Kt),[b,y]=Hr(Ao),[p,v]=nl(!1),[g,C]=Hr(Fr),[I,A]=Hr(Ui),w=tl(zr),m=Am(()=>d.filter(N=>N.type===e),[d,e]),S=d.length>0,X=_n(async()=>{try{let N=await q.integration.getAll();i(N),h(!0)}catch(N){console.error("Failed to load integrations:",N)}},[i]);fn(()=>{k?.integrationType===e&&!p&&k.api.getStatus().then(N=>{y(N),v(!0)}).catch(()=>{v(!0)})},[e,p,k,y]),fn(()=>{k?.integrationType===e&&b?.enabled&&b?.isVercelUser&&!I&&(w(!0),k.api.getTeams().then(N=>{C(N.teams),N.teams.length>0&&A(!0)}).catch(()=>{}).finally(()=>{w(!1)}))},[e,k,b,I,C,A,w]),fn(()=>{k?.integrationType===e&&b?.enabled&&b?.isVercelUser&&k.api.getTeams().then(N=>{N.teams.length>0&&(C(N.teams),A(!0))}).catch(()=>{})},[e,k,b?.enabled,b?.isVercelUser]),fn(()=>{X()},[X,e]),fn(()=>{l!==u.current&&(u.current=l,X())},[l,X]),fn(()=>{if(m.length>0&&!r&&!(t&&m.some(R=>R.id===t))){let R=m.find(G=>G.isManaged);o(R?.id||m[0].id)}},[m,t,r,o]);let ie=async N=>{await X(),o(N),c(R=>R+1)},L=async()=>{if(await X(),c(N=>N+1),k?.integrationType===e){let N=await k.api.getStatus();y(N)}},F=_n(()=>{a(co,{type:e,onSuccess:ie})},[e,a,ie]),$=_n(N=>{a(Gr,{integration:N,onSuccess:L,onDelete:L})},[a,L]),P=k?.integrationType===e&&b?.enabled&&b?.isVercelUser&&!b?.hasManagedKey,V=_n(async N=>{if(await X(),o(N),c(R=>R+1),k){let R=await k.api.getStatus();y(R)}},[X,o,c,k,y]),J=_n(()=>{s?s():P&&k?a(k.ConsentOverlay,{onConsent:V,onManualEntry:F}):F()},[s,P,k,a,V,F]);if(!S&&!f)return Se("div",{className:"flex flex-col gap-1",children:Ht("div",{className:"flex items-center gap-2 rounded-md px-2 py-1.5",children:[Se("div",{className:"size-4 shrink-0 animate-pulse rounded-full bg-muted"}),Se("div",{className:"h-4 flex-1 animate-pulse rounded bg-muted"}),Se("div",{className:"size-6 shrink-0 animate-pulse rounded bg-muted"})]})});let K=Dt(e)?.label||e,T=m.filter(N=>N.isManaged),z=m.filter(N=>!N.isManaged);if(m.length===0)return Se(qa,{children:Ht(D,{className:"w-full justify-start gap-2 border-orange-500/50 bg-orange-500/10 text-orange-600 hover:bg-orange-500/20 dark:text-orange-400",disabled:r,onClick:J,variant:"outline",children:[Se(km,{className:"size-4"}),Ht("span",{className:"flex-1 text-left",children:["Add ",K," connection"]}),Se(Cm,{className:"size-4"})]})});if(m.length===1){let N=m[0],R=N.name||`${K} API Key`;return Se(qa,{children:Ht("div",{className:x("flex h-9 w-full items-center gap-2 rounded-md border px-3 text-sm",r&&"cursor-not-allowed opacity-50"),children:[Se(Ua,{className:"size-4 shrink-0 text-green-600"}),Se("span",{className:"flex-1 truncate",children:R}),Se(D,{className:"size-6 shrink-0",disabled:r,onClick:()=>$(N),size:"icon",variant:"ghost",children:Se(Ka,{className:"size-3"})})]})})}return Se(qa,{children:Ht("div",{className:"flex flex-col gap-1",children:[T.map(N=>{let R=t===N.id,G=N.name||`${K} API Key`;return Ht("div",{className:x("flex w-full items-center gap-2 rounded-md px-[13px] py-1.5 text-sm transition-colors",R?"bg-primary/10 text-primary":"hover:bg-muted/50",r&&"cursor-not-allowed opacity-50"),children:[Ht("button",{className:"flex flex-1 items-center gap-2 text-left",disabled:r,onClick:()=>o(N.id),type:"button",children:[R?Se(Ua,{className:"size-4 shrink-0"}):Se(ol,{className:"size-4 shrink-0 text-muted-foreground"}),Se("span",{className:"truncate",children:G})]}),Se(D,{className:"size-6 shrink-0",disabled:r,onClick:ne=>{ne.stopPropagation(),$(N)},size:"icon",variant:"ghost",children:Se(Ka,{className:"size-3"})})]},N.id)}),z.map(N=>{let R=t===N.id,G=N.name||`${K} API Key`;return Ht("div",{className:x("flex w-full items-center gap-2 rounded-md px-[13px] py-1.5 text-sm transition-colors",R?"bg-primary/10 text-primary":"hover:bg-muted/50",r&&"cursor-not-allowed opacity-50"),children:[Ht("button",{className:"flex flex-1 items-center gap-2 text-left",disabled:r,onClick:()=>o(N.id),type:"button",children:[R?Se(Ua,{className:"size-4 shrink-0"}):Se(ol,{className:"size-4 shrink-0 text-muted-foreground"}),Se("span",{className:"truncate",children:G})]}),Se(D,{className:"size-6 shrink-0",disabled:r,onClick:ne=>{ne.stopPropagation(),$(N)},size:"icon",variant:"ghost",children:Se(Ka,{className:"size-3"})})]},N.id)}),n&&Ht("button",{className:"flex w-full items-center gap-2 rounded-md px-[13px] py-1.5 text-muted-foreground text-sm transition-colors hover:bg-muted/50 hover:text-foreground",disabled:r,onClick:n,type:"button",children:[Se(Tm,{className:"size-4 shrink-0"}),Se("span",{children:"Manage all connections"})]})]})})}import*as Ct from"@radix-ui/react-tooltip";import{jsx as gn,jsxs as Im}from"react/jsx-runtime";function yn({delayDuration:e=0,...t}){return gn(Ct.Provider,{"data-slot":"tooltip-provider",delayDuration:e,...t})}function Un({...e}){return gn(yn,{children:gn(Ct.Root,{"data-slot":"tooltip",...e})})}function Kn({...e}){return gn(Ct.Trigger,{"data-slot":"tooltip-trigger",...e})}function qn({className:e,sideOffset:t=0,children:o,...n}){return gn(Ct.Portal,{children:Im(Ct.Content,{"data-slot":"tooltip-content",sideOffset:t,className:x("bg-foreground text-background animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-fit origin-(--radix-tooltip-content-transform-origin) rounded-md px-3 py-1.5 text-xs text-balance",e),...n,children:[o,gn(Ct.Arrow,{className:"bg-foreground fill-foreground z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px]"})]})})}import{ChevronDown as Om}from"lucide-react";import{useState as Lm}from"react";import{useAtom as al}from"jotai";import{useEffect as ja,useRef as Ja,useState as vn}from"react";import{Fragment as Dm,jsx as Ya,jsxs as Rm}from"react/jsx-runtime";function Pm(e,t){let o=e.match(/\{\{@([^:]+):([^}]+)\}\}/);if(!o)return!1;let n=o[1];return t.some(r=>r.id===n)}function Em(e,t){let o=e.match(/\{\{@([^:]+):([^}]+)\}\}/);if(!o)return e;let n=o[1],r=o[2],s=t.find(l=>l.id===n);if(!s)return r;let a=s.data.label;if(!a&&s.data.type==="action"){let l=s.data.config?.actionType;l&&(a=fe(l)?.label)}let d=r.indexOf(".");if(d===-1)return a??r;let i=r.substring(d+1);return a?`${a}.${i}`:r}function sl({value:e="",onChange:t,placeholder:o,disabled:n,className:r,id:s,rows:a=3}){let[d,i]=vn(!1),l=Ja(null),[c,u]=vn(e),f=Ja(!0),[h]=al(ke),[k]=al(re),[b,y]=vn(!1),[p,v]=vn({top:0,left:0}),[g,C]=vn(""),[I,A]=vn(null),w=Ja(null);ja(()=>{e!==c&&!d&&(u(e),f.current=!0)},[e,d,c]),ja(()=>{!d&&c&&(f.current=!0)},[k,d,c]);let m=()=>{if(!l.current)return null;let T=window.getSelection();if(!T||T.rangeCount===0)return console.log("[Textarea] saveCursorPosition: No selection"),null;let z=T.getRangeAt(0),N=z.cloneRange();N.selectNodeContents(l.current),N.setEnd(z.endContainer,z.endOffset),console.log("[Textarea] saveCursorPosition: range.endContainer",z.endContainer,"endOffset",z.endOffset);let R=0,G=document.createTreeWalker(l.current,NodeFilter.SHOW_TEXT|NodeFilter.SHOW_ELEMENT,null),ne,de=!1;for(;(ne=G.nextNode())&&!de;)if(ne.nodeType===Node.TEXT_NODE)if(ne===z.endContainer)R+=z.endOffset,de=!0,console.log("[Textarea] saveCursorPosition: Found cursor in text node, offset:",R);else{let B=(ne.textContent||"").length;R+=B,console.log("[Textarea] saveCursorPosition: Text node before cursor, length:",B)}else if(ne.nodeType===Node.ELEMENT_NODE){let B=ne,Ae=B.getAttribute("data-template");Ae?B.contains(z.endContainer)||B===z.endContainer?(R+=Ae.length,de=!0,console.log("[Textarea] saveCursorPosition: Found cursor in badge, offset:",R)):(R+=Ae.length,console.log("[Textarea] saveCursorPosition: Badge before cursor, length:",Ae.length)):B.tagName==="BR"&&(B===z.endContainer||B.contains(z.endContainer)?de=!0:(R+=1,console.log("[Textarea] saveCursorPosition: BR before cursor")))}return console.log("[Textarea] saveCursorPosition: Final offset:",R),{offset:R}},S=T=>{if(!l.current||!T)return;let z=0,N=document.createTreeWalker(l.current,NodeFilter.SHOW_TEXT|NodeFilter.SHOW_ELEMENT,null),R,G=null,ne=0;for(;R=N.nextNode();)if(R.nodeType===Node.TEXT_NODE){let de=(R.textContent||"").length;if(z+de>=T.offset){G=R,ne=T.offset-z;break}z+=de}else if(R.nodeType===Node.ELEMENT_NODE){let de=R,B=de.getAttribute("data-template");if(B){if(z+B.length>=T.offset){G=de.nextSibling,ne=0,!G&&de.parentNode&&(G=document.createTextNode(""),de.parentNode.appendChild(G));break}z+=B.length}else if(de.tagName==="BR"){if(z+1>=T.offset){G=de.nextSibling,ne=0,!G&&de.parentNode&&(G=document.createTextNode(""),de.parentNode.appendChild(G));break}z+=1}}if(G){let de=document.createRange(),B=window.getSelection();try{de.setStart(G,Math.min(ne,G.textContent?.length||0)),de.collapse(!0),B?.removeAllRanges(),B?.addRange(de),l.current.focus()}catch{l.current.focus()}}},X=()=>{if(!l.current||!f.current)return;let T=l.current,z=c||"",N=d?m():null;if(w.current!==null&&(N={offset:w.current},w.current=null),T.innerHTML="",!z&&!d){T.innerHTML=`<span class="text-muted-foreground pointer-events-none">${o||""}</span>`;return}let R=/\{\{@([^:]+):([^}]+)\}\}/g,G=0,ne;for(;(ne=R.exec(z))!==null;){let[de,,B]=ne,Ae=ne.index;if(Ae>G){let $e=z.slice(G,Ae);ie(T,$e)}let Je=document.createElement("span"),Ye=Pm(de,k);Je.className=Ye?"inline-flex items-center gap-1 rounded bg-blue-500/10 px-1.5 py-0.5 text-blue-600 dark:text-blue-400 font-mono text-xs border border-blue-500/20 mx-0.5":"inline-flex items-center gap-1 rounded bg-red-500/10 px-1.5 py-0.5 text-red-600 dark:text-red-400 font-mono text-xs border border-red-500/20 mx-0.5",Je.contentEditable="false",Je.setAttribute("data-template",de),Je.textContent=Em(de,k),T.appendChild(Je),G=R.lastIndex}if(G<z.length){let de=z.slice(G);ie(T,de)}T.innerHTML===""&&d&&(T.innerHTML="<br>"),f.current=!1,N&&requestAnimationFrame(()=>S(N))},ie=(T,z)=>{let N=z.split(`
11
- `);N.forEach((R,G)=>{R&&T.appendChild(document.createTextNode(R)),G<N.length-1&&T.appendChild(document.createElement("br"))})},L=()=>{if(!l.current)return"";let T="",z=document.createTreeWalker(l.current,NodeFilter.SHOW_TEXT|NodeFilter.SHOW_ELEMENT,null),N;for(;N=z.nextNode();)if(N.nodeType===Node.TEXT_NODE){let R=N.parentElement,G=!1;for(;R&&R!==l.current;){if(R.getAttribute("data-template")){G=!0;break}R=R.parentElement}G?console.log("[Textarea] extractValue: Skipping text inside badge:",N.textContent):(T+=N.textContent,console.log("[Textarea] extractValue: Adding text node:",N.textContent))}else if(N.nodeType===Node.ELEMENT_NODE){let R=N,G=R.getAttribute("data-template");G?(T+=G,console.log("[Textarea] extractValue: Adding template:",G)):R.tagName==="BR"&&(T+=`
12
- `,console.log("[Textarea] extractValue: Adding line break"))}return console.log("[Textarea] extractValue: Final result:",T),T},F=()=>{let T=L();if(console.log("[Textarea] handleInput: newValue:",T),console.log("[Textarea] handleInput: internalValue:",c),console.log("[Textarea] handleInput: DOM innerHTML:",l.current?.innerHTML),T===c){console.log("[Textarea] handleInput: No change detected, ignoring");return}let z=(c.match(/\{\{@([^:]+):([^}]+)\}\}/g)||[]).length,N=(T.match(/\{\{@([^:]+):([^}]+)\}\}/g)||[]).length;if(console.log("[Textarea] handleInput: oldTemplates:",z,"newTemplates:",N),N>z){console.log("[Textarea] handleInput: New template added, rendering badge"),u(T),t?.(T),f.current=!0,y(!1),requestAnimationFrame(()=>X());return}if(N===z&&N>0){console.log("[Textarea] handleInput: Typing around existing badges, NOT updating display"),u(T),t?.(T);let G=T.lastIndexOf("@");if(G!==-1){let ne=T.slice(G+1);if(!ne.includes(" ")&&!ne.includes(`
13
- `)){if(C(ne),A(G),l.current){let de=l.current.getBoundingClientRect(),B={top:de.bottom+window.scrollY+4,left:de.left+window.scrollX};v(B)}y(!0)}else y(!1)}else y(!1);return}if(N<z){console.log("[Textarea] handleInput: Template removed, updating display"),u(T),t?.(T),f.current=!0,requestAnimationFrame(()=>X());return}console.log("[Textarea] handleInput: Normal typing, no badges"),u(T),t?.(T);let R=T.lastIndexOf("@");if(R!==-1){let G=T.slice(R+1);if(!G.includes(" ")&&!G.includes(`
14
- `)){if(C(G),A(R),l.current){let ne=l.current.getBoundingClientRect(),de={top:ne.bottom+window.scrollY+4,left:ne.left+window.scrollX};v(de)}y(!0)}else y(!1)}else y(!1)},$=T=>{if(!l.current||I===null)return;let z=L(),N=z.slice(0,I),R=z.slice(I+1+g.length),G=N+T+R,ne=N.length+T.length;console.log("[Textarea] Autocomplete select:",{currentText:z,atSignPosition:I,filter:g,template:T,beforeAt:N,afterFilter:R,newText:G,targetCursorPosition:ne}),u(G),t?.(G),f.current=!0,y(!1),A(null),w.current=ne,l.current.focus()},P=()=>{i(!0),f.current=!0},V=()=>{setTimeout(()=>{document.activeElement!==l.current&&(i(!1),f.current=!0,y(!1))},200)},J=T=>{T.preventDefault();let z=T.clipboardData.getData("text/plain");document.execCommand("insertText",!1,z)},W=T=>{T.key==="Enter"&&(T.preventDefault(),document.execCommand("insertLineBreak"))};ja(()=>{f.current&&X()},[c,d]);let K=`${a*1.5}rem`;return Rm(Dm,{children:[Ya("div",{className:x("flex w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm transition-colors focus-within:outline-none focus-within:ring-1 focus-within:ring-ring",n&&"cursor-not-allowed opacity-50",r),style:{minHeight:K},children:Ya("div",{className:"w-full outline-none whitespace-pre-wrap break-words",contentEditable:!n,id:s,onBlur:V,onFocus:P,onInput:F,onKeyDown:W,onPaste:J,ref:l,role:"textbox",suppressContentEditableWarning:!0})}),Ya(Lr,{currentNodeId:h||void 0,filter:g,isOpen:b,onClose:()=>y(!1),onSelect:$,position:p})]})}import{Fragment as $m,jsx as Qe,jsxs as jn}from"react/jsx-runtime";function Mm({field:e,value:t,onChange:o,disabled:n}){return Qe(Oe,{disabled:n,id:e.key,onChange:o,placeholder:e.placeholder,value:t})}function Wm({field:e,value:t,onChange:o,disabled:n}){return Qe(sl,{disabled:n,id:e.key,onChange:o,placeholder:e.placeholder,rows:e.rows||4,value:t})}function Fm({field:e,value:t,onChange:o,disabled:n}){return Qe(ae,{disabled:n,id:e.key,onChange:r=>o(r.target.value),placeholder:e.placeholder,value:t})}function zm({field:e,value:t,onChange:o,disabled:n}){return Qe(ae,{disabled:n,id:e.key,min:e.min,onChange:r=>o(r.target.value),placeholder:e.placeholder,type:"number",value:t})}function Bm({field:e,value:t,onChange:o,disabled:n}){return e.options?jn(ve,{disabled:n,onValueChange:o,value:t,children:[Qe(he,{className:"w-full",id:e.key,children:Qe(we,{placeholder:e.placeholder})}),Qe(be,{children:e.options.map(r=>Qe(te,{value:r.value,children:r.label},r.value))})]}):null}function Vm(e){return Qe(lo,{disabled:e.disabled,onChange:t=>e.onChange(JSON.stringify(t)),schema:e.value?JSON.parse(e.value):[]})}var Gm={"template-input":Mm,"template-textarea":Wm,text:Fm,number:zm,select:Bm,"schema-builder":Vm};function il(e,t,o,n){if(e.showWhen&&t[e.showWhen.field]!==e.showWhen.equals)return null;let r=t[e.key]||e.defaultValue||"",s=Gm[e.type];return jn("div",{className:"space-y-2",children:[jn(M,{className:"ml-1",htmlFor:e.key,children:[e.label,e.required&&Qe("span",{className:"text-red-500",children:"*"})]}),Qe(s,{disabled:n,field:e,onChange:a=>o(e.key,a),value:r})]},e.key)}function Hm({label:e,fields:t,config:o,onUpdateConfig:n,disabled:r,defaultExpanded:s=!1}){let[a,d]=Lm(s);return jn("div",{className:"space-y-2",children:[jn("button",{className:"ml-1 flex items-center gap-1 text-left",onClick:()=>d(!a),type:"button",children:[Qe("span",{className:"font-medium text-sm",children:e}),Qe(Om,{className:`h-3.5 w-3.5 text-muted-foreground transition-transform duration-200 ${a?"":"-rotate-90"}`})]}),a&&Qe("div",{className:"ml-1 space-y-4 border-primary/50 border-l-2 py-2 pl-3",children:t.map(i=>il(i,o,n,r))})]})}function ll({fields:e,config:t,onUpdateConfig:o,disabled:n}){return Qe($m,{children:e.map(r=>Qs(r)?Qe(Hm,{config:t,defaultExpanded:r.defaultExpanded,disabled:n,fields:r.fields,label:r.label,onUpdateConfig:o},`group-${r.label}`):il(r,t,o,n))})}import{Fragment as Zm,jsx as pe,jsxs as ht}from"react/jsx-runtime";function Ym({actionType:e,config:t,onUpdateConfig:o,disabled:n}){switch(e){case"HTTP Request":return pe(Oi,{config:t,disabled:n,onUpdateConfig:o});case"Database Query":return pe(Ri,{config:t,disabled:n,onUpdateConfig:o});case"Condition":return pe(Di,{config:t,disabled:n,onUpdateConfig:o});case"Loop":return pe(Li,{config:t,disabled:n,onUpdateConfig:o});case"Merge":return pe(Mi,{config:t,disabled:n,onUpdateConfig:o});case"Switch":return pe(Vi,{config:t,disabled:n,onUpdateConfig:o});case"Run Workflow":return pe(Fi,{config:t,disabled:n,onUpdateConfig:o});case"Run Workflows in Sequence":return pe(Bi,{config:t,disabled:n,onUpdateConfig:o});default:return null}}var ml=[{id:"HTTP Request",label:"HTTP Request"},{id:"Database Query",label:"Database Query"},{id:"Condition",label:"Condition"},{id:"Loop",label:"Loop"},{id:"Merge",label:"Merge"},{id:"Switch",label:"Switch"},{id:"Run Workflow",label:"Run Workflow"},{id:"Run Workflows in Sequence",label:"Run Workflows in Sequence"}],Xa=ml.map(e=>e.id),cl={"Database Query":"database"};function Xm(){return $r(()=>{let e=Js(),t={System:ml};for(let[o,n]of Object.entries(e))t[o]=n.map(r=>({id:r.id,label:r.label}));return t},[])}function ul(e){if(Xa.includes(e))return"System";let t=fe(e);return t?.category?t.category:null}function Qm(e){if(Xa.includes(e))return e;let t=fe(e);return t?t.id:e}function _r({config:e,onUpdateConfig:t,disabled:o,isOwner:n=!0}){let r=e?.actionType||"",s=Xm(),a=$r(()=>qs(),[]),d=r?ul(r):null,[i,l]=Jm(d||""),c=_m(Rt),u=dl(ft),{push:f}=oe(),h=dl(Wr);jm(()=>{let m=r?ul(r):null;l(m||"")},[r]);let k=m=>{l(m);let S=s[m]?.[0];S&&t("actionType",S.id)},b=m=>{t("actionType",m)},y=(m,S)=>{t(m,String(S))},p=r?fe(r):null,v=$r(()=>{if(!r)return;if(cl[r])return cl[r];let S=fe(r)?.integration;if(!(S&&!_o(S)))return S},[r]),g=v==="ai-gateway"&&h?.enabled&&h?.isVercelUser,C=$r(()=>v?u.some(m=>m.type===v):!1,[v,u]),I=m=>{t("integrationId",m),c(S=>S+1)},A=()=>{v&&f(co,{type:v,onSuccess:m=>{c(S=>S+1),t("integrationId",m)}})},w=()=>{g?f(Xi,{onConsent:I,onManualEntry:A}):A()};return ht(Zm,{children:[ht("div",{className:"grid grid-cols-2 gap-2",children:[ht("div",{className:"space-y-2",children:[pe(M,{className:"ml-1",htmlFor:"actionCategory",children:"Service"}),ht(ve,{disabled:o,onValueChange:k,value:i||void 0,children:[pe(he,{className:"w-full",id:"actionCategory",children:pe(we,{placeholder:"Select category"})}),ht(be,{children:[pe(te,{value:"System",children:ht("div",{className:"flex items-center gap-2",children:[pe(qm,{className:"size-4"}),pe("span",{children:"System"})]})}),pe(Dr,{}),a.map(m=>pe(te,{value:m.label,children:ht("div",{className:"flex items-center gap-2",children:[pe(Wt,{className:"size-4",integration:m.type}),pe("span",{children:m.label})]})},m.type))]})]})]}),ht("div",{className:"space-y-2",children:[pe(M,{className:"ml-1",htmlFor:"actionType",children:"Action"}),ht(ve,{disabled:o||!i,onValueChange:b,value:Qm(r)||void 0,children:[pe(he,{className:"w-full",id:"actionType",children:pe(we,{placeholder:"Select action"})}),pe(be,{children:i&&s[i]?.map(m=>pe(te,{value:m.id,children:m.label},m.id))})]})]})]}),v&&n&&ht("div",{className:"space-y-2",children:[ht("div",{className:"ml-1 flex items-center justify-between",children:[ht("div",{className:"flex items-center gap-1",children:[pe(M,{children:"Connection"}),pe(yn,{children:ht(Un,{children:[pe(Kn,{asChild:!0,children:pe(Um,{className:"size-3.5 text-muted-foreground"})}),pe(qn,{children:pe("p",{children:"API key or OAuth credentials for this service"})})]})})]}),C&&pe(D,{className:"size-6",disabled:o,onClick:w,size:"icon",variant:"ghost",children:pe(Km,{className:"size-4"})})]}),pe(rl,{disabled:o,integrationType:v,onChange:m=>t("integrationId",m),value:e?.integrationId||""})]}),pe(Ym,{actionType:e?.actionType||"",config:e,disabled:o,onUpdateConfig:t}),p&&!Xa.includes(r)&&pe(ll,{config:e,disabled:o,fields:p.configFields,onUpdateConfig:y})]})}import{ChevronRight as fp,Eye as wl,EyeOff as xl,Grid3X3 as gp,List as yp,MoreHorizontal as vp,Search as hp,Settings as kl,Zap as Cl}from"lucide-react";import{useEffect as bp,useMemo as Qa,useRef as wp,useState as Yn}from"react";import{Repeat as ep}from"lucide-react";import{jsx as tp}from"react/jsx-runtime";var Ur={id:"Loop",label:"Loop",description:"Loop through a list of items",category:"System",icon:tp(ep,{className:"size-12 text-cyan-300",strokeWidth:1.5}),codeGenerator:`export async function loopStep(input: {
10
+ Do you want to save anyway?`,confirmLabel:"Save Anyway",onConfirm:async()=>{await m()}}),d(!1)}},h=async()=>{let f=Object.values(y).some(x=>x&&x.length>0);try{l(!0),u(null);let x;f?x=await U.integration.testCredentials({type:t.type,config:y}):x=await U.integration.testConnection(t.id),u(x),x.status==="success"?Oo.success(x.message||"Connection successful"):Oo.error(x.message||"Connection failed")}catch(x){let G=x instanceof Error?x.message:"Connection test failed";u({status:"error",message:G}),Oo.error(G)}finally{l(!1)}},S=()=>{r(Qa,{integration:t,onSuccess:()=>{n?.(),s()}})},I=Mt(t.type)?.formFields,k=()=>t.type==="database"?Be(ml,{configKey:"url",fieldId:"url",helpText:"Connection string in the format: postgresql://user:password@host:port/database",label:"Database URL",onChange:p,placeholder:"postgresql://user:password@host:port/database",value:y.url||""}):I?I.map(f=>f.type==="password"?Be(ml,{configKey:f.configKey,fieldId:f.id,helpLink:f.helpLink,helpText:f.helpText,label:f.label,onChange:p,placeholder:f.placeholder,value:y[f.configKey]||""},f.id):gt("div",{className:"space-y-2",children:[Be(L,{htmlFor:f.id,children:f.label}),Be(ae,{id:f.id,onChange:x=>p(f.configKey,x.target.value),placeholder:f.placeholder,type:f.type,value:y[f.configKey]||""}),(f.helpText||f.helpLink)&&gt("p",{className:"text-muted-foreground text-xs",children:[f.helpText,f.helpLink&&Be("a",{className:"underline hover:text-foreground",href:f.helpLink.url,rel:"noopener noreferrer",target:"_blank",children:f.helpLink.text})]})]},f.id)):null;return gt(Oe,{actions:[{label:"Delete",variant:"ghost",onClick:S,disabled:a||i},{label:"Test",variant:"outline",onClick:h,loading:i,disabled:a},{label:"Update",onClick:w,loading:a}],overlayId:e,title:`Edit ${Km(t.type)}`,children:[Be("p",{className:"-mt-2 mb-4 text-muted-foreground text-sm",children:"Update your connection credentials"}),gt("div",{className:"space-y-4",children:[k(),gt("div",{className:"space-y-2",children:[Be(L,{htmlFor:"name",children:"Label (Optional)"}),Be(ae,{id:"name",onChange:f=>b(f.target.value),placeholder:"e.g. Production, Personal, Work",value:g})]})]})]})}function Qa({overlayId:e,integration:t,onSuccess:o}){let{pop:n}=oe(),r=Hm(Yt),[s,a]=go(!1),[d,i]=go(!0);return gt(Oe,{actions:[{label:"Cancel",variant:"outline",onClick:n},{label:"Delete",variant:"destructive",onClick:async()=>{try{a(!0),t.isManaged&&d&&r?await r.api.revokeConsent():await U.integration.delete(t.id),Oo.success("Connection deleted"),o?.()}catch(c){console.error("Failed to delete integration:",c),Oo.error("Failed to delete connection"),a(!1)}},loading:s}],overlayId:e,title:"Delete Connection",children:[Be("p",{className:"text-muted-foreground text-sm",children:"Are you sure you want to delete this connection? Workflows using it will fail until a new one is configured."}),t.isManaged&&gt("div",{className:"mt-4 flex items-center gap-2",children:[Be(ul,{checked:d,id:"revoke-key",onCheckedChange:c=>i(c)}),Be(L,{className:"cursor-pointer font-normal",htmlFor:"revoke-key",children:"Revoke API key from Vercel"})]})]})}import{Fragment as ts,jsx as Pe,jsxs as Kt}from"react/jsx-runtime";function vl({integrationType:e,value:t,onChange:o,onOpenSettings:n,disabled:r,onAddConnection:s}){let{push:a}=oe(),[d,i]=jr(bt),l=pl(Wt),c=fl(Wt),u=Xm(l),[g,b]=yl(!1),y=pl(Yt),[v,p]=jr(Do),[m,w]=yl(!1),[h,S]=jr($r),[D,I]=jr(rl),k=fl(_r),f=Ym(()=>d.filter(C=>C.type===e),[d,e]),x=d.length>0,G=Jn(async()=>{try{let C=await U.integration.getAll();i(C),b(!0)}catch(C){console.error("Failed to load integrations:",C)}},[i]);wn(()=>{y?.integrationType===e&&!m&&y.api.getStatus().then(C=>{p(C),w(!0)}).catch(()=>{w(!0)})},[e,m,y,p]),wn(()=>{y?.integrationType===e&&v?.enabled&&v?.isVercelUser&&!D&&(k(!0),y.api.getTeams().then(C=>{S(C.teams),C.teams.length>0&&I(!0)}).catch(()=>{}).finally(()=>{k(!1)}))},[e,y,v,D,S,I,k]),wn(()=>{y?.integrationType===e&&v?.enabled&&v?.isVercelUser&&y.api.getTeams().then(C=>{C.teams.length>0&&(S(C.teams),I(!0))}).catch(()=>{})},[e,y,v?.enabled,v?.isVercelUser]),wn(()=>{G()},[G,e]),wn(()=>{l!==u.current&&(u.current=l,G())},[l,G]),wn(()=>{if(f.length>0&&!r&&!(t&&f.some(R=>R.id===t))){let R=f.find(_=>_.isManaged);o(R?.id||f[0].id)}},[f,t,r,o]);let te=async C=>{await G(),o(C),c(R=>R+1)},O=async()=>{if(await G(),c(C=>C+1),y?.integrationType===e){let C=await y.api.getStatus();p(C)}},W=Jn(()=>{a(po,{type:e,onSuccess:te})},[e,a,te]),$=Jn(C=>{a(qr,{integration:C,onSuccess:O,onDelete:O})},[a,O]),T=y?.integrationType===e&&v?.enabled&&v?.isVercelUser&&!v?.hasManagedKey,H=Jn(async C=>{if(await G(),o(C),c(R=>R+1),y){let R=await y.api.getStatus();p(R)}},[G,o,c,y,p]),X=Jn(()=>{s?s():T&&y?a(y.ConsentOverlay,{onConsent:H,onManualEntry:W}):W()},[s,T,y,a,H,W]);if(!x&&!g)return Pe("div",{className:"flex flex-col gap-1",children:Kt("div",{className:"flex items-center gap-2 rounded-md px-2 py-1.5",children:[Pe("div",{className:"size-4 shrink-0 animate-pulse rounded-full bg-muted"}),Pe("div",{className:"h-4 flex-1 animate-pulse rounded bg-muted"}),Pe("div",{className:"size-6 shrink-0 animate-pulse rounded bg-muted"})]})});let j=Mt(e)?.label||e,A=f.filter(C=>C.isManaged),B=f.filter(C=>!C.isManaged);if(f.length===0)return Pe(ts,{children:Kt(E,{className:"w-full justify-start gap-2 border-orange-500/50 bg-orange-500/10 text-orange-600 hover:bg-orange-500/20 dark:text-orange-400",disabled:r,onClick:X,variant:"outline",children:[Pe(qm,{className:"size-4"}),Kt("span",{className:"flex-1 text-left",children:["Add ",j," connection"]}),Pe(jm,{className:"size-4"})]})});if(f.length===1){let C=f[0],R=C.name||`${j} API Key`;return Pe(ts,{children:Kt("div",{className:N("flex h-9 w-full items-center gap-2 rounded-md border px-3 text-sm",r&&"cursor-not-allowed opacity-50"),children:[Pe(Za,{className:"size-4 shrink-0 text-green-600"}),Pe("span",{className:"flex-1 truncate",children:R}),Pe(E,{className:"size-6 shrink-0",disabled:r,onClick:()=>$(C),size:"icon",variant:"ghost",children:Pe(es,{className:"size-3"})})]})})}return Pe(ts,{children:Kt("div",{className:"flex flex-col gap-1",children:[A.map(C=>{let R=t===C.id,_=C.name||`${j} API Key`;return Kt("div",{className:N("flex w-full items-center gap-2 rounded-md px-[13px] py-1.5 text-sm transition-colors",R?"bg-primary/10 text-primary":"hover:bg-muted/50",r&&"cursor-not-allowed opacity-50"),children:[Kt("button",{className:"flex flex-1 items-center gap-2 text-left",disabled:r,onClick:()=>o(C.id),type:"button",children:[R?Pe(Za,{className:"size-4 shrink-0"}):Pe(gl,{className:"size-4 shrink-0 text-muted-foreground"}),Pe("span",{className:"truncate",children:_})]}),Pe(E,{className:"size-6 shrink-0",disabled:r,onClick:ne=>{ne.stopPropagation(),$(C)},size:"icon",variant:"ghost",children:Pe(es,{className:"size-3"})})]},C.id)}),B.map(C=>{let R=t===C.id,_=C.name||`${j} API Key`;return Kt("div",{className:N("flex w-full items-center gap-2 rounded-md px-[13px] py-1.5 text-sm transition-colors",R?"bg-primary/10 text-primary":"hover:bg-muted/50",r&&"cursor-not-allowed opacity-50"),children:[Kt("button",{className:"flex flex-1 items-center gap-2 text-left",disabled:r,onClick:()=>o(C.id),type:"button",children:[R?Pe(Za,{className:"size-4 shrink-0"}):Pe(gl,{className:"size-4 shrink-0 text-muted-foreground"}),Pe("span",{className:"truncate",children:_})]}),Pe(E,{className:"size-6 shrink-0",disabled:r,onClick:ne=>{ne.stopPropagation(),$(C)},size:"icon",variant:"ghost",children:Pe(es,{className:"size-3"})})]},C.id)}),n&&Kt("button",{className:"flex w-full items-center gap-2 rounded-md px-[13px] py-1.5 text-muted-foreground text-sm transition-colors hover:bg-muted/50 hover:text-foreground",disabled:r,onClick:n,type:"button",children:[Pe(Jm,{className:"size-4 shrink-0"}),Pe("span",{children:"Manage all connections"})]})]})})}import*as It from"@radix-ui/react-tooltip";import{jsx as xn,jsxs as Qm}from"react/jsx-runtime";function Nn({delayDuration:e=0,...t}){return xn(It.Provider,{"data-slot":"tooltip-provider",delayDuration:e,...t})}function Yn({...e}){return xn(Nn,{children:xn(It.Root,{"data-slot":"tooltip",...e})})}function Xn({...e}){return xn(It.Trigger,{"data-slot":"tooltip-trigger",...e})}function Qn({className:e,sideOffset:t=0,children:o,...n}){return xn(It.Portal,{children:Qm(It.Content,{"data-slot":"tooltip-content",sideOffset:t,className:N("bg-foreground text-background animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-fit origin-(--radix-tooltip-content-transform-origin) rounded-md px-3 py-1.5 text-xs text-balance",e),...n,children:[o,xn(It.Arrow,{className:"bg-foreground fill-foreground z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px]"})]})})}import{ChevronDown as np}from"lucide-react";import{useState as rp}from"react";import{useAtom as hl}from"jotai";import{useEffect as os,useRef as ns,useState as kn}from"react";import{Fragment as tp,jsx as rs,jsxs as op}from"react/jsx-runtime";function Zm(e,t){let o=e.match(/\{\{@([^:]+):([^}]+)\}\}/);if(!o)return!1;let n=o[1];return t.some(r=>r.id===n)}function ep(e,t){let o=e.match(/\{\{@([^:]+):([^}]+)\}\}/);if(!o)return e;let n=o[1],r=o[2],s=t.find(l=>l.id===n);if(!s)return r;let a=s.data.label;if(!a&&s.data.type==="action"){let l=s.data.config?.actionType;l&&(a=ye(l)?.label)}let d=r.indexOf(".");if(d===-1)return a??r;let i=r.substring(d+1);return a?`${a}.${i}`:r}function bl({value:e="",onChange:t,placeholder:o,disabled:n,className:r,id:s,rows:a=3}){let[d,i]=kn(!1),l=ns(null),[c,u]=kn(e),g=ns(!0),[b]=hl(Te),[y]=hl(re),[v,p]=kn(!1),[m,w]=kn({top:0,left:0}),[h,S]=kn(""),[D,I]=kn(null),k=ns(null);os(()=>{e!==c&&!d&&(u(e),g.current=!0)},[e,d,c]),os(()=>{!d&&c&&(g.current=!0)},[y,d,c]);let f=()=>{if(!l.current)return null;let A=window.getSelection();if(!A||A.rangeCount===0)return console.log("[Textarea] saveCursorPosition: No selection"),null;let B=A.getRangeAt(0),C=B.cloneRange();C.selectNodeContents(l.current),C.setEnd(B.endContainer,B.endOffset),console.log("[Textarea] saveCursorPosition: range.endContainer",B.endContainer,"endOffset",B.endOffset);let R=0,_=document.createTreeWalker(l.current,NodeFilter.SHOW_TEXT|NodeFilter.SHOW_ELEMENT,null),ne,de=!1;for(;(ne=_.nextNode())&&!de;)if(ne.nodeType===Node.TEXT_NODE)if(ne===B.endContainer)R+=B.endOffset,de=!0,console.log("[Textarea] saveCursorPosition: Found cursor in text node, offset:",R);else{let V=(ne.textContent||"").length;R+=V,console.log("[Textarea] saveCursorPosition: Text node before cursor, length:",V)}else if(ne.nodeType===Node.ELEMENT_NODE){let V=ne,Ie=V.getAttribute("data-template");Ie?V.contains(B.endContainer)||V===B.endContainer?(R+=Ie.length,de=!0,console.log("[Textarea] saveCursorPosition: Found cursor in badge, offset:",R)):(R+=Ie.length,console.log("[Textarea] saveCursorPosition: Badge before cursor, length:",Ie.length)):V.tagName==="BR"&&(V===B.endContainer||V.contains(B.endContainer)?de=!0:(R+=1,console.log("[Textarea] saveCursorPosition: BR before cursor")))}return console.log("[Textarea] saveCursorPosition: Final offset:",R),{offset:R}},x=A=>{if(!l.current||!A)return;let B=0,C=document.createTreeWalker(l.current,NodeFilter.SHOW_TEXT|NodeFilter.SHOW_ELEMENT,null),R,_=null,ne=0;for(;R=C.nextNode();)if(R.nodeType===Node.TEXT_NODE){let de=(R.textContent||"").length;if(B+de>=A.offset){_=R,ne=A.offset-B;break}B+=de}else if(R.nodeType===Node.ELEMENT_NODE){let de=R,V=de.getAttribute("data-template");if(V){if(B+V.length>=A.offset){_=de.nextSibling,ne=0,!_&&de.parentNode&&(_=document.createTextNode(""),de.parentNode.appendChild(_));break}B+=V.length}else if(de.tagName==="BR"){if(B+1>=A.offset){_=de.nextSibling,ne=0,!_&&de.parentNode&&(_=document.createTextNode(""),de.parentNode.appendChild(_));break}B+=1}}if(_){let de=document.createRange(),V=window.getSelection();try{de.setStart(_,Math.min(ne,_.textContent?.length||0)),de.collapse(!0),V?.removeAllRanges(),V?.addRange(de),l.current.focus()}catch{l.current.focus()}}},G=()=>{if(!l.current||!g.current)return;let A=l.current,B=c||"",C=d?f():null;if(k.current!==null&&(C={offset:k.current},k.current=null),A.innerHTML="",!B&&!d){A.innerHTML=`<span class="text-muted-foreground pointer-events-none">${o||""}</span>`;return}let R=/\{\{@([^:]+):([^}]+)\}\}/g,_=0,ne;for(;(ne=R.exec(B))!==null;){let[de,,V]=ne,Ie=ne.index;if(Ie>_){let rt=B.slice(_,Ie);te(A,rt)}let nt=document.createElement("span"),Qe=Zm(de,y);nt.className=Qe?"inline-flex items-center gap-1 rounded bg-blue-500/10 px-1.5 py-0.5 text-blue-600 dark:text-blue-400 font-mono text-xs border border-blue-500/20 mx-0.5":"inline-flex items-center gap-1 rounded bg-red-500/10 px-1.5 py-0.5 text-red-600 dark:text-red-400 font-mono text-xs border border-red-500/20 mx-0.5",nt.contentEditable="false",nt.setAttribute("data-template",de),nt.textContent=ep(de,y),A.appendChild(nt),_=R.lastIndex}if(_<B.length){let de=B.slice(_);te(A,de)}A.innerHTML===""&&d&&(A.innerHTML="<br>"),g.current=!1,C&&requestAnimationFrame(()=>x(C))},te=(A,B)=>{let C=B.split(`
11
+ `);C.forEach((R,_)=>{R&&A.appendChild(document.createTextNode(R)),_<C.length-1&&A.appendChild(document.createElement("br"))})},O=()=>{if(!l.current)return"";let A="",B=document.createTreeWalker(l.current,NodeFilter.SHOW_TEXT|NodeFilter.SHOW_ELEMENT,null),C;for(;C=B.nextNode();)if(C.nodeType===Node.TEXT_NODE){let R=C.parentElement,_=!1;for(;R&&R!==l.current;){if(R.getAttribute("data-template")){_=!0;break}R=R.parentElement}_?console.log("[Textarea] extractValue: Skipping text inside badge:",C.textContent):(A+=C.textContent,console.log("[Textarea] extractValue: Adding text node:",C.textContent))}else if(C.nodeType===Node.ELEMENT_NODE){let R=C,_=R.getAttribute("data-template");_?(A+=_,console.log("[Textarea] extractValue: Adding template:",_)):R.tagName==="BR"&&(A+=`
12
+ `,console.log("[Textarea] extractValue: Adding line break"))}return console.log("[Textarea] extractValue: Final result:",A),A},W=()=>{let A=O();if(console.log("[Textarea] handleInput: newValue:",A),console.log("[Textarea] handleInput: internalValue:",c),console.log("[Textarea] handleInput: DOM innerHTML:",l.current?.innerHTML),A===c){console.log("[Textarea] handleInput: No change detected, ignoring");return}let B=(c.match(/\{\{@([^:]+):([^}]+)\}\}/g)||[]).length,C=(A.match(/\{\{@([^:]+):([^}]+)\}\}/g)||[]).length;if(console.log("[Textarea] handleInput: oldTemplates:",B,"newTemplates:",C),C>B){console.log("[Textarea] handleInput: New template added, rendering badge"),u(A),t?.(A),g.current=!0,p(!1),requestAnimationFrame(()=>G());return}if(C===B&&C>0){console.log("[Textarea] handleInput: Typing around existing badges, NOT updating display"),u(A),t?.(A);let _=A.lastIndexOf("@");if(_!==-1){let ne=A.slice(_+1);if(!ne.includes(" ")&&!ne.includes(`
13
+ `)){if(S(ne),I(_),l.current){let de=l.current.getBoundingClientRect(),V={top:de.bottom+window.scrollY+4,left:de.left+window.scrollX};w(V)}p(!0)}else p(!1)}else p(!1);return}if(C<B){console.log("[Textarea] handleInput: Template removed, updating display"),u(A),t?.(A),g.current=!0,requestAnimationFrame(()=>G());return}console.log("[Textarea] handleInput: Normal typing, no badges"),u(A),t?.(A);let R=A.lastIndexOf("@");if(R!==-1){let _=A.slice(R+1);if(!_.includes(" ")&&!_.includes(`
14
+ `)){if(S(_),I(R),l.current){let ne=l.current.getBoundingClientRect(),de={top:ne.bottom+window.scrollY+4,left:ne.left+window.scrollX};w(de)}p(!0)}else p(!1)}else p(!1)},$=A=>{if(!l.current||D===null)return;let B=O(),C=B.slice(0,D),R=B.slice(D+1+h.length),_=C+A+R,ne=C.length+A.length;console.log("[Textarea] Autocomplete select:",{currentText:B,atSignPosition:D,filter:h,template:A,beforeAt:C,afterFilter:R,newText:_,targetCursorPosition:ne}),u(_),t?.(_),g.current=!0,p(!1),I(null),k.current=ne,l.current.focus()},T=()=>{i(!0),g.current=!0},H=()=>{setTimeout(()=>{document.activeElement!==l.current&&(i(!1),g.current=!0,p(!1))},200)},X=A=>{A.preventDefault();let B=A.clipboardData.getData("text/plain");document.execCommand("insertText",!1,B)},z=A=>{A.key==="Enter"&&(A.preventDefault(),document.execCommand("insertLineBreak"))};os(()=>{g.current&&G()},[c,d]);let j=`${a*1.5}rem`;return op(tp,{children:[rs("div",{className:N("flex w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm transition-colors focus-within:outline-none focus-within:ring-1 focus-within:ring-ring",n&&"cursor-not-allowed opacity-50",r),style:{minHeight:j},children:rs("div",{className:"w-full outline-none whitespace-pre-wrap break-words",contentEditable:!n,id:s,onBlur:H,onFocus:T,onInput:W,onKeyDown:z,onPaste:X,ref:l,role:"textbox",suppressContentEditableWarning:!0})}),rs(Vr,{currentNodeId:b||void 0,filter:h,isOpen:v,onClose:()=>p(!1),onSelect:$,position:m})]})}import{Fragment as pp,jsx as Ze,jsxs as Zn}from"react/jsx-runtime";function ap({field:e,value:t,onChange:o,disabled:n}){return Ze(We,{disabled:n,id:e.key,onChange:o,placeholder:e.placeholder,value:t})}function sp({field:e,value:t,onChange:o,disabled:n}){return Ze(bl,{disabled:n,id:e.key,onChange:o,placeholder:e.placeholder,rows:e.rows||4,value:t})}function ip({field:e,value:t,onChange:o,disabled:n}){return Ze(ae,{disabled:n,id:e.key,onChange:r=>o(r.target.value),placeholder:e.placeholder,value:t})}function lp({field:e,value:t,onChange:o,disabled:n}){return Ze(ae,{disabled:n,id:e.key,min:e.min,onChange:r=>o(r.target.value),placeholder:e.placeholder,type:"number",value:t})}function dp({field:e,value:t,onChange:o,disabled:n}){return e.options?Zn(he,{disabled:n,onValueChange:o,value:t,children:[Ze(be,{className:"w-full",id:e.key,children:Ze(xe,{placeholder:e.placeholder})}),Ze(we,{children:e.options.map(r=>Ze(Q,{value:r.value,children:r.label},r.value))})]}):null}function cp(e){return Ze(mo,{disabled:e.disabled,onChange:t=>e.onChange(JSON.stringify(t)),schema:e.value?JSON.parse(e.value):[]})}var up={"template-input":ap,"template-textarea":sp,text:ip,number:lp,select:dp,"schema-builder":cp};function wl(e,t,o,n){if(e.showWhen&&t[e.showWhen.field]!==e.showWhen.equals)return null;let r=t[e.key]||e.defaultValue||"",s=up[e.type];return Zn("div",{className:"space-y-2",children:[Zn(L,{className:"ml-1",htmlFor:e.key,children:[e.label,e.required&&Ze("span",{className:"text-red-500",children:"*"})]}),Ze(s,{disabled:n,field:e,onChange:a=>o(e.key,a),value:r})]},e.key)}function mp({label:e,fields:t,config:o,onUpdateConfig:n,disabled:r,defaultExpanded:s=!1}){let[a,d]=rp(s);return Zn("div",{className:"space-y-2",children:[Zn("button",{className:"ml-1 flex items-center gap-1 text-left",onClick:()=>d(!a),type:"button",children:[Ze("span",{className:"font-medium text-sm",children:e}),Ze(np,{className:`h-3.5 w-3.5 text-muted-foreground transition-transform duration-200 ${a?"":"-rotate-90"}`})]}),a&&Ze("div",{className:"ml-1 space-y-4 border-primary/50 border-l-2 py-2 pl-3",children:t.map(i=>wl(i,o,n,r))})]})}function xl({fields:e,config:t,onUpdateConfig:o,disabled:n}){return Ze(pp,{children:e.map(r=>si(r)?Ze(mp,{config:t,defaultExpanded:r.defaultExpanded,disabled:n,fields:r.fields,label:r.label,onUpdateConfig:o},`group-${r.label}`):wl(r,t,o,n))})}import{Fragment as kp,jsx as ge,jsxs as kt}from"react/jsx-runtime";function wp({actionType:e,config:t,onUpdateConfig:o,onUpdateMultipleConfig:n,disabled:r}){switch(e){case"HTTP Request":return ge(Ki,{config:t,disabled:r,onUpdateConfig:o});case"Database Query":return ge(Ui,{config:t,disabled:r,onUpdateConfig:o});case"Condition":return ge(Gi,{config:t,disabled:r,onUpdateConfig:o,onUpdateMultipleConfig:n});case"Loop":return ge(qi,{config:t,disabled:r,onUpdateConfig:o});case"Merge":return ge(ji,{config:t,disabled:r,onUpdateConfig:o});case"Switch":return ge(Zi,{config:t,disabled:r,onUpdateConfig:o});case"Run Workflow":return ge(Yi,{config:t,disabled:r,onUpdateConfig:o});case"Run Workflows in Sequence":return ge(Qi,{config:t,disabled:r,onUpdateConfig:o});default:return null}}var Tl=[{id:"HTTP Request",label:"HTTP Request"},{id:"Database Query",label:"Database Query"},{id:"Condition",label:"Condition"},{id:"Loop",label:"Loop"},{id:"Merge",label:"Merge"},{id:"Switch",label:"Switch"},{id:"Run Workflow",label:"Run Workflow"},{id:"Run Workflows in Sequence",label:"Run Workflows in Sequence"}],as=Tl.map(e=>e.id),kl={"Database Query":"database"};function xp(){return Jr(()=>{let e=ni(),t={System:Tl};for(let[o,n]of Object.entries(e))t[o]=n.map(r=>({id:r.id,label:r.label}));return t},[])}function Cl(e){if(as.includes(e))return"System";let t=ye(e);return t?.category?t.category:null}function Np(e){if(as.includes(e))return e;let t=ye(e);return t?t.id:e}function Yr({config:e,onUpdateConfig:t,onUpdateMultipleConfig:o,disabled:n,isOwner:r=!0}){let s=e?.actionType||"",a=xp(),d=Jr(()=>ti(),[]),i=s?Cl(s):null,[l,c]=bp(i||""),u=fp(Wt),g=Nl(bt),{push:b}=oe(),y=Nl(Gr);hp(()=>{let x=s?Cl(s):null;c(x||"")},[s]);let v=x=>{c(x);let G=a[x]?.[0];G&&t("actionType",G.id)},p=x=>{t("actionType",x)},m=(x,G)=>{t(x,String(G))},w=s?ye(s):null,h=Jr(()=>{if(!s)return;if(kl[s])return kl[s];let G=ye(s)?.integration;if(!(G&&!Jo(G)))return G},[s]),S=h==="ai-gateway"&&y?.enabled&&y?.isVercelUser,D=Jr(()=>h?g.some(x=>x.type===h):!1,[h,g]),I=x=>{t("integrationId",x),u(G=>G+1)},k=()=>{h&&b(po,{type:h,onSuccess:x=>{u(G=>G+1),t("integrationId",x)}})},f=()=>{S?b(cl,{onConsent:I,onManualEntry:k}):k()};return kt(kp,{children:[kt("div",{className:"grid grid-cols-2 gap-2",children:[kt("div",{className:"space-y-2",children:[ge(L,{className:"ml-1",htmlFor:"actionCategory",children:"Service"}),kt(he,{disabled:n,onValueChange:v,value:l||void 0,children:[ge(be,{className:"w-full",id:"actionCategory",children:ge(xe,{placeholder:"Select category"})}),kt(we,{children:[ge(Q,{value:"System",children:kt("div",{className:"flex items-center gap-2",children:[ge(vp,{className:"size-4"}),ge("span",{children:"System"})]})}),ge(Fr,{}),d.map(x=>ge(Q,{value:x.label,children:kt("div",{className:"flex items-center gap-2",children:[ge(Bt,{className:"size-4",integration:x.type}),ge("span",{children:x.label})]})},x.type))]})]})]}),kt("div",{className:"space-y-2",children:[ge(L,{className:"ml-1",htmlFor:"actionType",children:"Action"}),kt(he,{disabled:n||!l,onValueChange:p,value:Np(s)||void 0,children:[ge(be,{className:"w-full",id:"actionType",children:ge(xe,{placeholder:"Select action"})}),ge(we,{children:l&&a[l]?.map(x=>ge(Q,{value:x.id,children:x.label},x.id))})]})]})]}),h&&r&&kt("div",{className:"space-y-2",children:[kt("div",{className:"ml-1 flex items-center justify-between",children:[kt("div",{className:"flex items-center gap-1",children:[ge(L,{children:"Connection"}),ge(Nn,{children:kt(Yn,{children:[ge(Xn,{asChild:!0,children:ge(gp,{className:"size-3.5 text-muted-foreground"})}),ge(Qn,{children:ge("p",{children:"API key or OAuth credentials for this service"})})]})})]}),D&&ge(E,{className:"size-6",disabled:n,onClick:f,size:"icon",variant:"ghost",children:ge(yp,{className:"size-4"})})]}),ge(vl,{disabled:n,integrationType:h,onChange:x=>t("integrationId",x),value:e?.integrationId||""})]}),ge(wp,{actionType:e?.actionType||"",config:e,disabled:n,onUpdateConfig:t,onUpdateMultipleConfig:o}),w&&!as.includes(s)&&ge(xl,{config:e,disabled:n,fields:w.configFields,onUpdateConfig:m})]})}import{ChevronRight as zp,Eye as Ol,EyeOff as Ll,Grid3X3 as Bp,List as Vp,MoreHorizontal as Hp,Search as Gp,Settings as Wl,Zap as Fl}from"lucide-react";import{useEffect as $p,useMemo as ss,useRef as _p,useState as tr}from"react";import{Repeat as Cp}from"lucide-react";import{jsx as Tp}from"react/jsx-runtime";var Xr={id:"Loop",label:"Loop",description:"Loop through a list of items",category:"System",icon:Tp(Cp,{className:"size-12 text-cyan-300",strokeWidth:1.5}),codeGenerator:`export async function loopStep(input: {
15
15
  items: unknown[];
16
16
  batchSize?: number;
17
17
  currentBatchIndex?: number;
@@ -39,89 +39,88 @@ Do you want to save anyway?`,confirmLabel:"Save Anyway",onConfirm:async()=>{awai
39
39
  items,
40
40
  batchSize,
41
41
  };
42
- }`};import{Merge as op}from"lucide-react";import{jsx as np}from"react/jsx-runtime";var Kr={id:"Merge",label:"Merge",description:"Combine data from two inputs",category:"System",icon:np(op,{className:"size-12 text-orange-300",strokeWidth:1.5}),codeGenerator:`export async function mergeStep(input: {
43
- input1: unknown[];
44
- input2: unknown[];
42
+ }`};import{Merge as Sp}from"lucide-react";import{jsx as Ap}from"react/jsx-runtime";var Cn={id:"Merge",label:"Merge",description:"Combine data from multiple inputs",category:"System",icon:Ap(Sp,{className:"size-12 text-orange-300",strokeWidth:1.5}),codeGenerator:`export async function mergeStep(input: {
43
+ inputCount?: number;
44
+ [key: string]: unknown;
45
45
  mode: "append" | "combineByPosition" | "combineByFields";
46
46
  matchField1?: string;
47
- matchField2?: string;
48
47
  joinType?: "inner" | "leftOuter" | "rightOuter" | "fullOuter";
49
48
  unmatchedHandling?: "discard" | "useNull";
50
49
  }) {
51
50
  "use step";
52
51
 
53
- const items1 = Array.isArray(input.input1) ? input.input1 : [];
54
- const items2 = Array.isArray(input.input2) ? input.input2 : [];
52
+ const count = Number(input.inputCount) || 2;
53
+ const inputs: unknown[][] = [];
54
+ for (let i = 1; i <= count; i++) {
55
+ const val = (input as Record<string, unknown>)[\`input\${i}\`];
56
+ inputs.push(Array.isArray(val) ? val : []);
57
+ }
55
58
  const mode = input.mode || "append";
56
59
 
57
60
  if (mode === "append") {
58
- const merged = [...items1, ...items2];
61
+ const merged = inputs.flat();
59
62
  return { merged, totalItems: merged.length };
60
63
  }
61
64
 
62
65
  if (mode === "combineByPosition") {
63
- const maxLength = Math.max(items1.length, items2.length);
66
+ const maxLength = Math.max(...inputs.map(arr => arr.length));
64
67
  const useNull = input.unmatchedHandling !== "discard";
65
68
  const merged = [];
66
69
  for (let i = 0; i < maxLength; i++) {
67
- const item1 = items1[i];
68
- const item2 = items2[i];
69
- if (!useNull && (item1 === undefined || item2 === undefined)) continue;
70
- merged.push({
71
- ...(item1 && typeof item1 === "object" ? item1 : { input1: item1 ?? null }),
72
- ...(item2 && typeof item2 === "object" ? item2 : { input2: item2 ?? null }),
73
- });
70
+ if (!useNull && inputs.some(arr => arr[i] === undefined)) continue;
71
+ const combined: Record<string, unknown> = {};
72
+ for (let j = 0; j < inputs.length; j++) {
73
+ const item = inputs[j][i];
74
+ if (item && typeof item === "object") Object.assign(combined, item);
75
+ else combined[\`input\${j + 1}\`] = item ?? null;
76
+ }
77
+ merged.push(combined);
74
78
  }
75
79
  return { merged, totalItems: merged.length };
76
80
  }
77
81
 
78
82
  if (mode === "combineByFields") {
79
- const field1 = input.matchField1 || "id";
80
- const field2 = input.matchField2 || "id";
83
+ const matchField = input.matchField1 || "id";
81
84
  const joinType = input.joinType || "inner";
82
85
  const getField = (item: unknown, field: string) =>
83
86
  item && typeof item === "object" ? (item as Record<string, unknown>)[field] : undefined;
84
87
 
85
- const map2 = new Map<unknown, unknown[]>();
86
- for (const item of items2) {
87
- const key = getField(item, field2);
88
- if (!map2.has(key)) map2.set(key, []);
89
- map2.get(key)!.push(item);
90
- }
91
-
92
- const merged: unknown[] = [];
93
- const matchedKeys2 = new Set<unknown>();
94
-
95
- for (const item1 of items1) {
96
- const key = getField(item1, field1);
97
- const matches = map2.get(key);
98
- if (matches && matches.length > 0) {
99
- matchedKeys2.add(key);
100
- for (const item2 of matches) {
101
- merged.push({
102
- ...(typeof item1 === "object" ? item1 : {}),
103
- ...(typeof item2 === "object" ? item2 : {}),
104
- });
88
+ let current = inputs[0];
89
+ for (let idx = 1; idx < inputs.length; idx++) {
90
+ const next = inputs[idx];
91
+ const map = new Map<unknown, unknown[]>();
92
+ for (const item of next) {
93
+ const key = getField(item, matchField);
94
+ if (!map.has(key)) map.set(key, []);
95
+ map.get(key)!.push(item);
96
+ }
97
+ const merged: unknown[] = [];
98
+ const matchedKeys = new Set<unknown>();
99
+ for (const item1 of current) {
100
+ const key = getField(item1, matchField);
101
+ const matches = map.get(key);
102
+ if (matches && matches.length > 0) {
103
+ matchedKeys.add(key);
104
+ for (const item2 of matches) {
105
+ merged.push({ ...(typeof item1 === "object" ? item1 : {}), ...(typeof item2 === "object" ? item2 : {}) });
106
+ }
107
+ } else if (joinType === "leftOuter" || joinType === "fullOuter") {
108
+ merged.push({ ...(typeof item1 === "object" ? item1 : {}) });
105
109
  }
106
- } else if (joinType === "leftOuter" || joinType === "fullOuter") {
107
- merged.push({ ...(typeof item1 === "object" ? item1 : {}) });
108
110
  }
109
- }
110
-
111
- if (joinType === "rightOuter" || joinType === "fullOuter") {
112
- for (const item2 of items2) {
113
- const key = getField(item2, field2);
114
- if (!matchedKeys2.has(key)) {
115
- merged.push({ ...(typeof item2 === "object" ? item2 : {}) });
111
+ if (joinType === "rightOuter" || joinType === "fullOuter") {
112
+ for (const item2 of next) {
113
+ const key = getField(item2, matchField);
114
+ if (!matchedKeys.has(key)) merged.push({ ...(typeof item2 === "object" ? item2 : {}) });
116
115
  }
117
116
  }
117
+ current = merged;
118
118
  }
119
-
120
- return { merged, totalItems: merged.length };
119
+ return { merged: current, totalItems: current.length };
121
120
  }
122
121
 
123
- return { merged: [...items1, ...items2], totalItems: items1.length + items2.length };
124
- }`};import{WorkflowIcon as rp}from"lucide-react";import{jsx as ap}from"react/jsx-runtime";var qr={id:"Run Workflow",label:"Run Workflow",description:"Execute another workflow and wait for it to complete",category:"System",icon:ap(rp,{className:"size-12 text-emerald-300",strokeWidth:1.5}),codeGenerator:`export async function runWorkflowStep(input: {
122
+ return { merged: inputs.flat(), totalItems: inputs.flat().length };
123
+ }`};import{WorkflowIcon as Ip}from"lucide-react";import{jsx as Pp}from"react/jsx-runtime";var Qr={id:"Run Workflow",label:"Run Workflow",description:"Execute another workflow and wait for it to complete",category:"System",icon:Pp(Ip,{className:"size-12 text-emerald-300",strokeWidth:1.5}),codeGenerator:`export async function runWorkflowStep(input: {
125
124
  workflowId: string;
126
125
  input?: string;
127
126
  }) {
@@ -130,7 +129,7 @@ Do you want to save anyway?`,confirmLabel:"Save Anyway",onConfirm:async()=>{awai
130
129
  // Note: Run Workflow is only available in the visual builder.
131
130
  // It executes another workflow internally and returns its output.
132
131
  throw new Error("Run Workflow is not supported in exported code. Use HTTP Request instead.");
133
- }`};import{ListOrdered as sp}from"lucide-react";import{jsx as ip}from"react/jsx-runtime";var jr={id:"Run Workflows in Sequence",label:"Run Workflows in Sequence",description:"Execute multiple workflows one after another in order",category:"System",icon:ip(sp,{className:"size-12 text-emerald-300",strokeWidth:1.5}),codeGenerator:`export async function runWorkflowsInSequenceStep(input: {
132
+ }`};import{ListOrdered as Ep}from"lucide-react";import{jsx as Dp}from"react/jsx-runtime";var Zr={id:"Run Workflows in Sequence",label:"Run Workflows in Sequence",description:"Execute multiple workflows one after another in order",category:"System",icon:Dp(Ep,{className:"size-12 text-emerald-300",strokeWidth:1.5}),codeGenerator:`export async function runWorkflowsInSequenceStep(input: {
134
133
  workflowIds: string[];
135
134
  continueOnFailure?: boolean;
136
135
  input?: string;
@@ -140,27 +139,18 @@ Do you want to save anyway?`,confirmLabel:"Save Anyway",onConfirm:async()=>{awai
140
139
  // Note: Run Workflows in Sequence is only available in the visual builder.
141
140
  // It executes multiple workflows internally in order and returns their outputs.
142
141
  throw new Error("Run Workflows in Sequence is not supported in exported code. Use HTTP Request instead.");
143
- }`};import{ArrowLeftRight as lp}from"lucide-react";import{jsx as dp}from"react/jsx-runtime";var Jr={id:"Switch",label:"Switch",description:"Route based on rules or values",category:"System",icon:dp(lp,{className:"size-12 text-violet-300",strokeWidth:1.5}),codeGenerator:`export async function switchStep(input: {
142
+ }`};import{ArrowLeftRight as Rp}from"lucide-react";import{jsx as Op}from"react/jsx-runtime";var Tn={id:"Switch",label:"Switch",description:"Route based on rules or values",category:"System",icon:Op(Rp,{className:"size-12 text-violet-300",strokeWidth:1.5}),codeGenerator:`export async function switchStep(input: {
144
143
  mode: "rules" | "expression";
145
144
  switchValue?: string;
146
- routeName0?: string;
147
- routeName1?: string;
148
- routeName2?: string;
149
- routeName3?: string;
150
- routeCondition0?: boolean;
151
- routeCondition1?: boolean;
152
- routeCondition2?: boolean;
153
- routeCondition3?: boolean;
154
- routeCaseValue0?: string;
155
- routeCaseValue1?: string;
156
- routeCaseValue2?: string;
157
- routeCaseValue3?: string;
145
+ routeCount?: number;
146
+ [key: string]: unknown;
158
147
  }) {
159
148
  "use step";
160
149
 
161
150
  const mode = input.mode || "rules";
151
+ const count = Number(input.routeCount) || 4;
162
152
  const routes = [];
163
- for (let i = 0; i < 4; i++) {
153
+ for (let i = 0; i < count; i++) {
164
154
  const name = (input as Record<string, unknown>)[\`routeName\${i}\`] as string | undefined;
165
155
  const condition = (input as Record<string, unknown>)[\`routeCondition\${i}\`] as boolean | undefined;
166
156
  const caseValue = (input as Record<string, unknown>)[\`routeCaseValue\${i}\`] as string | undefined;
@@ -183,16 +173,16 @@ Do you want to save anyway?`,confirmLabel:"Save Anyway",onConfirm:async()=>{awai
183
173
  }
184
174
 
185
175
  return { matchedRouteIndex: -1, matchedRouteName: "Default", isDefault: true };
186
- }`};import{useEffect as cp,useState as up}from"react";function pl(){let[e,t]=up(void 0);return cp(()=>{let o="ontouchstart"in window||navigator.maxTouchPoints>0||navigator.msMaxTouchPoints>0;t(o)},[]),e}import{DropdownMenu as bt}from"radix-ui";import{CheckIcon as vk,ChevronRightIcon as mp,CircleIcon as pp}from"lucide-react";import{jsx as mt,jsxs as bl}from"react/jsx-runtime";function Po({...e}){return mt(bt.Root,{"data-slot":"dropdown-menu",...e})}function Eo({...e}){return mt(bt.Trigger,{"data-slot":"dropdown-menu-trigger",...e})}function Do({className:e,sideOffset:t=4,...o}){return mt(bt.Portal,{children:mt(bt.Content,{"data-slot":"dropdown-menu-content",sideOffset:t,className:x("bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 max-h-(--radix-dropdown-menu-content-available-height) min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border p-1 shadow-md",e),...o})})}function wt({className:e,inset:t,variant:o="default",...n}){return mt(bt.Item,{"data-slot":"dropdown-menu-item","data-inset":t,"data-variant":o,className:x("focus:bg-accent focus:text-accent-foreground data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 dark:data-[variant=destructive]:focus:bg-destructive/20 data-[variant=destructive]:focus:text-destructive data-[variant=destructive]:*:[svg]:!text-destructive [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",e),...n})}function fl({...e}){return mt(bt.RadioGroup,{"data-slot":"dropdown-menu-radio-group",...e})}function Yr({className:e,children:t,...o}){return bl(bt.RadioItem,{"data-slot":"dropdown-menu-radio-item",className:x("focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",e),...o,children:[mt("span",{className:"pointer-events-none absolute left-2 flex size-3.5 items-center justify-center",children:mt(bt.ItemIndicator,{children:mt(pp,{className:"size-2 fill-current"})})}),t]})}function gl({className:e,inset:t,...o}){return mt(bt.Label,{"data-slot":"dropdown-menu-label","data-inset":t,className:x("px-2 py-1.5 text-sm font-medium data-[inset]:pl-8",e),...o})}function Jn({className:e,...t}){return mt(bt.Separator,{"data-slot":"dropdown-menu-separator",className:x("bg-border -mx-1 my-1 h-px",e),...t})}function yl({...e}){return mt(bt.Sub,{"data-slot":"dropdown-menu-sub",...e})}function vl({className:e,inset:t,children:o,...n}){return bl(bt.SubTrigger,{"data-slot":"dropdown-menu-sub-trigger","data-inset":t,className:x("focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",e),...n,children:[o,mt(mp,{className:"ml-auto size-4"})]})}function hl({className:e,...t}){return mt(bt.SubContent,{"data-slot":"dropdown-menu-sub-content",className:x("bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-hidden rounded-md border p-1 shadow-lg",e),...t})}import{Fragment as Nl,jsx as me,jsxs as it}from"react/jsx-runtime";var xp=[qo,Uo,Ko,Ur,Kr,Jr,qr,jr];function Np(){return Qa(()=>{let t=js().map(o=>({id:o.id,label:o.label,description:o.description,category:o.category,integration:o.integration}));return[...xp,...t]},[])}function kp({group:e}){let t=e.actions[0];return t?.integration?me(Wt,{className:"size-4",integration:t.integration}):e.category==="System"?me(kl,{className:"size-4"}):me(Cl,{className:"size-4"})}function Cp({action:e,className:t}){return e.integration?me(Wt,{className:t,integration:e.integration}):e.category==="System"?me(kl,{className:x(t,"text-muted-foreground")}):me(Cl,{className:x(t,"text-muted-foreground")})}var Tl="workflow-action-grid-hidden-groups",Al="workflow-action-grid-view-mode";function Tp(){if(typeof window>"u")return new Set;try{let e=localStorage.getItem(Tl);return e?new Set(JSON.parse(e)):new Set}catch{return new Set}}function Ap(){if(typeof window>"u")return"list";try{return localStorage.getItem(Al)==="grid"?"grid":"list"}catch{return"list"}}function Xr({onSelectAction:e,disabled:t,isNewlyCreated:o}){let[n,r]=Yn(""),[s,a]=Yn(new Set),[d,i]=Yn(Tp),[l,c]=Yn(!1),[u,f]=Yn(Ap),h=Np(),k=wp(null),b=pl(),y=()=>{let w=u==="list"?"grid":"list";f(w),localStorage.setItem(Al,w)},p=w=>{a(m=>{let S=new Set(m);return S.has(w)?S.delete(w):S.add(w),S})},v=w=>{i(m=>{let S=new Set(m);return S.has(w)?S.delete(w):S.add(w),localStorage.setItem(Tl,JSON.stringify([...S])),S})};bp(()=>{o&&b===!1&&k.current&&k.current.focus()},[o,b]);let g=h.filter(w=>{let m=n.toLowerCase();return w.label.toLowerCase().includes(m)||w.description.toLowerCase().includes(m)||w.category.toLowerCase().includes(m)}),C=Qa(()=>{let w={};for(let S of g){let X=S.category;w[X]||(w[X]=[]),w[X].push(S)}return Object.keys(w).sort((S,X)=>S==="System"?-1:X==="System"?1:S.localeCompare(X)).map(S=>({category:S,actions:w[S]}))},[g]),I=Qa(()=>l?C:C.filter(w=>!d.has(w.category)),[C,d,l]),A=d.size;return it("div",{className:"flex min-h-0 flex-1 flex-col gap-3",children:[it("div",{className:"flex shrink-0 gap-2",children:[it("div",{className:"relative flex-1",children:[me(hp,{className:"absolute top-1/2 left-3 size-4 -translate-y-1/2 text-muted-foreground"}),me(ae,{className:"pl-9","data-testid":"action-search-input",disabled:t,id:"action-filter",onChange:w=>r(w.target.value),placeholder:"Search actions...",ref:k,value:n})]}),me(yn,{children:it(Un,{children:[me(Kn,{asChild:!0,children:me(D,{className:"shrink-0",onClick:y,size:"icon",variant:"ghost",children:u==="list"?me(gp,{className:"size-4"}):me(yp,{className:"size-4"})})}),me(qn,{children:u==="list"?"Grid view":"List view"})]})}),A>0&&me(yn,{children:it(Un,{children:[me(Kn,{asChild:!0,children:me(D,{className:x("shrink-0",l&&"bg-muted"),onClick:()=>c(!l),size:"icon",variant:"ghost",children:l?me(wl,{className:"size-4"}):me(xl,{className:"size-4"})})}),me(qn,{children:l?"Hide hidden groups":`Show ${A} hidden group${A>1?"s":""}`})]})})]}),it("div",{className:"min-h-0 flex-1 overflow-y-auto pb-4","data-testid":"action-grid",children:[g.length===0&&me("p",{className:"py-4 text-center text-muted-foreground text-sm",children:"No actions found"}),g.length>0&&I.length===0&&me("p",{className:"py-4 text-center text-muted-foreground text-sm",children:"All groups are hidden"}),u==="grid"&&I.length>0&&me("div",{className:"grid gap-2 p-1",style:{gridTemplateColumns:"repeat(auto-fill, minmax(72px, 1fr))"},children:g.filter(w=>l||!d.has(w.category)).map(w=>it("button",{className:x("flex aspect-square flex-col items-center justify-center gap-1.5 rounded-lg border border-transparent p-2 text-center transition-colors hover:border-border hover:bg-muted",t&&"pointer-events-none opacity-50"),"data-testid":`action-option-${w.id.toLowerCase().replace(/\s+/g,"-")}`,disabled:t,onClick:()=>e(w.id),type:"button",children:[me(Cp,{action:w,className:"size-6"}),me("span",{className:"line-clamp-2 font-medium text-xs leading-tight",children:w.label})]},w.id))}),u==="list"&&I.length>0&&I.map((w,m)=>{let S=s.has(w.category),X=d.has(w.category);return it("div",{children:[m>0&&me("div",{className:"my-2 h-px bg-border"}),it("div",{className:x("sticky top-0 z-10 mb-1 flex items-center gap-2 bg-background px-3 py-2 font-medium text-muted-foreground text-xs uppercase tracking-wider",X&&"opacity-50"),children:[it("button",{className:"flex flex-1 items-center gap-2 text-left hover:text-foreground",onClick:()=>p(w.category),type:"button",children:[me(fp,{className:x("size-3.5 transition-transform",!S&&"rotate-90")}),me(kp,{group:w}),w.category]}),it(Po,{children:[me(Eo,{asChild:!0,children:me("button",{className:"rounded p-0.5 hover:bg-muted hover:text-foreground",type:"button",children:me(vp,{className:"size-4"})})}),me(Do,{align:"end",children:me(wt,{onClick:()=>v(w.category),children:X?it(Nl,{children:[me(wl,{className:"mr-2 size-4"}),"Show group"]}):it(Nl,{children:[me(xl,{className:"mr-2 size-4"}),"Hide group"]})})})]})]}),!S&&w.actions.map(ie=>me("button",{className:x("flex w-full items-center rounded-md px-3 py-2 text-left text-sm transition-colors hover:bg-muted",t&&"pointer-events-none opacity-50"),"data-testid":`action-option-${ie.id.toLowerCase().replace(/\s+/g,"-")}`,disabled:t,onClick:()=>e(ie.id),type:"button",children:it("span",{className:"min-w-0 flex-1 truncate",children:[me("span",{className:"font-medium",children:ie.label}),ie.description&&it("span",{className:"text-muted-foreground text-xs",children:[" ","- ",ie.description]})]})},ie.id))]},w.category)})]})]})}import{Clock as Ip,Copy as Pp,Play as Ep,Webhook as Dp}from"lucide-react";import{toast as Rp}from"sonner";import{jsx as Xn,jsxs as Sl}from"react/jsx-runtime";var Sp=[{label:"North America",zones:[{value:"America/New_York",label:"Eastern Time (ET)"},{value:"America/Chicago",label:"Central Time (CT)"},{value:"America/Denver",label:"Mountain Time (MT)"},{value:"America/Phoenix",label:"Arizona Time (MST)"},{value:"America/Los_Angeles",label:"Pacific Time (PT)"},{value:"America/Anchorage",label:"Alaska Time (AKT)"},{value:"Pacific/Honolulu",label:"Hawaii Time (HST)"},{value:"America/Toronto",label:"Toronto"},{value:"America/Vancouver",label:"Vancouver"}]},{label:"Europe",zones:[{value:"Europe/London",label:"London (GMT/BST)"},{value:"Europe/Paris",label:"Paris (CET/CEST)"},{value:"Europe/Berlin",label:"Berlin (CET/CEST)"},{value:"Europe/Rome",label:"Rome (CET/CEST)"},{value:"Europe/Madrid",label:"Madrid (CET/CEST)"},{value:"Europe/Amsterdam",label:"Amsterdam (CET/CEST)"},{value:"Europe/Brussels",label:"Brussels (CET/CEST)"},{value:"Europe/Stockholm",label:"Stockholm (CET/CEST)"},{value:"Europe/Warsaw",label:"Warsaw (CET/CEST)"},{value:"Europe/Athens",label:"Athens (EET/EEST)"},{value:"Europe/Moscow",label:"Moscow (MSK)"}]},{label:"Asia",zones:[{value:"Asia/Dubai",label:"Dubai (GST)"},{value:"Asia/Kolkata",label:"India (IST)"},{value:"Asia/Shanghai",label:"China (CST)"},{value:"Asia/Hong_Kong",label:"Hong Kong (HKT)"},{value:"Asia/Tokyo",label:"Tokyo (JST)"},{value:"Asia/Seoul",label:"Seoul (KST)"},{value:"Asia/Singapore",label:"Singapore (SGT)"},{value:"Asia/Bangkok",label:"Bangkok (ICT)"},{value:"Asia/Jakarta",label:"Jakarta (WIB)"}]},{label:"Australia & Pacific",zones:[{value:"Australia/Sydney",label:"Sydney (AEDT/AEST)"},{value:"Australia/Melbourne",label:"Melbourne (AEDT/AEST)"},{value:"Australia/Brisbane",label:"Brisbane (AEST)"},{value:"Australia/Perth",label:"Perth (AWST)"},{value:"Pacific/Auckland",label:"Auckland (NZDT/NZST)"}]},{label:"South America",zones:[{value:"America/Sao_Paulo",label:"S\xE3o Paulo (BRT)"},{value:"America/Argentina/Buenos_Aires",label:"Buenos Aires (ART)"},{value:"America/Santiago",label:"Santiago (CLT)"},{value:"America/Bogota",label:"Bogot\xE1 (COT)"},{value:"America/Lima",label:"Lima (PET)"}]},{label:"Africa & Middle East",zones:[{value:"Africa/Cairo",label:"Cairo (EET)"},{value:"Africa/Johannesburg",label:"Johannesburg (SAST)"},{value:"Africa/Lagos",label:"Lagos (WAT)"},{value:"Africa/Nairobi",label:"Nairobi (EAT)"},{value:"Asia/Jerusalem",label:"Jerusalem (IST)"}]},{label:"Other",zones:[{value:"UTC",label:"UTC (Coordinated Universal Time)"}]}];function Il({value:e,onValueChange:t,disabled:o,id:n}){return Sl(ve,{value:e,onValueChange:t,disabled:o,children:[Xn(he,{id:n,children:Xn(we,{placeholder:"Select timezone"})}),Xn(be,{children:Sp.map(r=>Sl(Ai,{children:[Xn(Si,{children:r.label}),r.zones.map(s=>Xn(te,{value:s.value,children:s.label},s.value))]},r.label))})]})}import{Fragment as Za,jsx as Pe,jsxs as lt}from"react/jsx-runtime";function Qr({config:e,onUpdateConfig:t,disabled:o,workflowId:n}){let r=n?`${typeof window<"u"?window.location.origin:""}/api/workflows/${n}/webhook`:"",s=()=>{r&&(navigator.clipboard.writeText(r),Rp.success("Webhook URL copied to clipboard"))};return lt(Za,{children:[lt("div",{className:"space-y-2",children:[Pe(M,{className:"ml-1",htmlFor:"triggerType",children:"Trigger Type"}),lt(ve,{disabled:o,onValueChange:a=>t("triggerType",a),value:e?.triggerType||"Manual",children:[Pe(he,{className:"w-full",id:"triggerType",children:Pe(we,{placeholder:"Select trigger type"})}),lt(be,{children:[Pe(te,{value:"Manual",children:lt("div",{className:"flex items-center gap-2",children:[Pe(Ep,{className:"h-4 w-4"}),"Manual"]})}),Pe(te,{value:"Schedule",children:lt("div",{className:"flex items-center gap-2",children:[Pe(Ip,{className:"h-4 w-4"}),"Schedule"]})}),Pe(te,{value:"Webhook",children:lt("div",{className:"flex items-center gap-2",children:[Pe(Dp,{className:"h-4 w-4"}),"Webhook"]})})]})]})]}),e?.triggerType==="Webhook"&&lt(Za,{children:[lt("div",{className:"space-y-2",children:[Pe(M,{className:"ml-1",children:"Webhook URL"}),lt("div",{className:"flex gap-2",children:[Pe(ae,{className:"font-mono text-xs",disabled:!0,value:r||"Save workflow to generate webhook URL"}),Pe(D,{disabled:!r,onClick:s,size:"icon",variant:"outline",children:Pe(Pp,{className:"h-4 w-4"})})]})]}),lt("div",{className:"space-y-2",children:[Pe(M,{children:"Request Schema (Optional)"}),Pe(lo,{disabled:o,onChange:a=>t("webhookSchema",JSON.stringify(a)),schema:e?.webhookSchema?JSON.parse(e.webhookSchema):[]}),Pe("p",{className:"text-muted-foreground text-xs",children:"Define the expected structure of the incoming webhook payload."})]}),lt("div",{className:"space-y-2",children:[Pe(M,{htmlFor:"webhookMockRequest",children:"Mock Request (Optional)"}),Pe("div",{className:"overflow-hidden rounded-md border",children:Pe(yt,{defaultLanguage:"json",height:"150px",onChange:a=>t("webhookMockRequest",a||""),options:{minimap:{enabled:!1},lineNumbers:"on",scrollBeyondLastLine:!1,fontSize:12,readOnly:o,wordWrap:"on"},value:e?.webhookMockRequest||""})}),Pe("p",{className:"text-muted-foreground text-xs",children:"Enter a sample JSON payload to test the webhook trigger."})]})]}),e?.triggerType==="Schedule"&&lt(Za,{children:[lt("div",{className:"space-y-2",children:[Pe(M,{className:"ml-1",htmlFor:"scheduleCron",children:"Cron Expression"}),Pe(ae,{disabled:o,id:"scheduleCron",onChange:a=>t("scheduleCron",a.target.value),placeholder:"0 9 * * * (every day at 9am)",value:e?.scheduleCron||""})]}),lt("div",{className:"space-y-2",children:[Pe(M,{className:"ml-1",htmlFor:"scheduleTimezone",children:"Timezone"}),Pe(Il,{disabled:o,id:"scheduleTimezone",onValueChange:a=>t("scheduleTimezone",a),value:e?.scheduleTimezone||"America/New_York"})]})]})]})}var Pl={"Database Query":Ko.codeGenerator,"HTTP Request":qo.codeGenerator,Condition:Uo.codeGenerator},es=`async function actionStep(input: Record<string, unknown>) {
176
+ }`};import{useEffect as Lp,useState as Mp}from"react";function Sl(){let[e,t]=Mp(void 0);return Lp(()=>{let o="ontouchstart"in window||navigator.maxTouchPoints>0||navigator.msMaxTouchPoints>0;t(o)},[]),e}import{DropdownMenu as Ct}from"radix-ui";import{CheckIcon as oC,ChevronRightIcon as Wp,CircleIcon as Fp}from"lucide-react";import{jsx as yt,jsxs as Rl}from"react/jsx-runtime";function Lo({...e}){return yt(Ct.Root,{"data-slot":"dropdown-menu",...e})}function Mo({...e}){return yt(Ct.Trigger,{"data-slot":"dropdown-menu-trigger",...e})}function Wo({className:e,sideOffset:t=4,...o}){return yt(Ct.Portal,{children:yt(Ct.Content,{"data-slot":"dropdown-menu-content",sideOffset:t,className:N("bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 max-h-(--radix-dropdown-menu-content-available-height) min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border p-1 shadow-md",e),...o})})}function vt({className:e,inset:t,variant:o="default",...n}){return yt(Ct.Item,{"data-slot":"dropdown-menu-item","data-inset":t,"data-variant":o,className:N("focus:bg-accent focus:text-accent-foreground data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 dark:data-[variant=destructive]:focus:bg-destructive/20 data-[variant=destructive]:focus:text-destructive data-[variant=destructive]:*:[svg]:!text-destructive [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",e),...n})}function Al({...e}){return yt(Ct.RadioGroup,{"data-slot":"dropdown-menu-radio-group",...e})}function ea({className:e,children:t,...o}){return Rl(Ct.RadioItem,{"data-slot":"dropdown-menu-radio-item",className:N("focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",e),...o,children:[yt("span",{className:"pointer-events-none absolute left-2 flex size-3.5 items-center justify-center",children:yt(Ct.ItemIndicator,{children:yt(Fp,{className:"size-2 fill-current"})})}),t]})}function Il({className:e,inset:t,...o}){return yt(Ct.Label,{"data-slot":"dropdown-menu-label","data-inset":t,className:N("px-2 py-1.5 text-sm font-medium data-[inset]:pl-8",e),...o})}function er({className:e,...t}){return yt(Ct.Separator,{"data-slot":"dropdown-menu-separator",className:N("bg-border -mx-1 my-1 h-px",e),...t})}function Pl({...e}){return yt(Ct.Sub,{"data-slot":"dropdown-menu-sub",...e})}function El({className:e,inset:t,children:o,...n}){return Rl(Ct.SubTrigger,{"data-slot":"dropdown-menu-sub-trigger","data-inset":t,className:N("focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",e),...n,children:[o,yt(Wp,{className:"ml-auto size-4"})]})}function Dl({className:e,...t}){return yt(Ct.SubContent,{"data-slot":"dropdown-menu-sub-content",className:N("bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-hidden rounded-md border p-1 shadow-lg",e),...t})}import{Fragment as Ml,jsx as me,jsxs as dt}from"react/jsx-runtime";var Up=[Qo,Yo,Xo,Xr,Cn,Tn,Qr,Zr];function Kp(){return ss(()=>{let t=oi().map(o=>({id:o.id,label:o.label,description:o.description,category:o.category,integration:o.integration}));return[...Up,...t]},[])}function qp({group:e}){let t=e.actions[0];return t?.integration?me(Bt,{className:"size-4",integration:t.integration}):e.category==="System"?me(Wl,{className:"size-4"}):me(Fl,{className:"size-4"})}function jp({action:e,className:t}){return e.integration?me(Bt,{className:t,integration:e.integration}):e.category==="System"?me(Wl,{className:N(t,"text-muted-foreground")}):me(Fl,{className:N(t,"text-muted-foreground")})}var zl="workflow-action-grid-hidden-groups",Bl="workflow-action-grid-view-mode";function Jp(){if(typeof window>"u")return new Set;try{let e=localStorage.getItem(zl);return e?new Set(JSON.parse(e)):new Set}catch{return new Set}}function Yp(){if(typeof window>"u")return"list";try{return localStorage.getItem(Bl)==="grid"?"grid":"list"}catch{return"list"}}function ta({onSelectAction:e,disabled:t,isNewlyCreated:o}){let[n,r]=tr(""),[s,a]=tr(new Set),[d,i]=tr(Jp),[l,c]=tr(!1),[u,g]=tr(Yp),b=Kp(),y=_p(null),v=Sl(),p=()=>{let k=u==="list"?"grid":"list";g(k),localStorage.setItem(Bl,k)},m=k=>{a(f=>{let x=new Set(f);return x.has(k)?x.delete(k):x.add(k),x})},w=k=>{i(f=>{let x=new Set(f);return x.has(k)?x.delete(k):x.add(k),localStorage.setItem(zl,JSON.stringify([...x])),x})};$p(()=>{o&&v===!1&&y.current&&y.current.focus()},[o,v]);let h=b.filter(k=>{let f=n.toLowerCase();return k.label.toLowerCase().includes(f)||k.description.toLowerCase().includes(f)||k.category.toLowerCase().includes(f)}),S=ss(()=>{let k={};for(let x of h){let G=x.category;k[G]||(k[G]=[]),k[G].push(x)}return Object.keys(k).sort((x,G)=>x==="System"?-1:G==="System"?1:x.localeCompare(G)).map(x=>({category:x,actions:k[x]}))},[h]),D=ss(()=>l?S:S.filter(k=>!d.has(k.category)),[S,d,l]),I=d.size;return dt("div",{className:"flex min-h-0 flex-1 flex-col gap-3",children:[dt("div",{className:"flex shrink-0 gap-2",children:[dt("div",{className:"relative flex-1",children:[me(Gp,{className:"absolute top-1/2 left-3 size-4 -translate-y-1/2 text-muted-foreground"}),me(ae,{className:"pl-9","data-testid":"action-search-input",disabled:t,id:"action-filter",onChange:k=>r(k.target.value),placeholder:"Search actions...",ref:y,value:n})]}),me(Nn,{children:dt(Yn,{children:[me(Xn,{asChild:!0,children:me(E,{className:"shrink-0",onClick:p,size:"icon",variant:"ghost",children:u==="list"?me(Bp,{className:"size-4"}):me(Vp,{className:"size-4"})})}),me(Qn,{children:u==="list"?"Grid view":"List view"})]})}),I>0&&me(Nn,{children:dt(Yn,{children:[me(Xn,{asChild:!0,children:me(E,{className:N("shrink-0",l&&"bg-muted"),onClick:()=>c(!l),size:"icon",variant:"ghost",children:l?me(Ol,{className:"size-4"}):me(Ll,{className:"size-4"})})}),me(Qn,{children:l?"Hide hidden groups":`Show ${I} hidden group${I>1?"s":""}`})]})})]}),dt("div",{className:"min-h-0 flex-1 overflow-y-auto pb-4","data-testid":"action-grid",children:[h.length===0&&me("p",{className:"py-4 text-center text-muted-foreground text-sm",children:"No actions found"}),h.length>0&&D.length===0&&me("p",{className:"py-4 text-center text-muted-foreground text-sm",children:"All groups are hidden"}),u==="grid"&&D.length>0&&me("div",{className:"grid gap-2 p-1",style:{gridTemplateColumns:"repeat(auto-fill, minmax(72px, 1fr))"},children:h.filter(k=>l||!d.has(k.category)).map(k=>dt("button",{className:N("flex aspect-square flex-col items-center justify-center gap-1.5 rounded-lg border border-transparent p-2 text-center transition-colors hover:border-border hover:bg-muted",t&&"pointer-events-none opacity-50"),"data-testid":`action-option-${k.id.toLowerCase().replace(/\s+/g,"-")}`,disabled:t,onClick:()=>e(k.id),type:"button",children:[me(jp,{action:k,className:"size-6"}),me("span",{className:"line-clamp-2 font-medium text-xs leading-tight",children:k.label})]},k.id))}),u==="list"&&D.length>0&&D.map((k,f)=>{let x=s.has(k.category),G=d.has(k.category);return dt("div",{children:[f>0&&me("div",{className:"my-2 h-px bg-border"}),dt("div",{className:N("sticky top-0 z-10 mb-1 flex items-center gap-2 bg-background px-3 py-2 font-medium text-muted-foreground text-xs uppercase tracking-wider",G&&"opacity-50"),children:[dt("button",{className:"flex flex-1 items-center gap-2 text-left hover:text-foreground",onClick:()=>m(k.category),type:"button",children:[me(zp,{className:N("size-3.5 transition-transform",!x&&"rotate-90")}),me(qp,{group:k}),k.category]}),dt(Lo,{children:[me(Mo,{asChild:!0,children:me("button",{className:"rounded p-0.5 hover:bg-muted hover:text-foreground",type:"button",children:me(Hp,{className:"size-4"})})}),me(Wo,{align:"end",children:me(vt,{onClick:()=>w(k.category),children:G?dt(Ml,{children:[me(Ol,{className:"mr-2 size-4"}),"Show group"]}):dt(Ml,{children:[me(Ll,{className:"mr-2 size-4"}),"Hide group"]})})})]})]}),!x&&k.actions.map(te=>me("button",{className:N("flex w-full items-center rounded-md px-3 py-2 text-left text-sm transition-colors hover:bg-muted",t&&"pointer-events-none opacity-50"),"data-testid":`action-option-${te.id.toLowerCase().replace(/\s+/g,"-")}`,disabled:t,onClick:()=>e(te.id),type:"button",children:dt("span",{className:"min-w-0 flex-1 truncate",children:[me("span",{className:"font-medium",children:te.label}),te.description&&dt("span",{className:"text-muted-foreground text-xs",children:[" ","- ",te.description]})]})},te.id))]},k.category)})]})]})}import{Clock as Qp,Copy as Zp,Play as ef,Webhook as tf}from"lucide-react";import{toast as of}from"sonner";import{jsx as or,jsxs as Vl}from"react/jsx-runtime";var Xp=[{label:"North America",zones:[{value:"America/New_York",label:"Eastern Time (ET)"},{value:"America/Chicago",label:"Central Time (CT)"},{value:"America/Denver",label:"Mountain Time (MT)"},{value:"America/Phoenix",label:"Arizona Time (MST)"},{value:"America/Los_Angeles",label:"Pacific Time (PT)"},{value:"America/Anchorage",label:"Alaska Time (AKT)"},{value:"Pacific/Honolulu",label:"Hawaii Time (HST)"},{value:"America/Toronto",label:"Toronto"},{value:"America/Vancouver",label:"Vancouver"}]},{label:"Europe",zones:[{value:"Europe/London",label:"London (GMT/BST)"},{value:"Europe/Paris",label:"Paris (CET/CEST)"},{value:"Europe/Berlin",label:"Berlin (CET/CEST)"},{value:"Europe/Rome",label:"Rome (CET/CEST)"},{value:"Europe/Madrid",label:"Madrid (CET/CEST)"},{value:"Europe/Amsterdam",label:"Amsterdam (CET/CEST)"},{value:"Europe/Brussels",label:"Brussels (CET/CEST)"},{value:"Europe/Stockholm",label:"Stockholm (CET/CEST)"},{value:"Europe/Warsaw",label:"Warsaw (CET/CEST)"},{value:"Europe/Athens",label:"Athens (EET/EEST)"},{value:"Europe/Moscow",label:"Moscow (MSK)"}]},{label:"Asia",zones:[{value:"Asia/Dubai",label:"Dubai (GST)"},{value:"Asia/Kolkata",label:"India (IST)"},{value:"Asia/Shanghai",label:"China (CST)"},{value:"Asia/Hong_Kong",label:"Hong Kong (HKT)"},{value:"Asia/Tokyo",label:"Tokyo (JST)"},{value:"Asia/Seoul",label:"Seoul (KST)"},{value:"Asia/Singapore",label:"Singapore (SGT)"},{value:"Asia/Bangkok",label:"Bangkok (ICT)"},{value:"Asia/Jakarta",label:"Jakarta (WIB)"}]},{label:"Australia & Pacific",zones:[{value:"Australia/Sydney",label:"Sydney (AEDT/AEST)"},{value:"Australia/Melbourne",label:"Melbourne (AEDT/AEST)"},{value:"Australia/Brisbane",label:"Brisbane (AEST)"},{value:"Australia/Perth",label:"Perth (AWST)"},{value:"Pacific/Auckland",label:"Auckland (NZDT/NZST)"}]},{label:"South America",zones:[{value:"America/Sao_Paulo",label:"S\xE3o Paulo (BRT)"},{value:"America/Argentina/Buenos_Aires",label:"Buenos Aires (ART)"},{value:"America/Santiago",label:"Santiago (CLT)"},{value:"America/Bogota",label:"Bogot\xE1 (COT)"},{value:"America/Lima",label:"Lima (PET)"}]},{label:"Africa & Middle East",zones:[{value:"Africa/Cairo",label:"Cairo (EET)"},{value:"Africa/Johannesburg",label:"Johannesburg (SAST)"},{value:"Africa/Lagos",label:"Lagos (WAT)"},{value:"Africa/Nairobi",label:"Nairobi (EAT)"},{value:"Asia/Jerusalem",label:"Jerusalem (IST)"}]},{label:"Other",zones:[{value:"UTC",label:"UTC (Coordinated Universal Time)"}]}];function Hl({value:e,onValueChange:t,disabled:o,id:n}){return Vl(he,{value:e,onValueChange:t,disabled:o,children:[or(be,{id:n,children:or(xe,{placeholder:"Select timezone"})}),or(we,{children:Xp.map(r=>Vl(Fi,{children:[or(zi,{children:r.label}),r.zones.map(s=>or(Q,{value:s.value,children:s.label},s.value))]},r.label))})]})}import{Fragment as is,jsx as De,jsxs as ct}from"react/jsx-runtime";function oa({config:e,onUpdateConfig:t,disabled:o,workflowId:n}){let r=n?`${typeof window<"u"?window.location.origin:""}/api/workflows/${n}/webhook`:"",s=()=>{r&&(navigator.clipboard.writeText(r),of.success("Webhook URL copied to clipboard"))};return ct(is,{children:[ct("div",{className:"space-y-2",children:[De(L,{className:"ml-1",htmlFor:"triggerType",children:"Trigger Type"}),ct(he,{disabled:o,onValueChange:a=>t("triggerType",a),value:e?.triggerType||"Manual",children:[De(be,{className:"w-full",id:"triggerType",children:De(xe,{placeholder:"Select trigger type"})}),ct(we,{children:[De(Q,{value:"Manual",children:ct("div",{className:"flex items-center gap-2",children:[De(ef,{className:"h-4 w-4"}),"Manual"]})}),De(Q,{value:"Schedule",children:ct("div",{className:"flex items-center gap-2",children:[De(Qp,{className:"h-4 w-4"}),"Schedule"]})}),De(Q,{value:"Webhook",children:ct("div",{className:"flex items-center gap-2",children:[De(tf,{className:"h-4 w-4"}),"Webhook"]})})]})]})]}),e?.triggerType==="Webhook"&&ct(is,{children:[ct("div",{className:"space-y-2",children:[De(L,{className:"ml-1",children:"Webhook URL"}),ct("div",{className:"flex gap-2",children:[De(ae,{className:"font-mono text-xs",disabled:!0,value:r||"Save workflow to generate webhook URL"}),De(E,{disabled:!r,onClick:s,size:"icon",variant:"outline",children:De(Zp,{className:"h-4 w-4"})})]})]}),ct("div",{className:"space-y-2",children:[De(L,{children:"Request Schema (Optional)"}),De(mo,{disabled:o,onChange:a=>t("webhookSchema",JSON.stringify(a)),schema:e?.webhookSchema?JSON.parse(e.webhookSchema):[]}),De("p",{className:"text-muted-foreground text-xs",children:"Define the expected structure of the incoming webhook payload."})]}),ct("div",{className:"space-y-2",children:[De(L,{htmlFor:"webhookMockRequest",children:"Mock Request (Optional)"}),De("div",{className:"overflow-hidden rounded-md border",children:De(xt,{defaultLanguage:"json",height:"150px",onChange:a=>t("webhookMockRequest",a||""),options:{minimap:{enabled:!1},lineNumbers:"on",scrollBeyondLastLine:!1,fontSize:12,readOnly:o,wordWrap:"on"},value:e?.webhookMockRequest||""})}),De("p",{className:"text-muted-foreground text-xs",children:"Enter a sample JSON payload to test the webhook trigger."})]})]}),e?.triggerType==="Schedule"&&ct(is,{children:[ct("div",{className:"space-y-2",children:[De(L,{className:"ml-1",htmlFor:"scheduleCron",children:"Cron Expression"}),De(ae,{disabled:o,id:"scheduleCron",onChange:a=>t("scheduleCron",a.target.value),placeholder:"0 9 * * * (every day at 9am)",value:e?.scheduleCron||""})]}),ct("div",{className:"space-y-2",children:[De(L,{className:"ml-1",htmlFor:"scheduleTimezone",children:"Timezone"}),De(Hl,{disabled:o,id:"scheduleTimezone",onValueChange:a=>t("scheduleTimezone",a),value:e?.scheduleTimezone||"America/New_York"})]})]})]})}var Gl={"Database Query":Xo.codeGenerator,"HTTP Request":Qo.codeGenerator,Condition:Yo.codeGenerator,Switch:Tn.codeGenerator,Merge:Cn.codeGenerator},ls=`async function actionStep(input: Record<string, unknown>) {
187
177
  "use step";
188
178
 
189
179
  console.log('Executing action');
190
180
  return { success: true };
191
- }`,Op=`async function unknownStep(input: Record<string, unknown>) {
181
+ }`,nf=`async function unknownStep(input: Record<string, unknown>) {
192
182
  "use step";
193
183
 
194
184
  return input;
195
- }`;function Lp(e,t){let o=e?.triggerType||"Manual";if(o==="Schedule"){let n=e?.scheduleCron||"0 9 * * *";return`{
185
+ }`;function rf(e,t){let o=e?.triggerType||"Manual";if(o==="Schedule"){let n=e?.scheduleCron||"0 9 * * *";return`{
196
186
  "crons": [
197
187
  {
198
188
  "path": "${t?`/api/workflow-builder/workflow/${t}/cron`:"/api/workflow-builder/workflow/<workflowId>/cron"}",
@@ -208,7 +198,7 @@ export async function POST(request: NextRequest) {
208
198
  await executeWorkflow(body);
209
199
 
210
200
  return Response.json({ success: true });
211
- }`:""}function Mp(e){if(!e)return es;if(Pl[e])return Pl[e];let t=fe(e);return t&&t.codegenTemplate||es}var hn=(e,t)=>e.data.type==="trigger"?Lp(e.data.config,t):e.data.type==="action"?Mp(e.data.config?.actionType):Op;import{useAtom as ts}from"jotai";import{Check as Ol,ChevronDown as ns,ChevronRight as rs,Clock as zp,Copy as Bp,ExternalLink as Vp,Loader2 as Gp,Play as Hp,Square as Dl,X as $p}from"lucide-react";import Rl from"next/image";import{useCallback as Qn,useEffect as Zr,useRef as _p,useState as Ro}from"react";function bn(e,t){return`${e} ${t}${e===1?"":"s"} ago`}function El(e){let t=new Date,o=new Date(e),n=Math.floor((t.getTime()-o.getTime())/1e3);if(n<60)return"just now";let r=Math.floor(n/60);if(r<60)return bn(r,"min");let s=Math.floor(r/60);if(s<24)return bn(s,"hour");let a=Math.floor(s/24);if(a<7)return bn(a,"day");let d=Math.floor(a/7);if(d<4)return bn(d,"week");let i=Math.floor(a/30);if(i<12)return bn(i,"month");let l=Math.floor(a/365);return bn(l,"year")}import{Loader2Icon as Wp}from"lucide-react";import{jsx as Fp}from"react/jsx-runtime";function Tt({className:e,...t}){let{ref:o,...n}=t;return Fp(Wp,{role:"status","aria-label":"Loading",className:x("size-4 animate-spin",e),...n})}import{Fragment as ta,jsx as H,jsxs as ze}from"react/jsx-runtime";function Up(e){return Ks(e)}function Kp(e,t){if(typeof e!="object"||e===null)return;let o=e[t.field];if(typeof o=="string"&&o.length>0)return o}function qp(e){return typeof e=="object"&&e!==null&&"base64"in e&&typeof e.base64=="string"&&e.base64.length>100}function os(e){let t={};for(let o of e)t[o.nodeId]={nodeId:o.nodeId,nodeName:o.nodeName,nodeType:o.nodeType,status:o.status,output:o.output};return t}function jp(e){try{let t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"}catch{return!1}}function Ll({data:e}){let o=JSON.stringify(e,null,2).split(/("https?:\/\/[^"]+"|"[^"]*")/g);return H(ta,{children:o.map(n=>{if(n.startsWith('"')&&n.endsWith('"')){let r=n.slice(1,-1);if(jp(r))return H("a",{className:"text-blue-500 underline hover:text-blue-400",href:r,rel:"noopener noreferrer",target:"_blank",children:n},r)}return n})})}function Jp({data:e,isError:t=!1}){let[o,n]=Ro(!1);return H(D,{className:"h-7 px-2",onClick:async s=>{s.stopPropagation();try{let a=t?String(e):JSON.stringify(e,null,2);await navigator.clipboard.writeText(a),n(!0),setTimeout(()=>n(!1),2e3)}catch(a){console.error("Failed to copy:",a)}},size:"sm",type:"button",variant:"ghost",children:o?H(Ol,{className:"h-3 w-3 text-green-600"}):H(Bp,{className:"h-3 w-3"})})}function ea({title:e,children:t,defaultExpanded:o=!1,copyData:n,isError:r=!1,externalLink:s}){let[a,d]=Ro(o);return ze("div",{children:[ze("div",{className:"mb-2 flex w-full items-center justify-between",children:[ze("button",{className:"flex items-center gap-1.5",onClick:()=>d(!a),type:"button",children:[a?H(ns,{className:"h-3 w-3 text-muted-foreground"}):H(rs,{className:"h-3 w-3 text-muted-foreground"}),H("span",{className:"font-medium text-muted-foreground text-xs uppercase tracking-wide",children:e})]}),ze("div",{className:"flex items-center gap-1",children:[s&&H(D,{asChild:!0,className:"h-7 px-2",size:"sm",variant:"ghost",children:H("a",{href:s,rel:"noopener noreferrer",target:"_blank",children:H(Vp,{className:"h-3 w-3"})})}),n!==void 0&&H(Jp,{data:n,isError:r})]})]}),a&&t]})}function Yp({output:e,input:t,actionType:o}){let r=(o?fe(o):void 0)?.outputConfig,s=o?Up(o):void 0,a=r?.type!=="component"?r:s,d=a?Kp(e,a):void 0,i=!(r||s)&&qp(e),c=(()=>{if(r?.type==="component"){let h=r.component;return H("div",{className:"overflow-hidden rounded-lg border bg-muted/50 p-3",children:H(h,{input:t,output:e})})}if(a&&d)switch(a.type){case"image":{let h=a.field==="base64"&&!d.startsWith("data:")?`data:image/png;base64,${d}`:d;return H("div",{className:"overflow-hidden rounded-lg border bg-muted/50 p-3",children:H(Rl,{alt:"Generated image",className:"max-h-96 w-auto rounded",height:384,src:h,unoptimized:!0,width:384})})}case"video":return H("div",{className:"overflow-hidden rounded-lg border bg-muted/50 p-3",children:H("video",{className:"max-h-96 w-auto rounded",controls:!0,src:d,children:H("track",{kind:"captions"})})});case"url":return H("div",{className:"overflow-hidden rounded-lg border bg-muted/50",children:H("iframe",{className:"h-96 w-full rounded",sandbox:"allow-scripts allow-same-origin",src:d,title:"Output preview"})});default:return null}return i?H("div",{className:"overflow-hidden rounded-lg border bg-muted/50 p-3",children:H(Rl,{alt:"AI generated output",className:"max-h-96 w-auto rounded",height:384,src:`data:image/png;base64,${e.base64}`,unoptimized:!0,width:384})}):null})(),u=c!==null,f=a?.type==="url"&&d?d:void 0;return ze(ta,{children:[H(ea,{copyData:e,title:"Output",children:H("pre",{className:"overflow-auto rounded-lg border bg-muted/50 p-3 font-mono text-xs leading-relaxed",children:H(Ll,{data:e})})}),u&&H(ea,{defaultExpanded:!0,externalLink:f,title:"Result",children:c})]})}function Xp({log:e,isExpanded:t,onToggle:o,getStatusIcon:n,getStatusDotClass:r,isFirst:s,isLast:a}){return ze("div",{className:"relative flex gap-3",children:[ze("div",{className:"relative -ml-px flex flex-col items-center pt-2",children:[!s&&H("div",{className:"absolute bottom-full h-2 w-px bg-border"}),H("div",{className:x("z-10 flex h-5 w-5 shrink-0 items-center justify-center rounded-full border-0",r(e.status)),children:n(e.status)}),!a&&H("div",{className:"absolute top-[calc(0.5rem+1.25rem)] bottom-0 w-px bg-border"})]}),ze("div",{className:"min-w-0 flex-1",children:[H("button",{className:"group w-full rounded-lg py-2 text-left transition-colors hover:bg-muted/50",onClick:o,type:"button",children:ze("div",{className:"flex items-center gap-3",children:[H("div",{className:"min-w-0 flex-1",children:ze("div",{className:"flex items-center gap-2",children:[t?H(ns,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}):H(rs,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),H("span",{className:"truncate font-medium text-sm transition-colors group-hover:text-foreground",children:e.nodeName||e.nodeType})]})}),e.duration&&H("span",{className:"shrink-0 font-mono text-muted-foreground text-xs tabular-nums",children:Number.parseInt(e.duration,10)<1e3?`${e.duration}ms`:`${(Number.parseInt(e.duration,10)/1e3).toFixed(2)}s`})]})}),t&&ze("div",{className:"mt-2 mb-2 space-y-3 px-3",children:[e.input!==null&&e.input!==void 0&&H(ea,{copyData:e.input,title:"Input",children:H("pre",{className:"overflow-auto rounded-lg border bg-muted/50 p-3 font-mono text-xs leading-relaxed",children:H(Ll,{data:e.input})})}),e.output!==null&&e.output!==void 0&&H(Yp,{actionType:e.nodeType,input:e.input,output:e.output}),e.error&&H(ea,{copyData:e.error,defaultExpanded:!0,isError:!0,title:"Error",children:H("pre",{className:"overflow-auto rounded-lg border border-red-500/20 bg-red-500/5 p-3 font-mono text-red-600 text-xs leading-relaxed",children:e.error})}),!(e.input||e.output||e.error)&&H("div",{className:"rounded-lg border bg-muted/30 py-4 text-center text-muted-foreground text-xs",children:"No data recorded"})]})]})]},e.id)}function wn({isActive:e=!1,onRefreshRef:t,onStartRun:o}){let[n]=ts(Ue),[r,s]=ts(no),[,a]=ts(Jo),[d,i]=Ro([]),[l,c]=Ro({}),[u,f]=Ro(new Set),[h,k]=Ro(new Set),[b,y]=Ro(!0),p=_p(null),v=Qn(async(L=!0)=>{if(!n){y(!1);return}try{L&&y(!0);let F=await q.workflow.getExecutions(n);i(F)}catch(F){console.error("Failed to load executions:",F),i([])}finally{L&&y(!1)}},[n]);Zr(()=>{t&&(t.current=()=>v(!1))},[v,t]),Zr(()=>{v()},[v]);let g=Qn((L,F)=>L.map($=>({id:$.id,nodeId:$.nodeId,nodeName:$.nodeName,nodeType:$.nodeType,status:$.status,startedAt:new Date($.startedAt),completedAt:$.completedAt?new Date($.completedAt):null,duration:$.duration,input:$.input,output:$.output,error:$.error})),[]),C=Qn(async L=>{try{let F=await q.workflow.getExecutionLogs(L),$=g(F.logs,F.execution.workflow);c(P=>({...P,[L]:$})),L===r&&a(os($))}catch(F){console.error("Failed to load execution logs:",F),c($=>({...$,[L]:[]}))}},[g,r,a]);Zr(()=>{if(d.length===0)return;let L=d[0];L.status==="running"&&L.id!==p.current&&(p.current=L.id,s(L.id),f(F=>{let $=new Set(F);return $.add(L.id),$}),C(L.id),o&&o(L.id))},[d,s,C,o]);let I=Qn(async L=>{try{let F=await q.workflow.getExecutionLogs(L),$=g(F.logs,F.execution.workflow);c(P=>({...P,[L]:$})),L===r&&a(os($))}catch(F){console.error(`Failed to refresh logs for ${L}:`,F)}},[g,r,a]);Zr(()=>{if(!(e&&n))return;let F=setInterval(async()=>{try{let $=await q.workflow.getExecutions(n);i($);for(let P of u)await I(P)}catch($){console.error("Failed to poll executions:",$)}},2e3);return()=>clearInterval(F)},[e,n,u,I]);let A=Qn(async L=>{try{await q.workflow.cancelExecution(L),await v(!1)}catch(F){console.error("Failed to cancel execution:",F)}},[v]),w=async L=>{let F=new Set(u);F.has(L)?F.delete(L):(F.add(L),await C(L)),f(F)},m=L=>{if(r===L){s(null),a({});return}s(L);let F=l[L]||[];a(os(F))},S=L=>{let F=new Set(h);F.has(L)?F.delete(L):F.add(L),k(F)},X=L=>{switch(L){case"success":return H(Ol,{className:"h-3 w-3 text-white"});case"error":return H($p,{className:"h-3 w-3 text-white"});case"cancelled":return H(Dl,{className:"h-3 w-3 text-white"});case"running":return H(Gp,{className:"h-3 w-3 animate-spin text-white"});default:return H(zp,{className:"h-3 w-3 text-white"})}},ie=L=>{switch(L){case"success":return"bg-green-600";case"error":return"bg-red-600";case"cancelled":return"bg-yellow-600";case"running":return"bg-blue-600";default:return"bg-muted-foreground"}};return b?H("div",{className:"flex items-center justify-center py-12",children:H(Tt,{})}):d.length===0?ze("div",{className:"flex flex-col items-center justify-center py-16",children:[H("div",{className:"mb-3 rounded-lg border border-dashed p-4",children:H(Hp,{className:"h-6 w-6 text-muted-foreground"})}),H("div",{className:"font-medium text-foreground text-sm",children:"No runs yet"}),H("div",{className:"mt-1 text-muted-foreground text-xs",children:"Execute your workflow to see runs here"})]}):H("div",{className:"space-y-3",children:d.map((L,F)=>{let $=u.has(L.id),P=r===L.id,V=(l[L.id]||[]).sort((J,W)=>new Date(J.startedAt).getTime()-new Date(W.startedAt).getTime());return ze("div",{className:x("overflow-hidden rounded-lg border bg-card transition-all",P&&"ring-2 ring-primary ring-offset-2 ring-offset-background"),children:[ze("div",{className:"flex w-full items-center gap-3 p-4",children:[H("button",{className:"flex size-5 shrink-0 items-center justify-center rounded-full border-0 transition-colors hover:bg-muted",onClick:()=>w(L.id),type:"button",children:H("div",{className:x("flex size-5 items-center justify-center rounded-full border-0",ie(L.status)),children:X(L.status)})}),ze("button",{className:"min-w-0 flex-1 text-left transition-colors hover:opacity-80",onClick:()=>m(L.id),type:"button",children:[H("div",{className:"mb-1 flex items-center gap-2",children:ze("span",{className:"font-semibold text-sm",children:["Run #",d.length-F]})}),ze("div",{className:"flex items-center gap-2 font-mono text-muted-foreground text-xs",children:[H("span",{children:El(L.startedAt)}),L.duration&&ze(ta,{children:[H("span",{children:"\u2022"}),H("span",{className:"tabular-nums",children:Number.parseInt(L.duration,10)<1e3?`${L.duration}ms`:`${(Number.parseInt(L.duration,10)/1e3).toFixed(2)}s`})]}),V.length>0&&ze(ta,{children:[H("span",{children:"\u2022"}),ze("span",{children:[V.length," ",V.length===1?"step":"steps"]})]})]})]}),(L.status==="running"||L.status==="pending")&&H("button",{className:"flex shrink-0 items-center justify-center rounded p-1 text-muted-foreground transition-colors hover:bg-destructive/10 hover:text-destructive",onClick:J=>{J.stopPropagation(),A(L.id)},title:"Stop execution",type:"button",children:H(Dl,{className:"h-3.5 w-3.5"})}),H("button",{className:"flex shrink-0 items-center justify-center rounded p-1 transition-colors hover:bg-muted",onClick:()=>w(L.id),type:"button",children:$?H(ns,{className:"h-4 w-4 text-muted-foreground"}):H(rs,{className:"h-4 w-4 text-muted-foreground"})})]}),$&&H("div",{className:"border-t bg-muted/20",children:V.length===0?H("div",{className:"py-8 text-center text-muted-foreground text-xs",children:"No steps recorded"}):H("div",{className:"p-4",children:V.map((J,W)=>H(Xp,{getStatusDotClass:ie,getStatusIcon:X,isExpanded:h.has(J.id),isFirst:W===0,isLast:W===V.length-1,log:J,onToggle:()=>S(J.id)},J.id))})})]},L.id)})})}import{Fragment as fo,jsx as O,jsxs as U}from"react/jsx-runtime";var of=/[^a-zA-Z0-9\s]/g,nf=/\s+/,Vl={"Database Query":"database"},rf=({selectedNodes:e,selectedEdges:t,onDelete:o})=>{let[n,r]=Zn(!1),s=e.length===1?"node":"nodes",a=t.length===1?"line":"lines",d=[];e.length>0&&d.push(`${e.length} ${s}`),t.length>0&&d.push(`${t.length} ${a}`);let i=d.join(" and ");return U(fo,{children:[U("div",{className:"flex size-full flex-col",children:[O("div",{className:"flex h-14 w-full shrink-0 items-center border-b bg-transparent px-4",children:O("h2",{className:"font-semibold text-foreground",children:"Properties"})}),U("div",{className:"flex-1 space-y-4 overflow-y-auto p-4",children:[U("div",{className:"space-y-2",children:[O(M,{children:"Selection"}),U("p",{className:"text-muted-foreground text-sm",children:[i," selected"]})]}),O("div",{className:"flex items-center gap-2 pt-4",children:U(D,{className:"text-muted-foreground",onClick:()=>r(!0),size:"sm",variant:"ghost",children:[O(oa,{className:"mr-2 size-4"}),"Delete"]})})]})]}),O(tn,{onOpenChange:r,open:n,children:U(on,{children:[U(nn,{children:[O(an,{children:"Delete Selected Items"}),U(sn,{children:["Are you sure you want to delete ",i,"? This action cannot be undone."]})]}),U(rn,{children:[O(dn,{children:"Cancel"}),O(ln,{onClick:()=>{o(),r(!1)},children:"Delete"})]})]})})]})},af=()=>{let[e]=po(ke),[t]=po(_e),[o]=po(re),n=as(ue),[r]=po(Nt),[s]=po(Ue),[a,d]=po(gt),i=as(oo),l=Oo(ro),c=Oo(ao),u=Oo(so),f=Oo(li),h=Oo(Xo),{open:k}=oe(),b=Oo(Tr),y=Oo(Nr),[p,v]=po(to),[g,C]=Zn(!1),[I,A]=Zn(!1),[w,m]=Zn(!1),[S,X]=Zn(!1),[ie,L]=po(Bt),F=Bl(null),$=Bl({}),P=o.find(ee=>ee.id===e),V=n.find(ee=>ee.id===t),J=o.filter(ee=>ee.selected),W=n.filter(ee=>ee.selected),K=J.length+W.length>1;zl(()=>{if(!P||ie!=="code")return;let ee=P.data.config?.actionType==="Condition",xe=P.data.type==="trigger"&&P.data.config?.triggerType==="Manual";(ee||xe)&&L("properties")},[P,ie,L]);let T=as(ft);zl(()=>{if(!(P&&i))return;let ee=P.data.config?.actionType,xe=P.data.config?.integrationId;if(!(ee&&xe))return;let E=fe(ee)?.integration||Vl[ee];if(!E||T.some(ce=>ce.id===xe))return;let Y=T.filter(ce=>ce.type===E);if(Y.length===1){let ce={...P.data.config,integrationId:Y[0].id};l({id:P.id,data:{config:ce}})}else if(Y.length===0){let ce={...P.data.config,integrationId:void 0};l({id:P.id,data:{config:ce}})}},[P,T,i,l]);let z=tf(()=>{let xe=`${a.replace(of,"").split(nf).map((E,_)=>_===0?E.toLowerCase():E.charAt(0).toUpperCase()+E.slice(1).toLowerCase()).join("")||"execute"}Workflow`,{code:Q}=mr(o,n,{functionName:xe});return Q},[o,n,a]),N=()=>{P&&navigator.clipboard.writeText(hn(P))},R=()=>{navigator.clipboard.writeText(z),xn.success("Code copied to clipboard")},G=()=>{e&&(c(e),C(!1))},ne=()=>{if(P){let ee=P.data.enabled??!0;l({id:P.id,data:{enabled:!ee}})}},de=()=>{t&&(u(t),A(!1))},B=async()=>{if(s)try{await q.workflow.deleteExecutions(s),b(),m(!1)}catch(ee){console.error("Failed to delete runs:",ee);let xe=ee instanceof Error?ee.message:"Failed to delete runs";xn.error(xe)}},Ae=ee=>{P&&l({id:P.id,data:{label:ee}})},Je=ee=>{P&&l({id:P.id,data:{description:ee}})},Ye=ef(async(ee,xe,Q,E)=>{let Y=fe(xe)?.integration||Vl[xe];if(!Y){y(ce=>{let De=new Set(ce);return De.delete(ee),De});return}try{let ce=await q.integration.getAll();if(E.aborted)return;let De=ce.filter(Me=>Me.type===Y);if(De.length===1&&!E.aborted){let Me={...Q,actionType:xe,integrationId:De[0].id};l({id:ee,data:{config:Me}})}}catch(ce){console.error("Failed to auto-select integration:",ce)}finally{E.aborted||y(ce=>{let De=new Set(ce);return De.delete(ee),De})}},[l,y]),$e=(ee,xe)=>{if(P){let Q={...P.data.config,[ee]:xe};if(ee==="actionType"&&P.data.config?.integrationId&&(Q={...Q,integrationId:void 0}),l({id:P.id,data:{config:Q}}),ee==="actionType"){let E=$.current[P.id];E&&E.abort();let _=new AbortController;$.current[P.id]=_,y(Y=>new Set(Y).add(P.id)),Ye(P.id,xe,Q,_.signal)}}},Zt=async ee=>{if(d(ee),s)try{await q.workflow.update(s,{name:ee,nodes:o,edges:n})}catch(xe){console.error("Failed to update workflow name:",xe),xn.error("Failed to update workspace name")}},Et=async()=>{X(!0);try{F.current&&await F.current()}catch(ee){console.error("Failed to refresh runs:",ee),xn.error("Failed to refresh runs")}finally{X(!1)}};return K?O(rf,{onDelete:f,selectedEdges:W,selectedNodes:J}):V?U(fo,{children:[U("div",{className:"flex size-full flex-col",children:[O("div",{className:"flex h-14 w-full shrink-0 items-center border-b bg-transparent px-4",children:O("h2",{className:"font-semibold text-foreground",children:"Properties"})}),U("div",{className:"flex-1 space-y-4 overflow-y-auto p-4",children:[U("div",{className:"space-y-2",children:[O(M,{className:"ml-1",htmlFor:"edge-id",children:"Edge ID"}),O(ae,{disabled:!0,id:"edge-id",value:V.id})]}),U("div",{className:"space-y-2",children:[O(M,{className:"ml-1",htmlFor:"edge-source",children:"Source"}),O(ae,{disabled:!0,id:"edge-source",value:V.source})]}),U("div",{className:"space-y-2",children:[O(M,{className:"ml-1",htmlFor:"edge-target",children:"Target"}),O(ae,{disabled:!0,id:"edge-target",value:V.target})]}),i&&O("div",{className:"flex items-center gap-2 pt-4",children:U(D,{className:"text-muted-foreground",onClick:()=>A(!0),size:"sm",variant:"ghost",children:[O(oa,{className:"mr-2 size-4"}),"Delete"]})})]})]}),O(tn,{onOpenChange:A,open:I,children:U(on,{children:[U(nn,{children:[O(an,{children:"Delete Edge"}),O(sn,{children:"Are you sure you want to delete this connection? This action cannot be undone."})]}),U(rn,{children:[O(dn,{children:"Cancel"}),O(ln,{onClick:de,children:"Delete"})]})]})})]}):P?U(fo,{children:[U(Ra,{className:"size-full","data-testid":"properties-panel",defaultValue:"properties",onValueChange:L,value:ie,children:[U(Oa,{className:"h-14 w-full shrink-0 rounded-none border-b bg-transparent px-4 py-2.5",children:[O(No,{className:"bg-transparent text-muted-foreground data-[state=active]:text-foreground data-[state=active]:shadow-none",value:"properties",children:"Properties"}),(P.data.type!=="trigger"||P.data.config?.triggerType!=="Manual")&&P.data.config?.actionType!=="Condition"?O(No,{className:"bg-transparent text-muted-foreground data-[state=active]:text-foreground data-[state=active]:shadow-none",value:"code",children:"Code"}):null,i&&O(No,{className:"bg-transparent text-muted-foreground data-[state=active]:text-foreground data-[state=active]:shadow-none",value:"runs",children:"Runs"})]}),U(ko,{className:"flex flex-col overflow-hidden",value:"properties",children:[P.data.type==="action"&&!P.data.config?.actionType&&i&&O("div",{className:"flex min-h-0 flex-1 flex-col px-4 pt-4",children:O(Xr,{disabled:r,isNewlyCreated:P?.id===p,onSelectAction:ee=>{$e("actionType",ee),P?.id===p&&v(null)}})}),!(P.data.type==="action"&&!P.data.config?.actionType&&i)&&U("div",{className:"flex-1 space-y-4 overflow-y-auto p-4",children:[U("div",{className:"space-y-2",children:[O(M,{className:"ml-1",htmlFor:"node-id",children:"Node ID"}),O(ae,{readOnly:!0,id:"node-id",value:P?.id||""})]}),P.data.type==="trigger"&&O(Qr,{config:P.data.config||{},disabled:r||!i,onUpdateConfig:$e,workflowId:s??void 0}),P.data.type==="action"&&!P.data.config?.actionType&&!i&&O("div",{className:"rounded-lg border border-muted bg-muted/30 p-3",children:O("p",{className:"text-muted-foreground text-sm",children:"No action configured for this step."})}),P.data.type==="action"&&P.data.config?.actionType?O(_r,{config:P.data.config||{},disabled:r||!i,isOwner:i,onUpdateConfig:$e}):null,P.data.type!=="action"||P.data.config?.actionType?U(fo,{children:[U("div",{className:"space-y-2",children:[O(M,{className:"ml-1",htmlFor:"label",children:"Label"}),O(ae,{disabled:r||!i,id:"label",onChange:ee=>Ae(ee.target.value),value:P.data.label})]}),U("div",{className:"space-y-2",children:[O(M,{className:"ml-1",htmlFor:"description",children:"Description"}),O(ae,{disabled:r||!i,id:"description",onChange:ee=>Je(ee.target.value),placeholder:"Optional description",value:P.data.description||""})]})]}):null,!i&&O("div",{className:"rounded-lg border border-muted bg-muted/30 p-3",children:O("p",{className:"text-muted-foreground text-sm",children:"You are viewing a public workflow. Duplicate it to make changes."})}),i&&U("div",{className:"flex items-center gap-2 pt-4",children:[P.data.type==="action"&&O(D,{className:"text-muted-foreground",onClick:ne,size:"sm",variant:"ghost",children:P.data.enabled===!1?U(fo,{children:[O(Zp,{className:"mr-2 size-4"}),"Disabled"]}):U(fo,{children:[O(Qp,{className:"mr-2 size-4"}),"Enabled"]})}),U(D,{className:"text-muted-foreground",onClick:()=>C(!0),size:"sm",variant:"ghost",children:[O(oa,{className:"mr-2 size-4"}),"Delete"]})]})]})]}),O(ko,{className:"flex flex-col overflow-hidden data-[state=inactive]:hidden",forceMount:!0,value:"code",children:(()=>{let ee=P.data.config?.triggerType,xe="",Q="typescript";return P.data.type==="trigger"?ee==="Schedule"?(xe="vercel.json",Q="json"):ee==="Webhook"&&(xe=`app/api${P.data.config?.webhookPath||"/webhook"}/route.ts`,Q="typescript"):xe=`steps/${P.data.config?.actionType?.toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9-]/g,"")||"action"}-step.ts`,U(fo,{children:[xe&&U("div",{className:"flex shrink-0 items-center justify-between border-b bg-muted/30 px-3 pb-2",children:[U("div",{className:"flex items-center gap-2",children:[O(Wl,{className:"size-3.5 text-muted-foreground"}),O("code",{className:"text-muted-foreground text-xs",children:xe})]}),U(D,{className:"text-muted-foreground",onClick:N,size:"sm",variant:"ghost",children:[O(Ml,{className:"mr-2 size-4"}),"Copy"]})]}),O("div",{className:"flex-1 overflow-hidden",children:O(yt,{height:"100%",language:Q,options:{readOnly:!0,minimap:{enabled:!1},scrollBeyondLastLine:!1,fontSize:13,lineNumbers:"on",folding:!1,wordWrap:"off",padding:{top:16,bottom:16}},value:hn(P)})})]})})()}),i&&U(ko,{className:"flex flex-col overflow-hidden",value:"runs",children:[U("div",{className:"flex shrink-0 items-center gap-2 border-b px-4 py-2",children:[U(D,{className:"text-muted-foreground",disabled:S,onClick:Et,size:"sm",variant:"ghost",children:[O(Fl,{className:`mr-2 size-4 ${S?"animate-spin":""}`}),"Refresh"]}),U(D,{className:"text-muted-foreground",onClick:()=>m(!0),size:"sm",variant:"ghost",children:[O(ss,{className:"mr-2 size-4"}),"Clear All"]})]}),O("div",{className:"flex-1 space-y-4 overflow-y-auto p-4",children:O(wn,{isActive:ie==="runs",onRefreshRef:F})})]})]}),O(tn,{onOpenChange:m,open:w,children:U(on,{children:[U(nn,{children:[O(an,{children:"Delete All Runs"}),O(sn,{children:"Are you sure you want to delete all workflow runs? This action cannot be undone."})]}),U(rn,{children:[O(dn,{children:"Cancel"}),O(ln,{onClick:B,children:"Delete"})]})]})}),O(tn,{onOpenChange:C,open:g,children:U(on,{children:[U(nn,{children:[O(an,{children:"Delete Step"}),O(sn,{children:"Are you sure you want to delete this node? This action cannot be undone."})]}),U(rn,{children:[O(dn,{children:"Cancel"}),O(ln,{onClick:G,children:"Delete"})]})]})})]}):U(fo,{children:[U(Ra,{className:"size-full",defaultValue:"properties",onValueChange:L,value:ie,children:[U(Oa,{className:"h-14 w-full shrink-0 rounded-none border-b bg-transparent px-4 py-2.5",children:[O(No,{className:"bg-transparent text-muted-foreground data-[state=active]:text-foreground data-[state=active]:shadow-none",value:"properties",children:"Properties"}),O(No,{className:"bg-transparent text-muted-foreground data-[state=active]:text-foreground data-[state=active]:shadow-none",value:"code",children:"Code"}),i&&O(No,{className:"bg-transparent text-muted-foreground data-[state=active]:text-foreground data-[state=active]:shadow-none",value:"runs",children:"Runs"})]}),O(ko,{className:"flex flex-col overflow-hidden",value:"properties",children:U("div",{className:"flex-1 space-y-4 overflow-y-auto p-4",children:[U("div",{className:"space-y-2",children:[O(M,{className:"ml-1",htmlFor:"workflow-name",children:"Workflow Name"}),O(ae,{disabled:!i,id:"workflow-name",onChange:ee=>Zt(ee.target.value),value:a})]}),U("div",{className:"space-y-2",children:[O(M,{className:"ml-1",htmlFor:"workflow-id",children:"Workflow ID"}),O(ae,{disabled:!0,id:"workflow-id",value:s||"Not saved"})]}),!i&&O("div",{className:"rounded-lg border border-muted bg-muted/30 p-3",children:O("p",{className:"text-muted-foreground text-sm",children:"You are viewing a public workflow. Duplicate it to make changes."})}),i&&U("div",{className:"flex items-center gap-2 pt-4",children:[U(D,{className:"text-muted-foreground",onClick:()=>{k(Ie,{title:"Clear Workflow",message:"Are you sure you want to clear all nodes and connections? This action cannot be undone.",confirmLabel:"Clear Workflow",confirmVariant:"destructive",destructive:!0,onConfirm:()=>{h()}})},size:"sm",variant:"ghost",children:[O(ss,{className:"mr-2 size-4"}),"Clear"]}),U(D,{className:"text-muted-foreground",onClick:()=>{k(Ie,{title:"Delete Workflow",message:`Are you sure you want to delete "${a}"? This will permanently delete the workflow. This cannot be undone.`,confirmLabel:"Delete Workflow",confirmVariant:"destructive",destructive:!0,onConfirm:async()=>{if(s)try{await q.workflow.delete(s),xn.success("Workflow deleted successfully"),window.location.href="/"}catch(ee){console.error("Failed to delete workflow:",ee),xn.error("Failed to delete workflow. Please try again.")}}})},size:"sm",variant:"ghost",children:[O(oa,{className:"mr-2 size-4"}),"Delete"]})]})]})}),i&&U(ko,{className:"flex flex-col overflow-hidden",value:"runs",children:[U("div",{className:"flex shrink-0 items-center gap-2 border-b px-4 py-2",children:[U(D,{className:"text-muted-foreground",disabled:S,onClick:Et,size:"sm",variant:"ghost",children:[O(Fl,{className:`mr-2 size-4 ${S?"animate-spin":""}`}),"Refresh"]}),U(D,{className:"text-muted-foreground",onClick:()=>m(!0),size:"sm",variant:"ghost",children:[O(ss,{className:"mr-2 size-4"}),"Clear All"]})]}),O("div",{className:"flex-1 space-y-4 overflow-y-auto p-4",children:O(wn,{isActive:ie==="runs",onRefreshRef:F})})]}),U(ko,{className:"flex flex-col overflow-hidden data-[state=inactive]:hidden",forceMount:!0,value:"code",children:[U("div",{className:"flex shrink-0 items-center justify-between border-b bg-muted/30 px-3 pb-2",children:[U("div",{className:"flex items-center gap-2",children:[O(Wl,{className:"size-3.5 text-muted-foreground"}),U("code",{className:"text-muted-foreground text-xs",children:["workflows/",a.toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9-]/g,"")||"workflow",".ts"]})]}),U(D,{className:"text-muted-foreground",onClick:R,size:"sm",variant:"ghost",children:[O(Ml,{className:"mr-2 size-4"}),"Copy"]})]}),O("div",{className:"flex-1 overflow-hidden",children:O(yt,{height:"100%",language:"typescript",options:{readOnly:!0,minimap:{enabled:!1},scrollBeyondLastLine:!1,fontSize:13,lineNumbers:"on",folding:!0,wordWrap:"off",padding:{top:16,bottom:16}},value:z})})]})]}),O(tn,{onOpenChange:m,open:w,children:U(on,{children:[U(nn,{children:[O(an,{children:"Delete All Runs"}),O(sn,{children:"Are you sure you want to delete all workflow runs? This action cannot be undone."})]}),U(rn,{children:[O(dn,{children:"Cancel"}),O(ln,{onClick:B,children:"Delete"})]})]})})]})},is=()=>O("div",{className:"hidden size-full flex-col bg-background md:flex",children:O(af,{})});import{jsx as It,jsxs as na}from"react/jsx-runtime";var cs=({workflowId:e})=>{let t=uf(),o=Vt(),[n,r]=$t(Nt),[s,a]=$t(Cr),[d]=$t(re),[i]=$t(ue),[l]=$t(Ue),[c]=$t(no),u=At(re),f=At(ue),h=At(Ue),k=At(gt),b=At(ro),y=At(nt),[p,v]=$t(di),g=At(kr),C=At(hr),I=At(br),[A,w]=$t(wr),[m,S]=$t(ri),X=At(yr),[ie,L]=$t(oo),F=At(ft),$=At(gr),P=sf(Rt),[V,J]=ls(30),[W,K]=ls(A),[T,z]=ls(!1),N=Lo(!1),R=Lo(!1);St(()=>{if(R.current)return;R.current=!0;let E=document.cookie.split("; ").find(Y=>Y.startsWith("sidebar-width="));if(E){let Y=Number.parseFloat(E.split("=")[1]);!Number.isNaN(Y)&&Y>=20&&Y<=50&&J(Y)}let _=document.cookie.split("; ").find(Y=>Y.startsWith("sidebar-collapsed="));_&&S(_.split("=")[1]==="true")},[S]);let G=Lo(!1);St(()=>{if(!G.current){G.current=!0;return}document.cookie=`sidebar-width=${V}; path=/; max-age=31536000`},[V]),St(()=>{R.current&&(document.cookie=`sidebar-collapsed=${m}; path=/; max-age=31536000`)},[m]),St(()=>{let E=sessionStorage.getItem("animate-sidebar")==="true";if(sessionStorage.removeItem("animate-sidebar"),A||!E){K(!0),w(!0);return}I(!0);let _=setTimeout(()=>{K(!0),w(!0)},100),Y=setTimeout(()=>I(!1),400);return()=>{clearTimeout(_),clearTimeout(Y),I(!1)}},[A,w,I]),St(()=>{let E=_=>{(_.metaKey||_.ctrlKey)&&_.key==="b"&&(_.preventDefault(),I(!0),S(Y=>!Y),setTimeout(()=>I(!1),350))};return window.addEventListener("keydown",E),()=>window.removeEventListener("keydown",E)},[I,S]),St(()=>(C(!o&&W&&!m?`${V}%`:null),()=>{C(null)}),[o,C,V,W,m]);let ne=go(E=>{E.preventDefault(),N.current=!0,z(!0);let _=ce=>{if(!N.current)return;let De=(window.innerWidth-ce.clientX)/window.innerWidth*100;J(Math.min(50,Math.max(20,De)))},Y=()=>{N.current=!1,z(!1),document.removeEventListener("mousemove",_),document.removeEventListener("mouseup",Y),document.body.style.cursor="",document.body.style.userSelect=""};document.addEventListener("mousemove",_),document.addEventListener("mouseup",Y),document.body.style.cursor="col-resize",document.body.style.userSelect="none"},[]),de=Lo(null),B=Lo(null),Ae=Lo(d);St(()=>{Ae.current=d},[d]);let Je=go(async E=>{r(!0),h(e),k("AI Generated Workflow");try{let _=await q.ai.generate(E),Y=(_.nodes||[]).map(ce=>({...ce,selected:!1}));u(Y),f(_.edges||[]),k(_.name||"AI Generated Workflow"),await q.workflow.update(e,{name:_.name,description:_.description,nodes:_.nodes,edges:_.edges})}catch(_){console.error("Failed to generate workflow:",_),ds.error("Failed to generate workflow")}finally{r(!1)}},[e,r,h,k,u,f]),Ye=go(async()=>{try{let E=await q.workflow.getById(e);if(!E){v(!0);return}let _=E.nodes.map(Y=>({...Y,selected:!1,data:{...Y.data,status:"idle"}}));u(_),f(E.edges),h(E.id),k(E.name),X(E.visibility??"private"),L(E.isOwner!==!1),y(!1),v(!1)}catch(E){console.error("Failed to load workflow:",E),ds.error("Failed to load workflow")}},[e,u,f,h,k,X,L,y,v]),$e=Lo(null);St(()=>{(async()=>{let _=t?.get("generating")==="true",Y=sessionStorage.getItem("ai-prompt"),ce=sessionStorage.getItem("generating-workflow-id");l===e&&d.length>0||(_&&Y&&ce===e?(sessionStorage.removeItem("ai-prompt"),sessionStorage.removeItem("generating-workflow-id"),await Je(Y)):await Ye())})()},[e,t,l,d.length,Je,Ye]),St(()=>{if(d.length===0||!l||!ie)return;let E=$e.current;if(E&&E.workflowId===l&&E.version===P)return;(async()=>{try{let Y=await q.integration.getAll();F(Y),$(!0);let ce=new Set(Y.map(Me=>Me.id)),De=d.map(Me=>fi(Me,Y,ce)).filter(Me=>Me!==null);for(let Me of De){let Wn=d.find(Na=>Na.id===Me.nodeId);Wn&&b({id:Me.nodeId,data:{config:{...Wn.data.config,integrationId:Me.newIntegrationId}}})}$e.current={workflowId:l,version:P},De.length>0&&y(!0)}catch(Y){console.error("Failed to auto-fix integrations:",Y)}})()},[d,l,P,ie,b,F,$,y]);let Zt=go(async()=>{if(!(!l||n)){a(!0);try{await q.workflow.update(l,{nodes:d,edges:i}),y(!1)}catch(E){console.error("Failed to save workflow:",E),ds.error("Failed to save workflow")}finally{a(!1)}}},[l,d,i,n,a,y]),Et=go(E=>E.tagName==="INPUT"||E.tagName==="TEXTAREA",[]),ee=go(E=>E.closest(".monaco-editor")!==null,[]),xe=go(E=>(E.metaKey||E.ctrlKey)&&E.key==="s"?(E.preventDefault(),E.stopPropagation(),Zt(),!0):!1,[Zt]),Q=go((E,_)=>(E.metaKey||E.ctrlKey)&&E.key==="Enter"?(Et(_)||ee(_)||(E.preventDefault(),E.stopPropagation(),g(!0)),!0):!1,[g,Et,ee]);return St(()=>{let E=_=>{let Y=_.target;xe(_)||Q(_,Y)};return document.addEventListener("keydown",E,!0),()=>document.removeEventListener("keydown",E,!0)},[xe,Q]),St(()=>()=>{de.current&&clearInterval(de.current),B.current&&clearInterval(B.current)},[]),St(()=>{if(B.current&&(clearInterval(B.current),B.current=null),!c){for(let _ of Ae.current)b({id:_.id,data:{status:"idle"}});return}let E=async()=>{try{let _=await q.workflow.getExecutionStatus(c);for(let Y of _.nodeStatuses)b({id:Y.nodeId,data:{status:Y.status}});_.status!=="running"&&B.current&&(clearInterval(B.current),B.current=null)}catch(_){console.error("Failed to poll selected execution status:",_),B.current&&(clearInterval(B.current),B.current=null)}};return E(),B.current=setInterval(E,500),()=>{B.current&&(clearInterval(B.current),B.current=null)}},[c,b]),na("div",{className:"flex h-dvh w-full flex-col overflow-hidden",children:[p&&It("div",{className:"pointer-events-auto absolute inset-0 z-20 flex items-center justify-center",children:na("div",{className:"rounded-lg border bg-background p-8 text-center shadow-lg",children:[It("h1",{className:"mb-2 font-semibold text-2xl",children:"Workflow Not Found"}),It("p",{className:"mb-6 text-muted-foreground",children:"The workflow you're looking for doesn't exist or has been deleted."}),It(D,{asChild:!0,children:It(cf,{href:"/",children:"New Workflow"})})]})}),!o&&m&&It("button",{className:"pointer-events-auto absolute top-1/2 right-0 z-20 flex size-6 -translate-y-1/2 items-center justify-center rounded-l-full border border-r-0 bg-background shadow-sm transition-colors hover:bg-muted",onClick:()=>{I(!0),S(!1),setTimeout(()=>I(!1),350)},type:"button",children:It(lf,{className:"size-4"})}),!o&&na("div",{className:"pointer-events-auto absolute inset-y-0 right-0 z-20 border-l bg-background transition-transform duration-300 ease-out",style:{width:`${V}%`,transform:W&&!m?"translateX(0)":"translateX(100%)"},children:[na("div",{"aria-orientation":"vertical","aria-valuenow":V,className:"group absolute inset-y-0 left-0 z-10 w-3 cursor-col-resize",onMouseDown:ne,role:"separator",tabIndex:0,children:[It("div",{className:"absolute inset-y-0 left-0 w-1 bg-transparent transition-colors group-hover:bg-blue-500 group-active:bg-blue-600"}),!(T||m)&&It("button",{className:"absolute top-1/2 left-0 flex size-6 -translate-x-1/2 -translate-y-1/2 items-center justify-center rounded-full border bg-background opacity-0 shadow-sm transition-opacity hover:bg-muted group-hover:opacity-100",onClick:E=>{E.stopPropagation(),I(!0),S(!0),setTimeout(()=>I(!1),350)},onMouseDown:E=>E.stopPropagation(),type:"button",children:It(df,{className:"size-4"})})]}),It(is,{})]}),o&&It(is,{})]})};import{useAtomValue as us,useSetAtom as er}from"jotai";import{nanoid as ff}from"nanoid";import{useRouter as gf}from"next/navigation";import{useCallback as Hl,useEffect as ra,useRef as yf}from"react";import{toast as vf}from"sonner";import{anonymousClient as mf}from"better-auth/client/plugins";import{createAuthClient as pf}from"better-auth/react";var Mo=pf({baseURL:typeof window<"u"?window.location.origin:"http://localhost:3000",plugins:[mf()]}),{signIn:m0,signOut:Gl,signUp:p0,useSession:Nn}=Mo;function hf(){return{id:ff(),type:"trigger",position:{x:0,y:0},data:{label:"",description:"",type:"trigger",config:{triggerType:"Manual"},status:"idle"}}}var $l=()=>{let e=gf(),{data:t}=Nn(),o=us(re),n=us(ue),r=er(re),s=er(ue),a=er(gt),d=er(wr),i=er(xr),l=yf(!1),c=us(gt);ra(()=>{d(!1)},[d]),ra(()=>{document.title=`${c} - AI Workflow Builder`},[c]);let u=Hl(async()=>{t||(await Mo.signIn.anonymous(),await new Promise(h=>setTimeout(h,100)))},[t]),f=Hl(()=>{let h=hf();r([h])},[r]);return ra(()=>{r([{id:"add-node-placeholder",type:"add",position:{x:0,y:0},data:{label:"",type:"add",onClick:f},draggable:!1,selectable:!1}]),s([]),a("New Workflow"),l.current=!1},[r,s,a,f]),ra(()=>{(async()=>{let k=o.filter(b=>b.type!=="add");if(!(k.length===0||l.current)){l.current=!0;try{await u();let b=await q.workflow.create({name:"Untitled Workflow",description:"",nodes:k,edges:n});sessionStorage.setItem("animate-sidebar","true"),i(!0),console.log("[Homepage] Navigating to workflow page"),e.replace(`/workflows/${b.id}`)}catch(b){console.error("Failed to create workflow:",b),vf.error("Failed to create workflow")}}})()},[o,n,e,u,i]),null};import{useRouter as bf}from"next/navigation";import{useEffect as wf}from"react";var _l=()=>{let e=bf();return wf(()=>{(async()=>{try{let n=(await q.workflow.getAll()).filter(r=>r.name!=="__current__");if(n.length>0){let r=n.sort((s,a)=>new Date(a.updatedAt).getTime()-new Date(s.updatedAt).getTime())[0];e.replace(`/workflows/${r.id}`)}else e.replace("/")}catch(o){console.error("Failed to load workflows:",o),e.replace("/")}})()},[e]),null};import{jsx as kn}from"react/jsx-runtime";var kf=()=>{let t=Nf().slug;return!t||t.length===0?kn($l,{}):t[0]==="auth"&&t.length===2?kn("main",{className:"flex items-center justify-center min-h-screen",children:kn(xf,{path:t[1]})}):t[0]==="workflows"&&t.length===1?kn(_l,{}):t[0]==="workflows"&&t.length===2?kn("div",{className:"pointer-events-none relative z-10",children:kn(cs,{workflowId:t[1]})}):null};import"virtual:workflow-builder-plugins";import{ReactFlowProvider as Yv}from"@xyflow/react";import{Provider as Xv,useSetAtom as Qv}from"jotai";import*as xa from"react";import{AnimatePresence as Af,LayoutGroup as ql,motion as Tn,useReducedMotion as jl}from"motion/react";import{useCallback as or,useLayoutEffect as nr,useRef as yo,useState as Jl}from"react";import{Drawer as tr}from"vaul";import{Dialog as Cn}from"radix-ui";import{XIcon as Cf}from"lucide-react";import{jsx as Wo,jsxs as ms}from"react/jsx-runtime";function aa({...e}){return Wo(Cn.Root,{"data-slot":"dialog",...e})}function ps({...e}){return Wo(Cn.Portal,{"data-slot":"dialog-portal",...e})}function Tf({className:e,...t}){return Wo(Cn.Overlay,{"data-slot":"dialog-overlay",className:x("data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",e),...t})}function Ul({className:e,children:t,showCloseButton:o=!0,...n}){return ms(ps,{"data-slot":"dialog-portal",children:[Wo(Tf,{}),ms(Cn.Content,{"data-slot":"dialog-content",className:x("bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 sm:max-w-lg",e),...n,children:[t,o&&ms(Cn.Close,{"data-slot":"dialog-close",className:"ring-offset-background focus:ring-ring data-[state=open]:bg-accent data-[state=open]:text-muted-foreground absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",children:[Wo(Cf,{}),Wo("span",{className:"sr-only",children:"Close"})]})]})]})}function Kl({className:e,...t}){return Wo(Cn.Title,{"data-slot":"dialog-title",className:x("text-lg leading-none font-semibold",e),...t})}import{jsx as We,jsxs as gs}from"react/jsx-runtime";var fs={type:"spring",stiffness:400,damping:35,mass:.8},Sf={type:"spring",stiffness:350,damping:30,mass:.8},If={hidden:{opacity:0,scale:.95},visible:{opacity:1,scale:1,transition:{type:"spring",stiffness:400,damping:30}},exit:{opacity:0,scale:.95,transition:{duration:.15,ease:[.4,0,1,1]}}};function Yl(e,t){return e?"0%":t?"-35%":"100%"}function Xl(e){let t=yo(e),o=yo(1);return e>t.current?o.current=1:e<t.current&&(o.current=-1),nr(()=>{t.current=e},[e]),o.current}function Pf(){let{stack:e,closeAll:t,pop:o}=oe(),n=jl(),[r,s]=Jl(0),a=yo(null),d=yo(!1),i=yo(e),l=Xl(e.length),c=e.length>0;c&&(i.current=e);let u=i.current,f=u.length-1;console.log("[DesktopOverlay]",{isOpen:c,stackLength:e.length,frozenStackLength:i.current.length,renderStackLength:u.length}),nr(()=>{let g=c&&!d.current;if(d.current=c,g&&s(0),a.current){let C=a.current.offsetHeight;C>0&&s(C)}},[e,c]);let h=e[e.length-1],k=n?{duration:.01}:fs,b=l===1,y=or(()=>{h?.options.closeOnBackdropClick!==!1&&t()},[h?.options.closeOnBackdropClick,t]),p=or(g=>{g.key==="Escape"&&h?.options.closeOnEscape!==!1&&o()},[h?.options.closeOnEscape,o]);nr(()=>{if(c)return document.addEventListener("keydown",p),()=>document.removeEventListener("keydown",p)},[c,p]);let v=or(()=>{console.log("[DesktopOverlay] handleExitComplete called"),i.current=[]},[]);return console.log("[DesktopOverlay] Rendering, isOpen:",c),!c&&i.current.length===0?null:We(Af,{onExitComplete:v,children:c&&We(aa,{modal:!1,open:!0,children:gs(ps,{forceMount:!0,children:[We(Tn.div,{animate:{opacity:1},className:"fixed inset-0 z-50 bg-black/60",exit:{opacity:0},initial:{opacity:0},onClick:y,transition:{duration:.2}}),We(Tn.div,{animate:"visible",className:"fixed top-1/2 left-1/2 z-50 w-full max-w-lg -translate-x-1/2 -translate-y-1/2 px-4",exit:"exit",initial:"hidden",variants:If,children:We(ql,{children:We(Tn.div,{className:"relative overflow-hidden rounded-xl border bg-background shadow-2xl ring-1 ring-black/5",layout:c,style:{minHeight:r>0?r:"auto"},transition:fs,children:We("div",{className:"relative",ref:a,children:u.map((g,C)=>{let I=C===f,A=C<f,m=I&&b&&u.length>1?{x:"100%",scale:1,opacity:1}:!1;return We(Tn.div,{animate:{x:Yl(I,A),scale:I?1:.94,opacity:I?1:0},"aria-hidden":!I,className:x("w-full",I?"relative":"pointer-events-none absolute inset-0"),initial:m,transition:k,children:We(g.component,{overlayId:g.id,...g.props})},g.id)})})})})})]})})})}function Ef(){let{stack:e,closeAll:t,pop:o}=oe(),n=jl(),[r,s]=Jl(0),a=yo(null),d=yo(!1),i=yo(e),l=Xl(e.length),c=e.length>0;c&&(i.current=e);let u=i.current,f=u.length-1;nr(()=>{let g=c&&!d.current;if(d.current=c,g&&s(0),a.current){let C=a.current.offsetHeight;C>0&&s(C)}},[e,c]);let h=e[e.length-1],k=u[f],b=n?{duration:.01}:fs,y=l===1,p=or(g=>{g.key==="Escape"&&h?.options.closeOnEscape!==!1&&o()},[h?.options.closeOnEscape,o]);nr(()=>{if(c)return document.addEventListener("keydown",p),()=>document.removeEventListener("keydown",p)},[c,p]);let v=or(()=>{c||(i.current=[])},[c]);return We(tr.Root,{onAnimationEnd:v,onOpenChange:g=>{g||t()},open:c,children:gs(tr.Portal,{children:[We(tr.Overlay,{className:"fixed inset-0 z-50 bg-black/60"}),gs(tr.Content,{className:x("fixed inset-x-0 bottom-0 z-50 flex max-h-[90vh] flex-col","rounded-t-2xl border-t bg-background shadow-2xl"),children:[We(tr.Title,{className:"sr-only",children:k?.options.title||"Dialog"}),We("div",{className:"mx-auto mt-3 h-1.5 w-12 shrink-0 rounded-full bg-muted-foreground/20"}),We(ql,{children:We(Tn.div,{className:"relative flex-1 overflow-hidden",layout:c,style:{minHeight:r>0?r:"auto"},transition:Sf,children:We("div",{className:"relative",ref:a,children:u.map((g,C)=>{let I=C===f,A=C<f,m=I&&y&&u.length>1?{x:"100%",scale:1,opacity:1}:!1;return We(Tn.div,{animate:{x:Yl(I,A),scale:I?1:.94,opacity:I?1:0},"aria-hidden":!I,className:x("w-full",I?"relative":"pointer-events-none absolute inset-0"),initial:m,transition:b,children:We(g.component,{overlayId:g.id,...g.props})},g.id)})})})}),We("div",{className:"h-safe-area-inset-bottom"})]})]})})}function Ql(){return Vt()?We(Ef,{}):We(Pf,{})}import{useAtom as Df}from"jotai";import{useEffect as Rf,useRef as Zl}from"react";import{atom as qt}from"jotai";var je=qt([]),Y0=qt(e=>e(je).length>0),X0=qt(e=>e(je).length);function ys(){return`overlay-${Date.now()}-${Math.random().toString(36).slice(2,9)}`}var Q0=qt(null,(e,t,o)=>{let n=ys(),r={id:n,component:o.component,props:o.props??{},options:o.options??{}};return t(je,[r]),n}),Z0=qt(null,(e,t,o)=>{let n=ys(),r={id:n,component:o.component,props:o.props??{},options:o.options??{}};return t(je,[...e(je),r]),n}),eT=qt(null,(e,t)=>{let o=e(je);if(o.length<=1){o[0]?.options.onClose?.(),t(je,[]);return}o[o.length-1]?.options.onClose?.(),t(je,o.slice(0,-1))}),tT=qt(null,(e,t,o)=>{let n=e(je),r=ys(),s={id:r,component:o.component,props:o.props??{},options:o.options??{}};return n.length===0?t(je,[s]):(n[n.length-1]?.options.onClose?.(),t(je,[...n.slice(0,-1),s])),r}),oT=qt(null,(e,t)=>{let o=e(je);for(let n of o)n.options.onClose?.();t(je,[])}),nT=qt(null,(e,t,o)=>{let n=e(je),r=n.findIndex(s=>s.id===o);if(r!==-1){for(let s=r;s<n.length;s++)n[s].options.onClose?.();t(je,n.slice(0,r))}});function ed(){let{stack:e}=oe(),[t,o]=Df(je),n=Zl(!1),r=Zl(!1);return Rf(()=>{if(n.current){n.current=!1;return}r.current=!0,o(e)},[e,o]),null}import{Fragment as Of,jsx as td,jsxs as Lf}from"react/jsx-runtime";var od=()=>Lf(Of,{children:[td(Ql,{}),td(ed,{})]});import{CircleCheckIcon as Mf,InfoIcon as Wf,Loader2Icon as Ff,OctagonXIcon as zf,TriangleAlertIcon as Bf}from"lucide-react";import{useTheme as Vf}from"next-themes";import{Toaster as Gf}from"sonner";import{jsx as An}from"react/jsx-runtime";var nd=({...e})=>{let{theme:t="system"}=Vf();return An(Gf,{theme:t,className:"toaster group",icons:{success:An(Mf,{className:"size-4"}),info:An(Wf,{className:"size-4"}),warning:An(Bf,{className:"size-4"}),error:An(zf,{className:"size-4"}),loading:An(Ff,{className:"size-4 animate-spin"})},style:{"--normal-bg":"var(--popover)","--normal-text":"var(--popover-foreground)","--normal-border":"var(--border)","--border-radius":"var(--radius)"},...e})};import{usePathname as $v}from"next/navigation";import{ConnectionMode as Mv,MiniMap as Wv,useReactFlow as Fv}from"@xyflow/react";import{useAtom as ur,useAtomValue as Hs,useSetAtom as bo}from"jotai";import{useCallback as xt,useEffect as wa,useMemo as zv,useRef as Ho,useState as Tc}from"react";import{Background as Hf,ReactFlow as $f}from"@xyflow/react";import{useAtomValue as _f}from"jotai";import"@xyflow/react/dist/style.css";import{jsx as Uf,jsxs as Kf}from"react/jsx-runtime";var rd=({children:e,...t})=>{let o=_f(jo);return Kf($f,{deleteKeyCode:["Backspace","Delete"],fitView:!0,panActivationKeyCode:null,selectionOnDrag:!1,snapToGrid:o.snapToGrid??!0,zoomOnDoubleClick:!1,zoomOnPinch:!0,...t,children:[Uf(Hf,{bgColor:"var(--sidebar)",color:"var(--border)",gap:24,size:2}),e]})};import{jsx as ad,jsxs as qf}from"react/jsx-runtime";var sd=({fromX:e,fromY:t,toX:o,toY:n})=>qf("g",{children:[ad("path",{className:"animated",d:`M${e},${t} C ${e+(o-e)*.5},${t} ${e+(o-e)*.5},${n} ${o},${n}`,fill:"none",stroke:"var(--color-ring)",strokeWidth:1}),ad("circle",{cx:o,cy:n,fill:"#fff",r:3,stroke:"var(--color-ring)",strokeWidth:1})]});import{useReactFlow as Xf}from"@xyflow/react";import{useAtom as Qf}from"jotai";import{MapPin as Zf,MapPinXInside as eg,Maximize2 as tg,ZoomIn as og,ZoomOut as ng}from"lucide-react";import{cva as jf}from"class-variance-authority";import{Slot as PT}from"radix-ui";import{jsx as Yf}from"react/jsx-runtime";var Jf=jf("flex w-fit items-stretch [&>*]:focus-visible:z-10 [&>*]:focus-visible:relative [&>[data-slot=select-trigger]:not([class*='w-'])]:w-fit [&>input]:flex-1 has-[select[aria-hidden=true]:last-child]:[&>[data-slot=select-trigger]:last-of-type]:rounded-r-md has-[>[data-slot=button-group]]:gap-2",{variants:{orientation:{horizontal:"[&>*:not(:first-child)]:rounded-l-none [&>*:not(:first-child)]:border-l-0 [&>*:not(:last-child)]:rounded-r-none",vertical:"flex-col [&>*:not(:first-child)]:rounded-t-none [&>*:not(:first-child)]:border-t-0 [&>*:not(:last-child)]:rounded-b-none"}},defaultVariants:{orientation:"horizontal"}});function _t({className:e,orientation:t,...o}){return Yf("div",{role:"group","data-slot":"button-group","data-orientation":t,className:x(Jf({orientation:t}),e),...o})}import{jsx as jt,jsxs as rg}from"react/jsx-runtime";var id=()=>{let{zoomIn:e,zoomOut:t,fitView:o}=Xf(),[n,r]=Qf(vr);return rg(_t,{orientation:"vertical",children:[jt(D,{className:"border hover:bg-black/5 disabled:opacity-100 dark:hover:bg-white/5 disabled:[&>svg]:text-muted-foreground",onClick:()=>{e()},size:"icon",title:"Zoom in",variant:"secondary",children:jt(og,{className:"size-4"})}),jt(D,{className:"border hover:bg-black/5 disabled:opacity-100 dark:hover:bg-white/5 disabled:[&>svg]:text-muted-foreground",onClick:()=>{t()},size:"icon",title:"Zoom out",variant:"secondary",children:jt(ng,{className:"size-4"})}),jt(D,{className:"border hover:bg-black/5 disabled:opacity-100 dark:hover:bg-white/5 disabled:[&>svg]:text-muted-foreground",onClick:()=>{o({padding:.2,duration:300})},size:"icon",title:"Fit view",variant:"secondary",children:jt(tg,{className:"size-4"})}),jt(D,{className:"border hover:bg-black/5 disabled:opacity-100 dark:hover:bg-white/5 disabled:[&>svg]:text-muted-foreground",onClick:()=>{r(!n)},size:"icon",title:n?"Hide minimap":"Show minimap",variant:"secondary",children:n?jt(Zf,{className:"size-4"}):jt(eg,{className:"size-4"})})]})};import{useReactFlow as cg}from"@xyflow/react";import{useAtom as Sn,useAtomValue as ug}from"jotai";import{ArrowUp as mg}from"lucide-react";import{useCallback as pg,useEffect as fg,useRef as dd,useState as vs}from"react";import{toast as hs}from"sonner";import{motion as ag}from"motion/react";import{memo as sg,useMemo as ig}from"react";import{jsx as dg}from"react/jsx-runtime";var lg=({children:e,as:t="p",className:o,duration:n=2,spread:r=2})=>{let s=ag.create(t),a=ig(()=>(e?.length??0)*r,[e,r]);return dg(s,{animate:{backgroundPosition:"0% center"},className:x("relative inline-block bg-[length:250%_100%,auto] bg-clip-text text-transparent","[--bg:linear-gradient(90deg,#0000_calc(50%-var(--spread)),var(--color-background),#0000_calc(50%+var(--spread)))] [background-repeat:no-repeat,padding-box]",o),initial:{backgroundPosition:"100% center"},style:{"--spread":`${a}px`,backgroundImage:"var(--bg), linear-gradient(var(--color-muted-foreground), var(--color-muted-foreground))"},transition:{repeat:Number.POSITIVE_INFINITY,duration:n,ease:"linear"},children:e})},ld=sg(lg);import{Fragment as gg,jsx as Jt,jsxs as bs}from"react/jsx-runtime";function cd({workflowId:e,onWorkflowCreated:t}){let[o,n]=Sn(Nt),[r,s]=vs(""),[a,d]=vs(!1),[i,l]=vs(!1),c=dd(null),u=dd(null),f=ug(re),[h,k]=Sn(ue),[b,y]=Sn(re),[p,v]=Sn(Ue),[g,C]=Sn(gt),[I,A]=Sn(ke),{fitView:w}=cg(),m=f.filter(F=>F.type!=="add"),S=m.length>0;fg(()=>{let F=$=>{($.metaKey||$.ctrlKey)&&$.key==="k"&&($.preventDefault(),c.current?.focus())};return window.addEventListener("keydown",F),()=>{window.removeEventListener("keydown",F)}},[]);let X=()=>{d(!0),l(!0)},ie=F=>{u.current?.contains(F.relatedTarget)||(l(!1),r.trim()||d(!1))},L=pg(async F=>{if(F.preventDefault(),!(!r.trim()||o)){n(!0);try{let $=S?{nodes:m,edges:h,name:g}:void 0;console.log("[AI Prompt] Generating workflow"),console.log("[AI Prompt] Has nodes:",S),console.log("[AI Prompt] Sending existing workflow:",!!$),$&&console.log("[AI Prompt] Existing workflow:",$.nodes.length,"nodes,",$.edges.length,"edges");let P=await q.ai.generateStream(r,W=>{let K=(W.edges||[]).map(N=>({...N,type:"animated"})),T=(W.nodes||[]).filter(N=>N.data?.type==="trigger"),z=K;if(T.length>1){let N=T[0],R=(W.nodes||[]).filter(ne=>ne.data?.type!=="trigger");W.nodes=[N,...R];let G=T.slice(1).map(ne=>ne.id);z=K.filter(ne=>!G.includes(ne.source)&&!G.includes(ne.target))}y(W.nodes||[]),k(z),W.name&&C(W.name),setTimeout(()=>{w({padding:.2,duration:200})},0)},$);console.log("[AI Prompt] Received final workflow data"),console.log("[AI Prompt] Nodes:",P.nodes?.length||0),console.log("[AI Prompt] Edges:",P.edges?.length||0);let V=(P.edges||[]).map(W=>({...W,type:"animated"}));console.log("[AI Prompt] Validating nodes:",P.nodes);let J=(P.nodes||[]).filter(W=>{let K=W.data?.type,T=W.data?.config||{};return console.log(`[AI Prompt] Checking node ${W.id}:`,{type:K,config:T,hasActionType:!!T.actionType,hasTriggerType:!!T.triggerType}),K==="trigger"?!T.triggerType:K==="action"?!T.actionType:!1});if(J.length>0)throw console.error("[AI Prompt] AI generated incomplete nodes:",J),console.error("[AI Prompt] Full workflow data:",JSON.stringify(P,null,2)),new Error(`Cannot create workflow: The AI tried to create ${J.length} incomplete node(s). The requested action type may not be supported. Please try a different description using supported actions: Send Email, Send Slack Message, Create Ticket, Database Query, HTTP Request, Generate Text, Generate Image, Scrape, or Search.`);if(e){v(e),console.log("[AI Prompt] Updating existing workflow:",e),console.log("[AI Prompt] Has existingWorkflow context:",!!$),$?(console.log("[AI Prompt] REPLACING workflow with AI response"),console.log("[AI Prompt] Replacing",m.length,"nodes with",P.nodes?.length||0,"nodes")):(console.log("[AI Prompt] Setting workflow for empty canvas"),hs.success("Generated workflow"));let W=P.nodes?.find(K=>K.selected);W&&A(W.id),await q.workflow.update(e,{name:P.name,description:P.description,nodes:P.nodes,edges:V})}else{let W=await q.workflow.create({name:P.name||"AI Generated Workflow",description:P.description||"",nodes:P.nodes||[],edges:V});v(W.id),hs.success("Created workflow"),t&&t(W.id)}s(""),d(!1),l(!1),c.current?.blur()}catch($){console.error("Failed to generate workflow:",$),hs.error("Failed to generate workflow")}finally{n(!1)}}},[r,o,e,S,f,h,n,v,y,k,C,A,t,w]);return Jt(gg,{children:Jt("div",{ref:u,className:"pointer-events-auto absolute bottom-4 left-1/2 z-10 -translate-x-1/2 px-4",style:{width:a?"min(100%, 42rem)":"20rem",transition:"width 150ms ease-out"},children:bs("form",{"aria-busy":o,"aria-label":"AI workflow prompt",className:"relative flex items-center gap-2 rounded-lg border bg-background pl-3 pr-2 py-2 shadow-lg cursor-text",onClick:F=>{(F.target===F.currentTarget||F.target.tagName!=="BUTTON")&&c.current?.focus()},onMouseDown:F=>{F.target===F.currentTarget&&F.preventDefault()},onSubmit:L,role:"search",children:[o&&r?Jt(ld,{className:"flex-1 text-sm whitespace-pre-wrap",duration:2,children:r}):Jt("textarea",{"aria-label":"Describe your workflow",className:"flex-1 bg-transparent text-sm outline-none placeholder:text-muted-foreground resize-none h-[22px] min-h-[22px] max-h-[200px] py-0 leading-[22px]",disabled:o,onBlur:ie,onChange:F=>{s(F.target.value),F.target.style.height="auto",F.target.style.height=`${F.target.scrollHeight}px`},onFocus:X,onKeyDown:F=>{F.key==="Enter"&&!F.shiftKey?(F.preventDefault(),L(F)):F.key==="Escape"&&(F.preventDefault(),s(""),d(!1),l(!1),c.current?.blur())},placeholder:i?"Describe your workflow with natural language...":"Ask AI...",ref:c,rows:1,value:r}),Jt("div",{className:"sr-only",children:o?"Generating workflow, please wait...":""}),bs("div",{className:"relative size-8 shrink-0 self-end",children:[Jt(D,{"aria-label":"Focus prompt input (\u2318K)",className:"absolute inset-0 h-8 px-0 text-xs text-muted-foreground hover:bg-transparent transition-[opacity,filter] ease-out",onClick:()=>c.current?.focus(),style:!r.trim()&&!o&&!i?{opacity:1,filter:"blur(0px)",pointerEvents:"auto",visibility:"visible"}:{opacity:0,filter:"blur(2px)",pointerEvents:"none",visibility:"hidden"},type:"button",variant:"ghost",children:bs("kbd",{"aria-hidden":"true",className:"pointer-events-none inline-flex h-5 select-none items-center gap-1 rounded border bg-muted px-1.5 font-mono text-[10px] font-medium text-muted-foreground opacity-100",children:[Jt("span",{className:"text-xs",children:"\u2318"}),"K"]})}),Jt(D,{"aria-label":o?"Generating workflow...":"Generate workflow",className:"size-8 transition-[opacity,filter] ease-out shrink-0",disabled:!r.trim()||o,size:"sm",style:!r.trim()&&!o&&!i?{opacity:0,filter:"blur(2px)",pointerEvents:"none",visibility:"hidden"}:{opacity:1,filter:"blur(0px)",pointerEvents:"auto",visibility:"visible"},type:"submit",children:Jt(mg,{"aria-hidden":"true",className:"size-4"})})]})]})})})}import{useReactFlow as uy}from"@xyflow/react";import{useAtom as et,useAtomValue as Xd,useSetAtom as Ut}from"jotai";import{Check as ga,ChevronDown as my,Copy as py,Download as fy,Globe as Qd,Loader2 as va,Lock as Zd,Play as gy,Plus as ec,Redo2 as tc,Save as yy,Settings2 as vy,Trash2 as hy,Undo2 as oc}from"lucide-react";import{nanoid as by}from"nanoid";import{useRouter as wy}from"next/navigation";import{useEffect as Ms,useRef as xy,useState as Ls}from"react";import{toast as dt}from"sonner";import{Panel as yg}from"@xyflow/react";import{jsx as vg}from"react/jsx-runtime";var sa=({className:e,...t})=>vg(yg,{className:x("m-4 rounded-md border bg-card p-1",e),...t});var ws="https://vercel.new/workflow-builder",iA=`[![Deploy with Vercel](https://vercel.com/button)](${ws})`;import{jsx as rr,jsxs as ud}from"react/jsx-runtime";function md(){return rr(D,{asChild:!0,className:"h-9 gap-1.5 border px-2 sm:px-3",size:"sm",variant:"secondary",children:ud("a",{href:ws,rel:"noopener noreferrer",target:"_blank",children:[ud("svg",{"aria-label":"Vercel logomark",className:"size-3.5",fill:"currentColor",viewBox:"0 0 76 76",children:[rr("title",{children:"Vercel logomark"}),rr("path",{d:"m38 0 38 66H0z"})]}),rr("span",{className:"text-sm sm:hidden",children:"Deploy"}),rr("span",{className:"hidden text-sm sm:inline",children:"Deploy Your Own"})]})})}import{jsx as pd}from"react/jsx-runtime";function fd({className:e}){return pd("svg",{"aria-label":"GitHub",className:e,fill:"currentColor",role:"img",viewBox:"0 0 24 24",children:pd("path",{d:"M12 0C5.37 0 0 5.37 0 12c0 5.31 3.435 9.795 8.205 11.385.6.105.825-.255.825-.57 0-.285-.015-1.23-.015-2.235-3.015.555-3.795-.735-4.035-1.41-.135-.345-.72-1.41-1.23-1.695-.42-.225-1.02-.78-.015-.795.945-.015 1.62.87 1.845 1.23 1.08 1.815 2.805 1.305 3.495.99.105-.78.42-1.305.765-1.605-2.67-.3-5.46-1.335-5.46-5.925 0-1.305.465-2.385 1.23-3.225-.12-.3-.54-1.53.12-3.18 0 0 1.005-.315 3.3 1.23.96-.27 1.98-.405 3-.405s2.04.135 3 .405c2.295-1.56 3.3-1.23 3.3-1.23.66 1.65.24 2.88.12 3.18.765.84 1.23 1.905 1.23 3.225 0 4.605-2.805 5.625-5.475 5.925.435.375.81 1.095.81 2.22 0 1.605-.015 2.895-.015 3.3 0 .315.225.69.825.57A12.02 12.02 0 0024 12c0-6.63-5.37-12-12-12z"})})}function gd(e){if(e>=1e6){let t=(e/1e6).toFixed(1);return t.endsWith(".0")?`${Math.floor(e/1e6)}M`:`${t}M`}if(e>=1e3){let t=(e/1e3).toFixed(1);return t.endsWith(".0")?`${Math.floor(e/1e3)}k`:`${t}k`}return e.toString()}import{createContext as hg,useContext as bg}from"react";import{jsx as hA}from"react/jsx-runtime";var wg=hg(null);function yd(){return bg(wg)}import{jsx as vd,jsxs as hd}from"react/jsx-runtime";var xg="https://github.com/vercel-labs/workflow-builder-template";function bd(){let e=yd();return vd(D,{asChild:!0,className:"h-9 gap-1.5 px-2 sm:px-3",size:"sm",variant:"ghost",children:hd("a",{className:"flex items-center",href:xg,rel:"noopener noreferrer",target:"_blank",children:[vd(fd,{className:"size-4.5"}),e!==null&&hd("span",{className:"hidden text-sm sm:inline",children:[gd(e)," stars"]})]})})}import{useAtom as Yt,useAtomValue as wd,useSetAtom as ar}from"jotai";import{Code as xd,Copy as Nd,Eraser as xs,Eye as Ng,EyeOff as kg,FileCode as kd,Play as Cd,RefreshCw as Td,Settings2 as Ad,Trash2 as Ns}from"lucide-react";import{useCallback as In,useEffect as Cg,useRef as Tg,useState as Ag}from"react";import{toast as Pn}from"sonner";import{Fragment as ks,jsx as Z,jsxs as se}from"react/jsx-runtime";var Sg={"Database Query":"database"},Ig=/[^a-zA-Z0-9\s]/g,Pg=/\s+/;function Eg(e){return e.data.type==="trigger"?e.data.config?.triggerType==="Schedule"?"vercel.json":`app/api${e.data.config?.webhookPath||"/webhook"}/route.ts`:`steps/${(e.data.config?.actionType||"action").toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9-]/g,"")}-step.ts`}function ia({overlayId:e}){let{push:t,closeAll:o}=oe(),[n]=Yt(ke),[r]=Yt(_e),[s]=Yt(re),[a]=Yt(ue),[d]=Yt(Nt),[i]=Yt(Ue),[l,c]=Yt(gt),u=wd(oo),f=ar(ro),h=ar(ao),k=ar(so),b=ar(Tr),y=ar(Xo),[p,v]=Yt(to),[g,C]=Yt(Bt),[I,A]=Ag(!1),w=Tg(null),m=s.find(B=>B.id===n),S=a.find(B=>B.id===r),X=wd(ft);Cg(()=>{if(!(m&&u))return;let B=m.data.config?.actionType,Ae=m.data.config?.integrationId;if(!(B&&Ae))return;let Ye=fe(B)?.integration||Sg[B];if(!Ye)return;let $e=X.filter(Et=>Et.type===Ye);!$e.some(Et=>Et.id===Ae)&&$e.length>0&&f({id:m.id,data:{config:{...m.data.config,integrationId:$e[0].id}}})},[m,X,u,f]);let ie=In((B,Ae)=>{m&&f({id:m.id,data:{config:{...m.data.config,[B]:Ae}}})},[m,f]),L=In(B=>{m&&f({id:m.id,data:{label:B}})},[m,f]),F=In(B=>{m&&f({id:m.id,data:{description:B}})},[m,f]),$=In(()=>{m&&f({id:m.id,data:{enabled:m.data.enabled===!1}})},[m,f]),P=In(()=>{t(Ie,{title:"Delete Step",message:"Are you sure you want to delete this node? This action cannot be undone.",confirmLabel:"Delete",confirmVariant:"destructive",onConfirm:()=>{m&&(h(m.id),o())}})},[m,h,o,t]),V=In(()=>{m&&(navigator.clipboard.writeText(hn(m,i)),Pn.success("Code copied to clipboard"))},[m]),J=async()=>{w.current&&(A(!0),await w.current(),A(!1))},W=()=>{t(Ie,{title:"Delete All Runs",message:"Are you sure you want to delete all workflow runs? This action cannot be undone.",confirmLabel:"Delete",confirmVariant:"destructive",onConfirm:async()=>{if(i)try{await q.workflow.deleteExecutions(i),b(),w.current&&await w.current(),Pn.success("All runs deleted")}catch(B){console.error("Failed to delete runs:",B),Pn.error("Failed to delete runs")}}})},K=m&&(m.data.type!=="trigger"||m.data.config?.triggerType!=="Manual")&&m.data.config?.actionType!=="Condition",T=()=>{if(!m)switch(g==="properties"||g==="code"||g==="runs"&&u?g:"properties"){case"properties":return"Workflow";case"code":return"Code";case"runs":return"Runs";default:return"Workflow"}switch(g){case"properties":return"Properties";case"code":return"Code";case"runs":return"Runs";default:return"Properties"}},z=async B=>{if(c(B),i)try{await q.workflow.update(i,{name:B})}catch(Ae){console.error("Failed to update workflow name:",Ae)}},N=()=>{t(Ie,{title:"Clear Workflow",message:"Are you sure you want to clear all nodes and connections? This action cannot be undone.",confirmLabel:"Clear Workflow",confirmVariant:"destructive",destructive:!0,onConfirm:()=>{y()}})},R=()=>{t(Ie,{title:"Delete Workflow",message:`Are you sure you want to delete "${l}"? This will permanently delete the workflow. This cannot be undone.`,confirmLabel:"Delete Workflow",confirmVariant:"destructive",destructive:!0,onConfirm:async()=>{if(i)try{await q.workflow.delete(i),o(),Pn.success("Workflow deleted successfully"),window.location.href="/"}catch(B){console.error("Failed to delete workflow:",B),Pn.error("Failed to delete workflow. Please try again.")}}})},G=(()=>{let Ae=`${l.replace(Ig,"").split(Pg).map((Ye,$e)=>$e===0?Ye.toLowerCase():Ye.charAt(0).toUpperCase()+Ye.slice(1).toLowerCase()).join("")}Workflow`,{code:Je}=mr(s,a,{functionName:Ae});return Je})(),ne=()=>{navigator.clipboard.writeText(G),Pn.success("Code copied to clipboard")},de=()=>{r&&t(Ie,{title:"Delete Connection",message:"Are you sure you want to delete this connection? This action cannot be undone.",confirmLabel:"Delete",confirmVariant:"destructive",onConfirm:()=>{k(r),o()}})};if(S&&!m)return se("div",{className:"flex h-full max-h-[80vh] flex-col",children:[Z(en,{overlayId:e,title:"Connection"}),se("div",{className:"flex-1 space-y-4 overflow-y-auto px-6 pt-4 pb-6",children:[se("div",{className:"space-y-2",children:[Z(M,{htmlFor:"edge-id",children:"Connection ID"}),Z(ae,{disabled:!0,id:"edge-id",value:S.id})]}),se("div",{className:"space-y-2",children:[Z(M,{htmlFor:"edge-source",children:"Source"}),Z(ae,{disabled:!0,id:"edge-source",value:S.source})]}),se("div",{className:"space-y-2",children:[Z(M,{htmlFor:"edge-target",children:"Target"}),Z(ae,{disabled:!0,id:"edge-target",value:S.target})]}),u&&Z("div",{className:"pt-2",children:se(D,{onClick:de,variant:"ghost",children:[Z(Ns,{className:"mr-2 size-4"}),"Delete Connection"]})})]})]});if(!m){let B=g==="properties"||g==="code"||g==="runs"&&u?g:"properties";return se("div",{className:"flex h-full max-h-[80vh] flex-col",children:[Z(en,{overlayId:e,title:T()}),se("div",{className:"flex-1 overflow-y-auto",children:[B==="properties"&&se("div",{className:"space-y-4 px-6 pt-4 pb-6",children:[se("div",{className:"space-y-2",children:[Z(M,{htmlFor:"workflow-name",children:"Workflow Name"}),Z(ae,{disabled:!u,id:"workflow-name",onChange:Ae=>z(Ae.target.value),value:l})]}),se("div",{className:"space-y-2",children:[Z(M,{htmlFor:"workflow-id",children:"Workflow ID"}),Z(ae,{disabled:!0,id:"workflow-id",value:i||"Not saved"})]}),!u&&Z("div",{className:"rounded-lg border border-muted bg-muted/30 p-3",children:Z("p",{className:"text-muted-foreground text-sm",children:"You are viewing a public workflow. Duplicate it to make changes."})}),u&&se("div",{className:"flex items-center gap-2 pt-2",children:[se(D,{onClick:N,variant:"ghost",children:[Z(xs,{className:"mr-2 size-4"}),"Clear"]}),se(D,{onClick:R,variant:"ghost",children:[Z(Ns,{className:"mr-2 size-4"}),"Delete"]})]})]}),B==="code"&&se("div",{className:"flex flex-col",children:[se("div",{className:"flex shrink-0 items-center justify-between border-b bg-muted/30 px-3 py-2",children:[se("div",{className:"flex items-center gap-2",children:[Z(kd,{className:"size-3.5 text-muted-foreground"}),Z("code",{className:"text-muted-foreground text-xs",children:"workflow.ts"})]}),se(D,{className:"h-7 text-xs",onClick:ne,size:"sm",variant:"ghost",children:[Z(Nd,{className:"mr-1 size-3"}),"Copy"]})]}),Z("div",{className:"h-[400px]",children:Z(yt,{defaultLanguage:"typescript",height:"100%",options:{readOnly:!0,minimap:{enabled:!1},lineNumbers:"on",scrollBeyondLastLine:!1,fontSize:12,wordWrap:"on"},value:G})})]}),B==="runs"&&u&&se("div",{className:"flex h-full flex-col",children:[se("div",{className:"flex shrink-0 items-center gap-2 border-b px-4 py-2",children:[Z(D,{className:"text-muted-foreground",disabled:I,onClick:J,size:"icon",variant:"ghost",children:Z(Td,{className:`size-4 ${I?"animate-spin":""}`})}),Z(D,{className:"text-muted-foreground",onClick:W,size:"icon",variant:"ghost",children:Z(xs,{className:"size-4"})})]}),Z("div",{className:"flex-1 overflow-y-auto p-4",children:Z(wn,{isActive:B==="runs",onRefreshRef:w})})]})]}),se("div",{className:"flex shrink-0 items-center justify-around border-t bg-background pb-safe",children:[se("button",{className:`flex flex-1 flex-col items-center gap-1 py-3 font-medium text-xs transition-colors ${B==="properties"?"text-foreground":"text-muted-foreground"}`,onClick:()=>C("properties"),type:"button",children:[Z(Ad,{className:"size-5"}),"Workflow"]}),se("button",{className:`flex flex-1 flex-col items-center gap-1 py-3 font-medium text-xs transition-colors ${B==="code"?"text-foreground":"text-muted-foreground"}`,onClick:()=>C("code"),type:"button",children:[Z(xd,{className:"size-5"}),"Code"]}),u&&se("button",{className:`flex flex-1 flex-col items-center gap-1 py-3 font-medium text-xs transition-colors ${B==="runs"?"text-foreground":"text-muted-foreground"}`,onClick:()=>C("runs"),type:"button",children:[Z(Cd,{className:"size-5"}),"Runs"]})]})]})}return se("div",{className:"flex h-full max-h-[80vh] flex-col",children:[Z(en,{overlayId:e,title:T()}),se("div",{className:"flex-1 overflow-y-auto",children:[g==="properties"&&se("div",{className:"space-y-4 px-6 pt-4 pb-6",children:[m.data.type==="action"&&!m.data.config?.actionType&&u&&Z(Xr,{disabled:d,isNewlyCreated:m?.id===p,onSelectAction:B=>{ie("actionType",B),m?.id===p&&v(null)}}),m.data.type==="trigger"&&Z(Qr,{config:m.data.config||{},disabled:d||!u,onUpdateConfig:ie,workflowId:i??void 0}),m.data.type==="action"&&m.data.config?.actionType!==void 0&&Z(_r,{config:m.data.config||{},disabled:d||!u,isOwner:u,onUpdateConfig:ie}),(m.data.type!=="action"||m.data.config?.actionType!==void 0)&&se(ks,{children:[se("div",{className:"space-y-2",children:[Z(M,{htmlFor:"label",children:"Label"}),Z(ae,{disabled:d||!u,id:"label",onChange:B=>L(B.target.value),value:m.data.label})]}),se("div",{className:"space-y-2",children:[Z(M,{htmlFor:"description",children:"Description"}),Z(ae,{disabled:d||!u,id:"description",onChange:B=>F(B.target.value),placeholder:"Optional description",value:m.data.description||""})]})]}),u&&se("div",{className:"flex items-center gap-2 pt-2",children:[m.data.type==="action"&&Z(D,{className:"text-muted-foreground",onClick:$,size:"sm",variant:"ghost",children:m.data.enabled===!1?se(ks,{children:[Z(kg,{className:"mr-2 size-4"}),"Disabled"]}):se(ks,{children:[Z(Ng,{className:"mr-2 size-4"}),"Enabled"]})}),se(D,{className:"text-muted-foreground",onClick:P,size:"sm",variant:"ghost",children:[Z(Ns,{className:"mr-2 size-4"}),"Delete"]})]})]}),K&&se("div",{className:`flex flex-col ${g==="code"?"":"invisible absolute -z-10"}`,children:[se("div",{className:"flex shrink-0 items-center justify-between border-b bg-muted/30 px-3 py-2",children:[se("div",{className:"flex items-center gap-2",children:[Z(kd,{className:"size-3.5 text-muted-foreground"}),Z("code",{className:"text-muted-foreground text-xs",children:Eg(m)})]}),se(D,{className:"text-muted-foreground",onClick:V,size:"sm",variant:"ghost",children:[Z(Nd,{className:"mr-2 size-4"}),"Copy"]})]}),Z("div",{className:"h-[400px]",children:Z(yt,{height:"100%",language:m.data.type==="trigger"&&m.data.config?.triggerType==="Schedule"?"json":"typescript",options:{readOnly:!0,minimap:{enabled:!1},scrollBeyondLastLine:!1,fontSize:13,lineNumbers:"on",folding:!1,wordWrap:"off",padding:{top:16,bottom:16}},value:hn(m,i)})})]}),g==="runs"&&u&&se("div",{className:"flex h-full flex-col",children:[se("div",{className:"flex shrink-0 items-center gap-2 border-b px-4 py-2",children:[se(D,{className:"text-muted-foreground",disabled:I,onClick:J,size:"sm",variant:"ghost",children:[Z(Td,{className:`mr-2 size-4 ${I?"animate-spin":""}`}),"Refresh"]}),se(D,{className:"text-muted-foreground",onClick:W,size:"sm",variant:"ghost",children:[Z(xs,{className:"mr-2 size-4"}),"Clear All"]})]}),Z("div",{className:"flex-1 overflow-y-auto p-4",children:Z(wn,{isActive:g==="runs",onRefreshRef:w})})]})]}),se("div",{className:"flex shrink-0 items-center justify-around border-t bg-background pb-safe",children:[se("button",{className:`flex flex-1 flex-col items-center gap-1 py-3 font-medium text-xs transition-colors ${g==="properties"?"text-foreground":"text-muted-foreground"}`,onClick:()=>C("properties"),type:"button",children:[Z(Ad,{className:"size-5"}),"Properties"]}),K&&se("button",{className:`flex flex-1 flex-col items-center gap-1 py-3 font-medium text-xs transition-colors ${g==="code"?"text-foreground":"text-muted-foreground"}`,onClick:()=>C("code"),type:"button",children:[Z(xd,{className:"size-5"}),"Code"]}),u&&se("button",{className:`flex flex-1 flex-col items-center gap-1 py-3 font-medium text-xs transition-colors ${g==="runs"?"text-foreground":"text-muted-foreground"}`,onClick:()=>C("runs"),type:"button",children:[Z(Cd,{className:"size-5"}),"Runs"]})]})]})}import{Download as Og,FlaskConical as Lg}from"lucide-react";import{cva as Dg}from"class-variance-authority";import{jsx as Cs}from"react/jsx-runtime";var Rg=Dg("relative w-full rounded-lg border px-4 py-3 text-sm grid has-[>svg]:grid-cols-[calc(var(--spacing)*4)_1fr] grid-cols-[0_1fr] has-[>svg]:gap-x-3 gap-y-0.5 items-start [&>svg]:size-4 [&>svg]:translate-y-0.5 [&>svg]:text-current",{variants:{variant:{default:"bg-card text-card-foreground",destructive:"text-destructive bg-card [&>svg]:text-current *:data-[slot=alert-description]:text-destructive/90"}},defaultVariants:{variant:"default"}});function Sd({className:e,variant:t,...o}){return Cs("div",{"data-slot":"alert",role:"alert",className:x(Rg({variant:t}),e),...o})}function Id({className:e,...t}){return Cs("div",{"data-slot":"alert-title",className:x("col-start-2 line-clamp-1 min-h-4 font-medium tracking-tight",e),...t})}function Pd({className:e,...t}){return Cs("div",{"data-slot":"alert-description",className:x("text-muted-foreground col-start-2 grid justify-items-start gap-1 text-sm [&_p]:leading-relaxed",e),...t})}import{jsx as En,jsxs as la}from"react/jsx-runtime";function Ed({overlayId:e,onExport:t,isDownloading:o}){let{closeAll:n}=oe();return la(Re,{actions:[{label:"Cancel",variant:"outline",onClick:n},{label:o?"Exporting...":"Export Project",onClick:()=>{n(),t()},loading:o}],overlayId:e,title:"Export Workflow as Code",children:[la("div",{className:"flex items-center gap-2 text-muted-foreground",children:[En(Og,{className:"size-5"}),En("p",{className:"text-sm",children:"Export your workflow as a standalone Next.js project that you can run independently."})]}),En("p",{className:"mt-4 text-muted-foreground text-sm",children:"This will generate a complete Next.js project containing your workflow code. Once exported, you can run your workflow outside of the Workflow Builder, deploy it to Vercel, or integrate it into your existing applications."}),la(Sd,{className:"mt-4",children:[En(Lg,{className:"size-4"}),En(Id,{children:"Experimental Feature"}),la(Pd,{className:"block",children:["This feature is experimental and may have limitations. If you encounter any issues, please"," ",En("a",{className:"font-medium text-foreground underline underline-offset-4 hover:text-primary",href:"https://github.com/vercel-labs/workflow-builder-template/issues",rel:"noopener noreferrer",target:"_blank",children:"report them on GitHub"}),"."]})]})]})}import{Globe as Mg}from"lucide-react";import{jsx as vo,jsxs as da}from"react/jsx-runtime";function Dd({overlayId:e,onConfirm:t}){let{closeAll:o}=oe();return da(Re,{actions:[{label:"Cancel",variant:"outline",onClick:o},{label:"Make Public",onClick:()=>{o(),t()}}],overlayId:e,title:"Make Workflow Public?",children:[da("div",{className:"flex items-center gap-2 text-muted-foreground",children:[vo(Mg,{className:"size-5 shrink-0"}),vo("p",{className:"text-sm",children:"Making this workflow public means anyone with the link can:"})]}),da("ul",{className:"mt-3 list-inside list-disc space-y-1 text-muted-foreground text-sm",children:[vo("li",{children:"View the workflow structure and steps"}),vo("li",{children:"See action types and configurations"}),vo("li",{children:"Duplicate the workflow to their own account"})]}),vo("p",{className:"mt-4 font-medium text-foreground text-sm",children:"The following will remain private:"}),da("ul",{className:"mt-2 list-inside list-disc space-y-1 text-muted-foreground text-sm",children:[vo("li",{children:"Your integration credentials (API keys, tokens)"}),vo("li",{children:"Execution logs and run history"})]})]})}import{useAtomValue as Rd,useSetAtom as Wg}from"jotai";import{AlertTriangle as Fg}from"lucide-react";import{jsx as Ze,jsxs as pt}from"react/jsx-runtime";function Od({overlayId:e,issues:t,onGoToStep:o,onRunAnyway:n}){let{push:r,closeAll:s}=oe(),a=Wg(Rt),d=Vt(),i=Rd(Kt),l=Rd(Ao),{brokenReferences:c,missingRequiredFields:u,missingIntegrations:f}=t,h=c.length+u.length+f.length,k=(v,g)=>{o(v,g),d?r(ia,{}):s()},b=v=>{r(co,{type:v,onSuccess:()=>{a(g=>g+1)}})},y=v=>{i?.integrationType===v&&l?.enabled&&l?.isVercelUser&&i?r(i.ConsentOverlay,{onConsent:()=>{a(I=>I+1)},onManualEntry:()=>b(v)}):b(v)};return pt(Re,{actions:[{label:"Run Anyway",variant:"outline",onClick:()=>{s(),n()}},{label:"Cancel",onClick:s}],overlayId:e,title:`Workflow Issues (${h})`,children:[pt("div",{className:"flex items-center gap-2 text-orange-500",children:[Ze(Fg,{className:"size-5"}),Ze("p",{className:"text-muted-foreground text-sm",children:"This workflow has issues that may cause it to fail."})]}),pt("div",{className:"mt-4 space-y-4",children:[f.length>0&&pt("div",{className:"space-y-1",children:[Ze("h4",{className:"font-medium text-muted-foreground text-xs uppercase tracking-wide",children:"Missing Connections"}),f.map(v=>pt("div",{className:"flex items-center gap-3 py-1",children:[Ze(Wt,{className:"size-4 shrink-0",integration:v.integrationType}),pt("p",{className:"min-w-0 flex-1 text-sm",children:[Ze("span",{className:"font-medium",children:v.integrationLabel}),pt("span",{className:"text-muted-foreground",children:[" \u2014 ",v.nodeNames.length>3?`${v.nodeNames.slice(0,3).join(", ")} +${v.nodeNames.length-3} more`:v.nodeNames.join(", ")]})]}),Ze(D,{className:"shrink-0",onClick:()=>y(v.integrationType),size:"sm",variant:"outline",children:"Add"})]},v.integrationType))]}),c.length>0&&pt("div",{className:"space-y-2",children:[Ze("h4",{className:"font-medium text-muted-foreground text-xs uppercase tracking-wide",children:"Broken References"}),c.map(v=>pt("div",{children:[Ze("p",{className:"font-medium text-sm",children:v.nodeLabel}),Ze("div",{className:"mt-1 space-y-0.5",children:v.brokenReferences.map((g,C)=>pt("div",{className:"flex items-center gap-3 py-0.5 pl-3",children:[pt("p",{className:"min-w-0 flex-1 text-muted-foreground text-sm",children:[Ze("span",{className:"font-mono",children:g.displayText})," in ",g.fieldLabel]}),Ze(D,{className:"shrink-0",onClick:()=>k(v.nodeId,g.fieldKey),size:"sm",variant:"outline",children:"Fix"})]},`${v.nodeId}-${g.fieldKey}-${C}`))})]},v.nodeId))]}),u.length>0&&pt("div",{className:"space-y-2",children:[Ze("h4",{className:"font-medium text-muted-foreground text-xs uppercase tracking-wide",children:"Missing Required Fields"}),u.map(v=>pt("div",{children:[Ze("p",{className:"font-medium text-sm",children:v.nodeLabel}),Ze("div",{className:"mt-1 space-y-0.5",children:v.missingFields.map(g=>pt("div",{className:"flex items-center gap-3 py-0.5 pl-3",children:[Ze("p",{className:"min-w-0 flex-1 text-muted-foreground text-sm",children:g.fieldLabel}),Ze(D,{className:"shrink-0",onClick:()=>k(v.nodeId,g.fieldKey),size:"sm",variant:"outline",children:"Fix"})]},`${v.nodeId}-${g.fieldKey}`))})]},v.nodeId))]})]})]})}import{jsx as Ts,jsxs as zg}from"react/jsx-runtime";function Ld({className:e}){return zg("svg",{className:e,fill:"none",height:"16",viewBox:"0 0 305 234",width:"16",xmlns:"http://www.w3.org/2000/svg",children:[Ts("path",{className:"fill-foreground",d:"M125.776 0C120.929 1.64945e-05 117 3.9291 117 8.77539V61.4248C117 66.2711 120.929 70.2002 125.776 70.2002H160.875L161.253 70.2051C169.032 70.4023 175.301 76.6734 175.495 84.4531L175.5 84.8252V143.325C175.5 148.171 179.429 152.101 184.276 152.101H219.375L219.753 152.105C227.53 152.303 233.798 158.571 233.995 166.348L234 166.726V225.225C234 230.071 237.929 234 242.776 234H295.425C300.271 234 304.2 230.071 304.2 225.225V172.575C304.2 167.729 300.271 163.8 295.425 163.8H260.25C252.334 163.76 245.905 157.43 245.705 149.553L245.7 149.176V90.6758C245.7 85.8295 241.771 81.9004 236.925 81.9004H201.825C193.874 81.9004 187.405 75.5551 187.205 67.6523L187.2 67.2754V8.77539C187.2 3.9291 183.271 1.64951e-05 178.425 0H125.776Z"}),Ts("path",{className:"fill-foreground",d:"M67.2755 81.9004C62.4293 81.9004 58.5002 85.8295 58.5002 90.6758V143.325C58.5004 148.171 62.4294 152.101 67.2755 152.101H102.375L102.753 152.105C110.53 152.303 116.798 158.571 116.995 166.348L117 166.726V225.225C117 230.071 120.929 234 125.776 234H178.425C183.271 234 187.2 230.071 187.2 225.225V172.575C187.2 167.729 183.271 163.8 178.425 163.8H143.25C135.334 163.76 128.905 157.43 128.705 149.553L128.7 149.176V90.6758C128.7 85.8295 124.771 81.9004 119.925 81.9004H67.2755Z"}),Ts("path",{className:"fill-foreground",d:"M8.77454 163.8C3.92844 163.8 0.00012207 167.729 0.00012207 172.575V225.225C0.00012207 230.071 3.92844 234 8.77454 234H61.4249C66.2712 234 70.2003 230.071 70.2003 225.225V172.575C70.2003 167.729 66.2712 163.8 61.4249 163.8H8.77454Z"})]})}import{Key as ny,LogOut as ry,Moon as ay,Plug as sy,Settings as iy,Sun as ly}from"lucide-react";import{useTheme as dy}from"next-themes";import cy from"next/link";import{useEffect as jd,useState as Jd}from"react";import{Copy as Bg,Key as Vg,Trash2 as Gg}from"lucide-react";import{useCallback as Hg,useEffect as $g,useState as Dn}from"react";import{toast as Rn}from"sonner";import{jsx as Ve,jsxs as Pt}from"react/jsx-runtime";function _g({overlayId:e,onCreated:t}){let{pop:o}=oe(),[n,r]=Dn(""),[s,a]=Dn(!1);return Pt(Re,{actions:[{label:"Create",onClick:async()=>{a(!0);try{let i=await fetch("/api/api-keys",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:n||null})});if(!i.ok){let c=await i.json();throw new Error(c.error||"Failed to create API key")}let l=await i.json();t(l),Rn.success("API key created successfully"),o()}catch(i){console.error("Failed to create API key:",i),Rn.error(i instanceof Error?i.message:"Failed to create API key")}finally{a(!1)}},loading:s}],overlayId:e,title:"Create API Key",children:[Ve("p",{className:"mb-4 text-muted-foreground text-sm",children:"Create a new API key for webhook authentication"}),Pt("div",{className:"space-y-2",children:[Ve(M,{htmlFor:"key-name",children:"Label (optional)"}),Ve(ae,{id:"key-name",onChange:i=>r(i.target.value),placeholder:"e.g., Production, Testing",value:n})]})]})}function Md({overlayId:e}){let{push:t,closeAll:o}=oe(),[n,r]=Dn(!0),[s,a]=Dn([]),[d,i]=Dn(null),[l,c]=Dn(null),u=Hg(async()=>{r(!0);try{let p=await fetch("/api/api-keys");if(!p.ok)throw new Error("Failed to load API keys");let v=await p.json();a(v)}catch(p){console.error("Failed to load API keys:",p),Rn.error("Failed to load API keys")}finally{r(!1)}},[]);$g(()=>{u()},[u]);let f=p=>{i(p.key??null),a(v=>[p,...v])},h=async p=>{c(p);try{if(!(await fetch(`/api/api-keys/${p}`,{method:"DELETE"})).ok)throw new Error("Failed to delete API key");a(g=>g.filter(C=>C.id!==p)),Rn.success("API key deleted")}catch(v){console.error("Failed to delete API key:",v),Rn.error("Failed to delete API key")}finally{c(null)}},k=p=>{t(Ie,{title:"Delete API Key",message:"Are you sure you want to delete this API key? Any webhooks using this key will stop working immediately.",confirmLabel:"Delete",confirmVariant:"destructive",destructive:!0,onConfirm:()=>h(p)})},b=p=>{navigator.clipboard.writeText(p),Rn.success("Copied to clipboard")},y=p=>new Date(p).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"});return Pt(Re,{actions:[{label:"New API Key",variant:"outline",onClick:()=>t(_g,{onCreated:f})},{label:"Done",onClick:o}],overlayId:e,title:"API Keys",children:[Ve("p",{className:"-mt-2 mb-4 text-muted-foreground text-sm",children:"Manage API keys for webhook authentication"}),n?Ve("div",{className:"flex items-center justify-center py-8",children:Ve(Tt,{})}):Pt("div",{className:"space-y-4",children:[d&&Pt("div",{className:"rounded-md border border-yellow-500/50 bg-yellow-500/10 p-3",children:[Ve("p",{className:"mb-2 font-medium text-sm text-yellow-600 dark:text-yellow-400",children:"Copy your API key now. You won't be able to see it again!"}),Pt("div",{className:"flex items-center gap-2",children:[Ve("code",{className:"flex-1 rounded bg-muted px-2 py-1 font-mono text-xs",children:d}),Ve(D,{onClick:()=>b(d),size:"sm",variant:"outline",children:Ve(Bg,{className:"size-4"})})]}),Ve(D,{className:"mt-2",onClick:()=>i(null),size:"sm",variant:"ghost",children:"Dismiss"})]}),s.length===0?Pt("div",{className:"py-8 text-center text-muted-foreground text-sm",children:[Ve(Vg,{className:"mx-auto mb-2 size-8 opacity-50"}),Ve("p",{children:"No API keys yet"}),Ve("p",{className:"text-xs",children:"Create an API key to authenticate webhook requests"})]}):Ve("div",{className:"space-y-2",children:s.map(p=>Pt("div",{className:"flex items-center justify-between rounded-md border p-3",children:[Pt("div",{className:"min-w-0 flex-1",children:[Pt("div",{className:"flex items-center gap-2",children:[Pt("code",{className:"rounded bg-muted px-1.5 py-0.5 font-mono text-xs",children:[p.keyPrefix,"..."]}),p.name&&Ve("span",{className:"truncate text-sm",children:p.name})]}),Pt("p",{className:"mt-1 text-muted-foreground text-xs",children:["Created ",y(p.createdAt),p.lastUsedAt&&` \xB7 Last used ${y(p.lastUsedAt)}`]})]}),Ve(D,{disabled:l===p.id,onClick:()=>k(p.id),size:"sm",variant:"ghost",children:l===p.id?Ve(Tt,{className:"size-4"}):Ve(Gg,{className:"size-4 text-destructive"})})]},p.id))})]})]})}import{useSetAtom as Xg}from"jotai";import{Search as Qg}from"lucide-react";import{useCallback as Is,useEffect as Zg,useRef as ey,useState as Fd}from"react";import{Pencil as Ug,Trash2 as Kg}from"lucide-react";import{useCallback as qg,useEffect as jg,useMemo as Jg,useState as As}from"react";import{toast as ca}from"sonner";import{jsx as He,jsxs as Ss}from"react/jsx-runtime";var Yg={database:"Database"};function Wd({onIntegrationChange:e,filter:t=""}){let{push:o}=oe(),[n,r]=As([]),[s,a]=As(!0),[d,i]=As(null),l=qg(async()=>{try{a(!0);let b=await q.integration.getAll();r(b)}catch(b){console.error("Failed to load integrations:",b),ca.error("Failed to load integrations")}finally{a(!1)}},[]);jg(()=>{l()},[l]);let c=Jg(()=>{let b=eo(),y=t.toLowerCase();return n.map(p=>({...p,label:b[p.type]||Yg[p.type]||p.type})).filter(p=>t?p.label.toLowerCase().includes(y)||p.name.toLowerCase().includes(y)||p.type.toLowerCase().includes(y):!0).sort((p,v)=>{let g=p.label.localeCompare(v.label);return g!==0?g:p.name.localeCompare(v.name)})},[n,t]),u=b=>{o(Gr,{integration:b,onSuccess:()=>{l(),e?.()},onDelete:()=>{l(),e?.()}})},f=b=>{o(_a,{integration:b,onSuccess:()=>{l(),e?.()}})},h=async b=>{try{i(b);let y=await q.integration.testConnection(b);y.status==="success"?ca.success(y.message||"Connection successful"):ca.error(y.message||"Connection test failed")}catch(y){console.error("Connection test failed:",y),ca.error(y instanceof Error?y.message:"Connection test failed")}finally{i(null)}};return s?He("div",{className:"flex items-center justify-center py-8",children:He(Tt,{})}):He("div",{className:"space-y-1",children:n.length===0?He("div",{className:"py-8 text-center",children:He("p",{className:"text-muted-foreground text-sm",children:"No connections configured yet"})}):c.length===0?He("div",{className:"py-8 text-center",children:He("p",{className:"text-muted-foreground text-sm",children:"No connections match your filter"})}):He("div",{className:"space-y-1",children:c.map(b=>Ss("div",{className:"flex items-center justify-between rounded-md px-2 py-1.5",children:[Ss("div",{className:"flex items-center gap-2",children:[He(Wt,{className:"size-4",integration:b.type==="ai-gateway"?"vercel":b.type}),He("span",{className:"font-medium text-sm",children:b.label}),He("span",{className:"text-muted-foreground text-sm",children:b.name})]}),Ss("div",{className:"flex items-center gap-1",children:[He(D,{className:"h-7 px-2",disabled:d===b.id,onClick:()=>h(b.id),size:"sm",variant:"outline",children:d===b.id?He(Tt,{className:"size-3"}):He("span",{className:"text-xs",children:"Test"})}),He(D,{className:"size-7",onClick:()=>u(b),size:"icon",variant:"outline",children:He(Ug,{className:"size-3"})}),He(D,{className:"size-7",onClick:()=>f(b),size:"icon",variant:"outline",children:He(Kg,{className:"size-3"})})]})]},b.id))})})}import{jsx as Fo,jsxs as Ps}from"react/jsx-runtime";function zd({overlayId:e}){let{push:t,closeAll:o}=oe(),[n,r]=Fd(!0),[s,a]=Fd(""),d=Xg(Rt),i=ey(!1),l=Is(async()=>{r(!0);try{await new Promise(h=>setTimeout(h,0))}finally{r(!1)}},[]);Zg(()=>{l(),i.current=!1,a("")},[l]);let c=Is(()=>{i.current&&d(h=>h+1),o()},[o,d]),u=Is(()=>{i.current=!0},[]);return Ps(Re,{actions:[{label:"Add Connection",variant:"outline",onClick:()=>{t(Ji,{onSuccess:u})}},{label:"Done",onClick:c}],overlayId:e,title:"Connections",children:[Fo("p",{className:"-mt-2 mb-4 text-muted-foreground text-sm",children:"Manage API keys and credentials used by your workflows"}),n?Fo("div",{className:"flex items-center justify-center py-8",children:Fo(Tt,{})}):Ps("div",{className:"space-y-4",children:[Ps("div",{className:"relative",children:[Fo(Qg,{className:"absolute top-1/2 left-3 size-4 -translate-y-1/2 text-muted-foreground"}),Fo(ae,{className:"pl-9",onChange:h=>a(h.target.value),placeholder:"Filter connections...",value:s})]}),Fo("div",{className:"max-h-[300px] overflow-y-auto",children:Fo(Wd,{filter:s,onIntegrationChange:u})})]})]})}import{useCallback as Hd,useEffect as ty,useState as pa}from"react";import{toast as $d}from"sonner";import{jsx as ma}from"react/jsx-runtime";function ua({className:e,...t}){return ma("div",{"data-slot":"card",className:x("text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-sm",e),...t})}function Bd({className:e,...t}){return ma("div",{"data-slot":"card-title",className:x("leading-none font-semibold",e),...t})}function Vd({className:e,...t}){return ma("div",{"data-slot":"card-description",className:x("text-muted-foreground text-sm",e),...t})}function Es({className:e,...t}){return ma("div",{"data-slot":"card-content",className:x("px-6",e),...t})}import{jsx as sr,jsxs as Ds}from"react/jsx-runtime";function Gd({accountName:e,accountEmail:t,onNameChange:o,onEmailChange:n}){return sr(ua,{className:"border-0 py-0 shadow-none",children:Ds(Es,{className:"space-y-4 p-0",children:[Ds("div",{className:"space-y-2",children:[sr(M,{className:"ml-1",htmlFor:"accountName",children:"Name"}),sr(ae,{id:"accountName",onChange:r=>o(r.target.value),placeholder:"Your name",value:e})]}),Ds("div",{className:"space-y-2",children:[sr(M,{className:"ml-1",htmlFor:"accountEmail",children:"Email"}),sr(ae,{id:"accountEmail",onChange:r=>n(r.target.value),placeholder:"your.email@example.com",type:"email",value:t})]})]})})}import{jsx as fa,jsxs as oy}from"react/jsx-runtime";function _d({overlayId:e}){let{closeAll:t}=oe(),[o,n]=pa(!0),[r,s]=pa(!1),[a,d]=pa(""),[i,l]=pa(""),c=Hd(async()=>{try{let h=await q.user.get();d(h.name||""),l(h.email||"")}catch(h){console.error("Failed to load account:",h)}},[]),u=Hd(async()=>{n(!0);try{await c()}finally{n(!1)}},[c]);return ty(()=>{u()},[u]),oy(Re,{actions:[{label:"Cancel",variant:"outline",onClick:t},{label:"Save",onClick:async()=>{try{s(!0),await q.user.update({name:a,email:i}),await c(),$d.success("Settings saved"),t()}catch(h){console.error("Failed to save account:",h),$d.error("Failed to save settings")}finally{s(!1)}},loading:r,disabled:o}],overlayId:e,title:"Settings",children:[fa("p",{className:"-mt-2 mb-4 text-muted-foreground text-sm",children:"Update your personal information"}),o?fa("div",{className:"flex items-center justify-center py-8",children:fa(Tt,{})}):fa(Gd,{accountEmail:i,accountName:a,onEmailChange:l,onNameChange:d})]})}import{Avatar as Rs}from"radix-ui";import{jsx as Os}from"react/jsx-runtime";function Ud({className:e,...t}){return Os(Rs.Root,{"data-slot":"avatar",className:x("relative flex size-8 shrink-0 overflow-hidden rounded-full",e),...t})}function Kd({className:e,...t}){return Os(Rs.Image,{"data-slot":"avatar-image",className:x("aspect-square size-full",e),...t})}function qd({className:e,...t}){return Os(Rs.Fallback,{"data-slot":"avatar-fallback",className:x("bg-muted flex size-full items-center justify-center rounded-full",e),...t})}import{jsx as Ne,jsxs as Ft}from"react/jsx-runtime";var Yd=()=>{let{data:e,isPending:t}=Nn(),{theme:o,setTheme:n}=dy(),{open:r}=oe(),[s,a]=Jd(null),[d,i]=Jd(!1);jd(()=>{i(!0)},[]),jd(()=>{e?.user&&!e.user.name?.startsWith("Anonymous")&&q.user.get().then(h=>a(h.providerId)).catch(()=>a(null))},[e?.user]);let l=async()=>{await Gl()},c=s==="vercel"||s==="github"||s==="google",u=()=>e?.user?.name?e.user.name.split(" ").map(h=>h[0]).join("").toUpperCase().slice(0,2):e?.user?.email?e.user.email.slice(0,2).toUpperCase():"U";return t||!d?Ne("div",{className:"h-9 w-9"}):!e?.user||e.user.name==="Anonymous"||e.user.email?.startsWith("temp-")?Ne("div",{className:"flex items-center gap-2",children:Ne(D,{className:"h-9 disabled:opacity-100 disabled:[&>*]:text-muted-foreground",size:"sm",variant:"default",asChild:!0,children:Ne(cy,{href:"/auth/sign-in",children:"Sign In"})})}):Ft(Po,{children:[Ne(Eo,{asChild:!0,children:Ne(D,{className:"relative h-9 w-9 rounded-full border p-0",variant:"ghost",children:Ft(Ud,{className:"h-9 w-9",children:[Ne(Kd,{alt:e?.user?.name||"",src:e?.user?.image||""}),Ne(qd,{children:u()})]})})}),Ft(Do,{align:"end",className:"w-56",children:[Ne(gl,{children:Ft("div",{className:"flex flex-col space-y-1",children:[Ne("p",{className:"font-medium text-sm leading-none",children:e?.user?.name||"User"}),Ne("p",{className:"text-muted-foreground text-xs leading-none",children:e?.user?.email})]})}),Ne(Jn,{}),!c&&Ft(wt,{onClick:()=>r(_d),children:[Ne(iy,{className:"size-4"}),Ne("span",{children:"Settings"})]}),Ft(wt,{onClick:()=>r(zd),children:[Ne(sy,{className:"size-4"}),Ne("span",{children:"Connections"})]}),Ft(wt,{onClick:()=>r(Md),children:[Ne(ny,{className:"size-4"}),Ne("span",{children:"API Keys"})]}),Ft(yl,{children:[Ft(vl,{children:[Ne(ly,{className:"size-4 rotate-0 scale-100 transition-all dark:-rotate-90 dark:scale-0"}),Ne(ay,{className:"absolute size-4 rotate-90 scale-0 transition-all dark:rotate-0 dark:scale-100"}),Ne("span",{children:"Theme"})]}),Ne(hl,{children:Ft(fl,{onValueChange:n,value:o,children:[Ne(Yr,{value:"light",children:"Light"}),Ne(Yr,{value:"dark",children:"Dark"}),Ne(Yr,{value:"system",children:"System"})]})})]}),Ne(Jn,{}),Ft(wt,{onClick:l,children:[Ne(ry,{className:"size-4"}),Ne("span",{children:"Logout"})]})]})]})};import{Fragment as ya,jsx as j,jsxs as Ee}from"react/jsx-runtime";function nc(e,t,o){for(let n of e)t({id:n.id,data:{status:o}})}var Ny={"Database Query":"database"},ky={database:"Database"};function Cy(e){if(typeof e!="string")return[];let t=/\{\{@([^:]+):([^}]+)\}\}/g,o=e.matchAll(t);return Array.from(o).map(n=>({nodeId:n[1],displayText:n[2]}))}function sc(e,t=""){let o=[];for(let[n,r]of Object.entries(e)){let s=t?`${t}.${n}`:n;if(typeof r=="string"){let a=Cy(r);for(let d of a)o.push({field:s,...d})}else typeof r=="object"&&r!==null&&!Array.isArray(r)&&o.push(...sc(r,s))}return o}function Ty(e){let t=new Set(e.map(n=>n.id)),o=[];for(let n of e){if(n.data.enabled===!1)continue;let r=n.data.config;if(!r||typeof r!="object")continue;let a=sc(r).filter(d=>!t.has(d.nodeId));if(a.length>0){let d=r.actionType,i=d?fe(d):void 0,l=i?Ca(i.configFields):[];o.push({nodeId:n.id,nodeLabel:n.data.label||i?.label||"Unnamed Step",brokenReferences:a.map(c=>{let u=l.find(f=>f.key===c.field);return{fieldKey:c.field,fieldLabel:u?.label||c.field,referencedNodeId:c.nodeId,displayText:c.displayText}})})}}return o}function Ay(e){return e==null||typeof e=="string"&&e.trim()===""}function Sy(e,t){return e.showWhen?t[e.showWhen.field]===e.showWhen.equals:!0}function Iy(e){if(e.data.enabled===!1)return null;let t=e.data.config,o=t?.actionType;if(!o)return null;let n=fe(o);if(!n)return null;let s=Ca(n.configFields).filter(a=>a.required&&Sy(a,t||{})&&Ay(t?.[a.key])).map(a=>({fieldKey:a.key,fieldLabel:a.label}));return s.length===0?null:{nodeId:e.id,nodeLabel:e.data.label||n.label||"Unnamed Step",missingFields:s}}function Py(e){return e.map(Iy).filter(t=>t!==null)}function Ey(e,t){let o=new Set(t.map(a=>a.type)),n=new Set(t.map(a=>a.id)),r=new Map,s=eo();for(let a of e){if(a.data.enabled===!1)continue;let d=a.data.config?.actionType;if(!d)continue;let l=fe(d)?.integration||Ny[d];if(!l||!_o(l))continue;let c=a.data.config?.integrationId;if(!(c&&n.has(c))&&!o.has(l)){let f=r.get(l)||[],h=fe(d);f.push(a.data.label||h?.label||d),r.set(l,f)}}return Array.from(r.entries()).map(([a,d])=>({integrationType:a,integrationLabel:s[a]||ky[a]||a,nodeNames:d}))}async function Dy({workflowId:e,nodes:t,updateNodeData:o,pollingIntervalRef:n,setIsExecuting:r,setSelectedExecutionId:s}){nc(t,o,"idle");for(let a of t)a.data.type==="trigger"&&o({id:a.id,data:{status:"running"}});try{let a=await fetch(`/api/workflow/${e}/execute`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({input:{}})});if(!a.ok)throw new Error("Failed to execute workflow");let d=await a.json();s(d.executionId);let i=setInterval(async()=>{try{let l=await q.workflow.getExecutionStatus(d.executionId);for(let c of l.nodeStatuses)o({id:c.nodeId,data:{status:c.status}});l.status!=="running"&&(n.current&&(clearInterval(n.current),n.current=null),r(!1))}catch(l){console.error("Failed to poll execution status:",l)}},500);n.current=i}catch(a){console.error("Failed to execute workflow:",a),dt.error(a instanceof Error?a.message:"Failed to execute workflow"),nc(t,o,"error"),r(!1)}}function Ry({currentWorkflowId:e,nodes:t,edges:o,updateNodeData:n,isExecuting:r,setIsExecuting:s,setIsSaving:a,setHasUnsavedChanges:d,setActiveTab:i,setNodes:l,setEdges:c,setSelectedNodeId:u,setSelectedExecutionId:f,userIntegrations:h}){let{open:k}=oe(),b=xy(null);Ms(()=>()=>{b.current&&clearInterval(b.current)},[]);let y=async()=>{if(e){a(!0);try{await q.workflow.update(e,{nodes:t,edges:o}),d(!1)}catch(C){console.error("Failed to save workflow:",C),dt.error("Failed to save workflow. Please try again.")}finally{a(!1)}}},p=async()=>{if(!e){dt.error("Please save the workflow before executing");return}i("runs"),l(t.map(C=>({...C,selected:!1}))),c(o.map(C=>({...C,selected:!1}))),u(null),s(!0),await Dy({workflowId:e,nodes:t,updateNodeData:n,pollingIntervalRef:b,setIsExecuting:s,setSelectedExecutionId:f})},v=(C,I)=>{u(C),i("properties"),I&&setTimeout(()=>{let A=document.getElementById(I);A&&(A.focus(),A.scrollIntoView({behavior:"smooth",block:"center"}))},100)};return{handleSave:y,handleExecute:async()=>{if(r)return;let C=Ty(t),I=Py(t),A=Ey(t,h);if(C.length>0||I.length>0||A.length>0){k(Od,{issues:{brokenReferences:C,missingRequiredFields:I,missingIntegrations:A},onGoToStep:v,onRunAnyway:p});return}await p()}}}function Oy(){let[e,t]=et(re),[o,n]=et(ue),[r,s]=et(ni),[a]=et(Nt),d=Ut(Xo),i=Ut(ro),[l]=et(Ue),[c,u]=et(gt),[f,h]=et(yr),k=Xd(oo),b=wy(),[y,p]=et(Cr),[v,g]=et(nt),C=Ut(ci),I=Ut(ui),A=Ut(Yo),[w]=et(mi),[m]=et(pi),{data:S}=Nn(),X=Ut(Bt),ie=Ut(ke),L=Ut(no),F=Xd(ft),[$,P]=et(kr),[V,J]=Ls(!1),[W,K]=Ls(!1),[T,z]=Ls([]);return Ms(()=>{(async()=>{try{let R=await q.workflow.getAll();z(R)}catch(R){console.error("Failed to load workflows:",R)}})()},[]),{nodes:e,edges:o,isExecuting:r,setIsExecuting:s,isGenerating:a,clearWorkflow:d,updateNodeData:i,currentWorkflowId:l,workflowName:c,setCurrentWorkflowName:u,workflowVisibility:f,setWorkflowVisibility:h,isOwner:k,router:b,isSaving:y,setIsSaving:p,hasUnsavedChanges:v,setHasUnsavedChanges:g,undo:C,redo:I,addNode:A,canUndo:w,canRedo:m,session:S,isDownloading:V,setIsDownloading:J,isDuplicating:W,setIsDuplicating:K,allWorkflows:T,setAllWorkflows:z,setActiveTab:X,setNodes:t,setEdges:n,setSelectedNodeId:ie,setSelectedExecutionId:L,userIntegrations:F,triggerExecute:$,setTriggerExecute:P}}function Ly(e){let{open:t}=oe(),{currentWorkflowId:o,workflowName:n,nodes:r,edges:s,updateNodeData:a,isExecuting:d,setIsExecuting:i,setIsSaving:l,setHasUnsavedChanges:c,clearWorkflow:u,setWorkflowVisibility:f,setAllWorkflows:h,setIsDownloading:k,setIsDuplicating:b,setActiveTab:y,setNodes:p,setEdges:v,setSelectedNodeId:g,setSelectedExecutionId:C,userIntegrations:I,triggerExecute:A,setTriggerExecute:w,router:m,session:S}=e,{handleSave:X,handleExecute:ie}=Ry({currentWorkflowId:o,nodes:r,edges:s,updateNodeData:a,isExecuting:d,setIsExecuting:i,setIsSaving:l,setHasUnsavedChanges:c,setActiveTab:y,setNodes:p,setEdges:v,setSelectedNodeId:g,setSelectedExecutionId:C,userIntegrations:I});return Ms(()=>{A&&(w(!1),ie())},[A,w,ie]),{handleSave:X,handleExecute:ie,handleClearWorkflow:()=>{t(Ie,{title:"Clear Workflow",message:"Are you sure you want to clear all nodes and connections? This action cannot be undone.",confirmLabel:"Clear Workflow",confirmVariant:"destructive",destructive:!0,onConfirm:()=>{u()}})},handleDeleteWorkflow:()=>{t(Ie,{title:"Delete Workflow",message:`Are you sure you want to delete "${n}"? This will permanently delete the workflow. This cannot be undone.`,confirmLabel:"Delete Workflow",confirmVariant:"destructive",destructive:!0,onConfirm:async()=>{if(o)try{await q.workflow.delete(o),dt.success("Workflow deleted successfully"),window.location.href="/"}catch(W){console.error("Failed to delete workflow:",W),dt.error("Failed to delete workflow. Please try again.")}}})},handleDownload:async()=>{if(!o){dt.error("Please save the workflow before downloading");return}k(!0),dt.info("Preparing workflow files for download...");try{let W=await q.workflow.download(o);if(!W.success)throw new Error(W.error||"Failed to prepare download");if(!W.files)throw new Error("No files to download");let K=(await import("jszip")).default,T=new K;for(let[G,ne]of Object.entries(W.files))T.file(G,ne);let z=await T.generateAsync({type:"blob"}),N=URL.createObjectURL(z),R=document.createElement("a");R.href=N,R.download=`${n.toLowerCase().replace(/[^a-z0-9]/g,"-")}-workflow.zip`,document.body.appendChild(R),R.click(),document.body.removeChild(R),URL.revokeObjectURL(N),dt.success("Workflow downloaded successfully!")}catch(W){dt.error(W instanceof Error?W.message:"Failed to download workflow")}finally{k(!1)}},loadWorkflows:async()=>{try{let W=await q.workflow.getAll();h(W)}catch(W){console.error("Failed to load workflows:",W)}},handleToggleVisibility:async W=>{if(o){if(W==="public"){t(Dd,{onConfirm:async()=>{try{await q.workflow.update(o,{visibility:"public"}),f("public"),dt.success("Workflow is now public")}catch(K){console.error("Failed to update visibility:",K),dt.error("Failed to update visibility. Please try again.")}}});return}try{await q.workflow.update(o,{visibility:W}),f(W),dt.success("Workflow is now private")}catch(K){console.error("Failed to update visibility:",K),dt.error("Failed to update visibility. Please try again.")}}},handleDuplicate:async()=>{if(o){b(!0);try{S?.user||(await Mo.signIn.anonymous(),await new Promise(K=>setTimeout(K,100)));let W=await q.workflow.duplicate(o);dt.success("Workflow duplicated successfully"),m.push(`/workflows/${W.id}`)}catch(W){console.error("Failed to duplicate workflow:",W),dt.error("Failed to duplicate workflow. Please try again.")}finally{b(!1)}}}}}function My({workflowId:e,state:t,actions:o}){let{open:n,push:r}=oe(),[s]=et(ke),[a]=et(_e),[d]=et(re),[i]=et(ue),l=Ut(ao),c=Ut(so),{screenToFlowPosition:u}=uy(),f=d.find(p=>p.id===s),h=i.find(p=>p.id===a),k=f||h;if(e&&!t.isOwner||!e)return null;let b=()=>{let v=!!s?"Node":"Connection";r(Ie,{title:`Delete ${v}`,message:`Are you sure you want to delete this ${v.toLowerCase()}? This action cannot be undone.`,confirmLabel:"Delete",confirmVariant:"destructive",onConfirm:()=>{s?l(s):a&&c(a)}})},y=()=>{let p=document.querySelector(".react-flow");if(!p)return;let v=p.getBoundingClientRect(),g=v.left+v.width/2,C=v.top+v.height/2,I=u({x:g,y:C}),A=192,w=192;I.x-=A/2,I.y-=w/2;let m=20,S=20,X={...I},ie=!0,L=0,F=20;for(;ie&&L<F;)ie=t.nodes.some(P=>{let V=Math.abs(P.position.x-X.x),J=Math.abs(P.position.y-X.y);return V<S&&J<S}),ie&&(X.x+=m,X.y+=m,L+=1);let $={id:by(),type:"action",position:X,data:{label:"",description:"",type:"action",config:{},status:"idle"}};t.addNode($),t.setSelectedNodeId($.id),t.setActiveTab("properties")};return Ee(ya,{children:[j(_t,{className:"flex lg:hidden",orientation:"vertical",children:j(D,{className:"border hover:bg-black/5 disabled:opacity-100 dark:hover:bg-white/5 disabled:[&>svg]:text-muted-foreground",disabled:t.isGenerating,onClick:y,size:"icon",title:"Add Step",variant:"secondary",children:j(ec,{className:"size-4"})})}),Ee(_t,{className:"flex lg:hidden",orientation:"vertical",children:[j(D,{className:"border hover:bg-black/5 dark:hover:bg-white/5",onClick:()=>n(ia,{}),size:"icon",title:"Configuration",variant:"secondary",children:j(vy,{className:"size-4"})}),k&&j(D,{className:"border hover:bg-black/5 dark:hover:bg-white/5",onClick:b,size:"icon",title:"Delete",variant:"secondary",children:j(hy,{className:"size-4"})})]}),j(_t,{className:"hidden lg:flex",orientation:"horizontal",children:j(D,{className:"border hover:bg-black/5 disabled:opacity-100 dark:hover:bg-white/5 disabled:[&>svg]:text-muted-foreground",disabled:t.isGenerating,onClick:y,size:"icon",title:"Add Step",variant:"secondary",children:j(ec,{className:"size-4"})})}),Ee(_t,{className:"flex lg:hidden",orientation:"vertical",children:[j(D,{className:"border hover:bg-black/5 disabled:opacity-100 dark:hover:bg-white/5 disabled:[&>svg]:text-muted-foreground",disabled:!t.canUndo||t.isGenerating,onClick:()=>t.undo(),size:"icon",title:"Undo",variant:"secondary",children:j(oc,{className:"size-4"})}),j(D,{className:"border hover:bg-black/5 disabled:opacity-100 dark:hover:bg-white/5 disabled:[&>svg]:text-muted-foreground",disabled:!t.canRedo||t.isGenerating,onClick:()=>t.redo(),size:"icon",title:"Redo",variant:"secondary",children:j(tc,{className:"size-4"})})]}),Ee(_t,{className:"hidden lg:flex",orientation:"horizontal",children:[j(D,{className:"border hover:bg-black/5 disabled:opacity-100 dark:hover:bg-white/5 disabled:[&>svg]:text-muted-foreground",disabled:!t.canUndo||t.isGenerating,onClick:()=>t.undo(),size:"icon",title:"Undo",variant:"secondary",children:j(oc,{className:"size-4"})}),j(D,{className:"border hover:bg-black/5 disabled:opacity-100 dark:hover:bg-white/5 disabled:[&>svg]:text-muted-foreground",disabled:!t.canRedo||t.isGenerating,onClick:()=>t.redo(),size:"icon",title:"Redo",variant:"secondary",children:j(tc,{className:"size-4"})})]}),Ee(_t,{className:"flex lg:hidden",orientation:"vertical",children:[j(rc,{handleSave:o.handleSave,state:t}),j(ac,{actions:o,state:t})]}),Ee(_t,{className:"hidden lg:flex",orientation:"horizontal",children:[j(rc,{handleSave:o.handleSave,state:t}),j(ac,{actions:o,state:t})]}),j(Wy,{actions:o,state:t}),j(Fy,{actions:o,state:t})]})}function rc({state:e,handleSave:t}){return Ee(D,{className:"relative border hover:bg-black/5 disabled:opacity-100 dark:hover:bg-white/5 disabled:[&>svg]:text-muted-foreground",disabled:!e.currentWorkflowId||e.isGenerating||e.isSaving,onClick:t,size:"icon",title:e.isSaving?"Saving...":"Save workflow",variant:"secondary",children:[e.isSaving?j(va,{className:"size-4 animate-spin"}):j(yy,{className:"size-4"}),e.hasUnsavedChanges&&!e.isSaving&&j("div",{className:"absolute top-1.5 right-1.5 size-2 rounded-full bg-primary"})]})}function ac({state:e,actions:t}){let{open:o}=oe(),n=()=>{o(Ed,{onExport:t.handleDownload,isDownloading:e.isDownloading})};return j(D,{className:"border hover:bg-black/5 disabled:opacity-100 dark:hover:bg-white/5 disabled:[&>svg]:text-muted-foreground",disabled:e.isDownloading||e.nodes.length===0||e.isGenerating||!e.currentWorkflowId,onClick:n,size:"icon",title:e.isDownloading?"Preparing download...":"Export workflow as code",variant:"secondary",children:e.isDownloading?j(va,{className:"size-4 animate-spin"}):j(fy,{className:"size-4"})})}function Wy({state:e,actions:t}){let o=e.workflowVisibility==="public";return Ee(Po,{children:[j(Eo,{asChild:!0,children:j(D,{className:"border hover:bg-black/5 dark:hover:bg-white/5",disabled:!e.currentWorkflowId||e.isGenerating,size:"icon",title:o?"Public workflow":"Private workflow",variant:"secondary",children:o?j(Qd,{className:"size-4"}):j(Zd,{className:"size-4"})})}),Ee(Do,{align:"end",children:[Ee(wt,{className:"flex items-center gap-2",onClick:()=>t.handleToggleVisibility("private"),children:[j(Zd,{className:"size-4"}),"Private",!o&&j(ga,{className:"ml-auto size-4"})]}),Ee(wt,{className:"flex items-center gap-2",onClick:()=>t.handleToggleVisibility("public"),children:[j(Qd,{className:"size-4"}),"Public",o&&j(ga,{className:"ml-auto size-4"})]})]})]})}function Fy({state:e,actions:t}){return j(D,{className:"border hover:bg-black/5 disabled:opacity-100 dark:hover:bg-white/5 disabled:[&>svg]:text-muted-foreground",disabled:e.isExecuting||e.nodes.length===0||e.isGenerating,onClick:()=>t.handleExecute(),size:"icon",title:"Run Workflow",variant:"secondary",children:e.isExecuting?j(va,{className:"size-4 animate-spin"}):j(gy,{className:"size-4"})})}function zy({isDuplicating:e,onDuplicate:t}){return Ee(D,{className:"h-9 border hover:bg-black/5 dark:hover:bg-white/5",disabled:e,onClick:t,size:"sm",title:"Duplicate to your workflows",variant:"secondary",children:[e?j(va,{className:"mr-2 size-4 animate-spin"}):j(py,{className:"mr-2 size-4"}),"Duplicate"]})}function By({workflowId:e,state:t,actions:o}){return Ee("div",{className:"flex flex-col gap-1",children:[j("div",{className:"flex h-9 max-w-[160px] items-center overflow-hidden rounded-md border bg-secondary text-secondary-foreground sm:max-w-none",children:Ee(Po,{onOpenChange:n=>n&&o.loadWorkflows(),children:[Ee(Eo,{className:"flex h-full cursor-pointer items-center gap-2 px-3 font-medium text-sm transition-all hover:bg-black/5 dark:hover:bg-white/5",children:[j(Ld,{className:"size-4 shrink-0"}),j("p",{className:"truncate font-medium text-sm",children:e?t.workflowName:Ee(ya,{children:[j("span",{className:"sm:hidden",children:"New"}),j("span",{className:"hidden sm:inline",children:"New Workflow"})]})}),j(my,{className:"size-3 shrink-0 opacity-50"})]}),Ee(Do,{align:"start",className:"w-64",children:[j(wt,{asChild:!0,className:"flex items-center justify-between",children:Ee("a",{href:"/",children:["New Workflow"," ",!e&&j(ga,{className:"size-4 shrink-0"})]})}),j(Jn,{}),t.allWorkflows.length===0?j(wt,{disabled:!0,children:"No workflows found"}):t.allWorkflows.filter(n=>n.name!=="__current__").map(n=>Ee(wt,{className:"flex items-center justify-between",onClick:()=>t.router.push(`/workflows/${n.id}`),children:[j("span",{className:"truncate",children:n.name}),n.id===t.currentWorkflowId&&j(ga,{className:"size-4 shrink-0"})]},n.id))]})]})}),e&&!t.isOwner&&j("span",{className:"text-muted-foreground text-xs uppercase lg:hidden",children:"Read-only"})]})}var ic=({workflowId:e})=>{let t=Oy(),o=Ly(t);return Ee(ya,{children:[j(sa,{className:"flex flex-col gap-2 rounded-none border-none bg-transparent p-0 lg:flex-row lg:items-center",position:"top-left",children:Ee("div",{className:"flex items-center gap-2",children:[j(By,{actions:o,state:t,workflowId:e}),e&&!t.isOwner&&j("span",{className:"hidden text-muted-foreground text-xs uppercase lg:inline",children:"Read-only"})]})}),j("div",{className:"pointer-events-auto absolute top-4 right-4 z-10",children:Ee("div",{className:"flex flex-col-reverse items-end gap-2 lg:flex-row lg:items-center",children:[j(My,{actions:o,state:t,workflowId:e}),Ee("div",{className:"flex items-center gap-2",children:[!e&&Ee(ya,{children:[j(bd,{}),j(md,{})]}),e&&!t.isOwner&&j(zy,{isDuplicating:t.isDuplicating,onDuplicate:o.handleDuplicate}),j(Yd,{})]})]})})]})};import"@xyflow/react/dist/style.css";import{PlayCircle as Bv,Zap as Vv}from"lucide-react";import{nanoid as $s}from"nanoid";import{BaseEdge as cc,getBezierPath as Vy,getSimpleBezierPath as Gy,getSmoothStepPath as Hy,Position as zo,useInternalNode as lc}from"@xyflow/react";import{useAtomValue as $y}from"jotai";import{jsx as uc}from"react/jsx-runtime";var _y=({id:e,sourceX:t,sourceY:o,targetX:n,targetY:r,sourcePosition:s,targetPosition:a,selected:d})=>{let[i]=Gy({sourceX:t,sourceY:o,sourcePosition:s,targetX:n,targetY:r,targetPosition:a});return uc(cc,{className:"stroke-1",id:e,path:i,style:{stroke:d?"var(--muted-foreground)":"var(--border)",strokeDasharray:"5, 5"}})},dc=(e,t)=>{let o=t===zo.Left?"target":"source",n=e.internals.handleBounds?.[o]?.find(i=>i.position===t);if(!n)return[0,0];let r=n.width/2,s=n.height/2;switch(t){case zo.Left:r=0;break;case zo.Right:r=n.width;break;case zo.Top:s=0;break;case zo.Bottom:s=n.height;break;default:throw new Error(`Invalid handle position: ${t}`)}let a=e.internals.positionAbsolute.x+n.x+r,d=e.internals.positionAbsolute.y+n.y+s;return[a,d]},Uy=(e,t)=>{let o=zo.Right,[n,r]=dc(e,o),s=zo.Left,[a,d]=dc(t,s);return{sx:n,sy:r,tx:a,ty:d,sourcePos:o,targetPos:s}},Ky=({id:e,source:t,target:o,style:n,selected:r})=>{let s=$y(jo),a=lc(t),d=lc(o);if(!(a&&d))return null;let{sx:i,sy:l,tx:c,ty:u,sourcePos:f,targetPos:h}=Uy(a,d),k={sourceX:i,sourceY:l,sourcePosition:f,targetX:c,targetY:u,targetPosition:h},[b]=s.edgeStyle==="bezier"?Vy(k):Hy(k);return uc(cc,{id:e,path:b,style:{...n,stroke:r?"var(--muted-foreground)":"var(--border)",strokeWidth:2,animation:"dashdraw 0.5s linear infinite",strokeDasharray:5}})},Ws={Temporary:_y,Animated:Ky};import{useAtomValue as lr}from"jotai";import{AlertTriangle as sv,Check as iv,Code as lv,EyeOff as vc,XCircle as dv,Zap as wc}from"lucide-react";import hc from"next/image";import{memo as cv,useState as uv}from"react";import{useAtomValue as Jy}from"jotai";import{Check as gc,Circle as Yy,EyeOff as Xy,ListOrdered as Qy,Loader2 as Zy,XCircle as yc}from"lucide-react";import{memo as ev,useEffect as tv,useState as ov}from"react";import{Handle as pc,Position as fc}from"@xyflow/react";import{Fragment as qy,jsx as ho,jsxs as Fs}from"react/jsx-runtime";var mc=({className:e})=>Fs(qy,{children:[ho("style",{children:`
201
+ }`:""}function af(e){if(!e)return ls;if(Gl[e])return Gl[e];let t=ye(e);return t&&t.codegenTemplate||ls}var Sn=(e,t)=>e.data.type==="trigger"?rf(e.data.config,t):e.data.type==="action"?af(e.data.config?.actionType):nf;import{useAtom as ds}from"jotai";import{Check as Ul,ChevronDown as us,ChevronRight as ms,Clock as sf,Copy as lf,ExternalLink as df,Loader2 as cf,Play as uf,Square as $l,X as mf}from"lucide-react";import _l from"next/image";import{useCallback as nr,useEffect as na,useRef as pf,useState as Fo}from"react";import{Fragment as aa,jsx as K,jsxs as Ve}from"react/jsx-runtime";function ff(e){return ei(e)}function gf(e,t){if(typeof e!="object"||e===null)return;let o=e[t.field];if(typeof o=="string"&&o.length>0)return o}function yf(e){return typeof e=="object"&&e!==null&&"base64"in e&&typeof e.base64=="string"&&e.base64.length>100}function cs(e){let t={};for(let o of e)t[o.nodeId]={nodeId:o.nodeId,nodeName:o.nodeName,nodeType:o.nodeType,status:o.status,output:o.output};return t}function vf(e){try{let t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"}catch{return!1}}function Kl({data:e}){let o=JSON.stringify(e,null,2).split(/("https?:\/\/[^"]+"|"[^"]*")/g);return K(aa,{children:o.map(n=>{if(n.startsWith('"')&&n.endsWith('"')){let r=n.slice(1,-1);if(vf(r))return K("a",{className:"text-blue-500 underline hover:text-blue-400",href:r,rel:"noopener noreferrer",target:"_blank",children:n},r)}return n})})}function hf({data:e,isError:t=!1}){let[o,n]=Fo(!1);return K(E,{className:"h-7 px-2",onClick:async s=>{s.stopPropagation();try{let a=t?String(e):JSON.stringify(e,null,2);await navigator.clipboard.writeText(a),n(!0),setTimeout(()=>n(!1),2e3)}catch(a){console.error("Failed to copy:",a)}},size:"sm",type:"button",variant:"ghost",children:o?K(Ul,{className:"h-3 w-3 text-green-600"}):K(lf,{className:"h-3 w-3"})})}function ra({title:e,children:t,defaultExpanded:o=!1,copyData:n,isError:r=!1,externalLink:s}){let[a,d]=Fo(o);return Ve("div",{children:[Ve("div",{className:"mb-2 flex w-full items-center justify-between",children:[Ve("button",{className:"flex items-center gap-1.5",onClick:()=>d(!a),type:"button",children:[a?K(us,{className:"h-3 w-3 text-muted-foreground"}):K(ms,{className:"h-3 w-3 text-muted-foreground"}),K("span",{className:"font-medium text-muted-foreground text-xs uppercase tracking-wide",children:e})]}),Ve("div",{className:"flex items-center gap-1",children:[s&&K(E,{asChild:!0,className:"h-7 px-2",size:"sm",variant:"ghost",children:K("a",{href:s,rel:"noopener noreferrer",target:"_blank",children:K(df,{className:"h-3 w-3"})})}),n!==void 0&&K(hf,{data:n,isError:r})]})]}),a&&t]})}function bf({output:e,input:t,actionType:o}){let r=(o?ye(o):void 0)?.outputConfig,s=o?ff(o):void 0,a=r?.type!=="component"?r:s,d=a?gf(e,a):void 0,i=!(r||s)&&yf(e),c=(()=>{if(r?.type==="component"){let b=r.component;return K("div",{className:"overflow-hidden rounded-lg border bg-muted/50 p-3",children:K(b,{input:t,output:e})})}if(a&&d)switch(a.type){case"image":{let b=a.field==="base64"&&!d.startsWith("data:")?`data:image/png;base64,${d}`:d;return K("div",{className:"overflow-hidden rounded-lg border bg-muted/50 p-3",children:K(_l,{alt:"Generated image",className:"max-h-96 w-auto rounded",height:384,src:b,unoptimized:!0,width:384})})}case"video":return K("div",{className:"overflow-hidden rounded-lg border bg-muted/50 p-3",children:K("video",{className:"max-h-96 w-auto rounded",controls:!0,src:d,children:K("track",{kind:"captions"})})});case"url":return K("div",{className:"overflow-hidden rounded-lg border bg-muted/50",children:K("iframe",{className:"h-96 w-full rounded",sandbox:"allow-scripts allow-same-origin",src:d,title:"Output preview"})});default:return null}return i?K("div",{className:"overflow-hidden rounded-lg border bg-muted/50 p-3",children:K(_l,{alt:"AI generated output",className:"max-h-96 w-auto rounded",height:384,src:`data:image/png;base64,${e.base64}`,unoptimized:!0,width:384})}):null})(),u=c!==null,g=a?.type==="url"&&d?d:void 0;return Ve(aa,{children:[K(ra,{copyData:e,title:"Output",children:K("pre",{className:"overflow-auto rounded-lg border bg-muted/50 p-3 font-mono text-xs leading-relaxed",children:K(Kl,{data:e})})}),u&&K(ra,{defaultExpanded:!0,externalLink:g,title:"Result",children:c})]})}function wf({log:e,isExpanded:t,onToggle:o,getStatusIcon:n,getStatusDotClass:r,isFirst:s,isLast:a}){return Ve("div",{className:"relative flex gap-3",children:[Ve("div",{className:"relative -ml-px flex flex-col items-center pt-2",children:[!s&&K("div",{className:"absolute bottom-full h-2 w-px bg-border"}),K("div",{className:N("z-10 flex h-5 w-5 shrink-0 items-center justify-center rounded-full border-0",r(e.status)),children:n(e.status)}),!a&&K("div",{className:"absolute top-[calc(0.5rem+1.25rem)] bottom-0 w-px bg-border"})]}),Ve("div",{className:"min-w-0 flex-1",children:[K("button",{className:"group w-full rounded-lg py-2 text-left transition-colors hover:bg-muted/50",onClick:o,type:"button",children:Ve("div",{className:"flex items-center gap-3",children:[K("div",{className:"min-w-0 flex-1",children:Ve("div",{className:"flex items-center gap-2",children:[t?K(us,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}):K(ms,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),K("span",{className:"truncate font-medium text-sm transition-colors group-hover:text-foreground",children:e.nodeName||e.nodeType})]})}),e.duration&&K("span",{className:"shrink-0 font-mono text-muted-foreground text-xs tabular-nums",children:Number.parseInt(e.duration,10)<1e3?`${e.duration}ms`:`${(Number.parseInt(e.duration,10)/1e3).toFixed(2)}s`})]})}),t&&Ve("div",{className:"mt-2 mb-2 space-y-3 px-3",children:[e.input!==null&&e.input!==void 0&&K(ra,{copyData:e.input,title:"Input",children:K("pre",{className:"overflow-auto rounded-lg border bg-muted/50 p-3 font-mono text-xs leading-relaxed",children:K(Kl,{data:e.input})})}),e.output!==null&&e.output!==void 0&&K(bf,{actionType:e.nodeType,input:e.input,output:e.output}),e.error&&K(ra,{copyData:e.error,defaultExpanded:!0,isError:!0,title:"Error",children:K("pre",{className:"overflow-auto rounded-lg border border-red-500/20 bg-red-500/5 p-3 font-mono text-red-600 text-xs leading-relaxed",children:e.error})}),!(e.input||e.output||e.error)&&K("div",{className:"rounded-lg border bg-muted/30 py-4 text-center text-muted-foreground text-xs",children:"No data recorded"})]})]})]},e.id)}function An({isActive:e=!1,onRefreshRef:t,onStartRun:o}){let[n]=ds(Ke),[r,s]=ds(so),[,a]=ds(tn),[d,i]=Fo([]),[l,c]=Fo({}),[u,g]=Fo(new Set),[b,y]=Fo(new Set),[v,p]=Fo(!0),m=pf(null),w=nr(async(O=!0)=>{if(!n){p(!1);return}try{O&&p(!0);let W=await U.workflow.getExecutions(n);i(W)}catch(W){console.error("Failed to load executions:",W),i([])}finally{O&&p(!1)}},[n]);na(()=>{t&&(t.current=()=>w(!1))},[w,t]),na(()=>{w()},[w]);let h=nr((O,W)=>O.map($=>({id:$.id,nodeId:$.nodeId,nodeName:$.nodeName,nodeType:$.nodeType,status:$.status,startedAt:new Date($.startedAt),completedAt:$.completedAt?new Date($.completedAt):null,duration:$.duration,input:$.input,output:$.output,error:$.error})),[]),S=nr(async O=>{try{let W=await U.workflow.getExecutionLogs(O),$=h(W.logs,W.execution.workflow);c(T=>({...T,[O]:$})),O===r&&a(cs($))}catch(W){console.error("Failed to load execution logs:",W),c($=>({...$,[O]:[]}))}},[h,r,a]);na(()=>{if(d.length===0)return;let O=d[0];O.status==="running"&&O.id!==m.current&&(m.current=O.id,s(O.id),g(W=>{let $=new Set(W);return $.add(O.id),$}),S(O.id),o&&o(O.id))},[d,s,S,o]);let D=nr(async O=>{try{let W=await U.workflow.getExecutionLogs(O),$=h(W.logs,W.execution.workflow);c(T=>({...T,[O]:$})),O===r&&a(cs($))}catch(W){console.error(`Failed to refresh logs for ${O}:`,W)}},[h,r,a]);na(()=>{if(!(e&&n))return;let W=setInterval(async()=>{try{let $=await U.workflow.getExecutions(n);i($);for(let T of u)await D(T)}catch($){console.error("Failed to poll executions:",$)}},2e3);return()=>clearInterval(W)},[e,n,u,D]);let I=nr(async O=>{try{await U.workflow.cancelExecution(O),await w(!1)}catch(W){console.error("Failed to cancel execution:",W)}},[w]),k=async O=>{let W=new Set(u);W.has(O)?W.delete(O):(W.add(O),await S(O)),g(W)},f=O=>{if(r===O){s(null),a({});return}s(O);let W=l[O]||[];a(cs(W))},x=O=>{let W=new Set(b);W.has(O)?W.delete(O):W.add(O),y(W)},G=O=>{switch(O){case"success":return K(Ul,{className:"h-3 w-3 text-white"});case"error":return K(mf,{className:"h-3 w-3 text-white"});case"cancelled":return K($l,{className:"h-3 w-3 text-white"});case"running":return K(cf,{className:"h-3 w-3 animate-spin text-white"});default:return K(sf,{className:"h-3 w-3 text-white"})}},te=O=>{switch(O){case"success":return"bg-green-600";case"error":return"bg-red-600";case"cancelled":return"bg-yellow-600";case"running":return"bg-blue-600";default:return"bg-muted-foreground"}};return v?K("div",{className:"flex items-center justify-center py-12",children:K(pt,{})}):d.length===0?Ve("div",{className:"flex flex-col items-center justify-center py-16",children:[K("div",{className:"mb-3 rounded-lg border border-dashed p-4",children:K(uf,{className:"h-6 w-6 text-muted-foreground"})}),K("div",{className:"font-medium text-foreground text-sm",children:"No runs yet"}),K("div",{className:"mt-1 text-muted-foreground text-xs",children:"Execute your workflow to see runs here"})]}):K("div",{className:"space-y-3",children:d.map((O,W)=>{let $=u.has(O.id),T=r===O.id,H=(l[O.id]||[]).sort((X,z)=>new Date(X.startedAt).getTime()-new Date(z.startedAt).getTime());return Ve("div",{className:N("overflow-hidden rounded-lg border bg-card transition-all",T&&"ring-2 ring-primary ring-offset-2 ring-offset-background"),children:[Ve("div",{className:"flex w-full items-center gap-3 p-4",children:[K("button",{className:"flex size-5 shrink-0 items-center justify-center rounded-full border-0 transition-colors hover:bg-muted",onClick:()=>k(O.id),type:"button",children:K("div",{className:N("flex size-5 items-center justify-center rounded-full border-0",te(O.status)),children:G(O.status)})}),Ve("button",{className:"min-w-0 flex-1 text-left transition-colors hover:opacity-80",onClick:()=>f(O.id),type:"button",children:[K("div",{className:"mb-1 flex items-center gap-2",children:Ve("span",{className:"font-semibold text-sm",children:["Run #",d.length-W]})}),Ve("div",{className:"flex items-center gap-2 font-mono text-muted-foreground text-xs",children:[K("span",{children:wr(O.startedAt)}),O.duration&&Ve(aa,{children:[K("span",{children:"\u2022"}),K("span",{className:"tabular-nums",children:Number.parseInt(O.duration,10)<1e3?`${O.duration}ms`:`${(Number.parseInt(O.duration,10)/1e3).toFixed(2)}s`})]}),H.length>0&&Ve(aa,{children:[K("span",{children:"\u2022"}),Ve("span",{children:[H.length," ",H.length===1?"step":"steps"]})]})]})]}),(O.status==="running"||O.status==="pending")&&K("button",{className:"flex shrink-0 items-center justify-center rounded p-1 text-muted-foreground transition-colors hover:bg-destructive/10 hover:text-destructive",onClick:X=>{X.stopPropagation(),I(O.id)},title:"Stop execution",type:"button",children:K($l,{className:"h-3.5 w-3.5"})}),K("button",{className:"flex shrink-0 items-center justify-center rounded p-1 transition-colors hover:bg-muted",onClick:()=>k(O.id),type:"button",children:$?K(us,{className:"h-4 w-4 text-muted-foreground"}):K(ms,{className:"h-4 w-4 text-muted-foreground"})})]}),$&&K("div",{className:"border-t bg-muted/20",children:H.length===0?K("div",{className:"py-8 text-center text-muted-foreground text-xs",children:"No steps recorded"}):K("div",{className:"p-4",children:H.map((X,z)=>K(wf,{getStatusDotClass:te,getStatusIcon:G,isExpanded:b.has(X.id),isFirst:z===0,isLast:z===H.length-1,log:X,onToggle:()=>x(X.id)},X.id))})})]},O.id)})})}import{Fragment as vo,jsx as M,jsxs as q}from"react/jsx-runtime";var Tf=/[^a-zA-Z0-9\s]/g,Sf=/\s+/,Ql={"Database Query":"database"},Af=({selectedNodes:e,selectedEdges:t,onDelete:o})=>{let[n,r]=rr(!1),s=e.length===1?"node":"nodes",a=t.length===1?"line":"lines",d=[];e.length>0&&d.push(`${e.length} ${s}`),t.length>0&&d.push(`${t.length} ${a}`);let i=d.join(" and ");return q(vo,{children:[q("div",{className:"flex size-full flex-col",children:[M("div",{className:"flex h-14 w-full shrink-0 items-center border-b bg-transparent px-4",children:M("h2",{className:"font-semibold text-foreground",children:"Properties"})}),q("div",{className:"flex-1 space-y-4 overflow-y-auto p-4",children:[q("div",{className:"space-y-2",children:[M(L,{children:"Selection"}),q("p",{className:"text-muted-foreground text-sm",children:[i," selected"]})]}),M("div",{className:"flex items-center gap-2 pt-4",children:q(E,{className:"text-muted-foreground",onClick:()=>r(!0),size:"sm",variant:"ghost",children:[M(sa,{className:"mr-2 size-4"}),"Delete"]})})]})]}),M(ln,{onOpenChange:r,open:n,children:q(dn,{children:[q(cn,{children:[M(mn,{children:"Delete Selected Items"}),q(pn,{children:["Are you sure you want to delete ",i,"? This action cannot be undone."]})]}),q(un,{children:[M(gn,{children:"Cancel"}),M(fn,{onClick:()=>{o(),r(!1)},children:"Delete"})]})]})})]})},If=()=>{let[e]=yo(Te),[t]=yo(Ue),[o]=yo(re),n=ps(ue),[r]=yo(St),[s]=yo(Ke),[a,d]=yo(wt),i=ps(ao),l=zo(io),c=zo(lo),u=zo(co),g=zo(bi),b=zo(nn),{open:y}=oe(),v=zo(Dr),p=zo(Ir),[m,w]=yo(ro),[h,S]=rr(!1),[D,I]=rr(!1),[k,f]=rr(!1),[x,G]=rr(!1),[te,O]=yo($t),W=Xl(null),$=Xl({}),T=o.find(Z=>Z.id===e),H=n.find(Z=>Z.id===t),X=o.filter(Z=>Z.selected),z=n.filter(Z=>Z.selected),j=X.length+z.length>1;Yl(()=>{if(!T||te!=="code")return;let Z=T.data.config?.actionType==="Condition",ke=T.data.type==="trigger"&&T.data.config?.triggerType==="Manual";(Z||ke)&&O("properties")},[T,te,O]);let A=ps(bt);Yl(()=>{if(!(T&&i))return;let Z=T.data.config?.actionType,ke=T.data.config?.integrationId;if(!(Z&&ke))return;let F=ye(Z)?.integration||Ql[Z];if(!F||A.some(pe=>pe.id===ke))return;let fe=A.filter(pe=>pe.type===F);if(fe.length===1){let pe={...T.data.config,integrationId:fe[0].id};l({id:T.id,data:{config:pe}})}else if(fe.length===0){let pe={...T.data.config,integrationId:void 0};l({id:T.id,data:{config:pe}})}},[T,A,i,l]);let B=Cf(()=>{let ke=`${a.replace(Tf,"").split(Sf).map((F,Y)=>Y===0?F.toLowerCase():F.charAt(0).toUpperCase()+F.slice(1).toLowerCase()).join("")||"execute"}Workflow`,{code:P}=vr(o,n,{functionName:ke});return P},[o,n,a]),C=()=>{T&&navigator.clipboard.writeText(Sn(T))},R=()=>{navigator.clipboard.writeText(B),In.success("Code copied to clipboard")},_=()=>{e&&(c(e),S(!1))},ne=()=>{if(T){let Z=T.data.enabled??!0;l({id:T.id,data:{enabled:!Z}})}},de=()=>{t&&(u(t),I(!1))},V=async()=>{if(s)try{await U.workflow.deleteExecutions(s),v(),f(!1)}catch(Z){console.error("Failed to delete runs:",Z);let ke=Z instanceof Error?Z.message:"Failed to delete runs";In.error(ke)}},Ie=Z=>{T&&l({id:T.id,data:{label:Z}})},nt=Z=>{T&&l({id:T.id,data:{description:Z}})},Qe=kf(async(Z,ke,P,F)=>{let fe=ye(ke)?.integration||Ql[ke];if(!fe){p(pe=>{let Ce=new Set(pe);return Ce.delete(Z),Ce});return}try{let pe=await U.integration.getAll();if(F.aborted)return;let Ce=pe.filter(mt=>mt.type===fe);if(Ce.length===1&&!F.aborted){let mt={...P,actionType:ke,integrationId:Ce[0].id};l({id:Z,data:{config:mt}})}}catch(pe){console.error("Failed to auto-select integration:",pe)}finally{F.aborted||p(pe=>{let Ce=new Set(pe);return Ce.delete(Z),Ce})}},[l,p]),rt=Z=>{if(T){let ke={...T.data.config,...Z};l({id:T.id,data:{config:ke}})}},Ht=(Z,ke)=>{if(T){let P={...T.data.config,[Z]:ke};if(Z==="actionType"&&T.data.config?.integrationId&&(P={...P,integrationId:void 0}),l({id:T.id,data:{config:P}}),Z==="actionType"){let F=$.current[T.id];F&&F.abort();let Y=new AbortController;$.current[T.id]=Y,p(fe=>new Set(fe).add(T.id)),Qe(T.id,ke,P,Y.signal)}}},Lt=async Z=>{if(d(Z),s)try{await U.workflow.update(s,{name:Z,nodes:o,edges:n})}catch(ke){console.error("Failed to update workflow name:",ke),In.error("Failed to update workspace name")}},To=async()=>{G(!0);try{W.current&&await W.current()}catch(Z){console.error("Failed to refresh runs:",Z),In.error("Failed to refresh runs")}finally{G(!1)}};return j?M(Af,{onDelete:g,selectedEdges:z,selectedNodes:X}):H?q(vo,{children:[q("div",{className:"flex size-full flex-col",children:[M("div",{className:"flex h-14 w-full shrink-0 items-center border-b bg-transparent px-4",children:M("h2",{className:"font-semibold text-foreground",children:"Properties"})}),q("div",{className:"flex-1 space-y-4 overflow-y-auto p-4",children:[q("div",{className:"space-y-2",children:[M(L,{className:"ml-1",htmlFor:"edge-id",children:"Edge ID"}),M(ae,{disabled:!0,id:"edge-id",value:H.id})]}),q("div",{className:"space-y-2",children:[M(L,{className:"ml-1",htmlFor:"edge-source",children:"Source"}),M(ae,{disabled:!0,id:"edge-source",value:H.source})]}),q("div",{className:"space-y-2",children:[M(L,{className:"ml-1",htmlFor:"edge-target",children:"Target"}),M(ae,{disabled:!0,id:"edge-target",value:H.target})]}),i&&M("div",{className:"flex items-center gap-2 pt-4",children:q(E,{className:"text-muted-foreground",onClick:()=>I(!0),size:"sm",variant:"ghost",children:[M(sa,{className:"mr-2 size-4"}),"Delete"]})})]})]}),M(ln,{onOpenChange:I,open:D,children:q(dn,{children:[q(cn,{children:[M(mn,{children:"Delete Edge"}),M(pn,{children:"Are you sure you want to delete this connection? This action cannot be undone."})]}),q(un,{children:[M(gn,{children:"Cancel"}),M(fn,{onClick:de,children:"Delete"})]})]})})]}):T?q(vo,{children:[q(Va,{className:"size-full","data-testid":"properties-panel",defaultValue:"properties",onValueChange:O,value:te,children:[q(Ha,{className:"h-14 w-full shrink-0 rounded-none border-b bg-transparent px-4 py-2.5",children:[M(Ao,{className:"bg-transparent text-muted-foreground data-[state=active]:text-foreground data-[state=active]:shadow-none",value:"properties",children:"Properties"}),(T.data.type!=="trigger"||T.data.config?.triggerType!=="Manual")&&T.data.config?.actionType!=="Condition"?M(Ao,{className:"bg-transparent text-muted-foreground data-[state=active]:text-foreground data-[state=active]:shadow-none",value:"code",children:"Code"}):null,i&&M(Ao,{className:"bg-transparent text-muted-foreground data-[state=active]:text-foreground data-[state=active]:shadow-none",value:"runs",children:"Runs"})]}),q(Io,{className:"flex flex-col overflow-hidden",value:"properties",children:[T.data.type==="action"&&!T.data.config?.actionType&&i&&M("div",{className:"flex min-h-0 flex-1 flex-col px-4 pt-4",children:M(ta,{disabled:r,isNewlyCreated:T?.id===m,onSelectAction:Z=>{Ht("actionType",Z),T?.id===m&&w(null)}})}),!(T.data.type==="action"&&!T.data.config?.actionType&&i)&&q("div",{className:"flex-1 space-y-4 overflow-y-auto p-4",children:[q("div",{className:"space-y-2",children:[M(L,{className:"ml-1",htmlFor:"node-id",children:"Node ID"}),M(ae,{readOnly:!0,id:"node-id",value:T?.id||""})]}),T.data.type==="trigger"&&M(oa,{config:T.data.config||{},disabled:r||!i,onUpdateConfig:Ht,workflowId:s??void 0}),T.data.type==="action"&&!T.data.config?.actionType&&!i&&M("div",{className:"rounded-lg border border-muted bg-muted/30 p-3",children:M("p",{className:"text-muted-foreground text-sm",children:"No action configured for this step."})}),T.data.type==="action"&&T.data.config?.actionType?M(Yr,{config:T.data.config||{},disabled:r||!i,isOwner:i,onUpdateConfig:Ht,onUpdateMultipleConfig:rt}):null,T.data.type!=="action"||T.data.config?.actionType?q(vo,{children:[q("div",{className:"space-y-2",children:[M(L,{className:"ml-1",htmlFor:"label",children:"Label"}),M(ae,{disabled:r||!i,id:"label",onChange:Z=>Ie(Z.target.value),value:T.data.label})]}),q("div",{className:"space-y-2",children:[M(L,{className:"ml-1",htmlFor:"description",children:"Description"}),M(ae,{disabled:r||!i,id:"description",onChange:Z=>nt(Z.target.value),placeholder:"Optional description",value:T.data.description||""})]})]}):null,!i&&M("div",{className:"rounded-lg border border-muted bg-muted/30 p-3",children:M("p",{className:"text-muted-foreground text-sm",children:"You are viewing a public workflow. Duplicate it to make changes."})}),i&&q("div",{className:"flex items-center gap-2 pt-4",children:[T.data.type==="action"&&M(E,{className:"text-muted-foreground",onClick:ne,size:"sm",variant:"ghost",children:T.data.enabled===!1?q(vo,{children:[M(Nf,{className:"mr-2 size-4"}),"Disabled"]}):q(vo,{children:[M(xf,{className:"mr-2 size-4"}),"Enabled"]})}),q(E,{className:"text-muted-foreground",onClick:()=>S(!0),size:"sm",variant:"ghost",children:[M(sa,{className:"mr-2 size-4"}),"Delete"]})]})]})]}),M(Io,{className:"flex flex-col overflow-hidden data-[state=inactive]:hidden",forceMount:!0,value:"code",children:(()=>{let Z=T.data.config?.triggerType,ke="",P="typescript";return T.data.type==="trigger"?Z==="Schedule"?(ke="vercel.json",P="json"):Z==="Webhook"&&(ke=`app/api${T.data.config?.webhookPath||"/webhook"}/route.ts`,P="typescript"):ke=`steps/${T.data.config?.actionType?.toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9-]/g,"")||"action"}-step.ts`,q(vo,{children:[ke&&q("div",{className:"flex shrink-0 items-center justify-between border-b bg-muted/30 px-3 pb-2",children:[q("div",{className:"flex items-center gap-2",children:[M(jl,{className:"size-3.5 text-muted-foreground"}),M("code",{className:"text-muted-foreground text-xs",children:ke})]}),q(E,{className:"text-muted-foreground",onClick:C,size:"sm",variant:"ghost",children:[M(ql,{className:"mr-2 size-4"}),"Copy"]})]}),M("div",{className:"flex-1 overflow-hidden",children:M(xt,{height:"100%",language:P,options:{readOnly:!0,minimap:{enabled:!1},scrollBeyondLastLine:!1,fontSize:13,lineNumbers:"on",folding:!1,wordWrap:"off",padding:{top:16,bottom:16}},value:Sn(T)})})]})})()}),i&&q(Io,{className:"flex flex-col overflow-hidden",value:"runs",children:[q("div",{className:"flex shrink-0 items-center gap-2 border-b px-4 py-2",children:[q(E,{className:"text-muted-foreground",disabled:x,onClick:To,size:"sm",variant:"ghost",children:[M(Jl,{className:`mr-2 size-4 ${x?"animate-spin":""}`}),"Refresh"]}),q(E,{className:"text-muted-foreground",onClick:()=>f(!0),size:"sm",variant:"ghost",children:[M(fs,{className:"mr-2 size-4"}),"Clear All"]})]}),M("div",{className:"flex-1 space-y-4 overflow-y-auto p-4",children:M(An,{isActive:te==="runs",onRefreshRef:W})})]})]}),M(ln,{onOpenChange:f,open:k,children:q(dn,{children:[q(cn,{children:[M(mn,{children:"Delete All Runs"}),M(pn,{children:"Are you sure you want to delete all workflow runs? This action cannot be undone."})]}),q(un,{children:[M(gn,{children:"Cancel"}),M(fn,{onClick:V,children:"Delete"})]})]})}),M(ln,{onOpenChange:S,open:h,children:q(dn,{children:[q(cn,{children:[M(mn,{children:"Delete Step"}),M(pn,{children:"Are you sure you want to delete this node? This action cannot be undone."})]}),q(un,{children:[M(gn,{children:"Cancel"}),M(fn,{onClick:_,children:"Delete"})]})]})})]}):q(vo,{children:[q(Va,{className:"size-full",defaultValue:"properties",onValueChange:O,value:te,children:[q(Ha,{className:"h-14 w-full shrink-0 rounded-none border-b bg-transparent px-4 py-2.5",children:[M(Ao,{className:"bg-transparent text-muted-foreground data-[state=active]:text-foreground data-[state=active]:shadow-none",value:"properties",children:"Properties"}),M(Ao,{className:"bg-transparent text-muted-foreground data-[state=active]:text-foreground data-[state=active]:shadow-none",value:"code",children:"Code"}),i&&M(Ao,{className:"bg-transparent text-muted-foreground data-[state=active]:text-foreground data-[state=active]:shadow-none",value:"runs",children:"Runs"})]}),M(Io,{className:"flex flex-col overflow-hidden",value:"properties",children:q("div",{className:"flex-1 space-y-4 overflow-y-auto p-4",children:[q("div",{className:"space-y-2",children:[M(L,{className:"ml-1",htmlFor:"workflow-name",children:"Workflow Name"}),M(ae,{disabled:!i,id:"workflow-name",onChange:Z=>Lt(Z.target.value),value:a})]}),q("div",{className:"space-y-2",children:[M(L,{className:"ml-1",htmlFor:"workflow-id",children:"Workflow ID"}),M(ae,{disabled:!0,id:"workflow-id",value:s||"Not saved"})]}),!i&&M("div",{className:"rounded-lg border border-muted bg-muted/30 p-3",children:M("p",{className:"text-muted-foreground text-sm",children:"You are viewing a public workflow. Duplicate it to make changes."})}),i&&q("div",{className:"flex items-center gap-2 pt-4",children:[q(E,{className:"text-muted-foreground",onClick:()=>{y(Ee,{title:"Clear Workflow",message:"Are you sure you want to clear all nodes and connections? This action cannot be undone.",confirmLabel:"Clear Workflow",confirmVariant:"destructive",destructive:!0,onConfirm:()=>{b()}})},size:"sm",variant:"ghost",children:[M(fs,{className:"mr-2 size-4"}),"Clear"]}),q(E,{className:"text-muted-foreground",onClick:()=>{y(Ee,{title:"Delete Workflow",message:`Are you sure you want to delete "${a}"? This will permanently delete the workflow. This cannot be undone.`,confirmLabel:"Delete Workflow",confirmVariant:"destructive",destructive:!0,onConfirm:async()=>{if(s)try{await U.workflow.delete(s),In.success("Workflow deleted successfully"),window.location.href="/"}catch(Z){console.error("Failed to delete workflow:",Z),In.error("Failed to delete workflow. Please try again.")}}})},size:"sm",variant:"ghost",children:[M(sa,{className:"mr-2 size-4"}),"Delete"]})]})]})}),i&&q(Io,{className:"flex flex-col overflow-hidden",value:"runs",children:[q("div",{className:"flex shrink-0 items-center gap-2 border-b px-4 py-2",children:[q(E,{className:"text-muted-foreground",disabled:x,onClick:To,size:"sm",variant:"ghost",children:[M(Jl,{className:`mr-2 size-4 ${x?"animate-spin":""}`}),"Refresh"]}),q(E,{className:"text-muted-foreground",onClick:()=>f(!0),size:"sm",variant:"ghost",children:[M(fs,{className:"mr-2 size-4"}),"Clear All"]})]}),M("div",{className:"flex-1 space-y-4 overflow-y-auto p-4",children:M(An,{isActive:te==="runs",onRefreshRef:W})})]}),q(Io,{className:"flex flex-col overflow-hidden data-[state=inactive]:hidden",forceMount:!0,value:"code",children:[q("div",{className:"flex shrink-0 items-center justify-between border-b bg-muted/30 px-3 pb-2",children:[q("div",{className:"flex items-center gap-2",children:[M(jl,{className:"size-3.5 text-muted-foreground"}),q("code",{className:"text-muted-foreground text-xs",children:["workflows/",a.toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9-]/g,"")||"workflow",".ts"]})]}),q(E,{className:"text-muted-foreground",onClick:R,size:"sm",variant:"ghost",children:[M(ql,{className:"mr-2 size-4"}),"Copy"]})]}),M("div",{className:"flex-1 overflow-hidden",children:M(xt,{height:"100%",language:"typescript",options:{readOnly:!0,minimap:{enabled:!1},scrollBeyondLastLine:!1,fontSize:13,lineNumbers:"on",folding:!0,wordWrap:"off",padding:{top:16,bottom:16}},value:B})})]})]}),M(ln,{onOpenChange:f,open:k,children:q(dn,{children:[q(cn,{children:[M(mn,{children:"Delete All Runs"}),M(pn,{children:"Are you sure you want to delete all workflow runs? This action cannot be undone."})]}),q(un,{children:[M(gn,{children:"Cancel"}),M(fn,{onClick:V,children:"Delete"})]})]})})]})},gs=()=>M("div",{className:"hidden size-full flex-col bg-background md:flex",children:M(If,{})});import{jsx as Dt,jsxs as ia}from"react/jsx-runtime";var hs=({workflowId:e})=>{let t=Of(),o=_t(),[n,r]=qt(St),[s,a]=qt(Er),[d]=qt(re),[i]=qt(ue),[l]=qt(Ke),[c]=qt(so),u=Pt(re),g=Pt(ue),b=Pt(Ke),y=Pt(wt),v=Pt(io),p=Pt(st),[m,w]=qt(wi),h=Pt(Pr),S=Pt(Cr),D=Pt(Tr),[I,k]=qt(Sr),[f,x]=qt(gi),G=Pt(Nr),[te,O]=qt(ao),W=Pt(bt),$=Pt(xr),T=Pf(Wt),[H,X]=ys(30),[z,j]=ys(I),[A,B]=ys(!1),C=Bo(!1),R=Bo(!1);Et(()=>{if(R.current)return;R.current=!0;let P=document.cookie.split("; ").find(Y=>Y.startsWith("sidebar-width="));if(P){let Y=Number.parseFloat(P.split("=")[1]);!Number.isNaN(Y)&&Y>=20&&Y<=50&&X(Y)}let F=document.cookie.split("; ").find(Y=>Y.startsWith("sidebar-collapsed="));F&&x(F.split("=")[1]==="true")},[x]);let _=Bo(!1);Et(()=>{if(!_.current){_.current=!0;return}document.cookie=`sidebar-width=${H}; path=/; max-age=31536000`},[H]),Et(()=>{R.current&&(document.cookie=`sidebar-collapsed=${f}; path=/; max-age=31536000`)},[f]),Et(()=>{let P=sessionStorage.getItem("animate-sidebar")==="true";if(sessionStorage.removeItem("animate-sidebar"),I||!P){j(!0),k(!0);return}D(!0);let F=setTimeout(()=>{j(!0),k(!0)},100),Y=setTimeout(()=>D(!1),400);return()=>{clearTimeout(F),clearTimeout(Y),D(!1)}},[I,k,D]),Et(()=>{let P=F=>{(F.metaKey||F.ctrlKey)&&F.key==="b"&&(F.preventDefault(),D(!0),x(Y=>!Y),setTimeout(()=>D(!1),350))};return window.addEventListener("keydown",P),()=>window.removeEventListener("keydown",P)},[D,x]),Et(()=>(S(!o&&z&&!f?`${H}%`:null),()=>{S(null)}),[o,S,H,z,f]);let ne=ho(P=>{P.preventDefault(),C.current=!0,B(!0);let F=fe=>{if(!C.current)return;let pe=(window.innerWidth-fe.clientX)/window.innerWidth*100;X(Math.min(50,Math.max(20,pe)))},Y=()=>{C.current=!1,B(!1),document.removeEventListener("mousemove",F),document.removeEventListener("mouseup",Y),document.body.style.cursor="",document.body.style.userSelect=""};document.addEventListener("mousemove",F),document.addEventListener("mouseup",Y),document.body.style.cursor="col-resize",document.body.style.userSelect="none"},[]),de=Bo(null),V=Bo(null),Ie=Bo(d);Et(()=>{Ie.current=d},[d]);let nt=ho(async P=>{r(!0),b(e),y("AI Generated Workflow");try{let F=await U.ai.generate(P),Y=(F.nodes||[]).map(fe=>({...fe,selected:!1}));u(Y),g(F.edges||[]),y(F.name||"AI Generated Workflow"),await U.workflow.update(e,{name:F.name,description:F.description,nodes:F.nodes,edges:F.edges})}catch(F){console.error("Failed to generate workflow:",F),vs.error("Failed to generate workflow")}finally{r(!1)}},[e,r,b,y,u,g]),Qe=ho(async()=>{try{let P=await U.workflow.getById(e);if(!P){w(!0);return}let F=P.nodes.map(Y=>({...Y,selected:!1,data:{...Y.data,status:"idle"}}));u(F),g(P.edges),b(P.id),y(P.name),G(P.visibility??"private"),O(P.isOwner!==!1),p(!1),w(!1)}catch(P){console.error("Failed to load workflow:",P),vs.error("Failed to load workflow")}},[e,u,g,b,y,G,O,p,w]),rt=Bo(null);Et(()=>{(async()=>{let F=t?.get("generating")==="true",Y=sessionStorage.getItem("ai-prompt"),fe=sessionStorage.getItem("generating-workflow-id");l===e&&d.length>0||(F&&Y&&fe===e?(sessionStorage.removeItem("ai-prompt"),sessionStorage.removeItem("generating-workflow-id"),await nt(Y)):await Qe())})()},[e,t,l,d.length,nt,Qe]),Et(()=>{if(d.length===0||!l||!te)return;let P=rt.current;if(P&&P.workflowId===l&&P.version===T)return;(async()=>{try{let Y=await U.integration.getAll();W(Y),$(!0);let fe=new Set(Y.map(Ce=>Ce.id)),pe=d.map(Ce=>Ti(Ce,Y,fe)).filter(Ce=>Ce!==null);for(let Ce of pe){let mt=d.find(yr=>yr.id===Ce.nodeId);mt&&v({id:Ce.nodeId,data:{config:{...mt.data.config,integrationId:Ce.newIntegrationId}}})}rt.current={workflowId:l,version:T},pe.length>0&&p(!0)}catch(Y){console.error("Failed to auto-fix integrations:",Y)}})()},[d,l,T,te,v,W,$,p]);let Ht=ho(async()=>{if(!(!l||n)){a(!0);try{await U.workflow.update(l,{nodes:d,edges:i}),p(!1)}catch(P){console.error("Failed to save workflow:",P),vs.error("Failed to save workflow")}finally{a(!1)}}},[l,d,i,n,a,p]),Lt=ho(P=>P.tagName==="INPUT"||P.tagName==="TEXTAREA",[]),To=ho(P=>P.closest(".monaco-editor")!==null,[]),Z=ho(P=>(P.metaKey||P.ctrlKey)&&P.key==="s"?(P.preventDefault(),P.stopPropagation(),Ht(),!0):!1,[Ht]),ke=ho((P,F)=>(P.metaKey||P.ctrlKey)&&P.key==="Enter"?(Lt(F)||To(F)||(P.preventDefault(),P.stopPropagation(),h(!0)),!0):!1,[h,Lt,To]);return Et(()=>{let P=F=>{let Y=F.target;Z(F)||ke(F,Y)};return document.addEventListener("keydown",P,!0),()=>document.removeEventListener("keydown",P,!0)},[Z,ke]),Et(()=>()=>{de.current&&clearInterval(de.current),V.current&&clearInterval(V.current)},[]),Et(()=>{if(V.current&&(clearInterval(V.current),V.current=null),!c){for(let F of Ie.current)v({id:F.id,data:{status:"idle"}});return}let P=async()=>{try{let F=await U.workflow.getExecutionStatus(c);for(let Y of F.nodeStatuses)v({id:Y.nodeId,data:{status:Y.status}});F.status!=="running"&&V.current&&(clearInterval(V.current),V.current=null)}catch(F){console.error("Failed to poll selected execution status:",F),V.current&&(clearInterval(V.current),V.current=null)}};return P(),V.current=setInterval(P,500),()=>{V.current&&(clearInterval(V.current),V.current=null)}},[c,v]),ia("div",{className:"flex h-dvh w-full flex-col overflow-hidden",children:[m&&Dt("div",{className:"pointer-events-auto absolute inset-0 z-20 flex items-center justify-center",children:ia("div",{className:"rounded-lg border bg-background p-8 text-center shadow-lg",children:[Dt("h1",{className:"mb-2 font-semibold text-2xl",children:"Workflow Not Found"}),Dt("p",{className:"mb-6 text-muted-foreground",children:"The workflow you're looking for doesn't exist or has been deleted."}),Dt(E,{asChild:!0,children:Dt(Rf,{href:"/",children:"New Workflow"})})]})}),!o&&f&&Dt("button",{className:"pointer-events-auto absolute top-1/2 right-0 z-20 flex size-6 -translate-y-1/2 items-center justify-center rounded-l-full border border-r-0 bg-background shadow-sm transition-colors hover:bg-muted",onClick:()=>{D(!0),x(!1),setTimeout(()=>D(!1),350)},type:"button",children:Dt(Ef,{className:"size-4"})}),!o&&ia("div",{className:"pointer-events-auto absolute inset-y-0 right-0 z-20 border-l bg-background transition-transform duration-300 ease-out",style:{width:`${H}%`,transform:z&&!f?"translateX(0)":"translateX(100%)"},children:[ia("div",{"aria-orientation":"vertical","aria-valuenow":H,className:"group absolute inset-y-0 left-0 z-10 w-3 cursor-col-resize",onMouseDown:ne,role:"separator",tabIndex:0,children:[Dt("div",{className:"absolute inset-y-0 left-0 w-1 bg-transparent transition-colors group-hover:bg-blue-500 group-active:bg-blue-600"}),!(A||f)&&Dt("button",{className:"absolute top-1/2 left-0 flex size-6 -translate-x-1/2 -translate-y-1/2 items-center justify-center rounded-full border bg-background opacity-0 shadow-sm transition-opacity hover:bg-muted group-hover:opacity-100",onClick:P=>{P.stopPropagation(),D(!0),x(!0),setTimeout(()=>D(!1),350)},onMouseDown:P=>P.stopPropagation(),type:"button",children:Dt(Df,{className:"size-4"})})]}),Dt(gs,{})]}),o&&Dt(gs,{})]})};import{useAtomValue as bs,useSetAtom as ar}from"jotai";import{nanoid as Wf}from"nanoid";import{useRouter as Ff}from"next/navigation";import{useCallback as ed,useEffect as la,useRef as zf}from"react";import{toast as Bf}from"sonner";import{anonymousClient as Lf}from"better-auth/client/plugins";import{createAuthClient as Mf}from"better-auth/react";var Vo=Mf({baseURL:typeof window<"u"?window.location.origin:"http://localhost:3000",plugins:[Lf()]}),{signIn:j0,signOut:Zl,signUp:J0,useSession:Pn}=Vo;function Vf(){return{id:Wf(),type:"trigger",position:{x:0,y:0},data:{label:"",description:"",type:"trigger",config:{triggerType:"Manual"},status:"idle"}}}var td=()=>{let e=Ff(),{data:t}=Pn(),o=bs(re),n=bs(ue),r=ar(re),s=ar(ue),a=ar(wt),d=ar(Sr),i=ar(Ar),l=zf(!1),c=bs(wt);la(()=>{d(!1)},[d]),la(()=>{document.title=`${c} - AI Workflow Builder`},[c]);let u=ed(async()=>{t||(await Vo.signIn.anonymous(),await new Promise(b=>setTimeout(b,100)))},[t]),g=ed(()=>{let b=Vf();r([b])},[r]);return la(()=>{r([{id:"add-node-placeholder",type:"add",position:{x:0,y:0},data:{label:"",type:"add",onClick:g},draggable:!1,selectable:!1}]),s([]),a("New Workflow"),l.current=!1},[r,s,a,g]),la(()=>{(async()=>{let y=o.filter(v=>v.type!=="add");if(!(y.length===0||l.current)){l.current=!0;try{await u();let v=await U.workflow.create({name:"Untitled Workflow",description:"",nodes:y,edges:n});sessionStorage.setItem("animate-sidebar","true"),i(!0),console.log("[Homepage] Navigating to workflow page"),e.replace(`/workflows/${v.id}`)}catch(v){console.error("Failed to create workflow:",v),Bf.error("Failed to create workflow")}}})()},[o,n,e,u,i]),null};import{useRouter as Hf}from"next/navigation";import{useEffect as Gf}from"react";var od=()=>{let e=Hf();return Gf(()=>{(async()=>{try{let n=(await U.workflow.getAll()).filter(r=>r.name!=="__current__");if(n.length>0){let r=n.sort((s,a)=>new Date(a.updatedAt).getTime()-new Date(s.updatedAt).getTime())[0];e.replace(`/workflows/${r.id}`)}else e.replace("/")}catch(o){console.error("Failed to load workflows:",o),e.replace("/")}})()},[e]),null};import{jsx as Ho}from"react/jsx-runtime";var Uf=()=>{let t=_f().slug;return!t||t.length===0?Ho(td,{}):t[0]==="dashboard"?Ho(Oa,{}):t[0]==="auth"&&t.length===2?Ho("main",{className:"flex items-center justify-center min-h-screen",children:Ho($f,{path:t[1]})}):t[0]==="workflows"&&t.length===1?Ho(od,{}):t[0]==="workflows"&&t.length===2?Ho("div",{className:"pointer-events-none relative z-10",children:Ho(hs,{workflowId:t[1]})}):null};import"virtual:workflow-builder-plugins";import{ReactFlowProvider as vh}from"@xyflow/react";import{Provider as hh,useSetAtom as bh}from"jotai";import*as Aa from"react";import{AnimatePresence as jf,LayoutGroup as ad,motion as Dn,useReducedMotion as sd}from"motion/react";import{useCallback as ir,useLayoutEffect as lr,useRef as bo,useState as id}from"react";import{Drawer as sr}from"vaul";import{Dialog as En}from"radix-ui";import{XIcon as Kf}from"lucide-react";import{jsx as Go,jsxs as ws}from"react/jsx-runtime";function da({...e}){return Go(En.Root,{"data-slot":"dialog",...e})}function xs({...e}){return Go(En.Portal,{"data-slot":"dialog-portal",...e})}function qf({className:e,...t}){return Go(En.Overlay,{"data-slot":"dialog-overlay",className:N("data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",e),...t})}function nd({className:e,children:t,showCloseButton:o=!0,...n}){return ws(xs,{"data-slot":"dialog-portal",children:[Go(qf,{}),ws(En.Content,{"data-slot":"dialog-content",className:N("bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 sm:max-w-lg",e),...n,children:[t,o&&ws(En.Close,{"data-slot":"dialog-close",className:"ring-offset-background focus:ring-ring data-[state=open]:bg-accent data-[state=open]:text-muted-foreground absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",children:[Go(Kf,{}),Go("span",{className:"sr-only",children:"Close"})]})]})]})}function rd({className:e,...t}){return Go(En.Title,{"data-slot":"dialog-title",className:N("text-lg leading-none font-semibold",e),...t})}import{jsx as ze,jsxs as ks}from"react/jsx-runtime";var Ns={type:"spring",stiffness:400,damping:35,mass:.8},Jf={type:"spring",stiffness:350,damping:30,mass:.8},Yf={hidden:{opacity:0,scale:.95},visible:{opacity:1,scale:1,transition:{type:"spring",stiffness:400,damping:30}},exit:{opacity:0,scale:.95,transition:{duration:.15,ease:[.4,0,1,1]}}};function ld(e,t){return e?"0%":t?"-35%":"100%"}function dd(e){let t=bo(e),o=bo(1);return e>t.current?o.current=1:e<t.current&&(o.current=-1),lr(()=>{t.current=e},[e]),o.current}function Xf(){let{stack:e,closeAll:t,pop:o}=oe(),n=sd(),[r,s]=id(0),a=bo(null),d=bo(!1),i=bo(e),l=dd(e.length),c=e.length>0;c&&(i.current=e);let u=i.current,g=u.length-1;console.log("[DesktopOverlay]",{isOpen:c,stackLength:e.length,frozenStackLength:i.current.length,renderStackLength:u.length}),lr(()=>{let h=c&&!d.current;if(d.current=c,h&&s(0),a.current){let S=a.current.offsetHeight;S>0&&s(S)}},[e,c]);let b=e[e.length-1],y=n?{duration:.01}:Ns,v=l===1,p=ir(()=>{b?.options.closeOnBackdropClick!==!1&&t()},[b?.options.closeOnBackdropClick,t]),m=ir(h=>{h.key==="Escape"&&b?.options.closeOnEscape!==!1&&o()},[b?.options.closeOnEscape,o]);lr(()=>{if(c)return document.addEventListener("keydown",m),()=>document.removeEventListener("keydown",m)},[c,m]);let w=ir(()=>{console.log("[DesktopOverlay] handleExitComplete called"),i.current=[]},[]);return console.log("[DesktopOverlay] Rendering, isOpen:",c),!c&&i.current.length===0?null:ze(jf,{onExitComplete:w,children:c&&ze(da,{modal:!1,open:!0,children:ks(xs,{forceMount:!0,children:[ze(Dn.div,{animate:{opacity:1},className:"fixed inset-0 z-50 bg-black/60",exit:{opacity:0},initial:{opacity:0},onClick:p,transition:{duration:.2}}),ze(Dn.div,{animate:"visible",className:"fixed top-1/2 left-1/2 z-50 w-full max-w-lg -translate-x-1/2 -translate-y-1/2 px-4",exit:"exit",initial:"hidden",variants:Yf,children:ze(ad,{children:ze(Dn.div,{className:"relative overflow-hidden rounded-xl border bg-background shadow-2xl ring-1 ring-black/5",layout:c,style:{minHeight:r>0?r:"auto"},transition:Ns,children:ze("div",{className:"relative",ref:a,children:u.map((h,S)=>{let D=S===g,I=S<g,f=D&&v&&u.length>1?{x:"100%",scale:1,opacity:1}:!1;return ze(Dn.div,{animate:{x:ld(D,I),scale:D?1:.94,opacity:D?1:0},"aria-hidden":!D,className:N("w-full",D?"relative":"pointer-events-none absolute inset-0"),initial:f,transition:y,children:ze(h.component,{overlayId:h.id,...h.props})},h.id)})})})})})]})})})}function Qf(){let{stack:e,closeAll:t,pop:o}=oe(),n=sd(),[r,s]=id(0),a=bo(null),d=bo(!1),i=bo(e),l=dd(e.length),c=e.length>0;c&&(i.current=e);let u=i.current,g=u.length-1;lr(()=>{let h=c&&!d.current;if(d.current=c,h&&s(0),a.current){let S=a.current.offsetHeight;S>0&&s(S)}},[e,c]);let b=e[e.length-1],y=u[g],v=n?{duration:.01}:Ns,p=l===1,m=ir(h=>{h.key==="Escape"&&b?.options.closeOnEscape!==!1&&o()},[b?.options.closeOnEscape,o]);lr(()=>{if(c)return document.addEventListener("keydown",m),()=>document.removeEventListener("keydown",m)},[c,m]);let w=ir(()=>{c||(i.current=[])},[c]);return ze(sr.Root,{onAnimationEnd:w,onOpenChange:h=>{h||t()},open:c,children:ks(sr.Portal,{children:[ze(sr.Overlay,{className:"fixed inset-0 z-50 bg-black/60"}),ks(sr.Content,{className:N("fixed inset-x-0 bottom-0 z-50 flex max-h-[90vh] flex-col","rounded-t-2xl border-t bg-background shadow-2xl"),children:[ze(sr.Title,{className:"sr-only",children:y?.options.title||"Dialog"}),ze("div",{className:"mx-auto mt-3 h-1.5 w-12 shrink-0 rounded-full bg-muted-foreground/20"}),ze(ad,{children:ze(Dn.div,{className:"relative flex-1 overflow-hidden",layout:c,style:{minHeight:r>0?r:"auto"},transition:Jf,children:ze("div",{className:"relative",ref:a,children:u.map((h,S)=>{let D=S===g,I=S<g,f=D&&p&&u.length>1?{x:"100%",scale:1,opacity:1}:!1;return ze(Dn.div,{animate:{x:ld(D,I),scale:D?1:.94,opacity:D?1:0},"aria-hidden":!D,className:N("w-full",D?"relative":"pointer-events-none absolute inset-0"),initial:f,transition:v,children:ze(h.component,{overlayId:h.id,...h.props})},h.id)})})})}),ze("div",{className:"h-safe-area-inset-bottom"})]})]})})}function cd(){return _t()?ze(Qf,{}):ze(Xf,{})}import{useAtom as Zf}from"jotai";import{useEffect as eg,useRef as ud}from"react";import{atom as Xt}from"jotai";var Xe=Xt([]),OT=Xt(e=>e(Xe).length>0),LT=Xt(e=>e(Xe).length);function Cs(){return`overlay-${Date.now()}-${Math.random().toString(36).slice(2,9)}`}var MT=Xt(null,(e,t,o)=>{let n=Cs(),r={id:n,component:o.component,props:o.props??{},options:o.options??{}};return t(Xe,[r]),n}),WT=Xt(null,(e,t,o)=>{let n=Cs(),r={id:n,component:o.component,props:o.props??{},options:o.options??{}};return t(Xe,[...e(Xe),r]),n}),FT=Xt(null,(e,t)=>{let o=e(Xe);if(o.length<=1){o[0]?.options.onClose?.(),t(Xe,[]);return}o[o.length-1]?.options.onClose?.(),t(Xe,o.slice(0,-1))}),zT=Xt(null,(e,t,o)=>{let n=e(Xe),r=Cs(),s={id:r,component:o.component,props:o.props??{},options:o.options??{}};return n.length===0?t(Xe,[s]):(n[n.length-1]?.options.onClose?.(),t(Xe,[...n.slice(0,-1),s])),r}),BT=Xt(null,(e,t)=>{let o=e(Xe);for(let n of o)n.options.onClose?.();t(Xe,[])}),VT=Xt(null,(e,t,o)=>{let n=e(Xe),r=n.findIndex(s=>s.id===o);if(r!==-1){for(let s=r;s<n.length;s++)n[s].options.onClose?.();t(Xe,n.slice(0,r))}});function md(){let{stack:e}=oe(),[t,o]=Zf(Xe),n=ud(!1),r=ud(!1);return eg(()=>{if(n.current){n.current=!1;return}r.current=!0,o(e)},[e,o]),null}import{Fragment as tg,jsx as pd,jsxs as og}from"react/jsx-runtime";var fd=()=>og(tg,{children:[pd(cd,{}),pd(md,{})]});import{CircleCheckIcon as ng,InfoIcon as rg,Loader2Icon as ag,OctagonXIcon as sg,TriangleAlertIcon as ig}from"lucide-react";import{useTheme as lg}from"next-themes";import{Toaster as dg}from"sonner";import{jsx as Rn}from"react/jsx-runtime";var gd=({...e})=>{let{theme:t="system"}=lg();return Rn(dg,{theme:t,className:"toaster group",icons:{success:Rn(ng,{className:"size-4"}),info:Rn(rg,{className:"size-4"}),warning:Rn(ig,{className:"size-4"}),error:Rn(sg,{className:"size-4"}),loading:Rn(ag,{className:"size-4 animate-spin"})},style:{"--normal-bg":"var(--popover)","--normal-text":"var(--popover-foreground)","--normal-border":"var(--border)","--border-radius":"var(--radius)"},...e})};import{usePathname as ch}from"next/navigation";import{ConnectionMode as oh,MiniMap as nh,useReactFlow as rh}from"@xyflow/react";import{useAtom as gr,useAtomValue as Xs,useSetAtom as No}from"jotai";import{useCallback as Tt,useEffect as Sa,useMemo as ah,useRef as ko,useState as Wc}from"react";import{Background as cg,ReactFlow as ug}from"@xyflow/react";import{useAtomValue as mg}from"jotai";import"@xyflow/react/dist/style.css";import{jsx as pg,jsxs as fg}from"react/jsx-runtime";var yd=({children:e,...t})=>{let o=mg(en);return fg(ug,{deleteKeyCode:["Backspace","Delete"],fitView:!0,panActivationKeyCode:null,selectionOnDrag:!1,snapToGrid:o.snapToGrid??!0,zoomOnDoubleClick:!1,zoomOnPinch:!0,...t,children:[pg(cg,{bgColor:"var(--sidebar)",color:"var(--border)",gap:24,size:2}),e]})};import{jsx as vd,jsxs as gg}from"react/jsx-runtime";var hd=({fromX:e,fromY:t,toX:o,toY:n})=>gg("g",{children:[vd("path",{className:"animated",d:`M${e},${t} C ${e+(o-e)*.5},${t} ${e+(o-e)*.5},${n} ${o},${n}`,fill:"none",stroke:"var(--color-ring)",strokeWidth:1}),vd("circle",{cx:o,cy:n,fill:"#fff",r:3,stroke:"var(--color-ring)",strokeWidth:1})]});import{useReactFlow as bg}from"@xyflow/react";import{useAtom as wg}from"jotai";import{MapPin as xg,MapPinXInside as Ng,Maximize2 as kg,ZoomIn as Cg,ZoomOut as Tg}from"lucide-react";import{cva as yg}from"class-variance-authority";import{Slot as mS}from"radix-ui";import{jsx as hg}from"react/jsx-runtime";var vg=yg("flex w-fit items-stretch [&>*]:focus-visible:z-10 [&>*]:focus-visible:relative [&>[data-slot=select-trigger]:not([class*='w-'])]:w-fit [&>input]:flex-1 has-[select[aria-hidden=true]:last-child]:[&>[data-slot=select-trigger]:last-of-type]:rounded-r-md has-[>[data-slot=button-group]]:gap-2",{variants:{orientation:{horizontal:"[&>*:not(:first-child)]:rounded-l-none [&>*:not(:first-child)]:border-l-0 [&>*:not(:last-child)]:rounded-r-none",vertical:"flex-col [&>*:not(:first-child)]:rounded-t-none [&>*:not(:first-child)]:border-t-0 [&>*:not(:last-child)]:rounded-b-none"}},defaultVariants:{orientation:"horizontal"}});function jt({className:e,orientation:t,...o}){return hg("div",{role:"group","data-slot":"button-group","data-orientation":t,className:N(vg({orientation:t}),e),...o})}import{jsx as Qt,jsxs as Sg}from"react/jsx-runtime";var bd=()=>{let{zoomIn:e,zoomOut:t,fitView:o}=bg(),[n,r]=wg(kr);return Sg(jt,{orientation:"vertical",children:[Qt(E,{className:"border hover:bg-black/5 disabled:opacity-100 dark:hover:bg-white/5 disabled:[&>svg]:text-muted-foreground",onClick:()=>{e()},size:"icon",title:"Zoom in",variant:"secondary",children:Qt(Cg,{className:"size-4"})}),Qt(E,{className:"border hover:bg-black/5 disabled:opacity-100 dark:hover:bg-white/5 disabled:[&>svg]:text-muted-foreground",onClick:()=>{t()},size:"icon",title:"Zoom out",variant:"secondary",children:Qt(Tg,{className:"size-4"})}),Qt(E,{className:"border hover:bg-black/5 disabled:opacity-100 dark:hover:bg-white/5 disabled:[&>svg]:text-muted-foreground",onClick:()=>{o({padding:.2,duration:300})},size:"icon",title:"Fit view",variant:"secondary",children:Qt(kg,{className:"size-4"})}),Qt(E,{className:"border hover:bg-black/5 disabled:opacity-100 dark:hover:bg-white/5 disabled:[&>svg]:text-muted-foreground",onClick:()=>{r(!n)},size:"icon",title:n?"Hide minimap":"Show minimap",variant:"secondary",children:n?Qt(xg,{className:"size-4"}):Qt(Ng,{className:"size-4"})})]})};import{useReactFlow as Rg}from"@xyflow/react";import{useAtom as On,useAtomValue as Og}from"jotai";import{ArrowUp as Lg}from"lucide-react";import{useCallback as Mg,useEffect as Wg,useRef as xd,useState as Ts}from"react";import{toast as Ss}from"sonner";import{motion as Ag}from"motion/react";import{memo as Ig,useMemo as Pg}from"react";import{jsx as Dg}from"react/jsx-runtime";var Eg=({children:e,as:t="p",className:o,duration:n=2,spread:r=2})=>{let s=Ag.create(t),a=Pg(()=>(e?.length??0)*r,[e,r]);return Dg(s,{animate:{backgroundPosition:"0% center"},className:N("relative inline-block bg-[length:250%_100%,auto] bg-clip-text text-transparent","[--bg:linear-gradient(90deg,#0000_calc(50%-var(--spread)),var(--color-background),#0000_calc(50%+var(--spread)))] [background-repeat:no-repeat,padding-box]",o),initial:{backgroundPosition:"100% center"},style:{"--spread":`${a}px`,backgroundImage:"var(--bg), linear-gradient(var(--color-muted-foreground), var(--color-muted-foreground))"},transition:{repeat:Number.POSITIVE_INFINITY,duration:n,ease:"linear"},children:e})},wd=Ig(Eg);import{Fragment as Fg,jsx as Zt,jsxs as As}from"react/jsx-runtime";function Nd({workflowId:e,onWorkflowCreated:t}){let[o,n]=On(St),[r,s]=Ts(""),[a,d]=Ts(!1),[i,l]=Ts(!1),c=xd(null),u=xd(null),g=Og(re),[b,y]=On(ue),[v,p]=On(re),[m,w]=On(Ke),[h,S]=On(wt),[D,I]=On(Te),{fitView:k}=Rg(),f=g.filter(W=>W.type!=="add"),x=f.length>0;Wg(()=>{let W=$=>{($.metaKey||$.ctrlKey)&&$.key==="k"&&($.preventDefault(),c.current?.focus())};return window.addEventListener("keydown",W),()=>{window.removeEventListener("keydown",W)}},[]);let G=()=>{d(!0),l(!0)},te=W=>{u.current?.contains(W.relatedTarget)||(l(!1),r.trim()||d(!1))},O=Mg(async W=>{if(W.preventDefault(),!(!r.trim()||o)){n(!0);try{let $=x?{nodes:f,edges:b,name:h}:void 0;console.log("[AI Prompt] Generating workflow"),console.log("[AI Prompt] Has nodes:",x),console.log("[AI Prompt] Sending existing workflow:",!!$),$&&console.log("[AI Prompt] Existing workflow:",$.nodes.length,"nodes,",$.edges.length,"edges");let T=await U.ai.generateStream(r,z=>{let j=(z.edges||[]).map(C=>({...C,type:"animated"})),A=(z.nodes||[]).filter(C=>C.data?.type==="trigger"),B=j;if(A.length>1){let C=A[0],R=(z.nodes||[]).filter(ne=>ne.data?.type!=="trigger");z.nodes=[C,...R];let _=A.slice(1).map(ne=>ne.id);B=j.filter(ne=>!_.includes(ne.source)&&!_.includes(ne.target))}p(z.nodes||[]),y(B),z.name&&S(z.name),setTimeout(()=>{k({padding:.2,duration:200})},0)},$);console.log("[AI Prompt] Received final workflow data"),console.log("[AI Prompt] Nodes:",T.nodes?.length||0),console.log("[AI Prompt] Edges:",T.edges?.length||0);let H=(T.edges||[]).map(z=>({...z,type:"animated"}));console.log("[AI Prompt] Validating nodes:",T.nodes);let X=(T.nodes||[]).filter(z=>{let j=z.data?.type,A=z.data?.config||{};return console.log(`[AI Prompt] Checking node ${z.id}:`,{type:j,config:A,hasActionType:!!A.actionType,hasTriggerType:!!A.triggerType}),j==="trigger"?!A.triggerType:j==="action"?!A.actionType:!1});if(X.length>0)throw console.error("[AI Prompt] AI generated incomplete nodes:",X),console.error("[AI Prompt] Full workflow data:",JSON.stringify(T,null,2)),new Error(`Cannot create workflow: The AI tried to create ${X.length} incomplete node(s). The requested action type may not be supported. Please try a different description using supported actions: Send Email, Send Slack Message, Create Ticket, Database Query, HTTP Request, Generate Text, Generate Image, Scrape, or Search.`);if(e){w(e),console.log("[AI Prompt] Updating existing workflow:",e),console.log("[AI Prompt] Has existingWorkflow context:",!!$),$?(console.log("[AI Prompt] REPLACING workflow with AI response"),console.log("[AI Prompt] Replacing",f.length,"nodes with",T.nodes?.length||0,"nodes")):(console.log("[AI Prompt] Setting workflow for empty canvas"),Ss.success("Generated workflow"));let z=T.nodes?.find(j=>j.selected);z&&I(z.id),await U.workflow.update(e,{name:T.name,description:T.description,nodes:T.nodes,edges:H})}else{let z=await U.workflow.create({name:T.name||"AI Generated Workflow",description:T.description||"",nodes:T.nodes||[],edges:H});w(z.id),Ss.success("Created workflow"),t&&t(z.id)}s(""),d(!1),l(!1),c.current?.blur()}catch($){console.error("Failed to generate workflow:",$),Ss.error("Failed to generate workflow")}finally{n(!1)}}},[r,o,e,x,g,b,n,w,p,y,S,I,t,k]);return Zt(Fg,{children:Zt("div",{ref:u,className:"pointer-events-auto absolute bottom-4 left-1/2 z-10 -translate-x-1/2 px-4",style:{width:a?"min(100%, 42rem)":"20rem",transition:"width 150ms ease-out"},children:As("form",{"aria-busy":o,"aria-label":"AI workflow prompt",className:"relative flex items-center gap-2 rounded-lg border bg-background pl-3 pr-2 py-2 shadow-lg cursor-text",onClick:W=>{(W.target===W.currentTarget||W.target.tagName!=="BUTTON")&&c.current?.focus()},onMouseDown:W=>{W.target===W.currentTarget&&W.preventDefault()},onSubmit:O,role:"search",children:[o&&r?Zt(wd,{className:"flex-1 text-sm whitespace-pre-wrap",duration:2,children:r}):Zt("textarea",{"aria-label":"Describe your workflow",className:"flex-1 bg-transparent text-sm outline-none placeholder:text-muted-foreground resize-none h-[22px] min-h-[22px] max-h-[200px] py-0 leading-[22px]",disabled:o,onBlur:te,onChange:W=>{s(W.target.value),W.target.style.height="auto",W.target.style.height=`${W.target.scrollHeight}px`},onFocus:G,onKeyDown:W=>{W.key==="Enter"&&!W.shiftKey?(W.preventDefault(),O(W)):W.key==="Escape"&&(W.preventDefault(),s(""),d(!1),l(!1),c.current?.blur())},placeholder:i?"Describe your workflow with natural language...":"Ask AI...",ref:c,rows:1,value:r}),Zt("div",{className:"sr-only",children:o?"Generating workflow, please wait...":""}),As("div",{className:"relative size-8 shrink-0 self-end",children:[Zt(E,{"aria-label":"Focus prompt input (\u2318K)",className:"absolute inset-0 h-8 px-0 text-xs text-muted-foreground hover:bg-transparent transition-[opacity,filter] ease-out",onClick:()=>c.current?.focus(),style:!r.trim()&&!o&&!i?{opacity:1,filter:"blur(0px)",pointerEvents:"auto",visibility:"visible"}:{opacity:0,filter:"blur(2px)",pointerEvents:"none",visibility:"hidden"},type:"button",variant:"ghost",children:As("kbd",{"aria-hidden":"true",className:"pointer-events-none inline-flex h-5 select-none items-center gap-1 rounded border bg-muted px-1.5 font-mono text-[10px] font-medium text-muted-foreground opacity-100",children:[Zt("span",{className:"text-xs",children:"\u2318"}),"K"]})}),Zt(E,{"aria-label":o?"Generating workflow...":"Generate workflow",className:"size-8 transition-[opacity,filter] ease-out shrink-0",disabled:!r.trim()||o,size:"sm",style:!r.trim()&&!o&&!i?{opacity:0,filter:"blur(2px)",pointerEvents:"none",visibility:"hidden"}:{opacity:1,filter:"blur(0px)",pointerEvents:"auto",visibility:"visible"},type:"submit",children:Zt(Lg,{"aria-hidden":"true",className:"size-4"})})]})]})})})}import{useReactFlow as Oy}from"@xyflow/react";import{useAtom as tt,useAtomValue as cc,useSetAtom as Jt}from"jotai";import{Check as ba,ChevronDown as Ly,Copy as My,Download as Wy,Globe as uc,Loader2 as xa,Lock as mc,Play as Fy,Plus as pc,Redo2 as fc,Save as zy,Settings2 as By,Trash2 as Vy,Undo2 as gc}from"lucide-react";import{nanoid as Hy}from"nanoid";import{useRouter as Gy}from"next/navigation";import{useEffect as $s,useRef as $y,useState as Gs}from"react";import{toast as ut}from"sonner";import{Panel as zg}from"@xyflow/react";import{jsx as Bg}from"react/jsx-runtime";var ca=({className:e,...t})=>Bg(zg,{className:N("m-4 rounded-md border bg-card p-1",e),...t});var Is="https://vercel.new/workflow-builder",_S=`[![Deploy with Vercel](https://vercel.com/button)](${Is})`;import{jsx as dr,jsxs as kd}from"react/jsx-runtime";function Cd(){return dr(E,{asChild:!0,className:"h-9 gap-1.5 border px-2 sm:px-3",size:"sm",variant:"secondary",children:kd("a",{href:Is,rel:"noopener noreferrer",target:"_blank",children:[kd("svg",{"aria-label":"Vercel logomark",className:"size-3.5",fill:"currentColor",viewBox:"0 0 76 76",children:[dr("title",{children:"Vercel logomark"}),dr("path",{d:"m38 0 38 66H0z"})]}),dr("span",{className:"text-sm sm:hidden",children:"Deploy"}),dr("span",{className:"hidden text-sm sm:inline",children:"Deploy Your Own"})]})})}import{jsx as Td}from"react/jsx-runtime";function Sd({className:e}){return Td("svg",{"aria-label":"GitHub",className:e,fill:"currentColor",role:"img",viewBox:"0 0 24 24",children:Td("path",{d:"M12 0C5.37 0 0 5.37 0 12c0 5.31 3.435 9.795 8.205 11.385.6.105.825-.255.825-.57 0-.285-.015-1.23-.015-2.235-3.015.555-3.795-.735-4.035-1.41-.135-.345-.72-1.41-1.23-1.695-.42-.225-1.02-.78-.015-.795.945-.015 1.62.87 1.845 1.23 1.08 1.815 2.805 1.305 3.495.99.105-.78.42-1.305.765-1.605-2.67-.3-5.46-1.335-5.46-5.925 0-1.305.465-2.385 1.23-3.225-.12-.3-.54-1.53.12-3.18 0 0 1.005-.315 3.3 1.23.96-.27 1.98-.405 3-.405s2.04.135 3 .405c2.295-1.56 3.3-1.23 3.3-1.23.66 1.65.24 2.88.12 3.18.765.84 1.23 1.905 1.23 3.225 0 4.605-2.805 5.625-5.475 5.925.435.375.81 1.095.81 2.22 0 1.605-.015 2.895-.015 3.3 0 .315.225.69.825.57A12.02 12.02 0 0024 12c0-6.63-5.37-12-12-12z"})})}function Ad(e){if(e>=1e6){let t=(e/1e6).toFixed(1);return t.endsWith(".0")?`${Math.floor(e/1e6)}M`:`${t}M`}if(e>=1e3){let t=(e/1e3).toFixed(1);return t.endsWith(".0")?`${Math.floor(e/1e3)}k`:`${t}k`}return e.toString()}import{createContext as Vg,useContext as Hg}from"react";import{jsx as tA}from"react/jsx-runtime";var Gg=Vg(null);function Id(){return Hg(Gg)}import{jsx as Pd,jsxs as Ed}from"react/jsx-runtime";var $g="https://github.com/vercel-labs/workflow-builder-template";function Dd(){let e=Id();return Pd(E,{asChild:!0,className:"h-9 gap-1.5 px-2 sm:px-3",size:"sm",variant:"ghost",children:Ed("a",{className:"flex items-center",href:$g,rel:"noopener noreferrer",target:"_blank",children:[Pd(Sd,{className:"size-4.5"}),e!==null&&Ed("span",{className:"hidden text-sm sm:inline",children:[Ad(e)," stars"]})]})})}import{useAtom as eo,useAtomValue as Rd,useSetAtom as cr}from"jotai";import{Code as Od,Copy as Ld,Eraser as Ps,Eye as _g,EyeOff as Ug,FileCode as Md,Play as Wd,RefreshCw as Fd,Settings2 as zd,Trash2 as Es}from"lucide-react";import{useCallback as Ln,useEffect as Kg,useRef as qg,useState as jg}from"react";import{toast as Mn}from"sonner";import{Fragment as Ds,jsx as ee,jsxs as ie}from"react/jsx-runtime";var Jg={"Database Query":"database"},Yg=/[^a-zA-Z0-9\s]/g,Xg=/\s+/;function Qg(e){return e.data.type==="trigger"?e.data.config?.triggerType==="Schedule"?"vercel.json":`app/api${e.data.config?.webhookPath||"/webhook"}/route.ts`:`steps/${(e.data.config?.actionType||"action").toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9-]/g,"")}-step.ts`}function ua({overlayId:e}){let{push:t,closeAll:o}=oe(),[n]=eo(Te),[r]=eo(Ue),[s]=eo(re),[a]=eo(ue),[d]=eo(St),[i]=eo(Ke),[l,c]=eo(wt),u=Rd(ao),g=cr(io),b=cr(lo),y=cr(co),v=cr(Dr),p=cr(nn),[m,w]=eo(ro),[h,S]=eo($t),[D,I]=jg(!1),k=qg(null),f=s.find(V=>V.id===n),x=a.find(V=>V.id===r),G=Rd(bt);Kg(()=>{if(!(f&&u))return;let V=f.data.config?.actionType,Ie=f.data.config?.integrationId;if(!(V&&Ie))return;let Qe=ye(V)?.integration||Jg[V];if(!Qe)return;let rt=G.filter(Lt=>Lt.type===Qe);!rt.some(Lt=>Lt.id===Ie)&&rt.length>0&&g({id:f.id,data:{config:{...f.data.config,integrationId:rt[0].id}}})},[f,G,u,g]);let te=Ln((V,Ie)=>{f&&g({id:f.id,data:{config:{...f.data.config,[V]:Ie}}})},[f,g]),O=Ln(V=>{f&&g({id:f.id,data:{label:V}})},[f,g]),W=Ln(V=>{f&&g({id:f.id,data:{description:V}})},[f,g]),$=Ln(()=>{f&&g({id:f.id,data:{enabled:f.data.enabled===!1}})},[f,g]),T=Ln(()=>{t(Ee,{title:"Delete Step",message:"Are you sure you want to delete this node? This action cannot be undone.",confirmLabel:"Delete",confirmVariant:"destructive",onConfirm:()=>{f&&(b(f.id),o())}})},[f,b,o,t]),H=Ln(()=>{f&&(navigator.clipboard.writeText(Sn(f,i)),Mn.success("Code copied to clipboard"))},[f]),X=async()=>{k.current&&(I(!0),await k.current(),I(!1))},z=()=>{t(Ee,{title:"Delete All Runs",message:"Are you sure you want to delete all workflow runs? This action cannot be undone.",confirmLabel:"Delete",confirmVariant:"destructive",onConfirm:async()=>{if(i)try{await U.workflow.deleteExecutions(i),v(),k.current&&await k.current(),Mn.success("All runs deleted")}catch(V){console.error("Failed to delete runs:",V),Mn.error("Failed to delete runs")}}})},j=f&&(f.data.type!=="trigger"||f.data.config?.triggerType!=="Manual")&&f.data.config?.actionType!=="Condition",A=()=>{if(!f)switch(h==="properties"||h==="code"||h==="runs"&&u?h:"properties"){case"properties":return"Workflow";case"code":return"Code";case"runs":return"Runs";default:return"Workflow"}switch(h){case"properties":return"Properties";case"code":return"Code";case"runs":return"Runs";default:return"Properties"}},B=async V=>{if(c(V),i)try{await U.workflow.update(i,{name:V})}catch(Ie){console.error("Failed to update workflow name:",Ie)}},C=()=>{t(Ee,{title:"Clear Workflow",message:"Are you sure you want to clear all nodes and connections? This action cannot be undone.",confirmLabel:"Clear Workflow",confirmVariant:"destructive",destructive:!0,onConfirm:()=>{p()}})},R=()=>{t(Ee,{title:"Delete Workflow",message:`Are you sure you want to delete "${l}"? This will permanently delete the workflow. This cannot be undone.`,confirmLabel:"Delete Workflow",confirmVariant:"destructive",destructive:!0,onConfirm:async()=>{if(i)try{await U.workflow.delete(i),o(),Mn.success("Workflow deleted successfully"),window.location.href="/"}catch(V){console.error("Failed to delete workflow:",V),Mn.error("Failed to delete workflow. Please try again.")}}})},_=(()=>{let Ie=`${l.replace(Yg,"").split(Xg).map((Qe,rt)=>rt===0?Qe.toLowerCase():Qe.charAt(0).toUpperCase()+Qe.slice(1).toLowerCase()).join("")}Workflow`,{code:nt}=vr(s,a,{functionName:Ie});return nt})(),ne=()=>{navigator.clipboard.writeText(_),Mn.success("Code copied to clipboard")},de=()=>{r&&t(Ee,{title:"Delete Connection",message:"Are you sure you want to delete this connection? This action cannot be undone.",confirmLabel:"Delete",confirmVariant:"destructive",onConfirm:()=>{y(r),o()}})};if(x&&!f)return ie("div",{className:"flex h-full max-h-[80vh] flex-col",children:[ee(sn,{overlayId:e,title:"Connection"}),ie("div",{className:"flex-1 space-y-4 overflow-y-auto px-6 pt-4 pb-6",children:[ie("div",{className:"space-y-2",children:[ee(L,{htmlFor:"edge-id",children:"Connection ID"}),ee(ae,{disabled:!0,id:"edge-id",value:x.id})]}),ie("div",{className:"space-y-2",children:[ee(L,{htmlFor:"edge-source",children:"Source"}),ee(ae,{disabled:!0,id:"edge-source",value:x.source})]}),ie("div",{className:"space-y-2",children:[ee(L,{htmlFor:"edge-target",children:"Target"}),ee(ae,{disabled:!0,id:"edge-target",value:x.target})]}),u&&ee("div",{className:"pt-2",children:ie(E,{onClick:de,variant:"ghost",children:[ee(Es,{className:"mr-2 size-4"}),"Delete Connection"]})})]})]});if(!f){let V=h==="properties"||h==="code"||h==="runs"&&u?h:"properties";return ie("div",{className:"flex h-full max-h-[80vh] flex-col",children:[ee(sn,{overlayId:e,title:A()}),ie("div",{className:"flex-1 overflow-y-auto",children:[V==="properties"&&ie("div",{className:"space-y-4 px-6 pt-4 pb-6",children:[ie("div",{className:"space-y-2",children:[ee(L,{htmlFor:"workflow-name",children:"Workflow Name"}),ee(ae,{disabled:!u,id:"workflow-name",onChange:Ie=>B(Ie.target.value),value:l})]}),ie("div",{className:"space-y-2",children:[ee(L,{htmlFor:"workflow-id",children:"Workflow ID"}),ee(ae,{disabled:!0,id:"workflow-id",value:i||"Not saved"})]}),!u&&ee("div",{className:"rounded-lg border border-muted bg-muted/30 p-3",children:ee("p",{className:"text-muted-foreground text-sm",children:"You are viewing a public workflow. Duplicate it to make changes."})}),u&&ie("div",{className:"flex items-center gap-2 pt-2",children:[ie(E,{onClick:C,variant:"ghost",children:[ee(Ps,{className:"mr-2 size-4"}),"Clear"]}),ie(E,{onClick:R,variant:"ghost",children:[ee(Es,{className:"mr-2 size-4"}),"Delete"]})]})]}),V==="code"&&ie("div",{className:"flex flex-col",children:[ie("div",{className:"flex shrink-0 items-center justify-between border-b bg-muted/30 px-3 py-2",children:[ie("div",{className:"flex items-center gap-2",children:[ee(Md,{className:"size-3.5 text-muted-foreground"}),ee("code",{className:"text-muted-foreground text-xs",children:"workflow.ts"})]}),ie(E,{className:"h-7 text-xs",onClick:ne,size:"sm",variant:"ghost",children:[ee(Ld,{className:"mr-1 size-3"}),"Copy"]})]}),ee("div",{className:"h-[400px]",children:ee(xt,{defaultLanguage:"typescript",height:"100%",options:{readOnly:!0,minimap:{enabled:!1},lineNumbers:"on",scrollBeyondLastLine:!1,fontSize:12,wordWrap:"on"},value:_})})]}),V==="runs"&&u&&ie("div",{className:"flex h-full flex-col",children:[ie("div",{className:"flex shrink-0 items-center gap-2 border-b px-4 py-2",children:[ee(E,{className:"text-muted-foreground",disabled:D,onClick:X,size:"icon",variant:"ghost",children:ee(Fd,{className:`size-4 ${D?"animate-spin":""}`})}),ee(E,{className:"text-muted-foreground",onClick:z,size:"icon",variant:"ghost",children:ee(Ps,{className:"size-4"})})]}),ee("div",{className:"flex-1 overflow-y-auto p-4",children:ee(An,{isActive:V==="runs",onRefreshRef:k})})]})]}),ie("div",{className:"flex shrink-0 items-center justify-around border-t bg-background pb-safe",children:[ie("button",{className:`flex flex-1 flex-col items-center gap-1 py-3 font-medium text-xs transition-colors ${V==="properties"?"text-foreground":"text-muted-foreground"}`,onClick:()=>S("properties"),type:"button",children:[ee(zd,{className:"size-5"}),"Workflow"]}),ie("button",{className:`flex flex-1 flex-col items-center gap-1 py-3 font-medium text-xs transition-colors ${V==="code"?"text-foreground":"text-muted-foreground"}`,onClick:()=>S("code"),type:"button",children:[ee(Od,{className:"size-5"}),"Code"]}),u&&ie("button",{className:`flex flex-1 flex-col items-center gap-1 py-3 font-medium text-xs transition-colors ${V==="runs"?"text-foreground":"text-muted-foreground"}`,onClick:()=>S("runs"),type:"button",children:[ee(Wd,{className:"size-5"}),"Runs"]})]})]})}return ie("div",{className:"flex h-full max-h-[80vh] flex-col",children:[ee(sn,{overlayId:e,title:A()}),ie("div",{className:"flex-1 overflow-y-auto",children:[h==="properties"&&ie("div",{className:"space-y-4 px-6 pt-4 pb-6",children:[f.data.type==="action"&&!f.data.config?.actionType&&u&&ee(ta,{disabled:d,isNewlyCreated:f?.id===m,onSelectAction:V=>{te("actionType",V),f?.id===m&&w(null)}}),f.data.type==="trigger"&&ee(oa,{config:f.data.config||{},disabled:d||!u,onUpdateConfig:te,workflowId:i??void 0}),f.data.type==="action"&&f.data.config?.actionType!==void 0&&ee(Yr,{config:f.data.config||{},disabled:d||!u,isOwner:u,onUpdateConfig:te}),(f.data.type!=="action"||f.data.config?.actionType!==void 0)&&ie(Ds,{children:[ie("div",{className:"space-y-2",children:[ee(L,{htmlFor:"label",children:"Label"}),ee(ae,{disabled:d||!u,id:"label",onChange:V=>O(V.target.value),value:f.data.label})]}),ie("div",{className:"space-y-2",children:[ee(L,{htmlFor:"description",children:"Description"}),ee(ae,{disabled:d||!u,id:"description",onChange:V=>W(V.target.value),placeholder:"Optional description",value:f.data.description||""})]})]}),u&&ie("div",{className:"flex items-center gap-2 pt-2",children:[f.data.type==="action"&&ee(E,{className:"text-muted-foreground",onClick:$,size:"sm",variant:"ghost",children:f.data.enabled===!1?ie(Ds,{children:[ee(Ug,{className:"mr-2 size-4"}),"Disabled"]}):ie(Ds,{children:[ee(_g,{className:"mr-2 size-4"}),"Enabled"]})}),ie(E,{className:"text-muted-foreground",onClick:T,size:"sm",variant:"ghost",children:[ee(Es,{className:"mr-2 size-4"}),"Delete"]})]})]}),j&&ie("div",{className:`flex flex-col ${h==="code"?"":"invisible absolute -z-10"}`,children:[ie("div",{className:"flex shrink-0 items-center justify-between border-b bg-muted/30 px-3 py-2",children:[ie("div",{className:"flex items-center gap-2",children:[ee(Md,{className:"size-3.5 text-muted-foreground"}),ee("code",{className:"text-muted-foreground text-xs",children:Qg(f)})]}),ie(E,{className:"text-muted-foreground",onClick:H,size:"sm",variant:"ghost",children:[ee(Ld,{className:"mr-2 size-4"}),"Copy"]})]}),ee("div",{className:"h-[400px]",children:ee(xt,{height:"100%",language:f.data.type==="trigger"&&f.data.config?.triggerType==="Schedule"?"json":"typescript",options:{readOnly:!0,minimap:{enabled:!1},scrollBeyondLastLine:!1,fontSize:13,lineNumbers:"on",folding:!1,wordWrap:"off",padding:{top:16,bottom:16}},value:Sn(f,i)})})]}),h==="runs"&&u&&ie("div",{className:"flex h-full flex-col",children:[ie("div",{className:"flex shrink-0 items-center gap-2 border-b px-4 py-2",children:[ie(E,{className:"text-muted-foreground",disabled:D,onClick:X,size:"sm",variant:"ghost",children:[ee(Fd,{className:`mr-2 size-4 ${D?"animate-spin":""}`}),"Refresh"]}),ie(E,{className:"text-muted-foreground",onClick:z,size:"sm",variant:"ghost",children:[ee(Ps,{className:"mr-2 size-4"}),"Clear All"]})]}),ee("div",{className:"flex-1 overflow-y-auto p-4",children:ee(An,{isActive:h==="runs",onRefreshRef:k})})]})]}),ie("div",{className:"flex shrink-0 items-center justify-around border-t bg-background pb-safe",children:[ie("button",{className:`flex flex-1 flex-col items-center gap-1 py-3 font-medium text-xs transition-colors ${h==="properties"?"text-foreground":"text-muted-foreground"}`,onClick:()=>S("properties"),type:"button",children:[ee(zd,{className:"size-5"}),"Properties"]}),j&&ie("button",{className:`flex flex-1 flex-col items-center gap-1 py-3 font-medium text-xs transition-colors ${h==="code"?"text-foreground":"text-muted-foreground"}`,onClick:()=>S("code"),type:"button",children:[ee(Od,{className:"size-5"}),"Code"]}),u&&ie("button",{className:`flex flex-1 flex-col items-center gap-1 py-3 font-medium text-xs transition-colors ${h==="runs"?"text-foreground":"text-muted-foreground"}`,onClick:()=>S("runs"),type:"button",children:[ee(Wd,{className:"size-5"}),"Runs"]})]})]})}import{Download as ty,FlaskConical as oy}from"lucide-react";import{cva as Zg}from"class-variance-authority";import{jsx as Rs}from"react/jsx-runtime";var ey=Zg("relative w-full rounded-lg border px-4 py-3 text-sm grid has-[>svg]:grid-cols-[calc(var(--spacing)*4)_1fr] grid-cols-[0_1fr] has-[>svg]:gap-x-3 gap-y-0.5 items-start [&>svg]:size-4 [&>svg]:translate-y-0.5 [&>svg]:text-current",{variants:{variant:{default:"bg-card text-card-foreground",destructive:"text-destructive bg-card [&>svg]:text-current *:data-[slot=alert-description]:text-destructive/90"}},defaultVariants:{variant:"default"}});function Bd({className:e,variant:t,...o}){return Rs("div",{"data-slot":"alert",role:"alert",className:N(ey({variant:t}),e),...o})}function Vd({className:e,...t}){return Rs("div",{"data-slot":"alert-title",className:N("col-start-2 line-clamp-1 min-h-4 font-medium tracking-tight",e),...t})}function Hd({className:e,...t}){return Rs("div",{"data-slot":"alert-description",className:N("text-muted-foreground col-start-2 grid justify-items-start gap-1 text-sm [&_p]:leading-relaxed",e),...t})}import{jsx as Wn,jsxs as ma}from"react/jsx-runtime";function Gd({overlayId:e,onExport:t,isDownloading:o}){let{closeAll:n}=oe();return ma(Oe,{actions:[{label:"Cancel",variant:"outline",onClick:n},{label:o?"Exporting...":"Export Project",onClick:()=>{n(),t()},loading:o}],overlayId:e,title:"Export Workflow as Code",children:[ma("div",{className:"flex items-center gap-2 text-muted-foreground",children:[Wn(ty,{className:"size-5"}),Wn("p",{className:"text-sm",children:"Export your workflow as a standalone Next.js project that you can run independently."})]}),Wn("p",{className:"mt-4 text-muted-foreground text-sm",children:"This will generate a complete Next.js project containing your workflow code. Once exported, you can run your workflow outside of the Workflow Builder, deploy it to Vercel, or integrate it into your existing applications."}),ma(Bd,{className:"mt-4",children:[Wn(oy,{className:"size-4"}),Wn(Vd,{children:"Experimental Feature"}),ma(Hd,{className:"block",children:["This feature is experimental and may have limitations. If you encounter any issues, please"," ",Wn("a",{className:"font-medium text-foreground underline underline-offset-4 hover:text-primary",href:"https://github.com/vercel-labs/workflow-builder-template/issues",rel:"noopener noreferrer",target:"_blank",children:"report them on GitHub"}),"."]})]})]})}import{Globe as ny}from"lucide-react";import{jsx as wo,jsxs as pa}from"react/jsx-runtime";function $d({overlayId:e,onConfirm:t}){let{closeAll:o}=oe();return pa(Oe,{actions:[{label:"Cancel",variant:"outline",onClick:o},{label:"Make Public",onClick:()=>{o(),t()}}],overlayId:e,title:"Make Workflow Public?",children:[pa("div",{className:"flex items-center gap-2 text-muted-foreground",children:[wo(ny,{className:"size-5 shrink-0"}),wo("p",{className:"text-sm",children:"Making this workflow public means anyone with the link can:"})]}),pa("ul",{className:"mt-3 list-inside list-disc space-y-1 text-muted-foreground text-sm",children:[wo("li",{children:"View the workflow structure and steps"}),wo("li",{children:"See action types and configurations"}),wo("li",{children:"Duplicate the workflow to their own account"})]}),wo("p",{className:"mt-4 font-medium text-foreground text-sm",children:"The following will remain private:"}),pa("ul",{className:"mt-2 list-inside list-disc space-y-1 text-muted-foreground text-sm",children:[wo("li",{children:"Your integration credentials (API keys, tokens)"}),wo("li",{children:"Execution logs and run history"})]})]})}import{useAtomValue as _d,useSetAtom as ry}from"jotai";import{AlertTriangle as ay}from"lucide-react";import{jsx as et,jsxs as ht}from"react/jsx-runtime";function Ud({overlayId:e,issues:t,onGoToStep:o,onRunAnyway:n}){let{push:r,closeAll:s}=oe(),a=ry(Wt),d=_t(),i=_d(Yt),l=_d(Do),{brokenReferences:c,missingRequiredFields:u,missingIntegrations:g}=t,b=c.length+u.length+g.length,y=(w,h)=>{o(w,h),d?r(ua,{}):s()},v=w=>{r(po,{type:w,onSuccess:()=>{a(h=>h+1)}})},p=w=>{i?.integrationType===w&&l?.enabled&&l?.isVercelUser&&i?r(i.ConsentOverlay,{onConsent:()=>{a(D=>D+1)},onManualEntry:()=>v(w)}):v(w)};return ht(Oe,{actions:[{label:"Run Anyway",variant:"outline",onClick:()=>{s(),n()}},{label:"Cancel",onClick:s}],overlayId:e,title:`Workflow Issues (${b})`,children:[ht("div",{className:"flex items-center gap-2 text-orange-500",children:[et(ay,{className:"size-5"}),et("p",{className:"text-muted-foreground text-sm",children:"This workflow has issues that may cause it to fail."})]}),ht("div",{className:"mt-4 space-y-4",children:[g.length>0&&ht("div",{className:"space-y-1",children:[et("h4",{className:"font-medium text-muted-foreground text-xs uppercase tracking-wide",children:"Missing Connections"}),g.map(w=>ht("div",{className:"flex items-center gap-3 py-1",children:[et(Bt,{className:"size-4 shrink-0",integration:w.integrationType}),ht("p",{className:"min-w-0 flex-1 text-sm",children:[et("span",{className:"font-medium",children:w.integrationLabel}),ht("span",{className:"text-muted-foreground",children:[" \u2014 ",w.nodeNames.length>3?`${w.nodeNames.slice(0,3).join(", ")} +${w.nodeNames.length-3} more`:w.nodeNames.join(", ")]})]}),et(E,{className:"shrink-0",onClick:()=>p(w.integrationType),size:"sm",variant:"outline",children:"Add"})]},w.integrationType))]}),c.length>0&&ht("div",{className:"space-y-2",children:[et("h4",{className:"font-medium text-muted-foreground text-xs uppercase tracking-wide",children:"Broken References"}),c.map(w=>ht("div",{children:[et("p",{className:"font-medium text-sm",children:w.nodeLabel}),et("div",{className:"mt-1 space-y-0.5",children:w.brokenReferences.map((h,S)=>ht("div",{className:"flex items-center gap-3 py-0.5 pl-3",children:[ht("p",{className:"min-w-0 flex-1 text-muted-foreground text-sm",children:[et("span",{className:"font-mono",children:h.displayText})," in ",h.fieldLabel]}),et(E,{className:"shrink-0",onClick:()=>y(w.nodeId,h.fieldKey),size:"sm",variant:"outline",children:"Fix"})]},`${w.nodeId}-${h.fieldKey}-${S}`))})]},w.nodeId))]}),u.length>0&&ht("div",{className:"space-y-2",children:[et("h4",{className:"font-medium text-muted-foreground text-xs uppercase tracking-wide",children:"Missing Required Fields"}),u.map(w=>ht("div",{children:[et("p",{className:"font-medium text-sm",children:w.nodeLabel}),et("div",{className:"mt-1 space-y-0.5",children:w.missingFields.map(h=>ht("div",{className:"flex items-center gap-3 py-0.5 pl-3",children:[et("p",{className:"min-w-0 flex-1 text-muted-foreground text-sm",children:h.fieldLabel}),et(E,{className:"shrink-0",onClick:()=>y(w.nodeId,h.fieldKey),size:"sm",variant:"outline",children:"Fix"})]},`${w.nodeId}-${h.fieldKey}`))})]},w.nodeId))]})]})]})}import{jsx as Os,jsxs as sy}from"react/jsx-runtime";function Kd({className:e}){return sy("svg",{className:e,fill:"none",height:"16",viewBox:"0 0 305 234",width:"16",xmlns:"http://www.w3.org/2000/svg",children:[Os("path",{className:"fill-foreground",d:"M125.776 0C120.929 1.64945e-05 117 3.9291 117 8.77539V61.4248C117 66.2711 120.929 70.2002 125.776 70.2002H160.875L161.253 70.2051C169.032 70.4023 175.301 76.6734 175.495 84.4531L175.5 84.8252V143.325C175.5 148.171 179.429 152.101 184.276 152.101H219.375L219.753 152.105C227.53 152.303 233.798 158.571 233.995 166.348L234 166.726V225.225C234 230.071 237.929 234 242.776 234H295.425C300.271 234 304.2 230.071 304.2 225.225V172.575C304.2 167.729 300.271 163.8 295.425 163.8H260.25C252.334 163.76 245.905 157.43 245.705 149.553L245.7 149.176V90.6758C245.7 85.8295 241.771 81.9004 236.925 81.9004H201.825C193.874 81.9004 187.405 75.5551 187.205 67.6523L187.2 67.2754V8.77539C187.2 3.9291 183.271 1.64951e-05 178.425 0H125.776Z"}),Os("path",{className:"fill-foreground",d:"M67.2755 81.9004C62.4293 81.9004 58.5002 85.8295 58.5002 90.6758V143.325C58.5004 148.171 62.4294 152.101 67.2755 152.101H102.375L102.753 152.105C110.53 152.303 116.798 158.571 116.995 166.348L117 166.726V225.225C117 230.071 120.929 234 125.776 234H178.425C183.271 234 187.2 230.071 187.2 225.225V172.575C187.2 167.729 183.271 163.8 178.425 163.8H143.25C135.334 163.76 128.905 157.43 128.705 149.553L128.7 149.176V90.6758C128.7 85.8295 124.771 81.9004 119.925 81.9004H67.2755Z"}),Os("path",{className:"fill-foreground",d:"M8.77454 163.8C3.92844 163.8 0.00012207 167.729 0.00012207 172.575V225.225C0.00012207 230.071 3.92844 234 8.77454 234H61.4249C66.2712 234 70.2003 230.071 70.2003 225.225V172.575C70.2003 167.729 66.2712 163.8 61.4249 163.8H8.77454Z"})]})}import{Key as Ty,LayoutDashboard as Sy,LogOut as Ay,Moon as Iy,Plug as Py,Settings as Ey,Sun as Dy}from"lucide-react";import{useTheme as Ry}from"next-themes";import sc from"next/link";import{useEffect as ic,useState as lc}from"react";import{Copy as iy,Key as ly,Trash2 as dy}from"lucide-react";import{useCallback as cy,useEffect as uy,useState as Fn}from"react";import{toast as zn}from"sonner";import{jsx as Ge,jsxs as Rt}from"react/jsx-runtime";function my({overlayId:e,onCreated:t}){let{pop:o}=oe(),[n,r]=Fn(""),[s,a]=Fn(!1);return Rt(Oe,{actions:[{label:"Create",onClick:async()=>{a(!0);try{let i=await fetch("/api/api-keys",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:n||null})});if(!i.ok){let c=await i.json();throw new Error(c.error||"Failed to create API key")}let l=await i.json();t(l),zn.success("API key created successfully"),o()}catch(i){console.error("Failed to create API key:",i),zn.error(i instanceof Error?i.message:"Failed to create API key")}finally{a(!1)}},loading:s}],overlayId:e,title:"Create API Key",children:[Ge("p",{className:"mb-4 text-muted-foreground text-sm",children:"Create a new API key for webhook authentication"}),Rt("div",{className:"space-y-2",children:[Ge(L,{htmlFor:"key-name",children:"Label (optional)"}),Ge(ae,{id:"key-name",onChange:i=>r(i.target.value),placeholder:"e.g., Production, Testing",value:n})]})]})}function qd({overlayId:e}){let{push:t,closeAll:o}=oe(),[n,r]=Fn(!0),[s,a]=Fn([]),[d,i]=Fn(null),[l,c]=Fn(null),u=cy(async()=>{r(!0);try{let m=await fetch("/api/api-keys");if(!m.ok)throw new Error("Failed to load API keys");let w=await m.json();a(w)}catch(m){console.error("Failed to load API keys:",m),zn.error("Failed to load API keys")}finally{r(!1)}},[]);uy(()=>{u()},[u]);let g=m=>{i(m.key??null),a(w=>[m,...w])},b=async m=>{c(m);try{if(!(await fetch(`/api/api-keys/${m}`,{method:"DELETE"})).ok)throw new Error("Failed to delete API key");a(h=>h.filter(S=>S.id!==m)),zn.success("API key deleted")}catch(w){console.error("Failed to delete API key:",w),zn.error("Failed to delete API key")}finally{c(null)}},y=m=>{t(Ee,{title:"Delete API Key",message:"Are you sure you want to delete this API key? Any webhooks using this key will stop working immediately.",confirmLabel:"Delete",confirmVariant:"destructive",destructive:!0,onConfirm:()=>b(m)})},v=m=>{navigator.clipboard.writeText(m),zn.success("Copied to clipboard")},p=m=>new Date(m).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"});return Rt(Oe,{actions:[{label:"New API Key",variant:"outline",onClick:()=>t(my,{onCreated:g})},{label:"Done",onClick:o}],overlayId:e,title:"API Keys",children:[Ge("p",{className:"-mt-2 mb-4 text-muted-foreground text-sm",children:"Manage API keys for webhook authentication"}),n?Ge("div",{className:"flex items-center justify-center py-8",children:Ge(pt,{})}):Rt("div",{className:"space-y-4",children:[d&&Rt("div",{className:"rounded-md border border-yellow-500/50 bg-yellow-500/10 p-3",children:[Ge("p",{className:"mb-2 font-medium text-sm text-yellow-600 dark:text-yellow-400",children:"Copy your API key now. You won't be able to see it again!"}),Rt("div",{className:"flex items-center gap-2",children:[Ge("code",{className:"flex-1 rounded bg-muted px-2 py-1 font-mono text-xs",children:d}),Ge(E,{onClick:()=>v(d),size:"sm",variant:"outline",children:Ge(iy,{className:"size-4"})})]}),Ge(E,{className:"mt-2",onClick:()=>i(null),size:"sm",variant:"ghost",children:"Dismiss"})]}),s.length===0?Rt("div",{className:"py-8 text-center text-muted-foreground text-sm",children:[Ge(ly,{className:"mx-auto mb-2 size-8 opacity-50"}),Ge("p",{children:"No API keys yet"}),Ge("p",{className:"text-xs",children:"Create an API key to authenticate webhook requests"})]}):Ge("div",{className:"space-y-2",children:s.map(m=>Rt("div",{className:"flex items-center justify-between rounded-md border p-3",children:[Rt("div",{className:"min-w-0 flex-1",children:[Rt("div",{className:"flex items-center gap-2",children:[Rt("code",{className:"rounded bg-muted px-1.5 py-0.5 font-mono text-xs",children:[m.keyPrefix,"..."]}),m.name&&Ge("span",{className:"truncate text-sm",children:m.name})]}),Rt("p",{className:"mt-1 text-muted-foreground text-xs",children:["Created ",p(m.createdAt),m.lastUsedAt&&` \xB7 Last used ${p(m.lastUsedAt)}`]})]}),Ge(E,{disabled:l===m.id,onClick:()=>y(m.id),size:"sm",variant:"ghost",children:l===m.id?Ge(pt,{className:"size-4"}):Ge(dy,{className:"size-4 text-destructive"})})]},m.id))})]})]})}import{useSetAtom as by}from"jotai";import{Search as wy}from"lucide-react";import{useCallback as Ws,useEffect as xy,useRef as Ny,useState as Jd}from"react";import{Pencil as py,Trash2 as fy}from"lucide-react";import{useCallback as gy,useEffect as yy,useMemo as vy,useState as Ls}from"react";import{toast as fa}from"sonner";import{jsx as _e,jsxs as Ms}from"react/jsx-runtime";var hy={database:"Database"};function jd({onIntegrationChange:e,filter:t=""}){let{push:o}=oe(),[n,r]=Ls([]),[s,a]=Ls(!0),[d,i]=Ls(null),l=gy(async()=>{try{a(!0);let v=await U.integration.getAll();r(v)}catch(v){console.error("Failed to load integrations:",v),fa.error("Failed to load integrations")}finally{a(!1)}},[]);yy(()=>{l()},[l]);let c=vy(()=>{let v=no(),p=t.toLowerCase();return n.map(m=>({...m,label:v[m.type]||hy[m.type]||m.type})).filter(m=>t?m.label.toLowerCase().includes(p)||m.name.toLowerCase().includes(p)||m.type.toLowerCase().includes(p):!0).sort((m,w)=>{let h=m.label.localeCompare(w.label);return h!==0?h:m.name.localeCompare(w.name)})},[n,t]),u=v=>{o(qr,{integration:v,onSuccess:()=>{l(),e?.()},onDelete:()=>{l(),e?.()}})},g=v=>{o(Qa,{integration:v,onSuccess:()=>{l(),e?.()}})},b=async v=>{try{i(v);let p=await U.integration.testConnection(v);p.status==="success"?fa.success(p.message||"Connection successful"):fa.error(p.message||"Connection test failed")}catch(p){console.error("Connection test failed:",p),fa.error(p instanceof Error?p.message:"Connection test failed")}finally{i(null)}};return s?_e("div",{className:"flex items-center justify-center py-8",children:_e(pt,{})}):_e("div",{className:"space-y-1",children:n.length===0?_e("div",{className:"py-8 text-center",children:_e("p",{className:"text-muted-foreground text-sm",children:"No connections configured yet"})}):c.length===0?_e("div",{className:"py-8 text-center",children:_e("p",{className:"text-muted-foreground text-sm",children:"No connections match your filter"})}):_e("div",{className:"space-y-1",children:c.map(v=>Ms("div",{className:"flex items-center justify-between rounded-md px-2 py-1.5",children:[Ms("div",{className:"flex items-center gap-2",children:[_e(Bt,{className:"size-4",integration:v.type==="ai-gateway"?"vercel":v.type}),_e("span",{className:"font-medium text-sm",children:v.label}),_e("span",{className:"text-muted-foreground text-sm",children:v.name})]}),Ms("div",{className:"flex items-center gap-1",children:[_e(E,{className:"h-7 px-2",disabled:d===v.id,onClick:()=>b(v.id),size:"sm",variant:"outline",children:d===v.id?_e(pt,{className:"size-3"}):_e("span",{className:"text-xs",children:"Test"})}),_e(E,{className:"size-7",onClick:()=>u(v),size:"icon",variant:"outline",children:_e(py,{className:"size-3"})}),_e(E,{className:"size-7",onClick:()=>g(v),size:"icon",variant:"outline",children:_e(fy,{className:"size-3"})})]})]},v.id))})})}import{jsx as $o,jsxs as Fs}from"react/jsx-runtime";function Yd({overlayId:e}){let{push:t,closeAll:o}=oe(),[n,r]=Jd(!0),[s,a]=Jd(""),d=by(Wt),i=Ny(!1),l=Ws(async()=>{r(!0);try{await new Promise(b=>setTimeout(b,0))}finally{r(!1)}},[]);xy(()=>{l(),i.current=!1,a("")},[l]);let c=Ws(()=>{i.current&&d(b=>b+1),o()},[o,d]),u=Ws(()=>{i.current=!0},[]);return Fs(Oe,{actions:[{label:"Add Connection",variant:"outline",onClick:()=>{t(ll,{onSuccess:u})}},{label:"Done",onClick:c}],overlayId:e,title:"Connections",children:[$o("p",{className:"-mt-2 mb-4 text-muted-foreground text-sm",children:"Manage API keys and credentials used by your workflows"}),n?$o("div",{className:"flex items-center justify-center py-8",children:$o(pt,{})}):Fs("div",{className:"space-y-4",children:[Fs("div",{className:"relative",children:[$o(wy,{className:"absolute top-1/2 left-3 size-4 -translate-y-1/2 text-muted-foreground"}),$o(ae,{className:"pl-9",onChange:b=>a(b.target.value),placeholder:"Filter connections...",value:s})]}),$o("div",{className:"max-h-[300px] overflow-y-auto",children:$o(jd,{filter:s,onIntegrationChange:u})})]})]})}import{useCallback as ec,useEffect as ky,useState as va}from"react";import{toast as tc}from"sonner";import{jsx as ya}from"react/jsx-runtime";function ga({className:e,...t}){return ya("div",{"data-slot":"card",className:N("text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-sm",e),...t})}function Xd({className:e,...t}){return ya("div",{"data-slot":"card-title",className:N("leading-none font-semibold",e),...t})}function Qd({className:e,...t}){return ya("div",{"data-slot":"card-description",className:N("text-muted-foreground text-sm",e),...t})}function zs({className:e,...t}){return ya("div",{"data-slot":"card-content",className:N("px-6",e),...t})}import{jsx as ur,jsxs as Bs}from"react/jsx-runtime";function Zd({accountName:e,accountEmail:t,onNameChange:o,onEmailChange:n}){return ur(ga,{className:"border-0 py-0 shadow-none",children:Bs(zs,{className:"space-y-4 p-0",children:[Bs("div",{className:"space-y-2",children:[ur(L,{className:"ml-1",htmlFor:"accountName",children:"Name"}),ur(ae,{id:"accountName",onChange:r=>o(r.target.value),placeholder:"Your name",value:e})]}),Bs("div",{className:"space-y-2",children:[ur(L,{className:"ml-1",htmlFor:"accountEmail",children:"Email"}),ur(ae,{id:"accountEmail",onChange:r=>n(r.target.value),placeholder:"your.email@example.com",type:"email",value:t})]})]})})}import{jsx as ha,jsxs as Cy}from"react/jsx-runtime";function oc({overlayId:e}){let{closeAll:t}=oe(),[o,n]=va(!0),[r,s]=va(!1),[a,d]=va(""),[i,l]=va(""),c=ec(async()=>{try{let b=await U.user.get();d(b.name||""),l(b.email||"")}catch(b){console.error("Failed to load account:",b)}},[]),u=ec(async()=>{n(!0);try{await c()}finally{n(!1)}},[c]);return ky(()=>{u()},[u]),Cy(Oe,{actions:[{label:"Cancel",variant:"outline",onClick:t},{label:"Save",onClick:async()=>{try{s(!0),await U.user.update({name:a,email:i}),await c(),tc.success("Settings saved"),t()}catch(b){console.error("Failed to save account:",b),tc.error("Failed to save settings")}finally{s(!1)}},loading:r,disabled:o}],overlayId:e,title:"Settings",children:[ha("p",{className:"-mt-2 mb-4 text-muted-foreground text-sm",children:"Update your personal information"}),o?ha("div",{className:"flex items-center justify-center py-8",children:ha(pt,{})}):ha(Zd,{accountEmail:i,accountName:a,onEmailChange:l,onNameChange:d})]})}import{Avatar as Vs}from"radix-ui";import{jsx as Hs}from"react/jsx-runtime";function nc({className:e,...t}){return Hs(Vs.Root,{"data-slot":"avatar",className:N("relative flex size-8 shrink-0 overflow-hidden rounded-full",e),...t})}function rc({className:e,...t}){return Hs(Vs.Image,{"data-slot":"avatar-image",className:N("aspect-square size-full",e),...t})}function ac({className:e,...t}){return Hs(Vs.Fallback,{"data-slot":"avatar-fallback",className:N("bg-muted flex size-full items-center justify-center rounded-full",e),...t})}import{jsx as Ne,jsxs as Ot}from"react/jsx-runtime";var dc=()=>{let{data:e,isPending:t}=Pn(),{theme:o,setTheme:n}=Ry(),{open:r}=oe(),[s,a]=lc(null),[d,i]=lc(!1);ic(()=>{i(!0)},[]),ic(()=>{e?.user&&!e.user.name?.startsWith("Anonymous")&&U.user.get().then(b=>a(b.providerId)).catch(()=>a(null))},[e?.user]);let l=async()=>{await Zl()},c=s==="vercel"||s==="github"||s==="google",u=()=>e?.user?.name?e.user.name.split(" ").map(b=>b[0]).join("").toUpperCase().slice(0,2):e?.user?.email?e.user.email.slice(0,2).toUpperCase():"U";return t||!d?Ne("div",{className:"h-9 w-9"}):!e?.user||e.user.name==="Anonymous"||e.user.email?.startsWith("temp-")?Ne("div",{className:"flex items-center gap-2",children:Ne(E,{className:"h-9 disabled:opacity-100 disabled:[&>*]:text-muted-foreground",size:"sm",variant:"default",asChild:!0,children:Ne(sc,{href:"/auth/sign-in",children:"Sign In"})})}):Ot(Lo,{children:[Ne(Mo,{asChild:!0,children:Ne(E,{className:"relative h-9 w-9 rounded-full border p-0",variant:"ghost",children:Ot(nc,{className:"h-9 w-9",children:[Ne(rc,{alt:e?.user?.name||"",src:e?.user?.image||""}),Ne(ac,{children:u()})]})})}),Ot(Wo,{align:"end",className:"w-56",children:[Ne(Il,{children:Ot("div",{className:"flex flex-col space-y-1",children:[Ne("p",{className:"font-medium text-sm leading-none",children:e?.user?.name||"User"}),Ne("p",{className:"text-muted-foreground text-xs leading-none",children:e?.user?.email})]})}),Ne(er,{}),Ne(vt,{asChild:!0,children:Ot(sc,{href:"/dashboard",children:[Ne(Sy,{className:"size-4"}),Ne("span",{children:"Dashboard"})]})}),!c&&Ot(vt,{onClick:()=>r(oc),children:[Ne(Ey,{className:"size-4"}),Ne("span",{children:"Settings"})]}),Ot(vt,{onClick:()=>r(Yd),children:[Ne(Py,{className:"size-4"}),Ne("span",{children:"Connections"})]}),Ot(vt,{onClick:()=>r(qd),children:[Ne(Ty,{className:"size-4"}),Ne("span",{children:"API Keys"})]}),Ot(Pl,{children:[Ot(El,{children:[Ne(Dy,{className:"size-4 rotate-0 scale-100 transition-all dark:-rotate-90 dark:scale-0"}),Ne(Iy,{className:"absolute size-4 rotate-90 scale-0 transition-all dark:rotate-0 dark:scale-100"}),Ne("span",{children:"Theme"})]}),Ne(Dl,{children:Ot(Al,{onValueChange:n,value:o,children:[Ne(ea,{value:"light",children:"Light"}),Ne(ea,{value:"dark",children:"Dark"}),Ne(ea,{value:"system",children:"System"})]})})]}),Ne(er,{}),Ot(vt,{onClick:l,children:[Ne(Ay,{className:"size-4"}),Ne("span",{children:"Logout"})]})]})]})};import{Fragment as wa,jsx as J,jsxs as Re}from"react/jsx-runtime";function yc(e,t,o){for(let n of e)t({id:n.id,data:{status:o}})}var _y={"Database Query":"database"},Uy={database:"Database"};function Ky(e){if(typeof e!="string")return[];let t=/\{\{@([^:]+):([^}]+)\}\}/g,o=e.matchAll(t);return Array.from(o).map(n=>({nodeId:n[1],displayText:n[2]}))}function bc(e,t=""){let o=[];for(let[n,r]of Object.entries(e)){let s=t?`${t}.${n}`:n;if(typeof r=="string"){let a=Ky(r);for(let d of a)o.push({field:s,...d})}else typeof r=="object"&&r!==null&&!Array.isArray(r)&&o.push(...bc(r,s))}return o}function qy(e){let t=new Set(e.map(n=>n.id)),o=[];for(let n of e){if(n.data.enabled===!1)continue;let r=n.data.config;if(!r||typeof r!="object")continue;let a=bc(r).filter(d=>!t.has(d.nodeId));if(a.length>0){let d=r.actionType,i=d?ye(d):void 0,l=i?Ea(i.configFields):[];o.push({nodeId:n.id,nodeLabel:n.data.label||i?.label||"Unnamed Step",brokenReferences:a.map(c=>{let u=l.find(g=>g.key===c.field);return{fieldKey:c.field,fieldLabel:u?.label||c.field,referencedNodeId:c.nodeId,displayText:c.displayText}})})}}return o}function jy(e){return e==null||typeof e=="string"&&e.trim()===""}function Jy(e,t){return e.showWhen?t[e.showWhen.field]===e.showWhen.equals:!0}function Yy(e){if(e.data.enabled===!1)return null;let t=e.data.config,o=t?.actionType;if(!o)return null;let n=ye(o);if(!n)return null;let s=Ea(n.configFields).filter(a=>a.required&&Jy(a,t||{})&&jy(t?.[a.key])).map(a=>({fieldKey:a.key,fieldLabel:a.label}));return s.length===0?null:{nodeId:e.id,nodeLabel:e.data.label||n.label||"Unnamed Step",missingFields:s}}function Xy(e){return e.map(Yy).filter(t=>t!==null)}function Qy(e,t){let o=new Set(t.map(a=>a.type)),n=new Set(t.map(a=>a.id)),r=new Map,s=no();for(let a of e){if(a.data.enabled===!1)continue;let d=a.data.config?.actionType;if(!d)continue;let l=ye(d)?.integration||_y[d];if(!l||!Jo(l))continue;let c=a.data.config?.integrationId;if(!(c&&n.has(c))&&!o.has(l)){let g=r.get(l)||[],b=ye(d);g.push(a.data.label||b?.label||d),r.set(l,g)}}return Array.from(r.entries()).map(([a,d])=>({integrationType:a,integrationLabel:s[a]||Uy[a]||a,nodeNames:d}))}async function Zy({workflowId:e,nodes:t,updateNodeData:o,pollingIntervalRef:n,setIsExecuting:r,setSelectedExecutionId:s}){yc(t,o,"idle");for(let a of t)a.data.type==="trigger"&&o({id:a.id,data:{status:"running"}});try{let a=await fetch(`/api/workflow/${e}/execute`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({input:{}})});if(!a.ok)throw new Error("Failed to execute workflow");let d=await a.json();s(d.executionId);let i=setInterval(async()=>{try{let l=await U.workflow.getExecutionStatus(d.executionId);for(let c of l.nodeStatuses)o({id:c.nodeId,data:{status:c.status}});l.status!=="running"&&(n.current&&(clearInterval(n.current),n.current=null),r(!1))}catch(l){console.error("Failed to poll execution status:",l)}},500);n.current=i}catch(a){console.error("Failed to execute workflow:",a),ut.error(a instanceof Error?a.message:"Failed to execute workflow"),yc(t,o,"error"),r(!1)}}function ev({currentWorkflowId:e,nodes:t,edges:o,updateNodeData:n,isExecuting:r,setIsExecuting:s,setIsSaving:a,setHasUnsavedChanges:d,setActiveTab:i,setNodes:l,setEdges:c,setSelectedNodeId:u,setSelectedExecutionId:g,userIntegrations:b}){let{open:y}=oe(),v=$y(null);$s(()=>()=>{v.current&&clearInterval(v.current)},[]);let p=async()=>{if(e){a(!0);try{await U.workflow.update(e,{nodes:t,edges:o}),d(!1)}catch(S){console.error("Failed to save workflow:",S),ut.error("Failed to save workflow. Please try again.")}finally{a(!1)}}},m=async()=>{if(!e){ut.error("Please save the workflow before executing");return}i("runs"),l(t.map(S=>({...S,selected:!1}))),c(o.map(S=>({...S,selected:!1}))),u(null),s(!0),await Zy({workflowId:e,nodes:t,updateNodeData:n,pollingIntervalRef:v,setIsExecuting:s,setSelectedExecutionId:g})},w=(S,D)=>{u(S),i("properties"),D&&setTimeout(()=>{let I=document.getElementById(D);I&&(I.focus(),I.scrollIntoView({behavior:"smooth",block:"center"}))},100)};return{handleSave:p,handleExecute:async()=>{if(r)return;let S=qy(t),D=Xy(t),I=Qy(t,b);if(S.length>0||D.length>0||I.length>0){y(Ud,{issues:{brokenReferences:S,missingRequiredFields:D,missingIntegrations:I},onGoToStep:w,onRunAnyway:m});return}await m()}}}function tv(){let[e,t]=tt(re),[o,n]=tt(ue),[r,s]=tt(fi),[a]=tt(St),d=Jt(nn),i=Jt(io),[l]=tt(Ke),[c,u]=tt(wt),[g,b]=tt(Nr),y=cc(ao),v=Gy(),[p,m]=tt(Er),[w,h]=tt(st),S=Jt(xi),D=Jt(Ni),I=Jt(on),[k]=tt(ki),[f]=tt(Ci),{data:x}=Pn(),G=Jt($t),te=Jt(Te),O=Jt(so),W=cc(bt),[$,T]=tt(Pr),[H,X]=Gs(!1),[z,j]=Gs(!1),[A,B]=Gs([]);return $s(()=>{(async()=>{try{let R=await U.workflow.getAll();B(R)}catch(R){console.error("Failed to load workflows:",R)}})()},[]),{nodes:e,edges:o,isExecuting:r,setIsExecuting:s,isGenerating:a,clearWorkflow:d,updateNodeData:i,currentWorkflowId:l,workflowName:c,setCurrentWorkflowName:u,workflowVisibility:g,setWorkflowVisibility:b,isOwner:y,router:v,isSaving:p,setIsSaving:m,hasUnsavedChanges:w,setHasUnsavedChanges:h,undo:S,redo:D,addNode:I,canUndo:k,canRedo:f,session:x,isDownloading:H,setIsDownloading:X,isDuplicating:z,setIsDuplicating:j,allWorkflows:A,setAllWorkflows:B,setActiveTab:G,setNodes:t,setEdges:n,setSelectedNodeId:te,setSelectedExecutionId:O,userIntegrations:W,triggerExecute:$,setTriggerExecute:T}}function ov(e){let{open:t}=oe(),{currentWorkflowId:o,workflowName:n,nodes:r,edges:s,updateNodeData:a,isExecuting:d,setIsExecuting:i,setIsSaving:l,setHasUnsavedChanges:c,clearWorkflow:u,setWorkflowVisibility:g,setAllWorkflows:b,setIsDownloading:y,setIsDuplicating:v,setActiveTab:p,setNodes:m,setEdges:w,setSelectedNodeId:h,setSelectedExecutionId:S,userIntegrations:D,triggerExecute:I,setTriggerExecute:k,router:f,session:x}=e,{handleSave:G,handleExecute:te}=ev({currentWorkflowId:o,nodes:r,edges:s,updateNodeData:a,isExecuting:d,setIsExecuting:i,setIsSaving:l,setHasUnsavedChanges:c,setActiveTab:p,setNodes:m,setEdges:w,setSelectedNodeId:h,setSelectedExecutionId:S,userIntegrations:D});return $s(()=>{I&&(k(!1),te())},[I,k,te]),{handleSave:G,handleExecute:te,handleClearWorkflow:()=>{t(Ee,{title:"Clear Workflow",message:"Are you sure you want to clear all nodes and connections? This action cannot be undone.",confirmLabel:"Clear Workflow",confirmVariant:"destructive",destructive:!0,onConfirm:()=>{u()}})},handleDeleteWorkflow:()=>{t(Ee,{title:"Delete Workflow",message:`Are you sure you want to delete "${n}"? This will permanently delete the workflow. This cannot be undone.`,confirmLabel:"Delete Workflow",confirmVariant:"destructive",destructive:!0,onConfirm:async()=>{if(o)try{await U.workflow.delete(o),ut.success("Workflow deleted successfully"),window.location.href="/"}catch(z){console.error("Failed to delete workflow:",z),ut.error("Failed to delete workflow. Please try again.")}}})},handleDownload:async()=>{if(!o){ut.error("Please save the workflow before downloading");return}y(!0),ut.info("Preparing workflow files for download...");try{let z=await U.workflow.download(o);if(!z.success)throw new Error(z.error||"Failed to prepare download");if(!z.files)throw new Error("No files to download");let j=(await import("jszip")).default,A=new j;for(let[_,ne]of Object.entries(z.files))A.file(_,ne);let B=await A.generateAsync({type:"blob"}),C=URL.createObjectURL(B),R=document.createElement("a");R.href=C,R.download=`${n.toLowerCase().replace(/[^a-z0-9]/g,"-")}-workflow.zip`,document.body.appendChild(R),R.click(),document.body.removeChild(R),URL.revokeObjectURL(C),ut.success("Workflow downloaded successfully!")}catch(z){ut.error(z instanceof Error?z.message:"Failed to download workflow")}finally{y(!1)}},loadWorkflows:async()=>{try{let z=await U.workflow.getAll();b(z)}catch(z){console.error("Failed to load workflows:",z)}},handleToggleVisibility:async z=>{if(o){if(z==="public"){t($d,{onConfirm:async()=>{try{await U.workflow.update(o,{visibility:"public"}),g("public"),ut.success("Workflow is now public")}catch(j){console.error("Failed to update visibility:",j),ut.error("Failed to update visibility. Please try again.")}}});return}try{await U.workflow.update(o,{visibility:z}),g(z),ut.success("Workflow is now private")}catch(j){console.error("Failed to update visibility:",j),ut.error("Failed to update visibility. Please try again.")}}},handleDuplicate:async()=>{if(o){v(!0);try{x?.user||(await Vo.signIn.anonymous(),await new Promise(j=>setTimeout(j,100)));let z=await U.workflow.duplicate(o);ut.success("Workflow duplicated successfully"),f.push(`/workflows/${z.id}`)}catch(z){console.error("Failed to duplicate workflow:",z),ut.error("Failed to duplicate workflow. Please try again.")}finally{v(!1)}}}}}function nv({workflowId:e,state:t,actions:o}){let{open:n,push:r}=oe(),[s]=tt(Te),[a]=tt(Ue),[d]=tt(re),[i]=tt(ue),l=Jt(lo),c=Jt(co),{screenToFlowPosition:u}=Oy(),g=d.find(m=>m.id===s),b=i.find(m=>m.id===a),y=g||b;if(e&&!t.isOwner||!e)return null;let v=()=>{let w=!!s?"Node":"Connection";r(Ee,{title:`Delete ${w}`,message:`Are you sure you want to delete this ${w.toLowerCase()}? This action cannot be undone.`,confirmLabel:"Delete",confirmVariant:"destructive",onConfirm:()=>{s?l(s):a&&c(a)}})},p=()=>{let m=document.querySelector(".react-flow");if(!m)return;let w=m.getBoundingClientRect(),h=w.left+w.width/2,S=w.top+w.height/2,D=u({x:h,y:S}),I=192,k=192;D.x-=I/2,D.y-=k/2;let f=20,x=20,G={...D},te=!0,O=0,W=20;for(;te&&O<W;)te=t.nodes.some(T=>{let H=Math.abs(T.position.x-G.x),X=Math.abs(T.position.y-G.y);return H<x&&X<x}),te&&(G.x+=f,G.y+=f,O+=1);let $={id:Hy(),type:"action",position:G,data:{label:"",description:"",type:"action",config:{},status:"idle"}};t.addNode($),t.setSelectedNodeId($.id),t.setActiveTab("properties")};return Re(wa,{children:[J(jt,{className:"flex lg:hidden",orientation:"vertical",children:J(E,{className:"border hover:bg-black/5 disabled:opacity-100 dark:hover:bg-white/5 disabled:[&>svg]:text-muted-foreground",disabled:t.isGenerating,onClick:p,size:"icon",title:"Add Step",variant:"secondary",children:J(pc,{className:"size-4"})})}),Re(jt,{className:"flex lg:hidden",orientation:"vertical",children:[J(E,{className:"border hover:bg-black/5 dark:hover:bg-white/5",onClick:()=>n(ua,{}),size:"icon",title:"Configuration",variant:"secondary",children:J(By,{className:"size-4"})}),y&&J(E,{className:"border hover:bg-black/5 dark:hover:bg-white/5",onClick:v,size:"icon",title:"Delete",variant:"secondary",children:J(Vy,{className:"size-4"})})]}),J(jt,{className:"hidden lg:flex",orientation:"horizontal",children:J(E,{className:"border hover:bg-black/5 disabled:opacity-100 dark:hover:bg-white/5 disabled:[&>svg]:text-muted-foreground",disabled:t.isGenerating,onClick:p,size:"icon",title:"Add Step",variant:"secondary",children:J(pc,{className:"size-4"})})}),Re(jt,{className:"flex lg:hidden",orientation:"vertical",children:[J(E,{className:"border hover:bg-black/5 disabled:opacity-100 dark:hover:bg-white/5 disabled:[&>svg]:text-muted-foreground",disabled:!t.canUndo||t.isGenerating,onClick:()=>t.undo(),size:"icon",title:"Undo",variant:"secondary",children:J(gc,{className:"size-4"})}),J(E,{className:"border hover:bg-black/5 disabled:opacity-100 dark:hover:bg-white/5 disabled:[&>svg]:text-muted-foreground",disabled:!t.canRedo||t.isGenerating,onClick:()=>t.redo(),size:"icon",title:"Redo",variant:"secondary",children:J(fc,{className:"size-4"})})]}),Re(jt,{className:"hidden lg:flex",orientation:"horizontal",children:[J(E,{className:"border hover:bg-black/5 disabled:opacity-100 dark:hover:bg-white/5 disabled:[&>svg]:text-muted-foreground",disabled:!t.canUndo||t.isGenerating,onClick:()=>t.undo(),size:"icon",title:"Undo",variant:"secondary",children:J(gc,{className:"size-4"})}),J(E,{className:"border hover:bg-black/5 disabled:opacity-100 dark:hover:bg-white/5 disabled:[&>svg]:text-muted-foreground",disabled:!t.canRedo||t.isGenerating,onClick:()=>t.redo(),size:"icon",title:"Redo",variant:"secondary",children:J(fc,{className:"size-4"})})]}),Re(jt,{className:"flex lg:hidden",orientation:"vertical",children:[J(vc,{handleSave:o.handleSave,state:t}),J(hc,{actions:o,state:t})]}),Re(jt,{className:"hidden lg:flex",orientation:"horizontal",children:[J(vc,{handleSave:o.handleSave,state:t}),J(hc,{actions:o,state:t})]}),J(rv,{actions:o,state:t}),J(av,{actions:o,state:t})]})}function vc({state:e,handleSave:t}){return Re(E,{className:"relative border hover:bg-black/5 disabled:opacity-100 dark:hover:bg-white/5 disabled:[&>svg]:text-muted-foreground",disabled:!e.currentWorkflowId||e.isGenerating||e.isSaving,onClick:t,size:"icon",title:e.isSaving?"Saving...":"Save workflow",variant:"secondary",children:[e.isSaving?J(xa,{className:"size-4 animate-spin"}):J(zy,{className:"size-4"}),e.hasUnsavedChanges&&!e.isSaving&&J("div",{className:"absolute top-1.5 right-1.5 size-2 rounded-full bg-primary"})]})}function hc({state:e,actions:t}){let{open:o}=oe(),n=()=>{o(Gd,{onExport:t.handleDownload,isDownloading:e.isDownloading})};return J(E,{className:"border hover:bg-black/5 disabled:opacity-100 dark:hover:bg-white/5 disabled:[&>svg]:text-muted-foreground",disabled:e.isDownloading||e.nodes.length===0||e.isGenerating||!e.currentWorkflowId,onClick:n,size:"icon",title:e.isDownloading?"Preparing download...":"Export workflow as code",variant:"secondary",children:e.isDownloading?J(xa,{className:"size-4 animate-spin"}):J(Wy,{className:"size-4"})})}function rv({state:e,actions:t}){let o=e.workflowVisibility==="public";return Re(Lo,{children:[J(Mo,{asChild:!0,children:J(E,{className:"border hover:bg-black/5 dark:hover:bg-white/5",disabled:!e.currentWorkflowId||e.isGenerating,size:"icon",title:o?"Public workflow":"Private workflow",variant:"secondary",children:o?J(uc,{className:"size-4"}):J(mc,{className:"size-4"})})}),Re(Wo,{align:"end",children:[Re(vt,{className:"flex items-center gap-2",onClick:()=>t.handleToggleVisibility("private"),children:[J(mc,{className:"size-4"}),"Private",!o&&J(ba,{className:"ml-auto size-4"})]}),Re(vt,{className:"flex items-center gap-2",onClick:()=>t.handleToggleVisibility("public"),children:[J(uc,{className:"size-4"}),"Public",o&&J(ba,{className:"ml-auto size-4"})]})]})]})}function av({state:e,actions:t}){return J(E,{className:"border hover:bg-black/5 disabled:opacity-100 dark:hover:bg-white/5 disabled:[&>svg]:text-muted-foreground",disabled:e.isExecuting||e.nodes.length===0||e.isGenerating,onClick:()=>t.handleExecute(),size:"icon",title:"Run Workflow",variant:"secondary",children:e.isExecuting?J(xa,{className:"size-4 animate-spin"}):J(Fy,{className:"size-4"})})}function sv({isDuplicating:e,onDuplicate:t}){return Re(E,{className:"h-9 border hover:bg-black/5 dark:hover:bg-white/5",disabled:e,onClick:t,size:"sm",title:"Duplicate to your workflows",variant:"secondary",children:[e?J(xa,{className:"mr-2 size-4 animate-spin"}):J(My,{className:"mr-2 size-4"}),"Duplicate"]})}function iv({workflowId:e,state:t,actions:o}){return Re("div",{className:"flex flex-col gap-1",children:[J("div",{className:"flex h-9 max-w-[160px] items-center overflow-hidden rounded-md border bg-secondary text-secondary-foreground sm:max-w-none",children:Re(Lo,{onOpenChange:n=>n&&o.loadWorkflows(),children:[Re(Mo,{className:"flex h-full cursor-pointer items-center gap-2 px-3 font-medium text-sm transition-all hover:bg-black/5 dark:hover:bg-white/5",children:[J(Kd,{className:"size-4 shrink-0"}),J("p",{className:"truncate font-medium text-sm",children:e?t.workflowName:Re(wa,{children:[J("span",{className:"sm:hidden",children:"New"}),J("span",{className:"hidden sm:inline",children:"New Workflow"})]})}),J(Ly,{className:"size-3 shrink-0 opacity-50"})]}),Re(Wo,{align:"start",className:"w-64",children:[J(vt,{asChild:!0,className:"flex items-center justify-between",children:Re("a",{href:"/",children:["New Workflow"," ",!e&&J(ba,{className:"size-4 shrink-0"})]})}),J(er,{}),t.allWorkflows.length===0?J(vt,{disabled:!0,children:"No workflows found"}):t.allWorkflows.filter(n=>n.name!=="__current__").map(n=>Re(vt,{className:"flex items-center justify-between",onClick:()=>t.router.push(`/workflows/${n.id}`),children:[J("span",{className:"truncate",children:n.name}),n.id===t.currentWorkflowId&&J(ba,{className:"size-4 shrink-0"})]},n.id))]})]})}),e&&!t.isOwner&&J("span",{className:"text-muted-foreground text-xs uppercase lg:hidden",children:"Read-only"})]})}var wc=({workflowId:e})=>{let t=tv(),o=ov(t);return Re(wa,{children:[J(ca,{className:"flex flex-col gap-2 rounded-none border-none bg-transparent p-0 lg:flex-row lg:items-center",position:"top-left",children:Re("div",{className:"flex items-center gap-2",children:[J(iv,{actions:o,state:t,workflowId:e}),e&&!t.isOwner&&J("span",{className:"hidden text-muted-foreground text-xs uppercase lg:inline",children:"Read-only"})]})}),J("div",{className:"pointer-events-auto absolute top-4 right-4 z-10",children:Re("div",{className:"flex flex-col-reverse items-end gap-2 lg:flex-row lg:items-center",children:[J(nv,{actions:o,state:t,workflowId:e}),Re("div",{className:"flex items-center gap-2",children:[!e&&Re(wa,{children:[J(Dd,{}),J(Cd,{})]}),e&&!t.isOwner&&J(sv,{isDuplicating:t.isDuplicating,onDuplicate:o.handleDuplicate}),J(dc,{})]})]})})]})};import"@xyflow/react/dist/style.css";import{PlayCircle as sh,Zap as ih}from"lucide-react";import{nanoid as Qs}from"nanoid";import{BaseEdge as kc,getBezierPath as lv,getSimpleBezierPath as dv,getSmoothStepPath as cv,Position as _o,useInternalNode as xc}from"@xyflow/react";import{useAtomValue as uv}from"jotai";import{jsx as Cc}from"react/jsx-runtime";var mv=({id:e,sourceX:t,sourceY:o,targetX:n,targetY:r,sourcePosition:s,targetPosition:a,selected:d})=>{let[i]=dv({sourceX:t,sourceY:o,sourcePosition:s,targetX:n,targetY:r,targetPosition:a});return Cc(kc,{className:"stroke-1",id:e,path:i,style:{stroke:d?"var(--muted-foreground)":"var(--border)",strokeDasharray:"5, 5"}})},Nc=(e,t,o)=>{let n=t===_o.Left?"target":"source",r=e.internals.handleBounds?.[n],s=o?r?.find(c=>c.id===o):r?.find(c=>c.position===t);if(!s)return[0,0];let a=s.width/2,d=s.height/2;switch(t){case _o.Left:a=0;break;case _o.Right:a=s.width;break;case _o.Top:d=0;break;case _o.Bottom:d=s.height;break;default:throw new Error(`Invalid handle position: ${t}`)}let i=e.internals.positionAbsolute.x+s.x+a,l=e.internals.positionAbsolute.y+s.y+d;return[i,l]},pv=(e,t,o,n)=>{let r=_o.Right,[s,a]=Nc(e,r,o),d=_o.Left,[i,l]=Nc(t,d,n);return{sx:s,sy:a,tx:i,ty:l,sourcePos:r,targetPos:d}},fv=({id:e,source:t,target:o,sourceHandleId:n,targetHandleId:r,style:s,selected:a})=>{let d=uv(en),i=xc(t),l=xc(o);if(!(i&&l))return null;let{sx:c,sy:u,tx:g,ty:b,sourcePos:y,targetPos:v}=pv(i,l,n,r),p={sourceX:c,sourceY:u,sourcePosition:y,targetX:g,targetY:b,targetPosition:v},[m]=d.edgeStyle==="bezier"?lv(p):cv(p);return Cc(kc,{id:e,path:m,style:{...s,stroke:a?"var(--muted-foreground)":"var(--border)",strokeWidth:2,animation:"dashdraw 0.5s linear infinite",strokeDasharray:5}})},_s={Temporary:mv,Animated:fv};import{useAtomValue as mr}from"jotai";import{AlertTriangle as Av,Check as Iv,Code as Pv,EyeOff as Ic,XCircle as Ev,Zap as Dc}from"lucide-react";import Pc from"next/image";import{memo as Dv,useState as Rv}from"react";import{useAtomValue as yv}from"jotai";import{Check as Sc,Circle as vv,EyeOff as hv,ListOrdered as bv,Loader2 as wv,XCircle as Ac}from"lucide-react";import{memo as xv,useEffect as Nv,useState as kv}from"react";import{Handle as Na,Position as ka}from"@xyflow/react";import{Fragment as gv,jsx as xo,jsxs as Us}from"react/jsx-runtime";var Tc=({className:e})=>Us(gv,{children:[xo("style",{children:`
212
202
  @property --angle {
213
203
  syntax: "<angle>";
214
204
  initial-value: 0deg;
@@ -233,4 +223,4 @@ export async function POST(request: NextRequest) {
233
223
  transparent 100%
234
224
  );
235
225
  }
236
- `}),ho("div",{className:x("pointer-events-none absolute inset-0 rounded-[inherit] animate-border-mask",e),children:Fs("svg",{className:"h-full w-full overflow-visible",xmlns:"http://www.w3.org/2000/svg",children:[ho("defs",{children:Fs("linearGradient",{id:"gradient-glow",x1:"0%",y1:"0%",x2:"100%",y2:"100%",children:[ho("stop",{offset:"0%",stopColor:"#60a5fa"}),ho("stop",{offset:"50%",stopColor:"#3b82f6"}),ho("stop",{offset:"100%",stopColor:"#60a5fa"})]})}),ho("rect",{x:"1",y:"1",width:"calc(100% - 2px)",height:"calc(100% - 2px)",rx:"6",fill:"none",stroke:"url(#gradient-glow)",strokeWidth:"2",style:{filter:"drop-shadow(0 0 4px #3b82f6)"}})]})}),ho("div",{className:x("pointer-events-none absolute inset-0 rounded-[inherit] border-2 border-blue-500/10",e)})]});import{jsx as ir,jsxs as jy}from"react/jsx-runtime";var Bo=({handles:e,className:t,status:o,...n})=>jy(ua,{className:x("node-container relative gap-0 rounded-md bg-card p-0 transition-all duration-200",o==="success"&&"border-green-500 border-2",o==="error"&&"border-red-500 border-2",t),...n,children:[o==="running"&&ir(mc,{}),e.target&&ir(pc,{position:fc.Left,type:"target"}),e.source&&ir(pc,{position:fc.Right,type:"source"}),n.children]});var Vo=e=>ir(Bd,{...e}),Go=e=>ir(Vd,{...e});import{jsx as tt,jsxs as Xt}from"react/jsx-runtime";function nv({status:e}){switch(e){case"pending":return tt(Yy,{className:"size-3 text-muted-foreground"});case"running":return tt(Zy,{className:"size-3 animate-spin text-blue-400"});case"success":return tt(gc,{className:"size-3 text-green-400"});case"error":return tt(yc,{className:"size-3 text-red-400"})}}function rv({index:e,name:t,status:o}){return Xt("div",{className:x("flex items-center gap-1.5 rounded px-1.5 py-0.5 text-[10px] leading-tight transition-colors",o==="running"&&"bg-blue-500/10",o==="success"&&"bg-green-500/10",o==="error"&&"bg-red-500/10"),children:[Xt("span",{className:"w-3 shrink-0 text-right text-muted-foreground",children:[e,"."]}),tt(nv,{status:o}),tt("span",{className:"min-w-0 flex-1 truncate",children:t})]})}function av({status:e}){return!e||e==="idle"||e==="running"?null:Xt("div",{className:x("absolute top-2 right-2 rounded-full p-1",e==="success"&&"bg-green-500/50",e==="error"&&"bg-red-500/50"),children:[e==="success"&&tt(gc,{className:"size-3.5 text-white",strokeWidth:2.5}),e==="error"&&tt(yc,{className:"size-3.5 text-white",strokeWidth:2.5})]})}var zs=ev(({data:e,selected:t,id:o})=>{let n=Jy(Jo),[r,s]=ov({}),a=e.status,d=e.enabled===!1,i=e.config?.workflowIds||"[]",l=[];try{let y=JSON.parse(i);Array.isArray(y)&&(l=y)}catch{l=i.split(",").map(y=>y.trim()).filter(Boolean)}tv(()=>{if(l.length===0)return;let y=!1;async function p(){try{let v=await fetch("/api/workflow-builder/workflows");if(!v.ok)return;let g=await v.json(),C=g.workflows||g||[],I={};for(let A of C)I[A.id]=A.name;y||s(I)}catch{}}return p(),()=>{y=!0}},[i]);let u=n[o]?.output,f=u?.results,h=new Map;if(f)for(let y of f)h.set(y.workflowId,y.success?"success":"error");function k(y,p){return f&&h.get(y)||"pending"}let b=l.length===0;return Xt(Bo,{className:x("relative flex w-56 flex-col shadow-none transition-all duration-150 ease-out",t&&"border-primary",d&&"opacity-50"),"data-testid":`action-node-${o}`,handles:{target:!0,source:!0},status:a,children:[d&&tt("div",{className:"absolute top-2 left-2 rounded-full bg-gray-500/50 p-1",children:tt(Xy,{className:"size-3.5 text-white"})}),tt(av,{status:a}),Xt("div",{className:"flex items-center gap-2 border-b px-3 py-2.5",children:[tt(Qy,{className:"size-4 shrink-0 text-emerald-300",strokeWidth:1.5}),Xt("div",{className:"min-w-0 flex-1",children:[tt(Vo,{className:"truncate text-xs font-medium",children:e.label||"Run Workflows in Sequence"}),!b&&Xt(Go,{className:"text-[10px]",children:[l.length," workflow",l.length!==1?"s":""]})]})]}),tt("div",{className:"flex flex-col gap-0.5 px-2 py-2",children:b?tt("p",{className:"px-1 py-2 text-center text-[10px] text-muted-foreground",children:"No workflows configured"}):l.map((y,p)=>tt(rv,{index:p+1,name:r[y]||y.slice(0,12)+"...",status:k(y,p)},`${y}-${p}`))}),u&&f&&Xt("div",{className:"border-t px-3 py-1.5 text-[10px] text-muted-foreground",children:[u.succeeded||0," passed",(u.failed||0)>0&&Xt("span",{className:"text-red-400",children:[" / ",u.failed," failed"]})]})]})});zs.displayName="SequenceNode";import{Fragment as wv,jsx as Te,jsxs as Qt}from"react/jsx-runtime";var mv=e=>({"gpt-5":"GPT-5","openai/gpt-5.1-instant":"GPT-5.1 Instant","openai/gpt-5.1-codex":"GPT-5.1 Codex","openai/gpt-5.1-codex-mini":"GPT-5.1 Codex Mini","openai/gpt-5.1-thinking":"GPT-5.1 Thinking","gpt-4":"GPT-4","gpt-4o":"GPT-4o","gpt-4o-mini":"GPT-4o Mini","claude-3-5-sonnet":"Claude 3.5","claude-3-opus":"Claude 3 Opus","anthropic/claude-opus-4.5":"Claude Opus 4.5","anthropic/claude-sonnet-4.5":"Claude Sonnet 4.5","anthropic/claude-haiku-4.5":"Claude Haiku 4.5","google/gemini-3-pro-preview":"Gemini 3 Pro Preview","google/gemini-2.5-flash-lite":"Gemini 2.5 Flash Lite","google/gemini-2.5-flash":"Gemini 2.5 Flash","google/gemini-2.5-pro":"Gemini 2.5 Pro","meta/llama-4-scout":"Llama 4 Scout","meta/llama-3.3-70b":"Llama 3.3 70B","meta/llama-3.1-8b":"Llama 3.1 8B","moonshotai/kimi-k2-0905":"Kimi K2","openai/gpt-oss-120b":"GPT OSS 120B","openai/gpt-oss-safeguard-20b":"GPT OSS Safeguard 20B","openai/gpt-oss-20b":"GPT OSS 20B","o1-preview":"o1 Preview","o1-mini":"o1 Mini","bfl/flux-2-pro":"FLUX.2 Pro","bfl/flux-1-pro":"FLUX.1 Pro","openai/dall-e-3":"DALL-E 3","google/imagen-4.0-generate":"Imagen 4.0"})[e]||e,bc={"HTTP Request":"System","Database Query":"Database",Condition:"Condition","Execute Code":"System",Loop:"Loop",Switch:"Switch",Merge:"Merge","Run Workflow":"System","Run Workflows in Sequence":"System"},pv=e=>{if(bc[e])return bc[e];let t=fe(e);return t?.integration&&Dt(t.integration)?.label||"System"};function fv(e){return typeof e=="object"&&e!==null&&"base64"in e&&typeof e.base64=="string"&&e.base64.length>100}var gv=e=>{if(["Database Query"].includes(e))return!0;let o=fe(e);return o?_o(o.integration):!1},yv=e=>{switch(e){case"HTTP Request":return qo.icon;case"Database Query":return Ko.icon;case"Execute Code":return Te(lv,{className:"size-12 text-green-300",strokeWidth:1.5});case"Condition":return Uo.icon;case"Loop":return Ur.icon;case"Merge":return Kr.icon;case"Switch":return Jr.icon;case"Run Workflow":return qr.icon;case"Run Workflows in Sequence":return jr.icon;default:break}let t=fe(e);if(t){let o=Dt(t.integration);if(o?.icon){let n=o.icon;return Te(n,{className:"size-12"})}}return Te(wc,{className:"size-12 text-amber-300",strokeWidth:1.5})},vv=({status:e})=>!e||e==="idle"||e==="running"?null:Qt("div",{className:x("absolute top-2 right-2 rounded-full p-1",e==="success"&&"bg-green-500/50",e==="error"&&"bg-red-500/50"),children:[e==="success"&&Te(iv,{className:"size-3.5 text-white",strokeWidth:2.5}),e==="error"&&Te(dv,{className:"size-3.5 text-white",strokeWidth:2.5})]}),hv=({model:e})=>e?Te("div",{className:"rounded-full border border-muted-foreground/50 px-2 py-0.5 font-medium text-[10px] text-muted-foreground",children:mv(e)}):null;function bv({base64:e}){let[t,o]=uv(!1);return Qt(wv,{children:[Te("button",{className:"relative size-12 cursor-zoom-in overflow-hidden rounded-lg transition-transform hover:scale-105",onClick:n=>{n.stopPropagation(),o(!0)},type:"button",children:Te(hc,{alt:"Generated image",className:"object-cover",fill:!0,sizes:"48px",src:`data:image/png;base64,${e}`,unoptimized:!0})}),Te(aa,{onOpenChange:o,open:t,children:Qt(Ul,{className:"max-w-3xl p-2",showCloseButton:!1,children:[Te(Kl,{className:"sr-only",children:"Generated Image"}),Te("div",{className:"relative aspect-square w-full overflow-hidden rounded-lg",children:Te(hc,{alt:"Generated image",className:"object-contain",fill:!0,sizes:"(max-width: 768px) 100vw, 768px",src:`data:image/png;base64,${e}`,unoptimized:!0})})]})})]})}var Bs=cv(({data:e,selected:t,id:o})=>{let n=lr(no),r=lr(Jo),s=lr(Nr),a=lr(ei),d=lr(gr);if(!e)return null;let i=e.config?.actionType||"",l=e.status;if(i==="Run Workflows in Sequence")return Te(zs,{data:e,id:o,selected:t});let c=r[o],u=n&&i==="Generate Image"&&c?.output&&fv(c.output);if(!i){let w=e.enabled===!1;return Qt(Bo,{className:x("flex h-48 w-48 flex-col items-center justify-center shadow-none transition-all duration-150 ease-out",t&&"border-primary",w&&"opacity-50"),"data-testid":`action-node-${o}`,handles:{target:!0,source:!0},status:l,children:[w&&Te("div",{className:"absolute top-2 left-2 rounded-full bg-gray-500/50 p-1",children:Te(vc,{className:"size-3.5 text-white"})}),Qt("div",{className:"flex flex-col items-center justify-center gap-3 p-6",children:[Te(wc,{className:"size-12 text-muted-foreground",strokeWidth:1.5}),Qt("div",{className:"flex flex-col items-center gap-1 text-center",children:[Te(Vo,{className:"text-base",children:e.label||"Action"}),Te(Go,{className:"text-xs",children:"Select an action"})]})]})]})}let f=fe(i),h=e.label||f?.label||i,k=e.description||pv(i),b=gv(i),y=s.has(o),p=e.config?.integrationId,v=p&&a.has(p),g=d&&b&&!v&&!y,I=i==="Generate Text"?e.config?.aiModel||"meta/llama-4-scout":i==="Generate Image"?e.config?.imageModel||"google/imagen-4.0-generate":null,A=e.enabled===!1;return Qt(Bo,{className:x("relative flex h-48 w-48 flex-col items-center justify-center shadow-none transition-all duration-150 ease-out",t&&"border-primary",A&&"opacity-50"),"data-testid":`action-node-${o}`,handles:{target:!0,source:!0},status:l,children:[A&&Te("div",{className:"absolute top-2 left-2 rounded-full bg-gray-500/50 p-1",children:Te(vc,{className:"size-3.5 text-white"})}),!A&&g&&Te("div",{className:"absolute top-2 left-2 rounded-full bg-orange-500/50 p-1",children:Te(sv,{className:"size-3.5 text-white"})}),Te(vv,{status:l}),Qt("div",{className:"flex flex-col items-center justify-center gap-3 p-6",children:[u?Te(bv,{base64:c.output.base64}):yv(i),Qt("div",{className:"flex flex-col items-center gap-1 text-center",children:[Te(Vo,{className:"text-base",children:h}),k&&Te(Go,{className:"text-xs",children:k}),I&&Te(hv,{model:I})]})]})]})});Bs.displayName="ActionNode";import{Plus as xv}from"lucide-react";import{jsx as On,jsxs as ha}from"react/jsx-runtime";function xc({data:e}){return ha("div",{className:"flex flex-col items-center justify-center gap-8 rounded-lg border border-border border-dashed bg-background/50 p-8 backdrop-blur-sm",children:[ha("div",{className:"text-center",children:[On("h1",{className:"mb-2 font-bold text-3xl",children:"AI Workflow Builder Template"}),ha("p",{className:"text-muted-foreground text-sm",children:["Powered by"," ",On("a",{className:"underline underline-offset-2 transition duration-200 ease-out hover:text-foreground",href:"https://useworkflow.dev/",rel:"noopener noreferrer",target:"_blank",children:"Workflow"}),","," ",On("a",{className:"underline underline-offset-2 transition duration-200 ease-out hover:text-foreground",href:"https://ai-sdk.dev/",rel:"noopener noreferrer",target:"_blank",children:"AI SDK"}),","," ",On("a",{className:"underline underline-offset-2 transition duration-200 ease-out hover:text-foreground",href:"https://vercel.com/ai-gateway",rel:"noopener noreferrer",target:"_blank",children:"AI Gateway"})," ","and"," ",On("a",{className:"underline underline-offset-2 transition duration-200 ease-out hover:text-foreground",href:"https://ai-sdk.dev/elements",rel:"noopener noreferrer",target:"_blank",children:"AI Elements"})]})]}),ha(D,{className:"gap-2 shadow-lg",onClick:e.onClick,size:"default",children:[On(xv,{className:"size-4"}),"Add a Step"]})]})}import{Check as Nv,Clock as kv,Play as Cv,Webhook as Tv,XCircle as Av}from"lucide-react";import{memo as Sv}from"react";import{jsx as dr,jsxs as ba}from"react/jsx-runtime";var Vs=Sv(({data:e,selected:t})=>{if(!e)return null;let o=e.config?.triggerType||"Manual",n=e.label||o,r=e.description||"Trigger",s=e.status,a=Cv;return o==="Schedule"?a=kv:o==="Webhook"&&(a=Tv),ba(Bo,{className:x("flex h-48 w-48 flex-col items-center justify-center shadow-none transition-all duration-150 ease-out",t&&"border-primary"),handles:{target:!1,source:!0},status:s,children:[s&&s!=="idle"&&s!=="running"&&ba("div",{className:x("absolute top-2 right-2 rounded-full p-1",s==="success"&&"bg-green-500/50",s==="error"&&"bg-red-500/50"),children:[s==="success"&&dr(Nv,{className:"size-3.5 text-white",strokeWidth:2.5}),s==="error"&&dr(Av,{className:"size-3.5 text-white",strokeWidth:2.5})]}),ba("div",{className:"flex flex-col items-center justify-center gap-3 p-6",children:[dr(a,{className:"size-12 text-blue-500",strokeWidth:1.5}),ba("div",{className:"flex flex-col items-center gap-1 text-center",children:[dr(Vo,{className:"text-base",children:n}),r&&dr(Go,{className:"text-xs",children:r})]})]})]})});Vs.displayName="TriggerNode";import{useAtomValue as Iv,useSetAtom as cr}from"jotai";import{Link2Off as Pv,Plus as Ev,Trash2 as Dv}from"lucide-react";import{nanoid as Rv}from"nanoid";import{useCallback as Mn,useEffect as Ov,useRef as Lv}from"react";import{jsx as Ln,jsxs as Cc}from"react/jsx-runtime";function Nc({menuState:e,onClose:t}){let o=Iv(re),n=cr(ao),r=cr(so),s=cr(Yo),a=cr(ke),d=cr(Bt),{open:i}=oe(),l=Lv(null),c=Mn(()=>{if(e?.nodeId){let b=e.nodeId;t(),i(Ie,{title:"Delete Step",message:"Are you sure you want to delete this node? This action cannot be undone.",confirmLabel:"Delete",confirmVariant:"destructive",onConfirm:()=>{n(b)}})}},[e,n,t,i]),u=Mn(()=>{if(e?.edgeId){let b=e.edgeId;t(),i(Ie,{title:"Delete Connection",message:"Are you sure you want to delete this connection? This action cannot be undone.",confirmLabel:"Delete",confirmVariant:"destructive",onConfirm:()=>{r(b)}})}},[e,r,t,i]),f=Mn(()=>{if(e?.flowPosition){let y={id:Rv(),type:"action",position:{x:e.flowPosition.x,y:e.flowPosition.y-96},data:{label:"",description:"",type:"action",config:{},status:"idle"},selected:!0};s(y),a(y.id),d("properties")}t()},[e,s,a,d,t]);if(Ov(()=>{if(!e)return;let b=v=>{l.current&&!l.current.contains(v.target)&&t()},y=v=>{v.key==="Escape"&&t()},p=setTimeout(()=>{document.addEventListener("mousedown",b),document.addEventListener("keydown",y)},0);return()=>{clearTimeout(p),document.removeEventListener("mousedown",b),document.removeEventListener("keydown",y)}},[e,t]),!e)return null;let h=!!(e.nodeId&&o.find(b=>b.id===e.nodeId)?.data.type==="trigger"),k=()=>e.nodeId&&o.find(y=>y.id===e.nodeId)?.data.label||"Step";return Cc("div",{className:"fade-in-0 zoom-in-95 fixed z-50 min-w-[8rem] animate-in overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md",ref:l,style:{left:e.position.x,top:e.position.y},children:[e.type==="node"&&Ln(Gs,{disabled:h,icon:Ln(Dv,{className:"size-4"}),label:`Delete ${k()}`,onClick:c,variant:"destructive"}),e.type==="edge"&&Ln(Gs,{icon:Ln(Pv,{className:"size-4"}),label:"Delete Connection",onClick:u,variant:"destructive"}),e.type==="pane"&&Ln(Gs,{icon:Ln(Ev,{className:"size-4"}),label:"Add Step",onClick:f})]})}function Gs({icon:e,label:t,onClick:o,variant:n="default",disabled:r}){return Cc("button",{className:x("relative flex w-full cursor-default select-none items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-none","hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground",n==="destructive"&&"text-destructive hover:bg-destructive/10 hover:text-destructive focus:bg-destructive/10 focus:text-destructive",r&&"pointer-events-none opacity-50"),disabled:r,onClick:o,type:"button",children:[e,t]})}function kc(e,t){let o=Mn((s,a)=>{s.preventDefault(),t({type:"node",position:{x:s.clientX,y:s.clientY},nodeId:a.id})},[t]),n=Mn((s,a)=>{s.preventDefault(),t({type:"edge",position:{x:s.clientX,y:s.clientY},edgeId:a.id})},[t]),r=Mn(s=>{s.preventDefault();let a=e({x:s.clientX,y:s.clientY});t({type:"pane",position:{x:s.clientX,y:s.clientY},flowPosition:a})},[e,t]);return{onNodeContextMenu:o,onEdgeContextMenu:n,onPaneContextMenu:r}}import{jsx as $o,jsxs as Ac}from"react/jsx-runtime";var Gv=[{type:"trigger",label:"",description:"",displayLabel:"Trigger",icon:Bv,defaultConfig:{triggerType:"Manual"}},{type:"action",label:"",description:"",displayLabel:"Action",icon:Vv,defaultConfig:{}}],Hv={animated:Ws.Animated,temporary:Ws.Temporary};function Sc(){let[e,t]=ur(re),[o,n]=ur(ue),[r]=ur(Nt),s=Hs(Ue),[a]=ur(vr),d=Hs(hr),i=Hs(br),[l,c]=ur(xr),u=bo(ai),f=bo(si),h=bo(ke),k=bo(_e),b=bo(Yo),y=bo(nt),p=bo(Ot),v=bo(Bt),{screenToFlowPosition:g,fitView:C,getViewport:I,setViewport:A}=Fv(),w=Ho(null),m=Ho(null),S=Ho(!1),X=Ho(!1),[ie,L]=Tc(!1),[F,$]=Tc(null),{onNodeContextMenu:P,onEdgeContextMenu:V,onPaneContextMenu:J}=kc(g,$),W=xt(()=>{$(null)},[]),K=Ho(void 0),T=e.some(Q=>Q.type!=="add"),z=Ho(!1),N=Ho(!1);wa(()=>{if(l&&!N.current){if(N.current=!0,document.cookie.split("; ").find(De=>De.startsWith("sidebar-collapsed="))?.split("=")[1]==="true")return;let _=I(),ce=window.innerWidth*.3/2;A({..._,x:_.x-ce},{duration:0})}},[l,I,A]),wa(()=>{if(K.current!==s){if(l&&X.current){K.current=s,L(!0),c(!1);return}setTimeout(()=>{C({maxZoom:1,minZoom:.5,padding:.2,duration:0}),K.current=s,X.current=!0,L(!0),c(!1)},0)}},[s,C,l,c]),wa(()=>{s||(T&&!z.current?(z.current=!0,setTimeout(()=>{C({maxZoom:1,minZoom:.5,padding:.2,duration:0}),X.current=!0,L(!0)},0)):T||(z.current=!1))},[s,T,C]),wa(()=>{let Q=E=>{(E.metaKey||E.ctrlKey)&&E.key==="/"&&(E.preventDefault(),C({padding:.2,duration:300}))};return window.addEventListener("keydown",Q),()=>{window.removeEventListener("keydown",Q)}},[C]);let R=zv(()=>({trigger:Vs,action:Bs,add:xc}),[]),G=xt((Q,E)=>{let _=e.find(Y=>Y.id===Q);return!_||_.type==="add"?!1:E==="target"?_.type!=="trigger":!0},[e]),ne=xt(Q=>!(!(Q.source&&Q.target)||Q.source===Q.target),[]),de=xt(Q=>{let E={id:$s(),...Q,type:"animated"};n([...o,E]),y(!0),p({immediate:!0})},[o,n,y,p]),B=xt((Q,E)=>{h(E.id)},[h]),Ae=xt((Q,E)=>{w.current=E.nodeId,m.current=E.handleType},[]),Je=xt(Q=>{let E="changedTouches"in Q?Q.changedTouches[0].clientX:Q.clientX,_="changedTouches"in Q?Q.changedTouches[0].clientY:Q.clientY;return{clientX:E,clientY:_}},[]),Ye=xt((Q,E,_)=>{let Y=Q.target.closest(".react-flow")?.getBoundingClientRect(),ce=Y?E-Y.left:E,De=Y?_-Y.top:_;return{adjustedX:ce,adjustedY:De}},[]),$e=xt(Q=>{let E=Q.getAttribute("data-id"),_=m.current==="source",Y=_?"target":"source",ce=w.current;E&&ce&&E!==ce&&G(E,Y)&&de({source:_?ce:E,target:_?E:ce,sourceHandle:null,targetHandle:null})},[G,de]),Zt=xt((Q,E,_)=>{let Y=w.current;if(!Y)return;let{adjustedX:ce,adjustedY:De}=Ye(Q,E,_),Me=Gv.find(ka=>ka.type==="action");if(!Me)return;let Wn=g({x:ce,y:De}),Na=192;Wn.y-=Na/2;let Fn={id:$s(),type:Me.type,position:Wn,data:{label:Me.label,description:Me.description,type:Me.type,config:Me.defaultConfig,status:"idle"},selected:!0};b(Fn),h(Fn.id),v("properties"),setTimeout(()=>{t(ka=>ka.map(Us=>({...Us,selected:Us.id===Fn.id})))},50);let _s=m.current==="source",Lc={id:$s(),source:_s?Y:Fn.id,target:_s?Fn.id:Y,type:"animated"};n([...o,Lc]),y(!0),p({immediate:!0}),S.current=!0,setTimeout(()=>{S.current=!1},100)},[Ye,g,b,o,n,t,h,v,y,p]),Et=xt(Q=>{if(!w.current)return;let{clientX:E,clientY:_}=Je(Q),Y="changedTouches"in Q?document.elementFromPoint(E,_):Q.target;if(!Y){w.current=null;return}let ce=Y.closest(".react-flow__node"),De=Y.closest(".react-flow__handle");if(ce&&!De&&m.current){$e(ce),w.current=null,m.current=null;return}ce||De||Zt(Q,E,_),w.current=null,m.current=null},[Je,$e,Zt]),ee=xt(()=>{S.current||(h(null),k(null),W())},[h,k,W]),xe=xt(({nodes:Q})=>{S.current&&Q.length===0||(Q.length===0?h(null):Q.length===1&&h(Q[0].id))},[h]);return Ac("div",{className:"relative h-full bg-background","data-testid":"workflow-canvas",style:{opacity:ie?1:0,width:d?`calc(100% - ${d})`:"100%",transition:i?"width 300ms ease-out, opacity 300ms":"opacity 300ms"},children:[$o("div",{className:"pointer-events-auto",children:$o(ic,{workflowId:s??void 0})}),Ac(rd,{className:"bg-background",connectionLineComponent:sd,connectionMode:Mv.Strict,edges:o,edgeTypes:Hv,elementsSelectable:!r,isValidConnection:ne,nodes:e,nodesConnectable:!r,nodesDraggable:!r,nodeTypes:R,onConnect:r?void 0:de,onConnectEnd:r?void 0:Et,onConnectStart:r?void 0:Ae,onEdgeContextMenu:r?void 0:V,onEdgesChange:r?void 0:f,onNodeClick:r?void 0:B,onNodeContextMenu:r?void 0:P,onNodesChange:r?void 0:u,onPaneClick:ee,onPaneContextMenu:r?void 0:J,onSelectionChange:r?void 0:xe,children:[$o(sa,{className:"workflow-controls-panel border-none bg-transparent p-0",position:"bottom-right",children:$o(id,{})}),a&&$o(Wv,{bgColor:"var(--sidebar)",nodeStrokeColor:"var(--border)"})]}),s&&$o(cd,{workflowId:s}),$o(Nc,{menuState:F,onClose:W})]})}import{jsx as Ic}from"react/jsx-runtime";function Pc(){let e=$v();return e==="/"||e.startsWith("/workflows/")?Ic("div",{className:"fixed inset-0 z-0",children:Ic(Sc,{})}):null}import{AuthUIProvider as _v}from"@daveyplate/better-auth-ui";import Uv from"next/link";import{useRouter as Kv}from"next/navigation";import{jsx as qv}from"react/jsx-runtime";var Ec=e=>{let t=Kv(),{children:o,...n}=e;return qv(_v,{...n,authClient:Mo,navigate:t.push,replace:t.replace,onSessionChange:()=>{t.refresh()},Link:Uv,children:o})};import{ThemeProvider as jv}from"next-themes";import{jsx as Jv}from"react/jsx-runtime";var Dc=({children:e,...t})=>Jv(jv,{...t,children:e});import{jsx as wo,jsxs as Rc}from"react/jsx-runtime";function Zv(e){Ki();let t=Qv(jo);return xa.useEffect(()=>{e.canvas&&t(o=>({...o,...e.canvas}))},[e.canvas,t]),Rc(xi,{children:[wo(xa.Suspense,{children:Rc(Yv,{children:[wo(Pc,{}),e.children]})}),wo(nd,{}),wo(od,{})]})}var Oc=e=>{let{children:t,canvas:o,...n}=e;return wo(Dc,{attribute:"class",defaultTheme:"system",disableTransitionOnChange:!0,enableSystem:!0,children:wo(Ec,{...n,children:wo(Xv,{children:wo(Zv,{canvas:o,children:t})})})})};import{jsx as th}from"react/jsx-runtime";var eh=e=>{let{children:t,canvas:o,...n}=e;return th(Oc,{canvas:o,...n,children:t})};function oh(){return process.env.AI_GATEWAY_MANAGED_KEYS_ENABLED==="true"}function nh(){return typeof window>"u"?process.env.AI_GATEWAY_MANAGED_KEYS_ENABLED==="true":process.env.NEXT_PUBLIC_AI_GATEWAY_MANAGED_KEYS_ENABLED==="true"}export{eh as Layout,cs as WorkflowEditor,kf as WorkflowPage,oh as isAiGatewayManagedKeysEnabled,nh as isAiGatewayManagedKeysEnabledClient};
226
+ `}),xo("div",{className:N("pointer-events-none absolute inset-0 rounded-[inherit] animate-border-mask",e),children:Us("svg",{className:"h-full w-full overflow-visible",xmlns:"http://www.w3.org/2000/svg",children:[xo("defs",{children:Us("linearGradient",{id:"gradient-glow",x1:"0%",y1:"0%",x2:"100%",y2:"100%",children:[xo("stop",{offset:"0%",stopColor:"#60a5fa"}),xo("stop",{offset:"50%",stopColor:"#3b82f6"}),xo("stop",{offset:"100%",stopColor:"#60a5fa"})]})}),xo("rect",{x:"1",y:"1",width:"calc(100% - 2px)",height:"calc(100% - 2px)",rx:"6",fill:"none",stroke:"url(#gradient-glow)",strokeWidth:"2",style:{filter:"drop-shadow(0 0 4px #3b82f6)"}})]})}),xo("div",{className:N("pointer-events-none absolute inset-0 rounded-[inherit] border-2 border-blue-500/10",e)})]});import{jsx as Vt,jsxs as Ks}from"react/jsx-runtime";var Uo=({handles:e,className:t,status:o,...n})=>Ks(ga,{className:N("node-container relative gap-0 rounded-md bg-card p-0 transition-all duration-200",o==="success"&&"border-green-500 border-2",o==="error"&&"border-red-500 border-2",t),...n,children:[o==="running"&&Vt(Tc,{}),e.targetHandles&&e.targetHandles.length>0?Vt("div",{className:"absolute top-0 -left-[4px] flex h-full flex-col items-start justify-center gap-1",children:e.targetHandles.map(r=>Ks("div",{className:"relative flex items-center",children:[Vt(Na,{id:r.id,position:ka.Left,style:{position:"relative",top:"auto",left:"auto",transform:"none"},type:"target"}),r.label&&Vt("span",{className:"ml-1.5 text-muted-foreground text-[9px] leading-none",children:r.label})]},r.id))}):e.target&&Vt(Na,{position:ka.Left,type:"target"}),e.sourceHandles&&e.sourceHandles.length>0?Vt("div",{className:"absolute top-0 -right-[4px] flex h-full flex-col items-end justify-center gap-1",children:e.sourceHandles.map((r,s)=>Ks("div",{className:"relative flex items-center",children:[r.label&&Vt("span",{className:"mr-1.5 text-muted-foreground text-[9px] leading-none",children:r.label}),Vt(Na,{id:r.id,position:ka.Right,style:{position:"relative",top:"auto",right:"auto",transform:"none"},type:"source"})]},r.id))}):e.source&&Vt(Na,{position:ka.Right,type:"source"}),n.children]});var Ko=e=>Vt(Xd,{...e}),qo=e=>Vt(Qd,{...e});import{jsx as ot,jsxs as to}from"react/jsx-runtime";function Cv({status:e}){switch(e){case"pending":return ot(vv,{className:"size-3 text-muted-foreground"});case"running":return ot(wv,{className:"size-3 animate-spin text-blue-400"});case"success":return ot(Sc,{className:"size-3 text-green-400"});case"error":return ot(Ac,{className:"size-3 text-red-400"})}}function Tv({index:e,name:t,status:o}){return to("div",{className:N("flex items-center gap-1.5 rounded px-1.5 py-0.5 text-[10px] leading-tight transition-colors",o==="running"&&"bg-blue-500/10",o==="success"&&"bg-green-500/10",o==="error"&&"bg-red-500/10"),children:[to("span",{className:"w-3 shrink-0 text-right text-muted-foreground",children:[e,"."]}),ot(Cv,{status:o}),ot("span",{className:"min-w-0 flex-1 truncate",children:t})]})}function Sv({status:e}){return!e||e==="idle"||e==="running"?null:to("div",{className:N("absolute top-2 right-2 rounded-full p-1",e==="success"&&"bg-green-500/50",e==="error"&&"bg-red-500/50"),children:[e==="success"&&ot(Sc,{className:"size-3.5 text-white",strokeWidth:2.5}),e==="error"&&ot(Ac,{className:"size-3.5 text-white",strokeWidth:2.5})]})}var qs=xv(({data:e,selected:t,id:o})=>{let n=yv(tn),[r,s]=kv({}),a=e.status,d=e.enabled===!1,i=e.config?.workflowIds||"[]",l=[];try{let p=JSON.parse(i);Array.isArray(p)&&(l=p)}catch{l=i.split(",").map(p=>p.trim()).filter(Boolean)}Nv(()=>{if(l.length===0)return;let p=!1;async function m(){try{let w=await fetch("/api/workflow-builder/workflows");if(!w.ok)return;let h=await w.json(),S=h.workflows||h||[],D={};for(let I of S)D[I.id]=I.name;p||s(D)}catch{}}return m(),()=>{p=!0}},[i]);let u=n[o]?.output,g=u?.results,b=new Map;if(g)for(let p of g)b.set(p.workflowId,p.success?"success":"error");function y(p,m){return g&&b.get(p)||"pending"}let v=l.length===0;return to(Uo,{className:N("relative flex w-56 flex-col shadow-none transition-all duration-150 ease-out",t&&"border-primary",d&&"opacity-50"),"data-testid":`action-node-${o}`,handles:{target:!0,source:!0},status:a,children:[d&&ot("div",{className:"absolute top-2 left-2 rounded-full bg-gray-500/50 p-1",children:ot(hv,{className:"size-3.5 text-white"})}),ot(Sv,{status:a}),to("div",{className:"flex items-center gap-2 border-b px-3 py-2.5",children:[ot(bv,{className:"size-4 shrink-0 text-emerald-300",strokeWidth:1.5}),to("div",{className:"min-w-0 flex-1",children:[ot(Ko,{className:"truncate text-xs font-medium",children:e.label||"Run Workflows in Sequence"}),!v&&to(qo,{className:"text-[10px]",children:[l.length," workflow",l.length!==1?"s":""]})]})]}),ot("div",{className:"flex flex-col gap-0.5 px-2 py-2",children:v?ot("p",{className:"px-1 py-2 text-center text-[10px] text-muted-foreground",children:"No workflows configured"}):l.map((p,m)=>ot(Tv,{index:m+1,name:r[p]||p.slice(0,12)+"...",status:y(p,m)},`${p}-${m}`))}),u&&g&&to("div",{className:"border-t px-3 py-1.5 text-[10px] text-muted-foreground",children:[u.succeeded||0," passed",(u.failed||0)>0&&to("span",{className:"text-red-400",children:[" / ",u.failed," failed"]})]})]})});qs.displayName="SequenceNode";import{Fragment as Hv,jsx as Ae,jsxs as oo}from"react/jsx-runtime";var Ov=e=>({"gpt-5":"GPT-5","openai/gpt-5.1-instant":"GPT-5.1 Instant","openai/gpt-5.1-codex":"GPT-5.1 Codex","openai/gpt-5.1-codex-mini":"GPT-5.1 Codex Mini","openai/gpt-5.1-thinking":"GPT-5.1 Thinking","gpt-4":"GPT-4","gpt-4o":"GPT-4o","gpt-4o-mini":"GPT-4o Mini","claude-3-5-sonnet":"Claude 3.5","claude-3-opus":"Claude 3 Opus","anthropic/claude-opus-4.5":"Claude Opus 4.5","anthropic/claude-sonnet-4.5":"Claude Sonnet 4.5","anthropic/claude-haiku-4.5":"Claude Haiku 4.5","google/gemini-3-pro-preview":"Gemini 3 Pro Preview","google/gemini-2.5-flash-lite":"Gemini 2.5 Flash Lite","google/gemini-2.5-flash":"Gemini 2.5 Flash","google/gemini-2.5-pro":"Gemini 2.5 Pro","meta/llama-4-scout":"Llama 4 Scout","meta/llama-3.3-70b":"Llama 3.3 70B","meta/llama-3.1-8b":"Llama 3.1 8B","moonshotai/kimi-k2-0905":"Kimi K2","openai/gpt-oss-120b":"GPT OSS 120B","openai/gpt-oss-safeguard-20b":"GPT OSS Safeguard 20B","openai/gpt-oss-20b":"GPT OSS 20B","o1-preview":"o1 Preview","o1-mini":"o1 Mini","bfl/flux-2-pro":"FLUX.2 Pro","bfl/flux-1-pro":"FLUX.1 Pro","openai/dall-e-3":"DALL-E 3","google/imagen-4.0-generate":"Imagen 4.0"})[e]||e,Ec={"HTTP Request":"System","Database Query":"Database",Condition:"Condition","Execute Code":"System",Loop:"Loop",Switch:"Switch",Merge:"Merge","Run Workflow":"System","Run Workflows in Sequence":"System"},Lv=e=>{if(Ec[e])return Ec[e];let t=ye(e);return t?.integration&&Mt(t.integration)?.label||"System"};function Mv(e){return typeof e=="object"&&e!==null&&"base64"in e&&typeof e.base64=="string"&&e.base64.length>100}var Wv=e=>{if(["Database Query"].includes(e))return!0;let o=ye(e);return o?Jo(o.integration):!1},Fv=e=>{switch(e){case"HTTP Request":return Qo.icon;case"Database Query":return Xo.icon;case"Execute Code":return Ae(Pv,{className:"size-12 text-green-300",strokeWidth:1.5});case"Condition":return Yo.icon;case"Loop":return Xr.icon;case"Merge":return Cn.icon;case"Switch":return Tn.icon;case"Run Workflow":return Qr.icon;case"Run Workflows in Sequence":return Zr.icon;default:break}let t=ye(e);if(t){let o=Mt(t.integration);if(o?.icon){let n=o.icon;return Ae(n,{className:"size-12"})}}return Ae(Dc,{className:"size-12 text-amber-300",strokeWidth:1.5})},zv=({status:e})=>!e||e==="idle"||e==="running"?null:oo("div",{className:N("absolute top-2 right-2 rounded-full p-1",e==="success"&&"bg-green-500/50",e==="error"&&"bg-red-500/50"),children:[e==="success"&&Ae(Iv,{className:"size-3.5 text-white",strokeWidth:2.5}),e==="error"&&Ae(Ev,{className:"size-3.5 text-white",strokeWidth:2.5})]}),Bv=({model:e})=>e?Ae("div",{className:"rounded-full border border-muted-foreground/50 px-2 py-0.5 font-medium text-[10px] text-muted-foreground",children:Ov(e)}):null;function Vv({base64:e}){let[t,o]=Rv(!1);return oo(Hv,{children:[Ae("button",{className:"relative size-12 cursor-zoom-in overflow-hidden rounded-lg transition-transform hover:scale-105",onClick:n=>{n.stopPropagation(),o(!0)},type:"button",children:Ae(Pc,{alt:"Generated image",className:"object-cover",fill:!0,sizes:"48px",src:`data:image/png;base64,${e}`,unoptimized:!0})}),Ae(da,{onOpenChange:o,open:t,children:oo(nd,{className:"max-w-3xl p-2",showCloseButton:!1,children:[Ae(rd,{className:"sr-only",children:"Generated Image"}),Ae("div",{className:"relative aspect-square w-full overflow-hidden rounded-lg",children:Ae(Pc,{alt:"Generated image",className:"object-contain",fill:!0,sizes:"(max-width: 768px) 100vw, 768px",src:`data:image/png;base64,${e}`,unoptimized:!0})})]})})]})}var js=Dv(({data:e,selected:t,id:o})=>{let n=mr(so),r=mr(tn),s=mr(Ir),a=mr(ui),d=mr(xr);if(!e)return null;let i=e.config?.actionType||"",l=e.status;if(i==="Run Workflows in Sequence")return Ae(qs,{data:e,id:o,selected:t});let c=r[o],u=n&&i==="Generate Image"&&c?.output&&Mv(c.output);if(!i){let $=e.enabled===!1;return oo(Uo,{className:N("flex h-48 w-48 flex-col items-center justify-center shadow-none transition-all duration-150 ease-out",t&&"border-primary",$&&"opacity-50"),"data-testid":`action-node-${o}`,handles:{target:!0,source:!0},status:l,children:[$&&Ae("div",{className:"absolute top-2 left-2 rounded-full bg-gray-500/50 p-1",children:Ae(Ic,{className:"size-3.5 text-white"})}),oo("div",{className:"flex flex-col items-center justify-center gap-3 p-6",children:[Ae(Dc,{className:"size-12 text-muted-foreground",strokeWidth:1.5}),oo("div",{className:"flex flex-col items-center gap-1 text-center",children:[Ae(Ko,{className:"text-base",children:e.label||"Action"}),Ae(qo,{className:"text-xs",children:"Select an action"})]})]})]})}let g=ye(i),b=e.label||g?.label||i,y=e.description||Lv(i),v=Wv(i),p=s.has(o),m=e.config?.integrationId,w=m&&a.has(m),h=d&&v&&!w&&!p,D=i==="Generate Text"?e.config?.aiModel||"meta/llama-4-scout":i==="Generate Image"?e.config?.imageModel||"google/imagen-4.0-generate":null,I=e.enabled===!1,k=i==="Switch",f=i==="Condition",x;if(k){let $=Number(e.config?.routeCount)||4;x=[];for(let T=0;T<$;T++){let H=e.config?.[`routeName${T}`]||`Route ${T+1}`;x.push({id:`route-${T}`,label:H})}x.push({id:"route-default",label:"Default"})}else f&&(x=[{id:"condition-true",label:"True"},{id:"condition-false",label:"False"}]);let G=k||f,te=i==="Merge",O;if(te){let $=Number(e.config?.inputCount)||2;O=[];for(let T=0;T<$;T++)O.push({id:`input-${T}`,label:`Input ${T+1}`})}return oo(Uo,{className:N("relative flex flex-col items-center justify-center shadow-none transition-all duration-150 ease-out",G||te?"min-h-48 w-48":"h-48 w-48",t&&"border-primary",I&&"opacity-50"),"data-testid":`action-node-${o}`,handles:{target:!te,source:!G,sourceHandles:x,targetHandles:O},status:l,children:[I&&Ae("div",{className:"absolute top-2 left-2 rounded-full bg-gray-500/50 p-1",children:Ae(Ic,{className:"size-3.5 text-white"})}),!I&&h&&Ae("div",{className:"absolute top-2 left-2 rounded-full bg-orange-500/50 p-1",children:Ae(Av,{className:"size-3.5 text-white"})}),Ae(zv,{status:l}),oo("div",{className:"flex flex-col items-center justify-center gap-3 p-6",children:[u?Ae(Vv,{base64:c.output.base64}):Fv(i),oo("div",{className:"flex flex-col items-center gap-1 text-center",children:[Ae(Ko,{className:"text-base",children:b}),y&&Ae(qo,{className:"text-xs",children:y}),D&&Ae(Bv,{model:D})]})]})]})});js.displayName="ActionNode";import{Plus as Gv}from"lucide-react";import{jsx as Bn,jsxs as Ca}from"react/jsx-runtime";function Rc({data:e}){return Ca("div",{className:"flex flex-col items-center justify-center gap-8 rounded-lg border border-border border-dashed bg-background/50 p-8 backdrop-blur-sm",children:[Ca("div",{className:"text-center",children:[Bn("h1",{className:"mb-2 font-bold text-3xl",children:"AI Workflow Builder Template"}),Ca("p",{className:"text-muted-foreground text-sm",children:["Powered by"," ",Bn("a",{className:"underline underline-offset-2 transition duration-200 ease-out hover:text-foreground",href:"https://useworkflow.dev/",rel:"noopener noreferrer",target:"_blank",children:"Workflow"}),","," ",Bn("a",{className:"underline underline-offset-2 transition duration-200 ease-out hover:text-foreground",href:"https://ai-sdk.dev/",rel:"noopener noreferrer",target:"_blank",children:"AI SDK"}),","," ",Bn("a",{className:"underline underline-offset-2 transition duration-200 ease-out hover:text-foreground",href:"https://vercel.com/ai-gateway",rel:"noopener noreferrer",target:"_blank",children:"AI Gateway"})," ","and"," ",Bn("a",{className:"underline underline-offset-2 transition duration-200 ease-out hover:text-foreground",href:"https://ai-sdk.dev/elements",rel:"noopener noreferrer",target:"_blank",children:"AI Elements"})]})]}),Ca(E,{className:"gap-2 shadow-lg",onClick:e.onClick,size:"default",children:[Bn(Gv,{className:"size-4"}),"Add a Step"]})]})}import{Check as $v,Clock as _v,Play as Uv,Webhook as Kv,XCircle as qv}from"lucide-react";import{memo as jv}from"react";import{jsx as pr,jsxs as Ta}from"react/jsx-runtime";var Js=jv(({data:e,selected:t})=>{if(!e)return null;let o=e.config?.triggerType||"Manual",n=e.label||o,r=e.description||"Trigger",s=e.status,a=Uv;return o==="Schedule"?a=_v:o==="Webhook"&&(a=Kv),Ta(Uo,{className:N("flex h-48 w-48 flex-col items-center justify-center shadow-none transition-all duration-150 ease-out",t&&"border-primary"),handles:{target:!1,source:!0},status:s,children:[s&&s!=="idle"&&s!=="running"&&Ta("div",{className:N("absolute top-2 right-2 rounded-full p-1",s==="success"&&"bg-green-500/50",s==="error"&&"bg-red-500/50"),children:[s==="success"&&pr($v,{className:"size-3.5 text-white",strokeWidth:2.5}),s==="error"&&pr(qv,{className:"size-3.5 text-white",strokeWidth:2.5})]}),Ta("div",{className:"flex flex-col items-center justify-center gap-3 p-6",children:[pr(a,{className:"size-12 text-blue-500",strokeWidth:1.5}),Ta("div",{className:"flex flex-col items-center gap-1 text-center",children:[pr(Ko,{className:"text-base",children:n}),r&&pr(qo,{className:"text-xs",children:r})]})]})]})});Js.displayName="TriggerNode";import{useAtomValue as Jv,useSetAtom as fr}from"jotai";import{Link2Off as Yv,Plus as Xv,Trash2 as Qv}from"lucide-react";import{nanoid as Zv}from"nanoid";import{useCallback as Hn,useEffect as eh,useRef as th}from"react";import{jsx as Vn,jsxs as Mc}from"react/jsx-runtime";function Oc({menuState:e,onClose:t}){let o=Jv(re),n=fr(lo),r=fr(co),s=fr(on),a=fr(Te),d=fr($t),{open:i}=oe(),l=th(null),c=Hn(()=>{if(e?.nodeId){let v=e.nodeId;t(),i(Ee,{title:"Delete Step",message:"Are you sure you want to delete this node? This action cannot be undone.",confirmLabel:"Delete",confirmVariant:"destructive",onConfirm:()=>{n(v)}})}},[e,n,t,i]),u=Hn(()=>{if(e?.edgeId){let v=e.edgeId;t(),i(Ee,{title:"Delete Connection",message:"Are you sure you want to delete this connection? This action cannot be undone.",confirmLabel:"Delete",confirmVariant:"destructive",onConfirm:()=>{r(v)}})}},[e,r,t,i]),g=Hn(()=>{if(e?.flowPosition){let p={id:Zv(),type:"action",position:{x:e.flowPosition.x,y:e.flowPosition.y-96},data:{label:"",description:"",type:"action",config:{},status:"idle"},selected:!0};s(p),a(p.id),d("properties")}t()},[e,s,a,d,t]);if(eh(()=>{if(!e)return;let v=w=>{l.current&&!l.current.contains(w.target)&&t()},p=w=>{w.key==="Escape"&&t()},m=setTimeout(()=>{document.addEventListener("mousedown",v),document.addEventListener("keydown",p)},0);return()=>{clearTimeout(m),document.removeEventListener("mousedown",v),document.removeEventListener("keydown",p)}},[e,t]),!e)return null;let b=!!(e.nodeId&&o.find(v=>v.id===e.nodeId)?.data.type==="trigger"),y=()=>e.nodeId&&o.find(p=>p.id===e.nodeId)?.data.label||"Step";return Mc("div",{className:"fade-in-0 zoom-in-95 fixed z-50 min-w-[8rem] animate-in overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md",ref:l,style:{left:e.position.x,top:e.position.y},children:[e.type==="node"&&Vn(Ys,{disabled:b,icon:Vn(Qv,{className:"size-4"}),label:`Delete ${y()}`,onClick:c,variant:"destructive"}),e.type==="edge"&&Vn(Ys,{icon:Vn(Yv,{className:"size-4"}),label:"Delete Connection",onClick:u,variant:"destructive"}),e.type==="pane"&&Vn(Ys,{icon:Vn(Xv,{className:"size-4"}),label:"Add Step",onClick:g})]})}function Ys({icon:e,label:t,onClick:o,variant:n="default",disabled:r}){return Mc("button",{className:N("relative flex w-full cursor-default select-none items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-none","hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground",n==="destructive"&&"text-destructive hover:bg-destructive/10 hover:text-destructive focus:bg-destructive/10 focus:text-destructive",r&&"pointer-events-none opacity-50"),disabled:r,onClick:o,type:"button",children:[e,t]})}function Lc(e,t){let o=Hn((s,a)=>{s.preventDefault(),t({type:"node",position:{x:s.clientX,y:s.clientY},nodeId:a.id})},[t]),n=Hn((s,a)=>{s.preventDefault(),t({type:"edge",position:{x:s.clientX,y:s.clientY},edgeId:a.id})},[t]),r=Hn(s=>{s.preventDefault();let a=e({x:s.clientX,y:s.clientY});t({type:"pane",position:{x:s.clientX,y:s.clientY},flowPosition:a})},[e,t]);return{onNodeContextMenu:o,onEdgeContextMenu:n,onPaneContextMenu:r}}import{jsx as jo,jsxs as Fc}from"react/jsx-runtime";var lh=[{type:"trigger",label:"",description:"",displayLabel:"Trigger",icon:sh,defaultConfig:{triggerType:"Manual"}},{type:"action",label:"",description:"",displayLabel:"Action",icon:ih,defaultConfig:{}}],dh={animated:_s.Animated,temporary:_s.Temporary};function zc(){let[e,t]=gr(re),[o,n]=gr(ue),[r]=gr(St),s=Xs(Ke),[a]=gr(kr),d=Xs(Cr),i=Xs(Tr),[l,c]=gr(Ar),u=No(yi),g=No(vi),b=No(Te),y=No(Ue),v=No(on),p=No(st),m=No(Ft),w=No($t),{screenToFlowPosition:h,fitView:S,getViewport:D,setViewport:I}=rh(),k=ko(null),f=ko(null),x=ko(null),G=ko(!1),te=ko(!1),[O,W]=Wc(!1),[$,T]=Wc(null),{onNodeContextMenu:H,onEdgeContextMenu:X,onPaneContextMenu:z}=Lc(h,T),j=Tt(()=>{T(null)},[]),A=ko(void 0),B=e.some(P=>P.type!=="add"),C=ko(!1),R=ko(!1);Sa(()=>{if(l&&!R.current){if(R.current=!0,document.cookie.split("; ").find(Ce=>Ce.startsWith("sidebar-collapsed="))?.split("=")[1]==="true")return;let Y=D(),pe=window.innerWidth*.3/2;I({...Y,x:Y.x-pe},{duration:0})}},[l,D,I]),Sa(()=>{if(A.current!==s){if(l&&te.current){A.current=s,W(!0),c(!1);return}setTimeout(()=>{S({maxZoom:1,minZoom:.5,padding:.2,duration:0}),A.current=s,te.current=!0,W(!0),c(!1)},0)}},[s,S,l,c]),Sa(()=>{s||(B&&!C.current?(C.current=!0,setTimeout(()=>{S({maxZoom:1,minZoom:.5,padding:.2,duration:0}),te.current=!0,W(!0)},0)):B||(C.current=!1))},[s,B,S]),Sa(()=>{let P=F=>{(F.metaKey||F.ctrlKey)&&F.key==="/"&&(F.preventDefault(),S({padding:.2,duration:300}))};return window.addEventListener("keydown",P),()=>{window.removeEventListener("keydown",P)}},[S]);let _=ah(()=>({trigger:Js,action:js,add:Rc}),[]),ne=Tt((P,F)=>{let Y=e.find(fe=>fe.id===P);return!Y||Y.type==="add"?!1:F==="target"?Y.type!=="trigger":!0},[e]),de=Tt(P=>!(!(P.source&&P.target)||P.source===P.target),[]),V=Tt(P=>{let F={id:Qs(),...P,type:"animated"};n([...o,F]),p(!0),m({immediate:!0})},[o,n,p,m]),Ie=Tt((P,F)=>{b(F.id)},[b]),nt=Tt((P,F)=>{k.current=F.nodeId,f.current=F.handleType,x.current=F.handleId},[]),Qe=Tt(P=>{let F="changedTouches"in P?P.changedTouches[0].clientX:P.clientX,Y="changedTouches"in P?P.changedTouches[0].clientY:P.clientY;return{clientX:F,clientY:Y}},[]),rt=Tt((P,F,Y)=>{let fe=P.target.closest(".react-flow")?.getBoundingClientRect(),pe=fe?F-fe.left:F,Ce=fe?Y-fe.top:Y;return{adjustedX:pe,adjustedY:Ce}},[]),Ht=Tt(P=>{let F=P.getAttribute("data-id"),Y=f.current==="source",fe=Y?"target":"source",pe=k.current;F&&pe&&F!==pe&&ne(F,fe)&&V({source:Y?pe:F,target:Y?F:pe,sourceHandle:Y?x.current:null,targetHandle:Y?null:x.current})},[ne,V]),Lt=Tt((P,F,Y)=>{let fe=k.current;if(!fe)return;let{adjustedX:pe,adjustedY:Ce}=rt(P,F,Y),mt=lh.find(Pa=>Pa.type==="action");if(!mt)return;let yr=h({x:pe,y:Ce}),Uc=192;yr.y-=Uc/2;let Gn={id:Qs(),type:mt.type,position:yr,data:{label:mt.label,description:mt.description,type:mt.type,config:mt.defaultConfig,status:"idle"},selected:!0};v(Gn),b(Gn.id),w("properties"),setTimeout(()=>{t(Pa=>Pa.map(Zs=>({...Zs,selected:Zs.id===Gn.id})))},50);let Ia=f.current==="source",Kc={id:Qs(),source:Ia?fe:Gn.id,target:Ia?Gn.id:fe,sourceHandle:Ia?x.current:null,type:"animated"};n([...o,Kc]),p(!0),m({immediate:!0}),G.current=!0,setTimeout(()=>{G.current=!1},100)},[rt,h,v,o,n,t,b,w,p,m]),To=Tt(P=>{if(!k.current)return;let{clientX:F,clientY:Y}=Qe(P),fe="changedTouches"in P?document.elementFromPoint(F,Y):P.target;if(!fe){k.current=null;return}let pe=fe.closest(".react-flow__node"),Ce=fe.closest(".react-flow__handle");if(pe&&!Ce&&f.current){Ht(pe),k.current=null,f.current=null;return}pe||Ce||Lt(P,F,Y),k.current=null,f.current=null},[Qe,Ht,Lt]),Z=Tt(()=>{G.current||(b(null),y(null),j())},[b,y,j]),ke=Tt(({nodes:P})=>{G.current&&P.length===0||(P.length===0?b(null):P.length===1&&b(P[0].id))},[b]);return Fc("div",{className:"relative h-full bg-background","data-testid":"workflow-canvas",style:{opacity:O?1:0,width:d?`calc(100% - ${d})`:"100%",transition:i?"width 300ms ease-out, opacity 300ms":"opacity 300ms"},children:[jo("div",{className:"pointer-events-auto",children:jo(wc,{workflowId:s??void 0})}),Fc(yd,{className:"bg-background",connectionLineComponent:hd,connectionMode:oh.Strict,edges:o,edgeTypes:dh,elementsSelectable:!r,isValidConnection:de,nodes:e,nodesConnectable:!r,nodesDraggable:!r,nodeTypes:_,onConnect:r?void 0:V,onConnectEnd:r?void 0:To,onConnectStart:r?void 0:nt,onEdgeContextMenu:r?void 0:X,onEdgesChange:r?void 0:g,onNodeClick:r?void 0:Ie,onNodeContextMenu:r?void 0:H,onNodesChange:r?void 0:u,onPaneClick:Z,onPaneContextMenu:r?void 0:z,onSelectionChange:r?void 0:ke,children:[jo(ca,{className:"workflow-controls-panel border-none bg-transparent p-0",position:"bottom-right",children:jo(bd,{})}),a&&jo(nh,{bgColor:"var(--sidebar)",nodeStrokeColor:"var(--border)"})]}),s&&jo(Nd,{workflowId:s}),jo(Oc,{menuState:$,onClose:j})]})}import{jsx as Bc}from"react/jsx-runtime";function Vc(){let e=ch();return e==="/"||e.startsWith("/workflows/")?Bc("div",{className:"fixed inset-0 z-0",children:Bc(zc,{})}):null}import{AuthUIProvider as uh}from"@daveyplate/better-auth-ui";import mh from"next/link";import{useRouter as ph}from"next/navigation";import{jsx as fh}from"react/jsx-runtime";var Hc=e=>{let t=ph(),{children:o,...n}=e;return fh(uh,{...n,authClient:Vo,navigate:t.push,replace:t.replace,onSessionChange:()=>{t.refresh()},Link:mh,children:o})};import{ThemeProvider as gh}from"next-themes";import{jsx as yh}from"react/jsx-runtime";var Gc=({children:e,...t})=>yh(gh,{...t,children:e});import{jsx as Co,jsxs as $c}from"react/jsx-runtime";function wh(e){al();let t=bh(en);return Aa.useEffect(()=>{e.canvas&&t(o=>({...o,...e.canvas}))},[e.canvas,t]),$c(Ri,{children:[Co(Aa.Suspense,{children:$c(vh,{children:[Co(Vc,{}),e.children]})}),Co(gd,{}),Co(fd,{})]})}var _c=e=>{let{children:t,canvas:o,...n}=e;return Co(Gc,{attribute:"class",defaultTheme:"system",disableTransitionOnChange:!0,enableSystem:!0,children:Co(Hc,{...n,children:Co(hh,{children:Co(wh,{canvas:o,children:t})})})})};import{jsx as Nh}from"react/jsx-runtime";var xh=e=>{let{children:t,canvas:o,...n}=e;return Nh(_c,{canvas:o,...n,children:t})};function kh(){return process.env.AI_GATEWAY_MANAGED_KEYS_ENABLED==="true"}function Ch(){return typeof window>"u"?process.env.AI_GATEWAY_MANAGED_KEYS_ENABLED==="true":process.env.NEXT_PUBLIC_AI_GATEWAY_MANAGED_KEYS_ENABLED==="true"}export{Oa as DashboardPage,xh as Layout,hs as WorkflowEditor,Uf as WorkflowPage,kh as isAiGatewayManagedKeysEnabled,Ch as isAiGatewayManagedKeysEnabledClient};