@membranehq/cli 0.10.4 → 0.10.6

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.
Files changed (2) hide show
  1. package/dist/index.js +1 -1
  2. package/package.json +2 -2
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- var Bi=Object.defineProperty;var c=(s,e)=>Bi(s,"name",{value:e,configurable:!0});import{jsx as m,jsxs as E,Fragment as Zt}from"react/jsx-runtime";import*as R from"node:path";import{resolve as Ui,dirname as qi,join as Ji}from"node:path";import{useInput as xe,Box as b,Text as S,Newline as Wi,render as mt}from"ink";import Gi from"minimist";import{SWRConfig as Vi}from"swr";import Pe,{createContext as ns,useState as F,useEffect as Ee,useContext as ss,useMemo as Hi,useRef as Yi}from"react";import is from"swr/immutable";import rs from"os";import B from"path";import zi from"conf";import{exec as Qi}from"node:child_process";import*as x from"node:fs";import{readFileSync as Xi}from"node:fs";import{EventEmitter as Zi}from"events";import{MembraneConfigLoader as er,MembraneClient as os,WorkspaceElementType as P,extractMembraneErrorData as te,WorkspaceElementSpecs as ye,setValueAtLocator as en,getDataCollectionCreateFields as tn,excludeWriteOnlyFieldsFromSchema as as,valueToSchema as gt,getRequiredFieldsFromSchema as tr,getValueAtLocator as nr,walkSchema as cs,makeDataLocationPath as ls,getDataCollectionUpdateFields as nn}from"@membranehq/sdk";import sn from"jsonwebtoken";import{Spinner as sr,TextInput as ir,Select as rr}from"@inkjs/ui";import yt from"ink-spinner";import or from"ink-text-input";import*as ar from"node:crypto";import{createHash as cr}from"node:crypto";import*as lr from"node:os";import M from"fs";import ur from"archiver";import fr from"form-data";import Ie from"js-yaml";import hr from"unzipper";import dr from"lodash/isEqual.js";import pr from"chokidar";import{fileURLToPath as mr}from"node:url";import k from"chalk";import{Command as gr}from"commander";import rn from"axios";import{FastMCP as yr}from"fastmcp";import{z}from"zod";import on from"lodash/merge.js";import wr from"@anthropic-ai/sdk";import{faker as Xe}from"@faker-js/faker";import br from"lodash/template.js";import Sr from"lodash/templateSettings.js";const J={LogAdded:"logAdded",StateChanged:"stateChanged",StatsChanged:"statsChanged",ConflictsChanged:"conflictsChanged",McpStatusChanged:"mcpStatusChanged",McpServersChanged:"mcpServersChanged",ConfigChanged:"configChanged"},D={NOT_INITIALIZED:"not_initialized",SETTING_UP:"setting_up",INITIALIZED:"initialized",NOT_SYNCED:"not_synced",PULLING:"pulling",PUSHING:"pushing",RESOLVING:"resolving",CONFLICTS:"conflicts",SYNCED:"synced",WATCHING:"watching",ERROR:"error"},us=ns(null);function Cr({children:s,membraneCLIService:e}){const{data:t}=is("/account"),[n,i]=F(D.NOT_INITIALIZED),[r,o]=F([]),[a,l]=F({}),[u,p]=F([]),[d,h]=F(null),w=t?.workspaces?.find(f=>f.workspaceKey===d?.workspaceKey)||null;return Ee(()=>{const f=c(({state:I})=>i(I),"handleStateChanged"),y=c(({stats:I})=>l(I),"handleStatsChanged"),C=c(({log:I})=>p(O=>[...O,I]),"handleLogAdded"),v=c(({conflicts:I})=>o(I),"handleConflictsUpdated"),A=c(({config:I})=>h(I),"handleConfigChanged");return e.notifications.on(J.StateChanged,f),e.notifications.on(J.StatsChanged,y),e.notifications.on(J.LogAdded,C),e.notifications.on(J.ConflictsChanged,v),e.notifications.on(J.ConfigChanged,A),e.init(),()=>{e.notifications.off(J.StateChanged,f),e.notifications.off(J.StatsChanged,y),e.notifications.off(J.LogAdded,C),e.notifications.off(J.ConflictsChanged,v),e.notifications.off(J.ConfigChanged,A)}},[]),m(us.Provider,{value:{state:n,stats:a,logs:u,currentWorkspace:w,conflicts:r,config:d,updateConfig:c(f=>e.updateConfig(f),"updateConfig"),resolveConflicts:c(f=>e.syncWorkspaces(f),"resolveConflicts"),pull:c(f=>e.pullWorkspace(f),"pull"),push:c(f=>e.pushWorkspace(f),"push"),exit:c(()=>e.shutdown(),"exit")},children:s})}c(Cr,"MembraneCLIServiceProvider");function oe(){const s=ss(us);if(!s)throw new Error("useMembraneCLIService must be used within MembraneCLIServiceProvider");return s}c(oe,"useMembraneCLIService");const kr="membrane",vr="membrane.config.yml",an="https://api.integration.app";function cn(){const s=process.cwd(),e=R.join(s,kr),t=R.join(s,vr),n=e,i=R.join(n,"workspace.yaml");return{membraneDirPath:e,configPath:t,payloadDirPath:n,workspaceDataFilePath:i}}c(cn,"getPaths");function Er(){return cn().membraneDirPath}c(Er,"getBasePath");const Ir={pat:{type:"string"},workspace:{type:"object"}},fs=new zi({schema:Ir,configName:"config",cwd:B.join(rs.homedir(),".membrane")}),Tr=c(s=>{fs.set("pat",s)},"setPat"),hs=c(()=>fs.get("pat"),"getPat");class ds{static{c(this,"AccountApiClient")}constructor(e=an){this.apiBaseUrl=e}async request(e,t={}){const n=t.headers?t.headers instanceof Headers?new Headers(t.headers):new Headers(t.headers):new Headers;if(!n.has("Authorization")){const o=hs();if(!o)throw new Error("Personal Access Token not found.");n.set("Authorization",`Bearer ${o}`)}t.body&&!n.has("Content-Type")&&n.set("Content-Type","application/json");const i=await fetch(`${this.apiBaseUrl}${e}`,{...t,headers:n});if(!i.ok){const o=await i.text();throw new Error(`API request failed: ${i.status} ${i.statusText} - ${o}`)}if(i.status===204)return{};const r=await i.text();return JSON.parse(r)}get(e){return this.request(e,{method:"GET"})}post(e,t){return this.request(e,{method:"POST",body:JSON.stringify(t)})}put(e,t){return this.request(e,{method:"PUT",body:JSON.stringify(t)})}patch(e,t){return this.request(e,{method:"PATCH",body:JSON.stringify(t)})}delete(e){return this.request(e,{method:"DELETE"})}}const Nr=c(s=>{const e=new ds(an);return t=>e.get(t)},"createAccountApiFetcher"),ps=ns(process.cwd());function Ar({cwd:s,children:e}){return m(ps.Provider,{value:s,children:e})}c(Ar,"CwdProvider");function Or(){return ss(ps)}c(Or,"useCwd");function wt({cwd:s,children:e,membraneCLIService:t}){const n=s||process.cwd();return m(Ar,{cwd:n,children:m(Vi,{value:{fetcher:Nr()},children:m(Cr,{membraneCLIService:t,children:e})})})}c(wt,"Layout");const ln=[{id:"claude-code",name:"Claude Code",description:"Anthropic Claude Code agent",actionDescription:"Adding membrane MCP to .mcp.json in the current directory",addConfig:c(()=>{const s=R.join(process.cwd(),".mcp.json"),e={mcpServers:{membrane:{command:"membrane",args:["mcp"],env:{AGENT_NAME:"Claude Code"}}}};let t={};if(x.existsSync(s))try{t=JSON.parse(x.readFileSync(s,"utf8"))}catch{t={}}const n={...t,mcpServers:{...t.mcpServers,...e.mcpServers}};return x.writeFileSync(s,JSON.stringify(n,null,2)),`MCP server configuration added to ${s}`},"addConfig")},{id:"cursor",name:"Cursor",description:"Cursor AI editor",actionDescription:"Adding membrane MCP to .cursor/mcp.json in the current directory",addConfig:c(()=>{const s=R.join(process.cwd(),".cursor"),e=R.join(s,"mcp.json");x.existsSync(s)||x.mkdirSync(s);const t={mcpServers:{membrane:{command:"membrane",args:["mcp"],env:{AGENT_NAME:"Cursor"}}}};let n={};if(x.existsSync(e))try{n=JSON.parse(x.readFileSync(e,"utf8"))}catch{n={}}const i={...n,mcpServers:{...n.mcpServers,...t.mcpServers}};return x.writeFileSync(e,JSON.stringify(i,null,2)),`MCP server configuration added to ${e}`},"addConfig")}];function $r({onExit:s,onComplete:e}){const[t,n]=F(0),[i,r]=F(!1),[o,a]=F(null),[l,u]=F(""),[p,d]=F("");xe((w,f)=>{if(l||p){(f.escape||w==="q"||f.return)&&e();return}if(i)f.return||w===" "?h(o):f.escape&&(r(!1),a(null));else if(f.escape)s();else if(f.upArrow||w==="k")n(Math.max(0,t-1));else if(f.downArrow||w==="j")n(Math.min(ln.length-1,t+1));else if(f.return||w===" "){const y=ln[t];a(y),r(!0)}});const h=c(w=>{try{const f=w.addConfig();u(f)}catch(f){d(`Failed to write configuration: ${f.message||f}`)}},"addMcpConfiguration"),g=Math.min(80,process.stdout.columns||80);return l?E(b,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:g,children:[m(b,{marginTop:-1,marginBottom:1,children:E(S,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",m(S,{color:"green",children:"Success"})]})}),E(b,{flexDirection:"column",paddingLeft:2,children:[m(S,{color:"green",children:l}),m(b,{marginTop:1,children:m(S,{color:"grey",children:"The agent will now be able to use Membrane's integration capabilities."})})]}),m(b,{marginTop:1,paddingLeft:2,children:m(S,{color:"white",children:"[esc/q/enter: exit]"})})]}):p?E(b,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:g,children:[m(b,{marginTop:-1,marginBottom:1,children:E(S,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",m(S,{color:"red",children:"Error"})]})}),m(b,{flexDirection:"column",paddingLeft:2,children:m(S,{color:"red",children:p})}),m(b,{marginTop:1,children:m(S,{color:"grey",children:"[esc/q/enter: exit]"})})]}):i&&o?E(b,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:g,children:[m(b,{marginTop:-1,marginBottom:1,children:E(S,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",m(S,{color:"cyan",children:"Confirmation"})]})}),E(b,{flexDirection:"column",paddingLeft:2,children:[E(S,{children:["Connect ",m(S,{bold:!0,children:o.name})," to Membrane via MCP?"]}),m(b,{marginTop:1,children:m(S,{color:"grey",children:"This will add an MCP server configuration that allows the agent to use Membrane's integration capabilities."})}),m(b,{marginTop:1,children:m(S,{color:"yellow",bold:!0,children:o.actionDescription})}),m(b,{marginTop:2,marginBottom:1,children:E(S,{children:[m(S,{color:"white",bold:!0,children:"[Enter] Confirm"})," ",m(S,{color:"gray",children:"[Esc] Cancel"})]})})]})]}):E(b,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:g,children:[m(b,{marginTop:-1,marginBottom:1,children:E(S,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",m(S,{color:"cyan",children:"Select Agent"})]})}),E(b,{flexDirection:"column",paddingLeft:2,children:[m(S,{color:"grey",children:"Choose an agent to connect to Membrane via MCP:"}),m(b,{marginTop:1,children:m(S,{color:"grey",children:"This will add an MCP server configuration that allows the agent to use Membrane's integration capabilities."})}),m(b,{marginTop:1,flexDirection:"column",children:ln.map((w,f)=>E(b,{children:[E(S,{color:t===f?"cyan":"white",children:[t===f?"\u25B6 ":" ",w.name]}),E(S,{color:"grey",children:[" \u2014 ",w.description]})]},w.id))})]}),m(b,{marginTop:1,children:m(S,{color:"grey",children:"[\u2191\u2193: select] [enter: choose] [esc: exit]"})})]})}c($r,"AddMcpServerScreen");class ms extends Zi{static{c(this,"TypedEventEmitter")}on(e,t){return super.on(e,t)}emit(e,...t){return super.emit(e,...t)}off(e,t){return super.off(e,t)}once(e,t){return super.once(e,t)}}class He{static{c(this,"ConfigLoader")}static instance=null;sdkLoader;constructor(){this.sdkLoader=new er}static getInstance(){return He.instance||(He.instance=new He),He.instance}loadConfig(e){e&&e!==this.sdkLoader.getCwd()&&this.sdkLoader.setCwd(e);try{return this.sdkLoader.loadConfig({validate:!0})}catch(t){if(t.message?.includes("Failed to parse"))throw t;return null}}clearCache(){this.sdkLoader.clearCache()}updateConfig(e){return this.sdkLoader.updateConfig(e)}isCacheDefined(e){return this.sdkLoader.hasValidConfig()}}const Ze=He.getInstance();function bt(s){return Ze.loadConfig(s)}c(bt,"readProjectConfig");class Lr{static{c(this,"MembraneClientManager")}client=null;currentConfig=null;tokenExpiry=0;async generateAccessToken(e,t){return sn.sign({name:"Membrane Agent",isAdmin:!0,exp:Math.floor(Date.now()/1e3)+3600,iss:e},t,{algorithm:"HS512"})}isTokenValid(){return Date.now()<this.tokenExpiry}getCurrentConfig(e){const t=bt(e);return!t?.workspaceKey||!t?.workspaceSecret?null:{workspaceKey:t.workspaceKey,workspaceSecret:t.workspaceSecret,apiUri:t.apiUri}}async createClient(e){const t=await this.generateAccessToken(e.workspaceKey,e.workspaceSecret);return this.tokenExpiry=Date.now()+36e5,this.currentConfig=e,new os({token:t,apiUri:e.apiUri})}async getClient(e=process.cwd()){const t=this.getCurrentConfig(e);if(!t)throw new Error("Unable to create MembraneClient: No workspace configuration found.");const n=!this.currentConfig||this.currentConfig.workspaceKey!==t.workspaceKey||this.currentConfig.workspaceSecret!==t.workspaceSecret||this.currentConfig.apiUri!==t.apiUri,i=!this.isTokenValid()||this.tokenExpiry-Date.now()<3e5;return(!this.client||n||i)&&(this.client=await this.createClient(t)),this.client}clearClient(){this.client=null,this.currentConfig=null,this.tokenExpiry=0}getCurrentConfigInfo(){return this.currentConfig}}const le=new Lr;async function gs(s){const e=await le.getClient(s);if(!e)throw new Error("No workspace configuration found");return(await e.get("org-workspace-id")).id}c(gs,"getWorkspaceId");class Dr extends ms{static{c(this,"WorkspaceNotifications")}constructor(e){super(),this.config=e}clientId;heartbeatInterval;isCleaningUp=!1;async connectToRemote(){await this.registerWithRemoteServer(),await this.startHeartbeatLoop()}async setState(e){this.emit(J.StateChanged,{state:e}),await this.emitRemote({status:e})}setConflicts(e){this.emit(J.ConflictsChanged,{conflicts:e})}setConfig(e){this.emit(J.ConfigChanged,{config:e})}setStats(e){this.emit(J.StatsChanged,{stats:e})}addLog(e){this.emit(J.LogAdded,{log:e})}setMcpStatus(e){this.emit(J.McpStatusChanged,{status:e})}async setMcpServers(e){this.emit(J.McpServersChanged,{servers:e}),await this.emitRemote({mcpServers:e.map(t=>({name:t.agentName,totalRequests:t.totalRequests}))})}async cleanup(){if(!(!this.clientId||this.isCleaningUp)){this.isCleaningUp=!0,this.heartbeatInterval&&(clearInterval(this.heartbeatInterval),this.heartbeatInterval=void 0);try{await(await le.getClient(process.cwd())).delete(`/local-clients/${this.clientId}`)}catch{}this.clientId=void 0}}async registerWithRemoteServer(){if(this.clientId)return;const t=await(await le.getClient(process.cwd())).post("/local-clients",{hostname:rs.hostname(),workingDirectory:process.cwd()});this.clientId=t.id}async startHeartbeatLoop(){this.heartbeatInterval=setInterval(async()=>{this.clientId&&await this.sendHeartbeat()},this.config.heartbeatIntervalMs)}async sendHeartbeat(){if(!this.clientId)return;await(await le.getClient(process.cwd())).post(`/local-clients/${this.clientId}/keep-alive`,{})}async emitRemote(e){if(!this.clientId)return;await(await le.getClient(process.cwd())).patch(`/local-clients/${this.clientId}`,e)}}const ue=new Dr({heartbeatIntervalMs:15e3});function xr(){const[s,e]=F(null),[t,n]=F([]),[i,r]=F(null);return Ee(()=>{const o=c(({status:l})=>{e(l),r(null)},"handleMcpStatusChanged"),a=c(({servers:l})=>{n(l),r(null)},"handleMcpServersChanged");return ue.on(J.McpStatusChanged,o),ue.on(J.McpServersChanged,a),()=>{ue.off(J.McpStatusChanged,o),ue.off(J.McpServersChanged,a)}},[]),{mcpStatus:s,allMcpServers:t,error:i,isRunning:s?.isRunning||!1,toolsCount:s?.toolsCount||0,totalRequests:s?.totalRequests||0,lastActivity:s?.lastActivity,processId:s?.processId,serverCount:t.length}}c(xr,"useMcpStatus");function Pr(){const{error:s,serverCount:e,allMcpServers:t}=xr(),n=Math.min(100,process.stdout.columns||100);return E(b,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:n,children:[m(b,{marginTop:-1,marginBottom:0,flexDirection:"column",children:E(S,{bold:!0,children:["\u{1F916} Connected AI Agents:"," ",s?m(S,{color:"red",children:"error reading status"}):e===0?m(S,{color:"yellow",children:"none"}):m(S,{color:"green",children:e})]})}),!s&&e===0&&m(b,{marginTop:1,children:E(S,{color:"grey",children:["Connect your AI agents to Membrane.",m(Wi,{}),"It will give them tools and context to build integrations."]})}),t.length>0&&m(b,{flexDirection:"column",paddingLeft:2,marginTop:1,children:t.map((i,r)=>m(b,{children:E(S,{color:"grey",children:["#",r+1," ",i.agentName,": ",i.totalRequests," calls"]})},i.processId))}),m(b,{marginTop:1,children:m(S,{color:"grey",children:"[a: connect an agent]"})})]})}c(Pr,"Agent");const St=c(s=>{switch(s){case"error":return"red";case"success":return"green";case"warning":return"yellow";default:return}},"getLogColor");function ys(s,e){return e<3?s.slice(0,Math.max(0,e)):s.length<=e?s:`${s.slice(0,e-3)}...`}c(ys,"truncateText");function un({children:s}){const{state:e,logs:t}=oe();if(!e||e===D.NOT_INITIALIZED)return E(b,{gap:1,flexDirection:"row",children:[m(sr,{type:"dots"}),m(S,{children:"Initializing..."})]});if(e===D.SETTING_UP)return m(b,{gap:1,flexDirection:"row",children:m(S,{children:"No workspace selected. Please run `membrane init` to select a workspace."})});if(e===D.ERROR){const n=t.filter(i=>i.type==="error");return m(b,{gap:1,flexDirection:"row",children:n.slice().map((i,r)=>m(S,{color:St(i.type),children:i.message},i.timestamp+r))})}return s}c(un,"EnsureInitialized");function ws({onExit:s,showEscOption:e=!0}){const[t,n]=F(""),{data:i,error:r,isLoading:o}=is("/account"),{updateConfig:a}=oe(),l=i?.workspaces,u=o;if(xe((f,y)=>{y.escape&&s?.()}),u)return E(b,{children:[m(yt,{}),m(S,{children:" Fetching workspaces..."})]});if(r)return E(b,{flexDirection:"column",children:[E(S,{color:"red",children:["Error: ",r.message]}),m(b,{marginTop:1,children:m(S,{color:"grey",children:"Press ESC to go back"})})]});const p=l?.filter(f=>f.name.toLowerCase().includes(t.toLowerCase()))??[],d=p.map(f=>({label:f.name,value:f.id})),h=d.length,g=l?.length??0;async function w(f){const y=p.find(A=>A.id===f);if(!y)return;const{key:C,secret:v}=y;!C||!v||(await a({workspaceKey:C,workspaceSecret:v}),s?.())}return c(w,"handleSelect"),E(b,{flexDirection:"column",borderStyle:"round",borderTop:!0,width:70,paddingX:1,children:[m(b,{marginTop:-1,children:m(S,{bold:!0,children:"\u{1F4C1} Select your workspace"})}),E(b,{marginTop:1,children:[m(S,{children:"Search: "}),m(ir,{placeholder:"Enter a search query...",onChange:n})]}),g>5&&E(S,{children:["Showing ",h," of ",g," workspaces."]}),m(b,{marginTop:1,children:m(rr,{options:d,onChange:c(f=>{f&&w(f)},"onChange")})}),e&&m(b,{marginTop:1,children:m(S,{color:"grey",children:"Press ESC to go back"})})]})}c(ws,"SelectWorkspace");function Mr({currentPat:s,onSubmit:e}){const[t,n]=F(""),[i,r]=F(!1),[o,a]=F(null);return E(b,{flexDirection:"column",borderStyle:"round",borderTop:!0,width:70,paddingX:1,children:[m(b,{marginTop:-1,marginBottom:1,children:m(S,{bold:!0,children:"\u{1F511} Enter your Personal Access Token"})}),m(S,{children:"Please provide your Personal Access Token. You can find it here:"}),m(b,{marginTop:1,marginBottom:1,children:m(S,{color:"yellow",children:"https://console.integration.app/w/0/manage-account/api-token"})}),s&&m(S,{dimColor:!0,children:"Press Enter to keep your current token or type a new one."}),m(or,{mask:"*",placeholder:`${s?"******":"Enter your token here..."}`,value:t,onChange:n,onSubmit:c(async u=>{a(null),r(!0);try{await e(u),n("")}catch{a("Invalid token. Please try again.")}finally{r(!1)}},"handleSubmit")}),i&&m(b,{marginTop:1,children:E(S,{children:[m(yt,{type:"dots"})," Validating token..."]})}),o&&m(S,{color:"red",children:o})]})}c(Mr,"PersonalAccessTokenInput");var et=(s=>(s[s.Authenticate=0]="Authenticate",s[s.ConnectWorkspace=1]="ConnectWorkspace",s))(et||{});const Rr={0:"Authenticate in Membrane",1:"Connect a Membrane Workspace"},fn=[et.Authenticate,et.ConnectWorkspace];function bs({onComplete:s}){const{config:e}=oe(),[t,n]=F(!1),[i,r]=F(0),o=!!(e?.workspaceKey&&e?.workspaceSecret),a=hs(),l=fn[i],u=i+1,p=fn.length,d=fn.map((w,f)=>{let y="pending";return f<i?y="done":f===i&&(y="current"),{id:w,label:Rr[w],status:y}});async function h(w){const f=a&&w===""?a:w,y=new ds;try{await y.request("/account",{headers:{Authorization:`Bearer ${f}`}}),Tr(f),r(C=>C+1)}catch(C){console.error(C)}}c(h,"handlePatSubmit");function g(){n(!0),s&&s()}return c(g,"handleWorkspaceSelected"),xe((w,f)=>{o&&f.escape&&s&&s()}),t?m(b,{children:m(S,{children:"\u2705 Setup complete. You are ready to go!"})}):E(b,{flexDirection:"column",alignSelf:"flex-start",gap:1,children:[E(b,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:70,children:[m(b,{marginTop:-1,marginBottom:1,children:E(S,{bold:!0,children:["\u{1F6E0}\uFE0F Setup \u2014"," ",E(S,{color:"cyan",children:["Step ",u," of ",p]}),o&&m(S,{color:"grey",children:" [esc: go back]"})]})}),m(b,{flexDirection:"column",paddingLeft:2,children:d.map(w=>m(Kr,{status:w.status,label:w.label},w.id))})]}),l===et.Authenticate&&m(Mr,{currentPat:a,onSubmit:h}),l===et.ConnectWorkspace&&m(ws,{onExit:g,showEscOption:!1})]})}c(bs,"Setup");function Kr({status:s,label:e}){return E(b,{children:[E(b,{width:2,children:[s==="current"&&m(yt,{type:"dots"}),s==="done"&&m(S,{children:"\u2705"})]}),m(S,{dimColor:s!=="current",children:e})]})}c(Kr,"StepDisplay");function hn(){const{stats:s}=oe(),e=Object.entries(s).filter(([t,n])=>n>0);return e.length===0?null:E(b,{flexDirection:"column",children:[m(b,{children:m(b,{width:12,children:m(S,{color:"grey",children:"Elements:"})})}),m(b,{flexDirection:"column",marginLeft:1,children:e.map(([t,n])=>E(b,{children:[m(b,{width:20,children:E(S,{children:[t,":"]})}),m(S,{color:"green",children:n})]},t))})]})}c(hn,"ElementStats");const dn=5,_r=6;function jr(){const{logs:s}=oe(),[e,t]=F(0),n=Math.min(100,process.stdout.columns||100),i=dn,r=Math.max(0,s.length-i-e),o=s.length-e,a=s.slice(r,o),l=n-_r,u=e<s.length-i,p=e>0;return xe((d,h)=>{if(s.length!==0)if(h.upArrow){const g=Math.max(0,s.length-i);t(w=>Math.min(g,w+1))}else h.downArrow?t(g=>Math.max(0,g-1)):(d==="G"||d==="g")&&t(0)}),E(b,{flexDirection:"column",paddingTop:1,children:[E(S,{color:"grey",children:["Recent Activity (",r+1,"-",o," of ",s.length,"):",s.length>dn&&m(S,{color:"grey",children:" [arrows: scroll] [g: end]"})]}),a.map((d,h)=>m(b,{marginLeft:1,children:m(S,{color:St(d.type),children:ys(d.message,l)})},d.timestamp+h)),s.length>dn&&E(b,{marginLeft:1,flexDirection:"row",children:[u&&m(S,{color:"grey",children:"\u2191 "}),p&&m(S,{color:"grey",children:"\u2193 "})]})]})}c(jr,"Logs");const X={UPDATE:"update",DELETE:"delete",CREATE:"create"},fe={INCOMING:"incoming",OUTGOING:"outgoing"},Ct=[{value:"sync",label:"Continue (overwrite/delete)",key:""},{value:"exit",label:"Cancel",key:""}];function Fr(){const{state:s,resolveConflicts:e,exit:t}=oe(),[n,i]=F(0),[r,o]=F(!1);return xe((a,l)=>{r||(l.upArrow?i(u=>u>0?u-1:Ct.length-1):l.downArrow?i(u=>u<Ct.length-1?u+1:0):a.toLowerCase()==="y"?i(0):a.toLowerCase()==="n"?i(1):(l.return||a===" ")&&(o(!0),Ct[n].value==="sync"?e({watch:!0}):t()))}),Ee(()=>{s!==D.CONFLICTS&&r&&o(!1)},[s,r]),E(b,{flexDirection:"column",paddingTop:1,children:[m(b,{children:m(b,{flexDirection:"row",gap:2,children:m(S,{bold:!0,color:"white",children:"Conflicts with remote"})})}),m(b,{children:m(S,{color:"grey",children:"The remote workspace has changes that aren't in your local workspace:"})}),m(b,{marginTop:1,marginLeft:2,children:m(pn,{})}),E(b,{marginTop:2,flexDirection:"row",gap:1,children:[m(S,{color:"white",bold:!0,children:"What would you like to do?"}),m(S,{color:"grey",children:"[up/down, enter]"})]}),m(b,{children:r?E(b,{flexDirection:"row",gap:1,children:[m(yt,{type:"dots"}),m(S,{color:"blue",bold:!0,children:"Syncing with remote..."})]}):m(b,{flexDirection:"column",children:Ct.map((a,l)=>m(b,{flexDirection:"column",children:E(b,{flexDirection:"row",gap:1,children:[m(S,{color:n===l?"cyan":"grey",children:n===l?"\u25B6":" "}),m(S,{color:n===l?"cyan":"grey",bold:n===l,children:a.label})]})},a.value))})})]})}c(Fr,"ResolveChangesUI");const Br={[X.UPDATE]:{incoming:{label:"Elements updated in remote",description:"(to be overwritten from remote)"},outgoing:{label:"Elements updated locally",description:"(to be pushed to remote)"}},[X.DELETE]:{incoming:{label:"Elements not existing in remote",description:"(to be deleted locally)"},outgoing:{label:"Elements deleted locally",description:"(to be deleted from remote)"}},[X.CREATE]:{incoming:{label:"Elements created in remote",description:"(to be created locally)"},outgoing:{label:"Elements created locally",description:"(to be created in remote)"}}};function pn(){const{conflicts:s}=oe(),e=Hi(()=>{const t={};return s.forEach(n=>{const i=`${n.type}-${n.direction}`;t[i]||(t[i]=[]),t[i].push(n)}),t},[s]);return m(b,{flexDirection:"column",children:Object.entries(e).map(([t,n])=>{if(n.length===0)return null;const[i,r]=t.split("-"),o=Br[i][r];return E(b,{flexDirection:"column",children:[E(b,{flexDirection:"row",gap:1,children:[E(S,{color:"yellow",children:[o.label," (",n.length,")"]}),m(S,{color:"white",children:o.description})]}),n.map(a=>m(b,{marginLeft:2,children:E(S,{color:"grey",children:["\u2022 ",a.element.id," (",a.element.relativePath,")"]})},a.element.id))]},t)})})}c(pn,"Conflicts");function Ur(){const{config:s,state:e,logs:t,currentWorkspace:n,pull:i}=oe(),r=n?.name,o=r?ys(r,30):s?.workspaceKey,a=Math.min(100,process.stdout.columns||100);return Ee(()=>{i({watch:!0})},[]),E(b,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:a,children:[m(b,{marginTop:-1,marginBottom:1,children:E(b,{flexDirection:"row",gap:1,children:[m(S,{bold:!0,children:"\u{1F504} Workspace"}),E(S,{color:Jr(e),children:[" [",qr(e),"] "]})]})}),E(b,{children:[m(b,{width:12,children:m(S,{color:"grey",children:"Local:"})}),m(S,{color:"grey",children:process.cwd()})]}),E(b,{children:[m(b,{width:12,children:m(S,{color:"grey",children:"Remote:"})}),s?.workspaceKey?E(S,{color:"grey",children:[o," [o: open in console] [w: change]"]}):E(S,{children:[m(S,{color:"yellow",children:"not selected"})," [w: select]"]})]}),e===D.CONFLICTS?m(Fr,{}):E(Zt,{children:[m(b,{paddingTop:1,children:m(hn,{})}),t.length>0&&m(jr,{})]})]})}c(Ur,"Workspace");function qr(s){switch(s){case D.PULLING:return"pulling";case D.PUSHING:return"pushing";case D.CONFLICTS:return"conflicts";case D.SYNCED:return"synced";case D.ERROR:return"error";case D.WATCHING:return"tracking changes";case D.RESOLVING:return"resolving";case D.NOT_SYNCED:return"not synced";case D.INITIALIZED:return"initialized";case D.SETTING_UP:return"setup required";default:return"unknown"}}c(qr,"getStatusDisplay");function Jr(s){switch(s){case D.PULLING:return"yellow";case D.PUSHING:return"yellow";case D.CONFLICTS:return"red";case D.SYNCED:return"green";case D.ERROR:return"red";case D.WATCHING:return"green";case D.RESOLVING:return"yellow";case D.NOT_SYNCED:return"grey";case D.SETTING_UP:return"yellow";default:return"grey"}}c(Jr,"getStatusColor");const Wr="https://console.integration.app/w";function Gr(){const s=Or(),e=Yi(!0),{exit:t,state:n}=oe(),[i,r]=F(null),o=i??(n===D.SETTING_UP?"setup":"main");xe(l=>{o==="main"&&(l==="w"&&r("workspace-selection"),l==="a"&&r("add-mcp-server"),l==="o"&&n===D.INITIALIZED&&a(),l==="s"&&r("setup"))});async function a(){try{const l=await gs(s),u=`${Wr}/${l}`,p=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";Qi(`${p} "${u}"`)}catch(l){console.error("Failed to open workspace:",l),t()}}return c(a,"handleOpenWorkspace"),Ee(()=>(e.current=!0,()=>{e.current=!1}),[]),o==="workspace-selection"?m(ws,{onExit:c(()=>r(null),"onExit")}):o==="add-mcp-server"?m($r,{onExit:c(()=>r(null),"onExit"),onComplete:c(()=>r(null),"onComplete")}):o==="setup"?m(bs,{onComplete:c(()=>r(null),"onComplete")},Date.now()):m(un,{children:E(b,{flexDirection:"column",children:[m(b,{flexGrow:1,children:m(Pr,{})}),m(Ur,{}),m(b,{paddingLeft:2,children:m(S,{color:"grey",children:"[s: (re-)setup]"})})]})})}c(Gr,"Main");class Vr{static{c(this,"WorkspaceLogger")}_logs;workspaceNotifications;constructor(){this._logs=[],this.workspaceNotifications=ue}get logs(){return[...this._logs]}get latestLogs(){return this._logs.slice(this._logs.length-5)}log(e,t="info"){const n={timestamp:new Date().toISOString(),message:e,type:t};this._logs.push(n),this._logs=this._logs.slice(0,1e3),this.workspaceNotifications.addLog(n)}info(e){this.log(e,"info")}success(e){this.log(e,"success")}warning(e){this.log(e,"warning")}error(e){this.log(e,"error")}clear(){this._logs=[]}}const T=new Vr,we=R.join(lr.tmpdir(),"membrane-mcp-status"),Ss=3e4;class Hr{static{c(this,"McpStatusService")}constructor(e=2e3){this.pollIntervalMs=e}isRunning=!1;pollInterval;async start(){this.isRunning||(this.isRunning=!0,this.pollInterval=setInterval(async()=>await this.checkStatus(),this.pollIntervalMs),await this.checkStatus())}async stop(){this.pollInterval&&(clearInterval(this.pollInterval),this.pollInterval=void 0,this.isRunning=!1)}async checkStatus(){try{const e=process.cwd(),t=kt(void 0,e),n=Cs(e);t&&ue.setMcpStatus(t),await ue.setMcpServers(n)}catch{T.error("Failed to check MCP status")}}}function kt(s,e){try{const t=e||process.cwd();if(!s){const i=Cs(t);return i.length===0?null:i[0]}const n=yn(s,t);if(x.existsSync(n)){const i=x.statSync(n),r=new Date;if(r.getTime()-i.mtime.getTime()>Ss)return tt(s,t),null;const a=x.readFileSync(n,"utf8"),l=JSON.parse(a);if(l.isRunning){const u=new Date(l.lastActivity).getTime();if(r.getTime()-u>Ss)return tt(s,t),null}return l}}catch{s&&e&&tt(s,e)}return null}c(kt,"getMcpStatus");function Cs(s){try{const e=s||process.cwd(),t=gn(e);if(!x.existsSync(we))return[];const n=x.readdirSync(we),i=[];for(const r of n){const o=r.match(new RegExp(`^mcp-${t}-(\\d+)\\.json$`));if(o){const a=parseInt(o[1],10),l=kt(a,e);l&&i.push(l)}}return i.sort((r,o)=>new Date(o.startTime).getTime()-new Date(r.startTime).getTime())}catch{return[]}}c(Cs,"getAllMcpStatusFiles");function mn(s){try{const t={...kt(s.processId,s.cwd)||{isRunning:!1,startTime:new Date().toISOString(),lastActivity:new Date().toISOString(),toolsCount:0,totalRequests:0,processId:s.processId,cwd:s.cwd,agentName:process.env.AGENT_NAME||"Unnamed Agent"},...s};x.existsSync(we)||x.mkdirSync(we,{recursive:!0});const n=yn(s.processId,s.cwd);x.writeFileSync(n,JSON.stringify(t,null,2))}catch{}}c(mn,"updateMcpStatus");function tt(s,e){try{const t=e||process.cwd();if(s){const n=yn(s,t);x.existsSync(n)&&x.unlinkSync(n)}else{const n=gn(t);if(x.existsSync(we)){const i=x.readdirSync(we);for(const r of i)r.match(new RegExp(`^mcp-${n}-\\d+\\.json$`))&&x.unlinkSync(R.join(we,r))}}}catch{}}c(tt,"clearMcpStatus");function Yr(s,e){const t=kt(s,e);t&&mn({processId:s,cwd:e,totalRequests:t.totalRequests+1,lastRequestTime:new Date().toISOString(),lastActivity:new Date().toISOString()})}c(Yr,"trackToolExecution");function gn(s){return cr("md5").update(s).digest("hex").slice(0,8)}c(gn,"getCwdHash");function yn(s,e){const t=gn(e);return R.join(we,`mcp-${t}-${s}.json`)}c(yn,"getStatusFilePath");const se={[P.Integration]:{element:"integration",elements:"integrations",exportable:!1,exportCleanup:c(s=>({id:s.id,key:s.key,name:s.name,connectorId:s.connectorId,baseUri:s.baseUri,connectorVersion:s.connectorVersion}),"exportCleanup")},[P.Connector]:{element:"connector",elements:"connectors",exportable:!1},[P.Action]:{element:"action",elements:"actions",integrationSpecific:!0,exportCleanup:c(s=>(delete s.integration,s),"exportCleanup")},[P.AppDataSchema]:{element:"appDataSchema",elements:"appDataSchemas"},[P.AppEventType]:{element:"appEventType",elements:"appEventTypes"},[P.DataLinkTable]:{element:"dataLinkTable",elements:"dataLinkTables"},[P.DataSource]:{element:"dataSource",elements:"dataSources",parentKey:"universalDataSourceId",integrationSpecific:!0},[P.FieldMapping]:{element:"fieldMapping",elements:"fieldMappings",integrationSpecific:!0,parentKey:"universalFieldMappingId",exportCleanup:c(s=>(delete s.dataSourceId,s),"exportCleanup")},[P.Flow]:{element:"flow",elements:"flows",integrationSpecific:!0,parentKey:"universalFlowId"}};function zr(s){return delete s.workspaceId,delete s.createdAt,delete s.updatedAt,delete s.revision,delete s.parentRevision,Object.keys(s).map(e=>{e.match(/universal.*Revision/g)&&delete s[e]}),s}c(zr,"baseExportCleanup");class ks{static{c(this,"ElementsCache")}elements=new Map;typeIndex=new Map;constructor(e){e&&this.addAll(e)}add(e){const t=e.id;this.elements.set(t,e),this.typeIndex.has(e.type)||this.typeIndex.set(e.type,new Set),this.typeIndex.get(e.type).add(t)}remove(e){const t=e.id,n=this.elements.delete(t);if(n){const i=this.typeIndex.get(e.type);i&&(i.delete(t),i.size===0&&this.typeIndex.delete(e.type))}return n}put(e){this.elements.has(e.id)&&this.remove(e),this.add(e)}get(e){return this.elements.get(e)}getElementsByType(e){const t=this.typeIndex.get(e);return t?Array.from(t).map(n=>this.elements.get(n)).filter(n=>n!==void 0):[]}getAll(){return Array.from(this.elements.values())??[]}getTypes(){return Array.from(this.typeIndex.keys())}addAll(e){for(const t of e)t&&this.add(t)}removeAll(e){for(const t of e)this.remove(t)}getElementIdsByType(e){return this.typeIndex.get(e)}clear(){this.elements.clear(),this.typeIndex.clear()}getAllIds(){return new Set(this.elements.keys())}}class vs{static{c(this,"ElementsManager")}cache;handler;connectorsMapping;constructor(e){this.cache=new ks,this.handler=e}async refresh(){try{const e=new ks,t=await this.handler.getIntegrations();e.addAll(t);const n=[P.Integration,P.Connector],i=Object.keys(se),r=await Promise.all(i.filter(o=>!n.includes(o)).map(async o=>this.handler.getElementsByType(o,t)));for(const o of r)e.addAll(o);this.cache.clear(),this.cache.addAll(e.getAll())}catch(e){throw T.error(`Failed to refresh elements: ${te(e)?.message??"Unknown error"}`),e}}async putElement(e){let t,n=this.cache.get(e.id);try{e.data.id&&n?(t="update",n=await this.handler.updateElement(e,n,{elements:this.cache.getAll(),connectorsMapping:this.connectorsMapping})):(t="create",n=await this.handler.createElement(e,{elements:this.cache.getAll(),connectorsMapping:this.connectorsMapping})),this.cache.put(n)}catch(i){T.error(`Failed to ${t} element ${e.type}/${e.key} ${e.integrationKey?`for integration ${e.integrationKey}`:""} (${e.id}): ${i instanceof Error?i.message:"Unknown error"}`)}}async deleteElement(e){try{await this.handler.deleteElement(e,{elements:this.cache.getAll(),connectorsMapping:this.connectorsMapping}),this.cache.remove(e)}catch(t){T.error(`Failed to delete element: ${t instanceof Error?t.message:"Unknown error"}`)}}setConnectorsMapping(e){this.connectorsMapping=e}}async function Qr(s,e="full"){const t={};T.info("[connectors] Getting remote workspace data");const n=await s.integrations.findAll();t.integration=n.map(i=>wn("integration",i));for(const i of Object.keys(se)){const r=se[i];if(r.exportable===!1)continue;const o=[];T.info(`[connectors] Reading ${r.elements} from remote workspace`);const a=await s[r.elements].findAll();if(o.push(...a.map(l=>wn(i,l))),r.integrationSpecific)for(const l of n){const u=await s[r.elements].findAll({integrationId:l.id});o.push(...u.map(p=>(p.integrationKey=l.key,wn(i,p))))}o.length>0&&e=="full"&&(console.table(o.map(l=>({key:l.key,integrationKey:l.integrationKey,universal:!l.integrationKey})).reduce((l,u)=>(l||(l={}),l[u.key]||(l[u.key]={}),u.universal&&(l[u.key].universal=!0),u.integrationKey&&(l[u.key].integration?l[u.key].integration+=` ${u.integrationKey}`:l[u.key].integration=u.integrationKey),l),{})),console.groupEnd()),t[i]=o}return T.success("[connectors] Remote workspace data retrieved successfully"),t}c(Qr,"getWorkspaceData");function wn(s,e){return e=zr(e),se[s].exportCleanup?se[s].exportCleanup(e):e}c(wn,"cleanUpForExport");const nt="connectors",st="development",bn={};async function Xr({integrations:s,allConnectors:e=!1}){const t=Er(),n=await le.getClient(process.cwd()),i=new Set,r={};for(const o of s){const a=o.connectorId,l=o.connectorVersion;if(!r[a]?.has(o.connectorVersion)){const u=await Es({client:n,connectorId:a}),d=!!u.workspaceId||e;if(!u?.key){T.error(`[connectors] Connector ${a} has no key. Skipping..`);continue}d&&(i.has(a)||(await so({basePath:t,connector:u}),i.add(a)),r[a]||(r[a]=new Set),r[a].has(l)||(await io({client:n,connector:u,connectorVersion:l,basePath:t}),r[a].add(l)))}}}c(Xr,"pullConnectors");async function Zr(){const s=await le.getClient(process.cwd()),e=await Qr(s,"minified"),n=(await s.get("org-workspace-id")).id,i={};T.info("[connectors] Loading custom connectors");const r=s,o=await r.get(`/connectors?workspaceId=${n}`);T.info("[connectors] Loading public connectors"),e.connector=o;const a=Sn(),u=(M.existsSync(a)?M.readdirSync(a):[]).filter(p=>{if(p.startsWith("."))return!1;const d=B.join(a,p);try{return M.statSync(d).isDirectory()}catch{return!1}});for(const p of u){T.info(`[connectors] Loading connector from: ${p}`);const d=M.readdirSync(B.join(a,p)),h=await Cn(p);if("baseUri"in h&&delete h.baseUri,h.uuid&&e.connector?.find(w=>w.uuid==h.uuid))i[h.id]=e.connector.find(w=>w.uuid==h.uuid).id,T.info(`[connectors] Matched ${h.name} uuid: ${h.uuid}`);else if(!i[h.id]){let w=!1;try{const f=await Es({client:s,connectorId:h.id});f&&!f.workspaceId&&(w=!0)}catch{}if(!w){T.info(`[connectors] Creating custom connector ${h.name} (${h.key})`);const f=await r.post("connectors",{...h,workspaceId:n});i[h.id]=f.id}}const g=d.filter(w=>M.statSync(B.join(a,p,w)).isDirectory());for(const w of g)await no({client:s,connector:h,version:w,connectorId:i[h.id]})}return i}c(Zr,"pushConnectors");function Sn(){const s=cn();return B.join(s.membraneDirPath,nt)}c(Sn,"getConnectorsPath");async function Cn(s){return Ie.load(M.readFileSync(B.join(Sn(),s,`${s}.yml`),"utf8"))}c(Cn,"readConnector");async function eo(s,e){return T.info(`[connectors] Zipping ${s} into ${e}`),new Promise((t,n)=>{const i=M.createWriteStream(e),r=ur("zip",{zlib:{level:9}});i.on("close",()=>{T.success(`[connectors] Successfully created ${e}`),t()}),i.on("end",()=>{T.info("[connectors] Data has been drained")}),r.on("warning",a=>{a.code==="ENOENT"?console.warn(a):n(a)}),r.on("error",a=>{n(a)}),r.pipe(i);const o=M.readdirSync(s);for(const a of o){const l=B.join(s,a),u=M.statSync(l);u.isFile()?r.file(l,{name:a}):u.isDirectory()&&r.directory(l,a)}r.finalize()})}c(eo,"createZipArchive");async function to(s,e){return T.info(`[connectors] Unzipping into ${e}`),new Promise((t,n)=>{const i=hr.Parse();i.on("entry",r=>{const o=r.path;if(r.type==="Directory"){const l=B.join(e,o);M.mkdirSync(l,{recursive:!0}),r.autodrain()}else{const l=B.join(e,o),u=B.dirname(l);M.mkdirSync(u,{recursive:!0});const p=M.createWriteStream(l);r.pipe(p),p.on("finish",()=>{})}}),i.on("end",()=>{T.success(`[connectors] Successfully extracted to ${e}`),t()}),i.on("error",r=>{n(r)}),i.write(s),i.end()})}c(to,"extractZipArchive");async function no({client:s,connector:e,version:t,connectorId:n}){const i=B.join(Sn(),vt(e),Is(t)),r=B.join(i,"src"),o=B.join(i,"src.zip"),a=M.existsSync(o);if(M.existsSync(r)&&(T.info(`[connectors] Archiving source code for ${e.name} version ${t}`),await eo(r,o)),!M.existsSync(o)){T.warning(`[connectors] No source code found for ${e.name} version ${t}`);return}try{const l=new fr;if(l.append("file",M.createReadStream(o),"file.zip"),T.info(`[connectors] Pushing connector version ${t} for ${e.name}`),t==st)T.info(`[connectors] Uploading connector ${n}`),await s.post(`connectors/${n}/upload`,l,{headers:{...l.getHeaders()}});else{if(l.append("version",t),l.append("changelog","Imported Version"),(await s.get(`/connectors/${n}/versions`)).find(p=>p.version==t)){T.info(`[connectors] Version ${t} already published`);return}T.info(`[connectors] Publishing version ${t} of connector ${n}`),await s.post(`connectors/${n}/publish-version`,l,{headers:{...l.getHeaders()}})}T.success(`Successfully pushed connector version ${t} for ${e.name}`)}catch(l){T.error(`Error pushing connector version ${t} for ${e.name}: ${l}`)}finally{!a&&M.existsSync(o)&&(T.info(`[connectors] Cleaning up temporary zip file for ${e.name} version ${t}`),M.unlinkSync(o))}}c(no,"pushConnectorVersion");async function Es({client:s,connectorId:e}){if(bn[e])return bn[e];const t=await s.get(`connectors/${e}`);return bn[e]=t,t}c(Es,"getConnector");async function so({basePath:s,connector:e}){const t=vt(e),n=B.join(s,nt,t);M.mkdirSync(n,{recursive:!0});const i=B.join(n,`${vt(e)}.yml`);M.writeFileSync(i,Ie.dump(e)),T.info(`[connectors] Pulled connector ${e.name}`)}c(so,"pullConnector");async function io({client:s,connector:e,connectorVersion:t,basePath:n}){const i=vt(e),r=Is(t),o=B.join(n,"connectors",i,r),a=await s.get(`connectors/${e.id}/download`,{version:t},{responseType:"arraybuffer",headers:{Accept:"application/zip"},timeout:1e6});M.mkdirSync(o,{recursive:!0});const l=B.join(o,"src.zip");if(M.writeFileSync(l,a),!t){const u=B.join(o,"src");M.mkdirSync(u,{recursive:!0}),await to(a,u)}T.info(`[connectors] Pulled connector version: ${e.name} (${r})`)}c(io,"pullConnectorVersion");function vt(s){return s.key}c(vt,"getConnectorDirName");function Is(s){return s??st}c(Is,"getConnectorVersionDirName");function ro(s){return s.match(`${nt}/[^/]+/${st}/src/.*`)!==null}c(ro,"isConnectorSourceFile");async function oo(s){const e=s.match(`${nt}/([^/]+)/${st}/src/(.*)`);if(!e)return;const t=e[1],n=e[2],i=await Cn(t);if(!i){T.warning(`[connectors] Connector ${t} not found. Ignoring file change`);return}const r=i.id,o=M.readFileSync(s,"utf-8");await(await le.getClient()).put(`connectors/${r}/files/${n}`,o,{headers:{"Content-Type":"text/plain"}}),T.info(`[connectors] Pushed file ${n} for connector ${i.name}`)}c(oo,"putConnectorFile");async function ao(s){const e=s.match(`${nt}/([^/]+)/${st}/src/(.*)`);if(!e)return;const t=e[1],n=e[2],i=await Cn(t);if(!i){T.warning(`[connectors] Connector ${t} not found. Ignoring file change`);return}const r=i.id;await(await le.getClient()).delete(`connectors/${r}/files/${n}`),T.info(`[connectors] Deleted file ${n} for connector ${i.name}`)}c(ao,"deleteConnectorFile");const co="membrane",lo=["**/node_modules/**","**/.git/**","**/.DS_Store","**/Thumbs.db","**/*.tmp","**/*.swp","**/*.swo","**/*.log","**/*.lock","**/.cache/**","**/.next/**","**/.vscode/**","**/.idea/**"];function Et(s){return R.join(s,co)}c(Et,"getMembraneDir");const uo=["id","workspaceId","integrationId","createdAt","updatedAt","revision","parentRevision","archivedAt","baseUri","state"],Ts=[P.Action,P.FieldMapping,P.Flow,P.DataSource];class G{static{c(this,"Element")}type;key;integrationKey;data;constructor(e,t,n,i){if(!i)throw new Error("Element must always contain data");if(!t)throw new Error("Element must have a key");this.type=e,this.key=t,this.data=i,this.integrationKey=n||G.extractIntegrationKey(i)}get id(){return G.makeId(this.type,this.key,this.integrationKey)}get dirPath(){const e=ye[this.type].apiPath;if(this.integrationKey){const t=ye[P.Integration].apiPath;return R.join(t,this.integrationKey,e,this.key)}return R.join(e,this.key)}get path(){return R.join(this.dirPath,"spec.yaml")}get relativePath(){return R.relative(Et(process.cwd()),this.path)}isEqual(e){if(this.id!==e.id)return!1;const t=this.clean(),n=e.clean();return dr(t,n)}hasParent(){const e=this.getParentKey();return!!e&&!!this.data?.[e]}clean(){const e={...this.data};return uo.forEach(t=>{delete e[t]}),Object.keys(e).forEach(t=>{t.match(/universal.*Revision/)&&delete e[t]}),e}getParentKey(){let e="parentId";return se?.[this.type]?.parentKey&&(e=se?.[this.type]?.parentKey),e}static new(e,t,n,i){return new G(e,t,n,i)}static fromData(e,t){if(!t?.key)throw new Error(`Element missing key: ${JSON.stringify(t)}`);const n=this.extractIntegrationKey(t);return new G(e,t.key,n,t)}static fromPathAndData(e,t){const n=G.parsePath(e);if(!t)return;const i=t?.key||n?.key;return n?G.new(n.type,i,n.integrationKey,t):void 0}static fromElement(e){return new G(e.type,e.key,e.integrationKey,{...e.data})}static idFromPath(e){const t=G.parsePath(e);if(t)return G.makeId(t.type,t.key,t.integrationKey)}static makeId(e,t,n){return e===P.Integration?`${e}:${t}`:G.isIntegrationSpecific(e)?`${n||"universal"}:${e}:${t}`:`${e}:${t}`}static parsePath(e){const t=this.getRelativePath(e);if(!this.isElementFile(t))return;const n=Object.values(ye).map(l=>l.apiPath).join("|"),i=new RegExp(`^(?<elementType>${n})/(?<elementKey>[^/]+)/spec\\.ya?ml$`),r=t.match(i);if(r?.groups){const{elementType:l,elementKey:u}=r.groups,p=this.getElementTypeFromPath(l);if(p)return{type:p,key:u}}const o=new RegExp(`^integrations/(?<integrationKey>[^/]+)/(?<elementType>${n})/(?<elementKey>[^/]+)/spec\\.ya?ml$`),a=t.match(o);if(a?.groups){const{integrationKey:l,elementType:u,elementKey:p}=a.groups,d=this.getElementTypeFromPath(u);if(d)return{type:d,key:p,integrationKey:l}}}static extractIntegrationKey(e){return e?.integrationKey||e?.integration?.key||e?.integration_key||void 0}static isElementFile(e){return e.endsWith(".yml")||e.endsWith(".yaml")}static getElementTypeFromPath(e){return Object.values(P).find(t=>ye[t].apiPath===e)}static getRelativePath(e){return R.relative(Et(process.cwd()),e)}static isIntegrationSpecific(e){return Ts.includes(e)}static canBeIntegrationSpecific(e){return Ts.includes(e)}}class fo{static{c(this,"LocalElementsHandler")}basePath;constructor(){this.basePath=Et(process.cwd())}async getElementsByType(e,t){const n=[],i=R.join(this.basePath,ye[e].apiPath),r=await this.readElementsInDir(i);n.push(...r);for(const o of t){const a=R.join(this.basePath,ye[P.Integration].apiPath,o.key,ye[e].apiPath),l=await this.readElementsInDir(a);n.push(...l)}return n.length>0&&T.success(`[local] Fetched ${n.length} ${e}${n.length!==1?"s":""}`),n}async fetchElement(e){return this.readElement(e.path)}async createElement(e){return this.updateElement(e,e)}async updateElement(e,t){if(!e.data)throw new Error("Element must have data to write");const n=R.join(this.basePath,t.dirPath),i=R.join(this.basePath,t.path);return x.existsSync(n)||x.mkdirSync(n,{recursive:!0}),x.writeFileSync(i,Ie.dump(e.data)),T.info(`[local] Written ${t.relativePath}`),t}async deleteElement(e){const t=R.join(this.basePath,e.path),n=R.join(this.basePath,e.dirPath);x.existsSync(t)&&x.rmSync(t,{force:!0}),this.pruneEmptyDir(n),T.info(`[local] Deleted ${e.relativePath}`)}async getIntegrations(){const e=R.join(this.basePath,ye[P.Integration].apiPath);return this.readElementsInDir(e)}async readElement(e){if(!x.existsSync(e))return;const t=x.readFileSync(e,"utf8"),n=Ie.load(t);if(n)return G.fromPathAndData(e,n)}async readElementsInDir(e){const t=[];if(!x.existsSync(e))return t;const n=x.readdirSync(e);if(n.length===0)return t;const i=n.map(async o=>{const a=R.join(e,o,"spec.yaml");return this.readElement(a)});return(await Promise.all(i)).filter(o=>o!=null)}pruneEmptyDir(e){try{if(!e.startsWith(this.basePath)||e===this.basePath||!x.existsSync(e)||x.readdirSync(e).length>0)return;x.rmdirSync(e),this.pruneEmptyDir(R.dirname(e))}catch(t){console.warn(`Failed to prune empty directory ${e}:`,t)}}}class ho{static{c(this,"RemoteElementsHandler")}client;async getElementsByType(e,t){const n=await this.findAll(e);if(!G.canBeIntegrationSpecific(e))return n;for(const i of t){const r=i.key,o=i.data.id,a=await this.findAll(e,{integrationKey:r,integrationId:o});n.push(...a)}return n.length>0&&T.success(`[remote] Fetched ${n.length} ${e}${n.length!==1?"s":""}`),n}async fetchElement(e){const n=await(await this.getClient())[se[e.type].element](e.data.id).get();return G.fromData(e.type,n)}async createElement(e,t){const n=e.clean(),i=await this.getClient();this.transformElementForCreate(e,n,t),e.key==="download-document-by-id"&&T.info(`CREATE ${e.id}:`+JSON.stringify(n));const r=await i[se[e.type].elements].create(n),o=G.fromData(e.type,r);return T.info(`[remote] Created ${o.id}`),o}async updateElement(e,t,n){if(!e.data.id)throw new Error("Element must have an id to update");const i=e.clean(),r=await this.getClient();this.transformElementForUpdate(e,i,n);const o=await r[se[e.type].element](t.data.id).put(i),a=G.fromData(t.type,o);return T.info(`[remote] Updated ${t.id}`),a}async deleteElement(e){if(!e.data.id)throw new Error("Element must have an id to delete");await(await this.getClient())[se[e.type].element](e.data.id).archive(),T.info(`[remote] Deleted ${e.id}`)}async getIntegrations(){const n=(await(await this.getClient()).integrations.findAll()).map(i=>G.fromData(P.Integration,i));return n.length>0&&T.success(`[remote] Fetched ${n.length} integrations`),n}transformElementForCreate(e,t,n){if(e.integrationKey){const i=n.elements.find(r=>r.type===P.Integration&&r.key===e.integrationKey);if(i)t.integrationId=i.data.id;else throw new Error(`Integration ${e.integrationKey} not found. Integrations: ${n.elements.filter(r=>r.type===P.Integration).map(r=>r.key).join(", ")}`)}if(e.type===P.Integration){const i=n.connectorsMapping?.[t.connectorId];i&&(t.connectorId=i)}}transformElementForUpdate(e,t,n){if(e.type===P.Integration){const i=n.connectorsMapping?.[t.connectorId];i&&(t.connectorId=i)}if(e.integrationKey){t.integrationKey=e.integrationKey;const i=n.elements.find(r=>r.type===P.Integration&&r.key===e.integrationKey);if(i)t.integrationId=i.data.id;else throw new Error(`Integration ${e.integrationKey} not found. Integrations: ${n.elements.filter(r=>r.type===P.Integration).map(r=>r.key).join(", ")}`)}}async findAll(e,t={}){return(await(await this.getClient())[se[e].elements].findAll(t)).filter(r=>r.key).map(r=>G.fromData(e,r))}async getClient(){return this.client||(this.client=await le.getClient(process.cwd())),this.client}}const kn=Symbol.for("yaml.alias"),vn=Symbol.for("yaml.document"),be=Symbol.for("yaml.map"),Ns=Symbol.for("yaml.pair"),he=Symbol.for("yaml.scalar"),Me=Symbol.for("yaml.seq"),ie=Symbol.for("yaml.node.type"),Se=c(s=>!!s&&typeof s=="object"&&s[ie]===kn,"isAlias"),Te=c(s=>!!s&&typeof s=="object"&&s[ie]===vn,"isDocument"),Re=c(s=>!!s&&typeof s=="object"&&s[ie]===be,"isMap"),j=c(s=>!!s&&typeof s=="object"&&s[ie]===Ns,"isPair"),K=c(s=>!!s&&typeof s=="object"&&s[ie]===he,"isScalar$1"),Ke=c(s=>!!s&&typeof s=="object"&&s[ie]===Me,"isSeq");function U(s){if(s&&typeof s=="object")switch(s[ie]){case be:case Me:return!0}return!1}c(U,"isCollection$1");function q(s){if(s&&typeof s=="object")switch(s[ie]){case kn:case be:case he:case Me:return!0}return!1}c(q,"isNode");const As=c(s=>(K(s)||U(s))&&!!s.anchor,"hasAnchor"),ee=Symbol("break visit"),Os=Symbol("skip children"),de=Symbol("remove node");function Ne(s,e){const t=$s(e);Te(s)?_e(null,s.contents,t,Object.freeze([s]))===de&&(s.contents=null):_e(null,s,t,Object.freeze([]))}c(Ne,"visit$1"),Ne.BREAK=ee,Ne.SKIP=Os,Ne.REMOVE=de;function _e(s,e,t,n){const i=Ls(s,e,t,n);if(q(i)||j(i))return Ds(s,n,i),_e(s,i,t,n);if(typeof i!="symbol"){if(U(e)){n=Object.freeze(n.concat(e));for(let r=0;r<e.items.length;++r){const o=_e(r,e.items[r],t,n);if(typeof o=="number")r=o-1;else{if(o===ee)return ee;o===de&&(e.items.splice(r,1),r-=1)}}}else if(j(e)){n=Object.freeze(n.concat(e));const r=_e("key",e.key,t,n);if(r===ee)return ee;r===de&&(e.key=null);const o=_e("value",e.value,t,n);if(o===ee)return ee;o===de&&(e.value=null)}}return i}c(_e,"visit_");async function It(s,e){const t=$s(e);Te(s)?await je(null,s.contents,t,Object.freeze([s]))===de&&(s.contents=null):await je(null,s,t,Object.freeze([]))}c(It,"visitAsync"),It.BREAK=ee,It.SKIP=Os,It.REMOVE=de;async function je(s,e,t,n){const i=await Ls(s,e,t,n);if(q(i)||j(i))return Ds(s,n,i),je(s,i,t,n);if(typeof i!="symbol"){if(U(e)){n=Object.freeze(n.concat(e));for(let r=0;r<e.items.length;++r){const o=await je(r,e.items[r],t,n);if(typeof o=="number")r=o-1;else{if(o===ee)return ee;o===de&&(e.items.splice(r,1),r-=1)}}}else if(j(e)){n=Object.freeze(n.concat(e));const r=await je("key",e.key,t,n);if(r===ee)return ee;r===de&&(e.key=null);const o=await je("value",e.value,t,n);if(o===ee)return ee;o===de&&(e.value=null)}}return i}c(je,"visitAsync_");function $s(s){return typeof s=="object"&&(s.Collection||s.Node||s.Value)?Object.assign({Alias:s.Node,Map:s.Node,Scalar:s.Node,Seq:s.Node},s.Value&&{Map:s.Value,Scalar:s.Value,Seq:s.Value},s.Collection&&{Map:s.Collection,Seq:s.Collection},s):s}c($s,"initVisitor");function Ls(s,e,t,n){if(typeof t=="function")return t(s,e,n);if(Re(e))return t.Map?.(s,e,n);if(Ke(e))return t.Seq?.(s,e,n);if(j(e))return t.Pair?.(s,e,n);if(K(e))return t.Scalar?.(s,e,n);if(Se(e))return t.Alias?.(s,e,n)}c(Ls,"callVisitor");function Ds(s,e,t){const n=e[e.length-1];if(U(n))n.items[s]=t;else if(j(n))s==="key"?n.key=t:n.value=t;else if(Te(n))n.contents=t;else{const i=Se(n)?"alias":"scalar";throw new Error(`Cannot replace node with ${i} parent`)}}c(Ds,"replaceNode");const po={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},mo=c(s=>s.replace(/[!,[\]{}]/g,e=>po[e]),"escapeTagName");class Z{static{c(this,"Directives")}constructor(e,t){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},Z.defaultYaml,e),this.tags=Object.assign({},Z.defaultTags,t)}clone(){const e=new Z(this.yaml,this.tags);return e.docStart=this.docStart,e}atDocument(){const e=new Z(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:Z.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},Z.defaultTags);break}return e}add(e,t){this.atNextDocument&&(this.yaml={explicit:Z.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},Z.defaultTags),this.atNextDocument=!1);const n=e.trim().split(/[ \t]+/),i=n.shift();switch(i){case"%TAG":{if(n.length!==2&&(t(0,"%TAG directive should contain exactly two parts"),n.length<2))return!1;const[r,o]=n;return this.tags[r]=o,!0}case"%YAML":{if(this.yaml.explicit=!0,n.length!==1)return t(0,"%YAML directive should contain exactly one part"),!1;const[r]=n;if(r==="1.1"||r==="1.2")return this.yaml.version=r,!0;{const o=/^\d+\.\d+$/.test(r);return t(6,`Unsupported YAML version ${r}`,o),!1}}default:return t(0,`Unknown directive ${i}`,!0),!1}}tagName(e,t){if(e==="!")return"!";if(e[0]!=="!")return t(`Not a valid tag: ${e}`),null;if(e[1]==="<"){const o=e.slice(2,-1);return o==="!"||o==="!!"?(t(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==">"&&t("Verbatim tags must end with a >"),o)}const[,n,i]=e.match(/^(.*!)([^!]*)$/s);i||t(`The ${e} tag has no suffix`);const r=this.tags[n];if(r)try{return r+decodeURIComponent(i)}catch(o){return t(String(o)),null}return n==="!"?e:(t(`Could not resolve tag: ${e}`),null)}tagString(e){for(const[t,n]of Object.entries(this.tags))if(e.startsWith(n))return t+mo(e.substring(n.length));return e[0]==="!"?e:`!<${e}>`}toString(e){const t=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],n=Object.entries(this.tags);let i;if(e&&n.length>0&&q(e.contents)){const r={};Ne(e.contents,(o,a)=>{q(a)&&a.tag&&(r[a.tag]=!0)}),i=Object.keys(r)}else i=[];for(const[r,o]of n)r==="!!"&&o==="tag:yaml.org,2002:"||(!e||i.some(a=>a.startsWith(o)))&&t.push(`%TAG ${r} ${o}`);return t.join(`
2
+ var Bi=Object.defineProperty;var c=(s,e)=>Bi(s,"name",{value:e,configurable:!0});import{jsx as m,jsxs as E,Fragment as Zt}from"react/jsx-runtime";import*as R from"node:path";import{resolve as Ui,dirname as qi,join as Ji}from"node:path";import{useInput as xe,Box as b,Text as S,Newline as Wi,render as mt}from"ink";import Gi from"minimist";import{SWRConfig as Vi}from"swr";import Pe,{createContext as ns,useState as F,useEffect as Ee,useContext as ss,useMemo as Hi,useRef as Yi}from"react";import is from"swr/immutable";import rs from"os";import B from"path";import zi from"conf";import{exec as Qi}from"node:child_process";import*as x from"node:fs";import{readFileSync as Xi}from"node:fs";import{EventEmitter as Zi}from"events";import{MembraneConfigLoader as er,MembraneClient as os,WorkspaceElementType as P,extractMembraneErrorData as te,WorkspaceElementSpecs as ye,setValueAtLocator as en,getDataCollectionCreateFields as tn,excludeWriteOnlyFieldsFromSchema as as,valueToSchema as gt,getRequiredFieldsFromSchema as tr,getValueAtLocator as nr,walkSchema as cs,makeDataLocationPath as ls,getDataCollectionUpdateFields as nn}from"@membranehq/sdk";import sn from"jsonwebtoken";import{Spinner as sr,TextInput as ir,Select as rr}from"@inkjs/ui";import yt from"ink-spinner";import or from"ink-text-input";import*as ar from"node:crypto";import{createHash as cr}from"node:crypto";import*as lr from"node:os";import M from"fs";import ur from"archiver";import fr from"form-data";import Ie from"js-yaml";import hr from"unzipper";import dr from"lodash/isEqual.js";import pr from"chokidar";import{fileURLToPath as mr}from"node:url";import k from"chalk";import{Command as gr}from"commander";import rn from"axios";import{FastMCP as yr}from"fastmcp";import{z}from"zod";import on from"lodash/merge.js";import wr from"@anthropic-ai/sdk";import{faker as Xe}from"@faker-js/faker";import br from"lodash/template.js";import Sr from"lodash/templateSettings.js";const J={LogAdded:"logAdded",StateChanged:"stateChanged",StatsChanged:"statsChanged",ConflictsChanged:"conflictsChanged",McpStatusChanged:"mcpStatusChanged",McpServersChanged:"mcpServersChanged",ConfigChanged:"configChanged"},D={NOT_INITIALIZED:"not_initialized",SETTING_UP:"setting_up",INITIALIZED:"initialized",NOT_SYNCED:"not_synced",PULLING:"pulling",PUSHING:"pushing",RESOLVING:"resolving",CONFLICTS:"conflicts",SYNCED:"synced",WATCHING:"watching",ERROR:"error"},us=ns(null);function Cr({children:s,membraneCLIService:e}){const{data:t}=is("/account"),[n,i]=F(D.NOT_INITIALIZED),[r,o]=F([]),[a,l]=F({}),[u,p]=F([]),[d,h]=F(null),w=t?.workspaces?.find(f=>f.workspaceKey===d?.workspaceKey)||null;return Ee(()=>{const f=c(({state:I})=>i(I),"handleStateChanged"),y=c(({stats:I})=>l(I),"handleStatsChanged"),C=c(({log:I})=>p(O=>[...O,I]),"handleLogAdded"),v=c(({conflicts:I})=>o(I),"handleConflictsUpdated"),A=c(({config:I})=>h(I),"handleConfigChanged");return e.notifications.on(J.StateChanged,f),e.notifications.on(J.StatsChanged,y),e.notifications.on(J.LogAdded,C),e.notifications.on(J.ConflictsChanged,v),e.notifications.on(J.ConfigChanged,A),e.init(),()=>{e.notifications.off(J.StateChanged,f),e.notifications.off(J.StatsChanged,y),e.notifications.off(J.LogAdded,C),e.notifications.off(J.ConflictsChanged,v),e.notifications.off(J.ConfigChanged,A)}},[]),m(us.Provider,{value:{state:n,stats:a,logs:u,currentWorkspace:w,conflicts:r,config:d,updateConfig:c(f=>e.updateConfig(f),"updateConfig"),resolveConflicts:c(f=>e.syncWorkspaces(f),"resolveConflicts"),pull:c(f=>e.pullWorkspace(f),"pull"),push:c(f=>e.pushWorkspace(f),"push"),exit:c(()=>e.shutdown(),"exit")},children:s})}c(Cr,"MembraneCLIServiceProvider");function oe(){const s=ss(us);if(!s)throw new Error("useMembraneCLIService must be used within MembraneCLIServiceProvider");return s}c(oe,"useMembraneCLIService");const kr="membrane",vr="membrane.config.yml",an="https://api.integration.app";function cn(){const s=process.cwd(),e=R.join(s,kr),t=R.join(s,vr),n=e,i=R.join(n,"workspace.yaml");return{membraneDirPath:e,configPath:t,payloadDirPath:n,workspaceDataFilePath:i}}c(cn,"getPaths");function Er(){return cn().membraneDirPath}c(Er,"getBasePath");const Ir={pat:{type:"string"},workspace:{type:"object"}},fs=new zi({schema:Ir,configName:"config",cwd:B.join(rs.homedir(),".membrane")}),Tr=c(s=>{fs.set("pat",s)},"setPat"),hs=c(()=>fs.get("pat"),"getPat");class ds{static{c(this,"AccountApiClient")}constructor(e=an){this.apiBaseUrl=e}async request(e,t={}){const n=t.headers?t.headers instanceof Headers?new Headers(t.headers):new Headers(t.headers):new Headers;if(!n.has("Authorization")){const o=hs();if(!o)throw new Error("Personal Access Token not found.");n.set("Authorization",`Bearer ${o}`)}t.body&&!n.has("Content-Type")&&n.set("Content-Type","application/json");const i=await fetch(`${this.apiBaseUrl}${e}`,{...t,headers:n});if(!i.ok){const o=await i.text();throw new Error(`API request failed: ${i.status} ${i.statusText} - ${o}`)}if(i.status===204)return{};const r=await i.text();return JSON.parse(r)}get(e){return this.request(e,{method:"GET"})}post(e,t){return this.request(e,{method:"POST",body:JSON.stringify(t)})}put(e,t){return this.request(e,{method:"PUT",body:JSON.stringify(t)})}patch(e,t){return this.request(e,{method:"PATCH",body:JSON.stringify(t)})}delete(e){return this.request(e,{method:"DELETE"})}}const Nr=c(s=>{const e=new ds(an);return t=>e.get(t)},"createAccountApiFetcher"),ps=ns(process.cwd());function Ar({cwd:s,children:e}){return m(ps.Provider,{value:s,children:e})}c(Ar,"CwdProvider");function Or(){return ss(ps)}c(Or,"useCwd");function wt({cwd:s,children:e,membraneCLIService:t}){const n=s||process.cwd();return m(Ar,{cwd:n,children:m(Vi,{value:{fetcher:Nr()},children:m(Cr,{membraneCLIService:t,children:e})})})}c(wt,"Layout");const ln=[{id:"claude-code",name:"Claude Code",description:"Anthropic Claude Code agent",actionDescription:"Adding membrane MCP to .mcp.json in the current directory",addConfig:c(()=>{const s=R.join(process.cwd(),".mcp.json"),e={mcpServers:{membrane:{command:"membrane",args:["mcp"],env:{AGENT_NAME:"Claude Code"}}}};let t={};if(x.existsSync(s))try{t=JSON.parse(x.readFileSync(s,"utf8"))}catch{t={}}const n={...t,mcpServers:{...t.mcpServers,...e.mcpServers}};return x.writeFileSync(s,JSON.stringify(n,null,2)),`MCP server configuration added to ${s}`},"addConfig")},{id:"cursor",name:"Cursor",description:"Cursor AI editor",actionDescription:"Adding membrane MCP to .cursor/mcp.json in the current directory",addConfig:c(()=>{const s=R.join(process.cwd(),".cursor"),e=R.join(s,"mcp.json");x.existsSync(s)||x.mkdirSync(s);const t={mcpServers:{membrane:{command:"membrane",args:["mcp"],env:{AGENT_NAME:"Cursor"}}}};let n={};if(x.existsSync(e))try{n=JSON.parse(x.readFileSync(e,"utf8"))}catch{n={}}const i={...n,mcpServers:{...n.mcpServers,...t.mcpServers}};return x.writeFileSync(e,JSON.stringify(i,null,2)),`MCP server configuration added to ${e}`},"addConfig")}];function $r({onExit:s,onComplete:e}){const[t,n]=F(0),[i,r]=F(!1),[o,a]=F(null),[l,u]=F(""),[p,d]=F("");xe((w,f)=>{if(l||p){(f.escape||w==="q"||f.return)&&e();return}if(i)f.return||w===" "?h(o):f.escape&&(r(!1),a(null));else if(f.escape)s();else if(f.upArrow||w==="k")n(Math.max(0,t-1));else if(f.downArrow||w==="j")n(Math.min(ln.length-1,t+1));else if(f.return||w===" "){const y=ln[t];a(y),r(!0)}});const h=c(w=>{try{const f=w.addConfig();u(f)}catch(f){d(`Failed to write configuration: ${f.message||f}`)}},"addMcpConfiguration"),g=Math.min(80,process.stdout.columns||80);return l?E(b,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:g,children:[m(b,{marginTop:-1,marginBottom:1,children:E(S,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",m(S,{color:"green",children:"Success"})]})}),E(b,{flexDirection:"column",paddingLeft:2,children:[m(S,{color:"green",children:l}),m(b,{marginTop:1,children:m(S,{color:"grey",children:"The agent will now be able to use Membrane's integration capabilities."})})]}),m(b,{marginTop:1,paddingLeft:2,children:m(S,{color:"white",children:"[esc/q/enter: exit]"})})]}):p?E(b,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:g,children:[m(b,{marginTop:-1,marginBottom:1,children:E(S,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",m(S,{color:"red",children:"Error"})]})}),m(b,{flexDirection:"column",paddingLeft:2,children:m(S,{color:"red",children:p})}),m(b,{marginTop:1,children:m(S,{color:"grey",children:"[esc/q/enter: exit]"})})]}):i&&o?E(b,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:g,children:[m(b,{marginTop:-1,marginBottom:1,children:E(S,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",m(S,{color:"cyan",children:"Confirmation"})]})}),E(b,{flexDirection:"column",paddingLeft:2,children:[E(S,{children:["Connect ",m(S,{bold:!0,children:o.name})," to Membrane via MCP?"]}),m(b,{marginTop:1,children:m(S,{color:"grey",children:"This will add an MCP server configuration that allows the agent to use Membrane's integration capabilities."})}),m(b,{marginTop:1,children:m(S,{color:"yellow",bold:!0,children:o.actionDescription})}),m(b,{marginTop:2,marginBottom:1,children:E(S,{children:[m(S,{color:"white",bold:!0,children:"[Enter] Confirm"})," ",m(S,{color:"gray",children:"[Esc] Cancel"})]})})]})]}):E(b,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:g,children:[m(b,{marginTop:-1,marginBottom:1,children:E(S,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",m(S,{color:"cyan",children:"Select Agent"})]})}),E(b,{flexDirection:"column",paddingLeft:2,children:[m(S,{color:"grey",children:"Choose an agent to connect to Membrane via MCP:"}),m(b,{marginTop:1,children:m(S,{color:"grey",children:"This will add an MCP server configuration that allows the agent to use Membrane's integration capabilities."})}),m(b,{marginTop:1,flexDirection:"column",children:ln.map((w,f)=>E(b,{children:[E(S,{color:t===f?"cyan":"white",children:[t===f?"\u25B6 ":" ",w.name]}),E(S,{color:"grey",children:[" \u2014 ",w.description]})]},w.id))})]}),m(b,{marginTop:1,children:m(S,{color:"grey",children:"[\u2191\u2193: select] [enter: choose] [esc: exit]"})})]})}c($r,"AddMcpServerScreen");class ms extends Zi{static{c(this,"TypedEventEmitter")}on(e,t){return super.on(e,t)}emit(e,...t){return super.emit(e,...t)}off(e,t){return super.off(e,t)}once(e,t){return super.once(e,t)}}class He{static{c(this,"ConfigLoader")}static instance=null;sdkLoader;constructor(){this.sdkLoader=new er}static getInstance(){return He.instance||(He.instance=new He),He.instance}loadConfig(e){e&&e!==this.sdkLoader.getCwd()&&this.sdkLoader.setCwd(e);try{return this.sdkLoader.loadConfig({validate:!0})}catch(t){if(t.message?.includes("Failed to parse"))throw t;return null}}clearCache(){this.sdkLoader.clearCache()}updateConfig(e){return this.sdkLoader.updateConfig(e)}isCacheDefined(e){return this.sdkLoader.hasValidConfig()}}const Ze=He.getInstance();function bt(s){return Ze.loadConfig(s)}c(bt,"readProjectConfig");class Lr{static{c(this,"MembraneClientManager")}client=null;currentConfig=null;tokenExpiry=0;async generateAccessToken(e,t){return sn.sign({name:"Membrane Agent",isAdmin:!0,exp:Math.floor(Date.now()/1e3)+3600,iss:e},t,{algorithm:"HS512"})}isTokenValid(){return Date.now()<this.tokenExpiry}getCurrentConfig(e){const t=bt(e);return!t?.workspaceKey||!t?.workspaceSecret?null:{workspaceKey:t.workspaceKey,workspaceSecret:t.workspaceSecret,apiUri:t.apiUri}}async createClient(e){const t=await this.generateAccessToken(e.workspaceKey,e.workspaceSecret);return this.tokenExpiry=Date.now()+36e5,this.currentConfig=e,new os({token:t,apiUri:e.apiUri})}async getClient(e=process.cwd()){const t=this.getCurrentConfig(e);if(!t)throw new Error("Unable to create MembraneClient: No workspace configuration found.");const n=!this.currentConfig||this.currentConfig.workspaceKey!==t.workspaceKey||this.currentConfig.workspaceSecret!==t.workspaceSecret||this.currentConfig.apiUri!==t.apiUri,i=!this.isTokenValid()||this.tokenExpiry-Date.now()<3e5;return(!this.client||n||i)&&(this.client=await this.createClient(t)),this.client}clearClient(){this.client=null,this.currentConfig=null,this.tokenExpiry=0}getCurrentConfigInfo(){return this.currentConfig}}const le=new Lr;async function gs(s){const e=await le.getClient(s);if(!e)throw new Error("No workspace configuration found");return(await e.get("org-workspace-id")).id}c(gs,"getWorkspaceId");class Dr extends ms{static{c(this,"WorkspaceNotifications")}constructor(e){super(),this.config=e}clientId;heartbeatInterval;isCleaningUp=!1;async connectToRemote(){await this.registerWithRemoteServer(),await this.startHeartbeatLoop()}async setState(e){this.emit(J.StateChanged,{state:e}),await this.emitRemote({status:e})}setConflicts(e){this.emit(J.ConflictsChanged,{conflicts:e})}setConfig(e){this.emit(J.ConfigChanged,{config:e})}setStats(e){this.emit(J.StatsChanged,{stats:e})}addLog(e){this.emit(J.LogAdded,{log:e})}setMcpStatus(e){this.emit(J.McpStatusChanged,{status:e})}async setMcpServers(e){this.emit(J.McpServersChanged,{servers:e}),await this.emitRemote({mcpServers:e.map(t=>({name:t.agentName,totalRequests:t.totalRequests}))})}async cleanup(){if(!(!this.clientId||this.isCleaningUp)){this.isCleaningUp=!0,this.heartbeatInterval&&(clearInterval(this.heartbeatInterval),this.heartbeatInterval=void 0);try{await(await le.getClient(process.cwd())).delete(`/local-clients/${this.clientId}`)}catch{}this.clientId=void 0}}async registerWithRemoteServer(){if(this.clientId)return;const t=await(await le.getClient(process.cwd())).post("/local-clients",{hostname:rs.hostname(),workingDirectory:process.cwd()});this.clientId=t.id}async startHeartbeatLoop(){this.heartbeatInterval=setInterval(async()=>{this.clientId&&await this.sendHeartbeat()},this.config.heartbeatIntervalMs)}async sendHeartbeat(){if(!this.clientId)return;await(await le.getClient(process.cwd())).post(`/local-clients/${this.clientId}/keep-alive`,{})}async emitRemote(e){if(!this.clientId)return;await(await le.getClient(process.cwd())).patch(`/local-clients/${this.clientId}`,e)}}const ue=new Dr({heartbeatIntervalMs:15e3});function xr(){const[s,e]=F(null),[t,n]=F([]),[i,r]=F(null);return Ee(()=>{const o=c(({status:l})=>{e(l),r(null)},"handleMcpStatusChanged"),a=c(({servers:l})=>{n(l),r(null)},"handleMcpServersChanged");return ue.on(J.McpStatusChanged,o),ue.on(J.McpServersChanged,a),()=>{ue.off(J.McpStatusChanged,o),ue.off(J.McpServersChanged,a)}},[]),{mcpStatus:s,allMcpServers:t,error:i,isRunning:s?.isRunning||!1,toolsCount:s?.toolsCount||0,totalRequests:s?.totalRequests||0,lastActivity:s?.lastActivity,processId:s?.processId,serverCount:t.length}}c(xr,"useMcpStatus");function Pr(){const{error:s,serverCount:e,allMcpServers:t}=xr(),n=Math.min(100,process.stdout.columns||100);return E(b,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:n,children:[m(b,{marginTop:-1,marginBottom:0,flexDirection:"column",children:E(S,{bold:!0,children:["\u{1F916} Connected AI Agents:"," ",s?m(S,{color:"red",children:"error reading status"}):e===0?m(S,{color:"yellow",children:"none"}):m(S,{color:"green",children:e})]})}),!s&&e===0&&m(b,{marginTop:1,children:E(S,{color:"grey",children:["Connect your AI agents to Membrane.",m(Wi,{}),"It will give them tools and context to build integrations."]})}),t.length>0&&m(b,{flexDirection:"column",paddingLeft:2,marginTop:1,children:t.map((i,r)=>m(b,{children:E(S,{color:"grey",children:["#",r+1," ",i.agentName,": ",i.totalRequests," calls"]})},i.processId))}),m(b,{marginTop:1,children:m(S,{color:"grey",children:"[a: connect an agent]"})})]})}c(Pr,"Agent");const St=c(s=>{switch(s){case"error":return"red";case"success":return"green";case"warning":return"yellow";default:return}},"getLogColor");function ys(s,e){return e<3?s.slice(0,Math.max(0,e)):s.length<=e?s:`${s.slice(0,e-3)}...`}c(ys,"truncateText");function un({children:s}){const{state:e,logs:t}=oe();if(!e||e===D.NOT_INITIALIZED)return E(b,{gap:1,flexDirection:"row",children:[m(sr,{type:"dots"}),m(S,{children:"Initializing..."})]});if(e===D.SETTING_UP)return m(b,{gap:1,flexDirection:"row",children:m(S,{children:"No workspace selected. Please run `membrane init` to select a workspace."})});if(e===D.ERROR){const n=t.filter(i=>i.type==="error");return m(b,{gap:1,flexDirection:"row",children:n.slice().map((i,r)=>m(S,{color:St(i.type),children:i.message},i.timestamp+r))})}return s}c(un,"EnsureInitialized");function ws({onExit:s,showEscOption:e=!0}){const[t,n]=F(""),{data:i,error:r,isLoading:o}=is("/account"),{updateConfig:a}=oe(),l=i?.workspaces,u=o;if(xe((f,y)=>{y.escape&&s?.()}),u)return E(b,{children:[m(yt,{}),m(S,{children:" Fetching workspaces..."})]});if(r)return E(b,{flexDirection:"column",children:[E(S,{color:"red",children:["Error: ",r.message]}),m(b,{marginTop:1,children:m(S,{color:"grey",children:"Press ESC to go back"})})]});const p=l?.filter(f=>f.name.toLowerCase().includes(t.toLowerCase()))??[],d=p.map(f=>({label:f.name,value:f.id})),h=d.length,g=l?.length??0;async function w(f){const y=p.find(A=>A.id===f);if(!y)return;const{key:C,secret:v}=y;!C||!v||(await a({workspaceKey:C,workspaceSecret:v}),s?.())}return c(w,"handleSelect"),E(b,{flexDirection:"column",borderStyle:"round",borderTop:!0,width:70,paddingX:1,children:[m(b,{marginTop:-1,children:m(S,{bold:!0,children:"\u{1F4C1} Select your workspace"})}),E(b,{marginTop:1,children:[m(S,{children:"Search: "}),m(ir,{placeholder:"Enter a search query...",onChange:n})]}),g>5&&E(S,{children:["Showing ",h," of ",g," workspaces."]}),m(b,{marginTop:1,children:m(rr,{options:d,onChange:c(f=>{f&&w(f)},"onChange")})}),e&&m(b,{marginTop:1,children:m(S,{color:"grey",children:"Press ESC to go back"})})]})}c(ws,"SelectWorkspace");function Mr({currentPat:s,onSubmit:e}){const[t,n]=F(""),[i,r]=F(!1),[o,a]=F(null);return E(b,{flexDirection:"column",borderStyle:"round",borderTop:!0,width:70,paddingX:1,children:[m(b,{marginTop:-1,marginBottom:1,children:m(S,{bold:!0,children:"\u{1F511} Enter your Personal Access Token"})}),m(S,{children:"Please provide your Personal Access Token. You can find it here:"}),m(b,{marginTop:1,marginBottom:1,children:m(S,{color:"yellow",children:"https://console.integration.app/w/0/manage-account/api-token"})}),s&&m(S,{dimColor:!0,children:"Press Enter to keep your current token or type a new one."}),m(or,{mask:"*",placeholder:`${s?"******":"Enter your token here..."}`,value:t,onChange:n,onSubmit:c(async u=>{a(null),r(!0);try{await e(u),n("")}catch{a("Invalid token. Please try again.")}finally{r(!1)}},"handleSubmit")}),i&&m(b,{marginTop:1,children:E(S,{children:[m(yt,{type:"dots"})," Validating token..."]})}),o&&m(S,{color:"red",children:o})]})}c(Mr,"PersonalAccessTokenInput");var et=(s=>(s[s.Authenticate=0]="Authenticate",s[s.ConnectWorkspace=1]="ConnectWorkspace",s))(et||{});const Rr={0:"Authenticate in Membrane",1:"Connect a Membrane Workspace"},fn=[et.Authenticate,et.ConnectWorkspace];function bs({onComplete:s}){const{config:e}=oe(),[t,n]=F(!1),[i,r]=F(0),o=!!(e?.workspaceKey&&e?.workspaceSecret),a=hs(),l=fn[i],u=i+1,p=fn.length,d=fn.map((w,f)=>{let y="pending";return f<i?y="done":f===i&&(y="current"),{id:w,label:Rr[w],status:y}});async function h(w){const f=a&&w===""?a:w,y=new ds;try{await y.request("/account",{headers:{Authorization:`Bearer ${f}`}}),Tr(f),r(C=>C+1)}catch(C){console.error(C)}}c(h,"handlePatSubmit");function g(){n(!0),s&&s()}return c(g,"handleWorkspaceSelected"),xe((w,f)=>{o&&f.escape&&s&&s()}),t?m(b,{children:m(S,{children:"\u2705 Setup complete. You are ready to go!"})}):E(b,{flexDirection:"column",alignSelf:"flex-start",gap:1,children:[E(b,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:70,children:[m(b,{marginTop:-1,marginBottom:1,children:E(S,{bold:!0,children:["\u{1F6E0}\uFE0F Setup \u2014"," ",E(S,{color:"cyan",children:["Step ",u," of ",p]}),o&&m(S,{color:"grey",children:" [esc: go back]"})]})}),m(b,{flexDirection:"column",paddingLeft:2,children:d.map(w=>m(Kr,{status:w.status,label:w.label},w.id))})]}),l===et.Authenticate&&m(Mr,{currentPat:a,onSubmit:h}),l===et.ConnectWorkspace&&m(ws,{onExit:g,showEscOption:!1})]})}c(bs,"Setup");function Kr({status:s,label:e}){return E(b,{children:[E(b,{width:2,children:[s==="current"&&m(yt,{type:"dots"}),s==="done"&&m(S,{children:"\u2705"})]}),m(S,{dimColor:s!=="current",children:e})]})}c(Kr,"StepDisplay");function hn(){const{stats:s}=oe(),e=Object.entries(s).filter(([t,n])=>n>0);return e.length===0?null:E(b,{flexDirection:"column",children:[m(b,{children:m(b,{width:12,children:m(S,{color:"grey",children:"Elements:"})})}),m(b,{flexDirection:"column",marginLeft:1,children:e.map(([t,n])=>E(b,{children:[m(b,{width:20,children:E(S,{children:[t,":"]})}),m(S,{color:"green",children:n})]},t))})]})}c(hn,"ElementStats");const dn=5,_r=6;function jr(){const{logs:s}=oe(),[e,t]=F(0),n=Math.min(100,process.stdout.columns||100),i=dn,r=Math.max(0,s.length-i-e),o=s.length-e,a=s.slice(r,o),l=n-_r,u=e<s.length-i,p=e>0;return xe((d,h)=>{if(s.length!==0)if(h.upArrow){const g=Math.max(0,s.length-i);t(w=>Math.min(g,w+1))}else h.downArrow?t(g=>Math.max(0,g-1)):(d==="G"||d==="g")&&t(0)}),E(b,{flexDirection:"column",paddingTop:1,children:[E(S,{color:"grey",children:["Recent Activity (",r+1,"-",o," of ",s.length,"):",s.length>dn&&m(S,{color:"grey",children:" [arrows: scroll] [g: end]"})]}),a.map((d,h)=>m(b,{marginLeft:1,children:m(S,{color:St(d.type),children:ys(d.message,l)})},d.timestamp+h)),s.length>dn&&E(b,{marginLeft:1,flexDirection:"row",children:[u&&m(S,{color:"grey",children:"\u2191 "}),p&&m(S,{color:"grey",children:"\u2193 "})]})]})}c(jr,"Logs");const X={UPDATE:"update",DELETE:"delete",CREATE:"create"},fe={INCOMING:"incoming",OUTGOING:"outgoing"},Ct=[{value:"sync",label:"Continue (overwrite/delete)",key:""},{value:"exit",label:"Cancel",key:""}];function Fr(){const{state:s,resolveConflicts:e,exit:t}=oe(),[n,i]=F(0),[r,o]=F(!1);return xe((a,l)=>{r||(l.upArrow?i(u=>u>0?u-1:Ct.length-1):l.downArrow?i(u=>u<Ct.length-1?u+1:0):a.toLowerCase()==="y"?i(0):a.toLowerCase()==="n"?i(1):(l.return||a===" ")&&(o(!0),Ct[n].value==="sync"?e({watch:!0}):t()))}),Ee(()=>{s!==D.CONFLICTS&&r&&o(!1)},[s,r]),E(b,{flexDirection:"column",paddingTop:1,children:[m(b,{children:m(b,{flexDirection:"row",gap:2,children:m(S,{bold:!0,color:"white",children:"Conflicts with remote"})})}),m(b,{children:m(S,{color:"grey",children:"The remote workspace has changes that aren't in your local workspace:"})}),m(b,{marginTop:1,marginLeft:2,children:m(pn,{})}),E(b,{marginTop:2,flexDirection:"row",gap:1,children:[m(S,{color:"white",bold:!0,children:"What would you like to do?"}),m(S,{color:"grey",children:"[up/down, enter]"})]}),m(b,{children:r?E(b,{flexDirection:"row",gap:1,children:[m(yt,{type:"dots"}),m(S,{color:"blue",bold:!0,children:"Syncing with remote..."})]}):m(b,{flexDirection:"column",children:Ct.map((a,l)=>m(b,{flexDirection:"column",children:E(b,{flexDirection:"row",gap:1,children:[m(S,{color:n===l?"cyan":"grey",children:n===l?"\u25B6":" "}),m(S,{color:n===l?"cyan":"grey",bold:n===l,children:a.label})]})},a.value))})})]})}c(Fr,"ResolveChangesUI");const Br={[X.UPDATE]:{incoming:{label:"Elements updated in remote",description:"(to be overwritten from remote)"},outgoing:{label:"Elements updated locally",description:"(to be pushed to remote)"}},[X.DELETE]:{incoming:{label:"Elements not existing in remote",description:"(to be deleted locally)"},outgoing:{label:"Elements deleted locally",description:"(to be deleted from remote)"}},[X.CREATE]:{incoming:{label:"Elements created in remote",description:"(to be created locally)"},outgoing:{label:"Elements created locally",description:"(to be created in remote)"}}};function pn(){const{conflicts:s}=oe(),e=Hi(()=>{const t={};return s.forEach(n=>{const i=`${n.type}-${n.direction}`;t[i]||(t[i]=[]),t[i].push(n)}),t},[s]);return m(b,{flexDirection:"column",children:Object.entries(e).map(([t,n])=>{if(n.length===0)return null;const[i,r]=t.split("-"),o=Br[i][r];return E(b,{flexDirection:"column",children:[E(b,{flexDirection:"row",gap:1,children:[E(S,{color:"yellow",children:[o.label," (",n.length,")"]}),m(S,{color:"white",children:o.description})]}),n.map(a=>m(b,{marginLeft:2,children:E(S,{color:"grey",children:["\u2022 ",a.element.id," (",a.element.relativePath,")"]})},a.element.id))]},t)})})}c(pn,"Conflicts");function Ur(){const{config:s,state:e,logs:t,currentWorkspace:n,pull:i}=oe(),r=n?.name,o=r?ys(r,30):s?.workspaceKey,a=Math.min(100,process.stdout.columns||100);return Ee(()=>{i({watch:!0})},[]),E(b,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:a,children:[m(b,{marginTop:-1,marginBottom:1,children:E(b,{flexDirection:"row",gap:1,children:[m(S,{bold:!0,children:"\u{1F504} Workspace"}),E(S,{color:Jr(e),children:[" [",qr(e),"] "]})]})}),E(b,{children:[m(b,{width:12,children:m(S,{color:"grey",children:"Local:"})}),m(S,{color:"grey",children:process.cwd()})]}),E(b,{children:[m(b,{width:12,children:m(S,{color:"grey",children:"Remote:"})}),s?.workspaceKey?E(S,{color:"grey",children:[o," [o: open in console] [w: change]"]}):E(S,{children:[m(S,{color:"yellow",children:"not selected"})," [w: select]"]})]}),e===D.CONFLICTS?m(Fr,{}):E(Zt,{children:[m(b,{paddingTop:1,children:m(hn,{})}),t.length>0&&m(jr,{})]})]})}c(Ur,"Workspace");function qr(s){switch(s){case D.PULLING:return"pulling";case D.PUSHING:return"pushing";case D.CONFLICTS:return"conflicts";case D.SYNCED:return"synced";case D.ERROR:return"error";case D.WATCHING:return"tracking changes";case D.RESOLVING:return"resolving";case D.NOT_SYNCED:return"not synced";case D.INITIALIZED:return"initialized";case D.SETTING_UP:return"setup required";default:return"unknown"}}c(qr,"getStatusDisplay");function Jr(s){switch(s){case D.PULLING:return"yellow";case D.PUSHING:return"yellow";case D.CONFLICTS:return"red";case D.SYNCED:return"green";case D.ERROR:return"red";case D.WATCHING:return"green";case D.RESOLVING:return"yellow";case D.NOT_SYNCED:return"grey";case D.SETTING_UP:return"yellow";default:return"grey"}}c(Jr,"getStatusColor");const Wr="https://console.integration.app/w";function Gr(){const s=Or(),e=Yi(!0),{exit:t,state:n}=oe(),[i,r]=F(null),o=i??(n===D.SETTING_UP?"setup":"main");xe(l=>{o==="main"&&(l==="w"&&r("workspace-selection"),l==="a"&&r("add-mcp-server"),l==="o"&&n===D.INITIALIZED&&a(),l==="s"&&r("setup"))});async function a(){try{const l=await gs(s),u=`${Wr}/${l}`,p=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";Qi(`${p} "${u}"`)}catch(l){console.error("Failed to open workspace:",l),t()}}return c(a,"handleOpenWorkspace"),Ee(()=>(e.current=!0,()=>{e.current=!1}),[]),o==="workspace-selection"?m(ws,{onExit:c(()=>r(null),"onExit")}):o==="add-mcp-server"?m($r,{onExit:c(()=>r(null),"onExit"),onComplete:c(()=>r(null),"onComplete")}):o==="setup"?m(bs,{onComplete:c(()=>r(null),"onComplete")},Date.now()):m(un,{children:E(b,{flexDirection:"column",children:[m(b,{flexGrow:1,children:m(Pr,{})}),m(Ur,{}),m(b,{paddingLeft:2,children:m(S,{color:"grey",children:"[s: (re-)setup]"})})]})})}c(Gr,"Main");class Vr{static{c(this,"WorkspaceLogger")}_logs;workspaceNotifications;constructor(){this._logs=[],this.workspaceNotifications=ue}get logs(){return[...this._logs]}get latestLogs(){return this._logs.slice(this._logs.length-5)}log(e,t="info"){const n={timestamp:new Date().toISOString(),message:e,type:t};this._logs.push(n),this._logs=this._logs.slice(0,1e3),this.workspaceNotifications.addLog(n)}info(e){this.log(e,"info")}success(e){this.log(e,"success")}warning(e){this.log(e,"warning")}error(e){this.log(e,"error")}clear(){this._logs=[]}}const T=new Vr,we=R.join(lr.tmpdir(),"membrane-mcp-status"),Ss=3e4;class Hr{static{c(this,"McpStatusService")}constructor(e=2e3){this.pollIntervalMs=e}isRunning=!1;pollInterval;async start(){this.isRunning||(this.isRunning=!0,this.pollInterval=setInterval(async()=>await this.checkStatus(),this.pollIntervalMs),await this.checkStatus())}async stop(){this.pollInterval&&(clearInterval(this.pollInterval),this.pollInterval=void 0,this.isRunning=!1)}async checkStatus(){try{const e=process.cwd(),t=kt(void 0,e),n=Cs(e);t&&ue.setMcpStatus(t),await ue.setMcpServers(n)}catch{T.error("Failed to check MCP status")}}}function kt(s,e){try{const t=e||process.cwd();if(!s){const i=Cs(t);return i.length===0?null:i[0]}const n=yn(s,t);if(x.existsSync(n)){const i=x.statSync(n),r=new Date;if(r.getTime()-i.mtime.getTime()>Ss)return tt(s,t),null;const a=x.readFileSync(n,"utf8"),l=JSON.parse(a);if(l.isRunning){const u=new Date(l.lastActivity).getTime();if(r.getTime()-u>Ss)return tt(s,t),null}return l}}catch{s&&e&&tt(s,e)}return null}c(kt,"getMcpStatus");function Cs(s){try{const e=s||process.cwd(),t=gn(e);if(!x.existsSync(we))return[];const n=x.readdirSync(we),i=[];for(const r of n){const o=r.match(new RegExp(`^mcp-${t}-(\\d+)\\.json$`));if(o){const a=parseInt(o[1],10),l=kt(a,e);l&&i.push(l)}}return i.sort((r,o)=>new Date(o.startTime).getTime()-new Date(r.startTime).getTime())}catch{return[]}}c(Cs,"getAllMcpStatusFiles");function mn(s){try{const t={...kt(s.processId,s.cwd)||{isRunning:!1,startTime:new Date().toISOString(),lastActivity:new Date().toISOString(),toolsCount:0,totalRequests:0,processId:s.processId,cwd:s.cwd,agentName:process.env.AGENT_NAME||"Unnamed Agent"},...s};x.existsSync(we)||x.mkdirSync(we,{recursive:!0});const n=yn(s.processId,s.cwd);x.writeFileSync(n,JSON.stringify(t,null,2))}catch{}}c(mn,"updateMcpStatus");function tt(s,e){try{const t=e||process.cwd();if(s){const n=yn(s,t);x.existsSync(n)&&x.unlinkSync(n)}else{const n=gn(t);if(x.existsSync(we)){const i=x.readdirSync(we);for(const r of i)r.match(new RegExp(`^mcp-${n}-\\d+\\.json$`))&&x.unlinkSync(R.join(we,r))}}}catch{}}c(tt,"clearMcpStatus");function Yr(s,e){const t=kt(s,e);t&&mn({processId:s,cwd:e,totalRequests:t.totalRequests+1,lastRequestTime:new Date().toISOString(),lastActivity:new Date().toISOString()})}c(Yr,"trackToolExecution");function gn(s){return cr("md5").update(s).digest("hex").slice(0,8)}c(gn,"getCwdHash");function yn(s,e){const t=gn(e);return R.join(we,`mcp-${t}-${s}.json`)}c(yn,"getStatusFilePath");const se={[P.Integration]:{element:"integration",elements:"integrations",exportable:!1,exportCleanup:c(s=>({id:s.id,key:s.key,name:s.name,connectorId:s.connectorId,baseUri:s.baseUri,connectorVersion:s.connectorVersion}),"exportCleanup")},[P.Connector]:{element:"connector",elements:"connectors",exportable:!1},[P.Action]:{element:"action",elements:"actions",integrationSpecific:!0,exportCleanup:c(s=>(delete s.integration,s),"exportCleanup")},[P.AppDataSchema]:{element:"appDataSchema",elements:"appDataSchemas"},[P.AppEventType]:{element:"appEventType",elements:"appEventTypes"},[P.DataLinkTable]:{element:"dataLinkTable",elements:"dataLinkTables"},[P.DataSource]:{element:"dataSource",elements:"dataSources",parentKey:"universalDataSourceId",integrationSpecific:!0},[P.FieldMapping]:{element:"fieldMapping",elements:"fieldMappings",integrationSpecific:!0,parentKey:"universalFieldMappingId",exportCleanup:c(s=>(delete s.dataSourceId,s),"exportCleanup")},[P.Flow]:{element:"flow",elements:"flows",integrationSpecific:!0,parentKey:"universalFlowId"}};function zr(s){return delete s.workspaceId,delete s.createdAt,delete s.updatedAt,delete s.revision,Object.keys(s).map(e=>{e.match(/universal.*Revision/g)&&delete s[e]}),s}c(zr,"baseExportCleanup");class ks{static{c(this,"ElementsCache")}elements=new Map;typeIndex=new Map;constructor(e){e&&this.addAll(e)}add(e){const t=e.id;this.elements.set(t,e),this.typeIndex.has(e.type)||this.typeIndex.set(e.type,new Set),this.typeIndex.get(e.type).add(t)}remove(e){const t=e.id,n=this.elements.delete(t);if(n){const i=this.typeIndex.get(e.type);i&&(i.delete(t),i.size===0&&this.typeIndex.delete(e.type))}return n}put(e){this.elements.has(e.id)&&this.remove(e),this.add(e)}get(e){return this.elements.get(e)}getElementsByType(e){const t=this.typeIndex.get(e);return t?Array.from(t).map(n=>this.elements.get(n)).filter(n=>n!==void 0):[]}getAll(){return Array.from(this.elements.values())??[]}getTypes(){return Array.from(this.typeIndex.keys())}addAll(e){for(const t of e)t&&this.add(t)}removeAll(e){for(const t of e)this.remove(t)}getElementIdsByType(e){return this.typeIndex.get(e)}clear(){this.elements.clear(),this.typeIndex.clear()}getAllIds(){return new Set(this.elements.keys())}}class vs{static{c(this,"ElementsManager")}cache;handler;connectorsMapping;constructor(e){this.cache=new ks,this.handler=e}async refresh(){try{const e=new ks,t=await this.handler.getIntegrations();e.addAll(t);const n=[P.Integration,P.Connector],i=Object.keys(se),r=await Promise.all(i.filter(o=>!n.includes(o)).map(async o=>this.handler.getElementsByType(o,t)));for(const o of r)e.addAll(o);this.cache.clear(),this.cache.addAll(e.getAll())}catch(e){throw T.error(`Failed to refresh elements: ${te(e)?.message??"Unknown error"}`),e}}async putElement(e){let t,n=this.cache.get(e.id);try{e.data.id&&n?(t="update",n=await this.handler.updateElement(e,n,{elements:this.cache.getAll(),connectorsMapping:this.connectorsMapping})):(t="create",n=await this.handler.createElement(e,{elements:this.cache.getAll(),connectorsMapping:this.connectorsMapping})),this.cache.put(n)}catch(i){T.error(`Failed to ${t} element ${e.type}/${e.key} ${e.integrationKey?`for integration ${e.integrationKey}`:""} (${e.id}): ${i instanceof Error?i.message:"Unknown error"}`)}}async deleteElement(e){try{await this.handler.deleteElement(e,{elements:this.cache.getAll(),connectorsMapping:this.connectorsMapping}),this.cache.remove(e)}catch(t){T.error(`Failed to delete element: ${t instanceof Error?t.message:"Unknown error"}`)}}setConnectorsMapping(e){this.connectorsMapping=e}}async function Qr(s,e="full"){const t={};T.info("[connectors] Getting remote workspace data");const n=await s.integrations.findAll();t.integration=n.map(i=>wn("integration",i));for(const i of Object.keys(se)){const r=se[i];if(r.exportable===!1)continue;const o=[];T.info(`[connectors] Reading ${r.elements} from remote workspace`);const a=await s[r.elements].findAll();if(o.push(...a.map(l=>wn(i,l))),r.integrationSpecific)for(const l of n){const u=await s[r.elements].findAll({integrationId:l.id});o.push(...u.map(p=>(p.integrationKey=l.key,wn(i,p))))}o.length>0&&e=="full"&&(console.table(o.map(l=>({key:l.key,integrationKey:l.integrationKey,universal:!l.integrationKey})).reduce((l,u)=>(l||(l={}),l[u.key]||(l[u.key]={}),u.universal&&(l[u.key].universal=!0),u.integrationKey&&(l[u.key].integration?l[u.key].integration+=` ${u.integrationKey}`:l[u.key].integration=u.integrationKey),l),{})),console.groupEnd()),t[i]=o}return T.success("[connectors] Remote workspace data retrieved successfully"),t}c(Qr,"getWorkspaceData");function wn(s,e){return e=zr(e),se[s].exportCleanup?se[s].exportCleanup(e):e}c(wn,"cleanUpForExport");const nt="connectors",st="development",bn={};async function Xr({integrations:s,allConnectors:e=!1}){const t=Er(),n=await le.getClient(process.cwd()),i=new Set,r={};for(const o of s){const a=o.connectorId,l=o.connectorVersion;if(!r[a]?.has(o.connectorVersion)){const u=await Es({client:n,connectorId:a}),d=!!u.workspaceId||e;if(!u?.key){T.error(`[connectors] Connector ${a} has no key. Skipping..`);continue}d&&(i.has(a)||(await so({basePath:t,connector:u}),i.add(a)),r[a]||(r[a]=new Set),r[a].has(l)||(await io({client:n,connector:u,connectorVersion:l,basePath:t}),r[a].add(l)))}}}c(Xr,"pullConnectors");async function Zr(){const s=await le.getClient(process.cwd()),e=await Qr(s,"minified"),n=(await s.get("org-workspace-id")).id,i={};T.info("[connectors] Loading custom connectors");const r=s,o=await r.get(`/connectors?workspaceId=${n}`);T.info("[connectors] Loading public connectors"),e.connector=o;const a=Sn(),u=(M.existsSync(a)?M.readdirSync(a):[]).filter(p=>{if(p.startsWith("."))return!1;const d=B.join(a,p);try{return M.statSync(d).isDirectory()}catch{return!1}});for(const p of u){T.info(`[connectors] Loading connector from: ${p}`);const d=M.readdirSync(B.join(a,p)),h=await Cn(p);if("baseUri"in h&&delete h.baseUri,h.uuid&&e.connector?.find(w=>w.uuid==h.uuid))i[h.id]=e.connector.find(w=>w.uuid==h.uuid).id,T.info(`[connectors] Matched ${h.name} uuid: ${h.uuid}`);else if(!i[h.id]){let w=!1;try{const f=await Es({client:s,connectorId:h.id});f&&!f.workspaceId&&(w=!0)}catch{}if(!w){T.info(`[connectors] Creating custom connector ${h.name} (${h.key})`);const f=await r.post("connectors",{...h,workspaceId:n});i[h.id]=f.id}}const g=d.filter(w=>M.statSync(B.join(a,p,w)).isDirectory());for(const w of g)await no({client:s,connector:h,version:w,connectorId:i[h.id]})}return i}c(Zr,"pushConnectors");function Sn(){const s=cn();return B.join(s.membraneDirPath,nt)}c(Sn,"getConnectorsPath");async function Cn(s){return Ie.load(M.readFileSync(B.join(Sn(),s,`${s}.yml`),"utf8"))}c(Cn,"readConnector");async function eo(s,e){return T.info(`[connectors] Zipping ${s} into ${e}`),new Promise((t,n)=>{const i=M.createWriteStream(e),r=ur("zip",{zlib:{level:9}});i.on("close",()=>{T.success(`[connectors] Successfully created ${e}`),t()}),i.on("end",()=>{T.info("[connectors] Data has been drained")}),r.on("warning",a=>{a.code==="ENOENT"?console.warn(a):n(a)}),r.on("error",a=>{n(a)}),r.pipe(i);const o=M.readdirSync(s);for(const a of o){const l=B.join(s,a),u=M.statSync(l);u.isFile()?r.file(l,{name:a}):u.isDirectory()&&r.directory(l,a)}r.finalize()})}c(eo,"createZipArchive");async function to(s,e){return T.info(`[connectors] Unzipping into ${e}`),new Promise((t,n)=>{const i=hr.Parse();i.on("entry",r=>{const o=r.path;if(r.type==="Directory"){const l=B.join(e,o);M.mkdirSync(l,{recursive:!0}),r.autodrain()}else{const l=B.join(e,o),u=B.dirname(l);M.mkdirSync(u,{recursive:!0});const p=M.createWriteStream(l);r.pipe(p),p.on("finish",()=>{})}}),i.on("end",()=>{T.success(`[connectors] Successfully extracted to ${e}`),t()}),i.on("error",r=>{n(r)}),i.write(s),i.end()})}c(to,"extractZipArchive");async function no({client:s,connector:e,version:t,connectorId:n}){const i=B.join(Sn(),vt(e),Is(t)),r=B.join(i,"src"),o=B.join(i,"src.zip"),a=M.existsSync(o);if(M.existsSync(r)&&(T.info(`[connectors] Archiving source code for ${e.name} version ${t}`),await eo(r,o)),!M.existsSync(o)){T.warning(`[connectors] No source code found for ${e.name} version ${t}`);return}try{const l=new fr;if(l.append("file",M.createReadStream(o),"file.zip"),T.info(`[connectors] Pushing connector version ${t} for ${e.name}`),t==st)T.info(`[connectors] Uploading connector ${n}`),await s.post(`connectors/${n}/upload`,l,{headers:{...l.getHeaders()}});else{if(l.append("version",t),l.append("changelog","Imported Version"),(await s.get(`/connectors/${n}/versions`)).find(p=>p.version==t)){T.info(`[connectors] Version ${t} already published`);return}T.info(`[connectors] Publishing version ${t} of connector ${n}`),await s.post(`connectors/${n}/publish-version`,l,{headers:{...l.getHeaders()}})}T.success(`Successfully pushed connector version ${t} for ${e.name}`)}catch(l){T.error(`Error pushing connector version ${t} for ${e.name}: ${l}`)}finally{!a&&M.existsSync(o)&&(T.info(`[connectors] Cleaning up temporary zip file for ${e.name} version ${t}`),M.unlinkSync(o))}}c(no,"pushConnectorVersion");async function Es({client:s,connectorId:e}){if(bn[e])return bn[e];const t=await s.get(`connectors/${e}`);return bn[e]=t,t}c(Es,"getConnector");async function so({basePath:s,connector:e}){const t=vt(e),n=B.join(s,nt,t);M.mkdirSync(n,{recursive:!0});const i=B.join(n,`${vt(e)}.yml`);M.writeFileSync(i,Ie.dump(e)),T.info(`[connectors] Pulled connector ${e.name}`)}c(so,"pullConnector");async function io({client:s,connector:e,connectorVersion:t,basePath:n}){const i=vt(e),r=Is(t),o=B.join(n,"connectors",i,r),a=await s.get(`connectors/${e.id}/download`,{version:t},{responseType:"arraybuffer",headers:{Accept:"application/zip"},timeout:1e6});M.mkdirSync(o,{recursive:!0});const l=B.join(o,"src.zip");if(M.writeFileSync(l,a),!t){const u=B.join(o,"src");M.mkdirSync(u,{recursive:!0}),await to(a,u)}T.info(`[connectors] Pulled connector version: ${e.name} (${r})`)}c(io,"pullConnectorVersion");function vt(s){return s.key}c(vt,"getConnectorDirName");function Is(s){return s??st}c(Is,"getConnectorVersionDirName");function ro(s){return s.match(`${nt}/[^/]+/${st}/src/.*`)!==null}c(ro,"isConnectorSourceFile");async function oo(s){const e=s.match(`${nt}/([^/]+)/${st}/src/(.*)`);if(!e)return;const t=e[1],n=e[2],i=await Cn(t);if(!i){T.warning(`[connectors] Connector ${t} not found. Ignoring file change`);return}const r=i.id,o=M.readFileSync(s,"utf-8");await(await le.getClient()).put(`connectors/${r}/files/${n}`,o,{headers:{"Content-Type":"text/plain"}}),T.info(`[connectors] Pushed file ${n} for connector ${i.name}`)}c(oo,"putConnectorFile");async function ao(s){const e=s.match(`${nt}/([^/]+)/${st}/src/(.*)`);if(!e)return;const t=e[1],n=e[2],i=await Cn(t);if(!i){T.warning(`[connectors] Connector ${t} not found. Ignoring file change`);return}const r=i.id;await(await le.getClient()).delete(`connectors/${r}/files/${n}`),T.info(`[connectors] Deleted file ${n} for connector ${i.name}`)}c(ao,"deleteConnectorFile");const co="membrane",lo=["**/node_modules/**","**/.git/**","**/.DS_Store","**/Thumbs.db","**/*.tmp","**/*.swp","**/*.swo","**/*.log","**/*.lock","**/.cache/**","**/.next/**","**/.vscode/**","**/.idea/**"];function Et(s){return R.join(s,co)}c(Et,"getMembraneDir");const uo=["id","workspaceId","integrationId","createdAt","updatedAt","revision","archivedAt","baseUri","state"],Ts=[P.Action,P.FieldMapping,P.Flow,P.DataSource];class G{static{c(this,"Element")}type;key;integrationKey;data;constructor(e,t,n,i){if(!i)throw new Error("Element must always contain data");if(!t)throw new Error("Element must have a key");this.type=e,this.key=t,this.data=i,this.integrationKey=n||G.extractIntegrationKey(i)}get id(){return G.makeId(this.type,this.key,this.integrationKey)}get dirPath(){const e=ye[this.type].apiPath;if(this.integrationKey){const t=ye[P.Integration].apiPath;return R.join(t,this.integrationKey,e,this.key)}return R.join(e,this.key)}get path(){return R.join(this.dirPath,"spec.yaml")}get relativePath(){return R.relative(Et(process.cwd()),this.path)}isEqual(e){if(this.id!==e.id)return!1;const t=this.clean(),n=e.clean();return dr(t,n)}hasParent(){const e=this.getParentKey();return!!e&&!!this.data?.[e]}clean(){const e={...this.data};return uo.forEach(t=>{delete e[t]}),Object.keys(e).forEach(t=>{t.match(/universal.*Revision/)&&delete e[t]}),e}getParentKey(){let e="parentId";return se?.[this.type]?.parentKey&&(e=se?.[this.type]?.parentKey),e}static new(e,t,n,i){return new G(e,t,n,i)}static fromData(e,t){if(!t?.key)throw new Error(`Element missing key: ${JSON.stringify(t)}`);const n=this.extractIntegrationKey(t);return new G(e,t.key,n,t)}static fromPathAndData(e,t){const n=G.parsePath(e);if(!t)return;const i=t?.key||n?.key;return n?G.new(n.type,i,n.integrationKey,t):void 0}static fromElement(e){return new G(e.type,e.key,e.integrationKey,{...e.data})}static idFromPath(e){const t=G.parsePath(e);if(t)return G.makeId(t.type,t.key,t.integrationKey)}static makeId(e,t,n){return e===P.Integration?`${e}:${t}`:G.isIntegrationSpecific(e)?`${n||"universal"}:${e}:${t}`:`${e}:${t}`}static parsePath(e){const t=this.getRelativePath(e);if(!this.isElementFile(t))return;const n=Object.values(ye).map(l=>l.apiPath).join("|"),i=new RegExp(`^(?<elementType>${n})/(?<elementKey>[^/]+)/spec\\.ya?ml$`),r=t.match(i);if(r?.groups){const{elementType:l,elementKey:u}=r.groups,p=this.getElementTypeFromPath(l);if(p)return{type:p,key:u}}const o=new RegExp(`^integrations/(?<integrationKey>[^/]+)/(?<elementType>${n})/(?<elementKey>[^/]+)/spec\\.ya?ml$`),a=t.match(o);if(a?.groups){const{integrationKey:l,elementType:u,elementKey:p}=a.groups,d=this.getElementTypeFromPath(u);if(d)return{type:d,key:p,integrationKey:l}}}static extractIntegrationKey(e){return e?.integrationKey||e?.integration?.key||e?.integration_key||void 0}static isElementFile(e){return e.endsWith(".yml")||e.endsWith(".yaml")}static getElementTypeFromPath(e){return Object.values(P).find(t=>ye[t].apiPath===e)}static getRelativePath(e){return R.relative(Et(process.cwd()),e)}static isIntegrationSpecific(e){return Ts.includes(e)}static canBeIntegrationSpecific(e){return Ts.includes(e)}}class fo{static{c(this,"LocalElementsHandler")}basePath;constructor(){this.basePath=Et(process.cwd())}async getElementsByType(e,t){const n=[],i=R.join(this.basePath,ye[e].apiPath),r=await this.readElementsInDir(i);n.push(...r);for(const o of t){const a=R.join(this.basePath,ye[P.Integration].apiPath,o.key,ye[e].apiPath),l=await this.readElementsInDir(a);n.push(...l)}return n.length>0&&T.success(`[local] Fetched ${n.length} ${e}${n.length!==1?"s":""}`),n}async fetchElement(e){return this.readElement(e.path)}async createElement(e){return this.updateElement(e,e)}async updateElement(e,t){if(!e.data)throw new Error("Element must have data to write");const n=R.join(this.basePath,t.dirPath),i=R.join(this.basePath,t.path);return x.existsSync(n)||x.mkdirSync(n,{recursive:!0}),x.writeFileSync(i,Ie.dump(e.data)),T.info(`[local] Written ${t.relativePath}`),t}async deleteElement(e){const t=R.join(this.basePath,e.path),n=R.join(this.basePath,e.dirPath);x.existsSync(t)&&x.rmSync(t,{force:!0}),this.pruneEmptyDir(n),T.info(`[local] Deleted ${e.relativePath}`)}async getIntegrations(){const e=R.join(this.basePath,ye[P.Integration].apiPath);return this.readElementsInDir(e)}async readElement(e){if(!x.existsSync(e))return;const t=x.readFileSync(e,"utf8"),n=Ie.load(t);if(n)return G.fromPathAndData(e,n)}async readElementsInDir(e){const t=[];if(!x.existsSync(e))return t;const n=x.readdirSync(e);if(n.length===0)return t;const i=n.map(async o=>{const a=R.join(e,o,"spec.yaml");return this.readElement(a)});return(await Promise.all(i)).filter(o=>o!=null)}pruneEmptyDir(e){try{if(!e.startsWith(this.basePath)||e===this.basePath||!x.existsSync(e)||x.readdirSync(e).length>0)return;x.rmdirSync(e),this.pruneEmptyDir(R.dirname(e))}catch(t){console.warn(`Failed to prune empty directory ${e}:`,t)}}}class ho{static{c(this,"RemoteElementsHandler")}client;async getElementsByType(e,t){const n=await this.findAll(e);if(!G.canBeIntegrationSpecific(e))return n;for(const i of t){const r=i.key,o=i.data.id,a=await this.findAll(e,{integrationKey:r,integrationId:o});n.push(...a)}return n.length>0&&T.success(`[remote] Fetched ${n.length} ${e}${n.length!==1?"s":""}`),n}async fetchElement(e){const n=await(await this.getClient())[se[e.type].element](e.data.id).get();return G.fromData(e.type,n)}async createElement(e,t){const n=e.clean(),i=await this.getClient();this.transformElementForCreate(e,n,t),e.key==="download-document-by-id"&&T.info(`CREATE ${e.id}:`+JSON.stringify(n));const r=await i[se[e.type].elements].create(n),o=G.fromData(e.type,r);return T.info(`[remote] Created ${o.id}`),o}async updateElement(e,t,n){if(!e.data.id)throw new Error("Element must have an id to update");const i=e.clean(),r=await this.getClient();this.transformElementForUpdate(e,i,n);const o=await r[se[e.type].element](t.data.id).put(i),a=G.fromData(t.type,o);return T.info(`[remote] Updated ${t.id}`),a}async deleteElement(e){if(!e.data.id)throw new Error("Element must have an id to delete");await(await this.getClient())[se[e.type].element](e.data.id).archive(),T.info(`[remote] Deleted ${e.id}`)}async getIntegrations(){const n=(await(await this.getClient()).integrations.findAll()).map(i=>G.fromData(P.Integration,i));return n.length>0&&T.success(`[remote] Fetched ${n.length} integrations`),n}transformElementForCreate(e,t,n){if(e.integrationKey){const i=n.elements.find(r=>r.type===P.Integration&&r.key===e.integrationKey);if(i)t.integrationId=i.data.id;else throw new Error(`Integration ${e.integrationKey} not found. Integrations: ${n.elements.filter(r=>r.type===P.Integration).map(r=>r.key).join(", ")}`)}if(e.type===P.Integration){const i=n.connectorsMapping?.[t.connectorId];i&&(t.connectorId=i)}}transformElementForUpdate(e,t,n){if(e.type===P.Integration){const i=n.connectorsMapping?.[t.connectorId];i&&(t.connectorId=i)}if(e.integrationKey){t.integrationKey=e.integrationKey;const i=n.elements.find(r=>r.type===P.Integration&&r.key===e.integrationKey);if(i)t.integrationId=i.data.id;else throw new Error(`Integration ${e.integrationKey} not found. Integrations: ${n.elements.filter(r=>r.type===P.Integration).map(r=>r.key).join(", ")}`)}}async findAll(e,t={}){return(await(await this.getClient())[se[e].elements].findAll(t)).filter(r=>r.key).map(r=>G.fromData(e,r))}async getClient(){return this.client||(this.client=await le.getClient(process.cwd())),this.client}}const kn=Symbol.for("yaml.alias"),vn=Symbol.for("yaml.document"),be=Symbol.for("yaml.map"),Ns=Symbol.for("yaml.pair"),he=Symbol.for("yaml.scalar"),Me=Symbol.for("yaml.seq"),ie=Symbol.for("yaml.node.type"),Se=c(s=>!!s&&typeof s=="object"&&s[ie]===kn,"isAlias"),Te=c(s=>!!s&&typeof s=="object"&&s[ie]===vn,"isDocument"),Re=c(s=>!!s&&typeof s=="object"&&s[ie]===be,"isMap"),j=c(s=>!!s&&typeof s=="object"&&s[ie]===Ns,"isPair"),K=c(s=>!!s&&typeof s=="object"&&s[ie]===he,"isScalar$1"),Ke=c(s=>!!s&&typeof s=="object"&&s[ie]===Me,"isSeq");function U(s){if(s&&typeof s=="object")switch(s[ie]){case be:case Me:return!0}return!1}c(U,"isCollection$1");function q(s){if(s&&typeof s=="object")switch(s[ie]){case kn:case be:case he:case Me:return!0}return!1}c(q,"isNode");const As=c(s=>(K(s)||U(s))&&!!s.anchor,"hasAnchor"),ee=Symbol("break visit"),Os=Symbol("skip children"),de=Symbol("remove node");function Ne(s,e){const t=$s(e);Te(s)?_e(null,s.contents,t,Object.freeze([s]))===de&&(s.contents=null):_e(null,s,t,Object.freeze([]))}c(Ne,"visit$1"),Ne.BREAK=ee,Ne.SKIP=Os,Ne.REMOVE=de;function _e(s,e,t,n){const i=Ls(s,e,t,n);if(q(i)||j(i))return Ds(s,n,i),_e(s,i,t,n);if(typeof i!="symbol"){if(U(e)){n=Object.freeze(n.concat(e));for(let r=0;r<e.items.length;++r){const o=_e(r,e.items[r],t,n);if(typeof o=="number")r=o-1;else{if(o===ee)return ee;o===de&&(e.items.splice(r,1),r-=1)}}}else if(j(e)){n=Object.freeze(n.concat(e));const r=_e("key",e.key,t,n);if(r===ee)return ee;r===de&&(e.key=null);const o=_e("value",e.value,t,n);if(o===ee)return ee;o===de&&(e.value=null)}}return i}c(_e,"visit_");async function It(s,e){const t=$s(e);Te(s)?await je(null,s.contents,t,Object.freeze([s]))===de&&(s.contents=null):await je(null,s,t,Object.freeze([]))}c(It,"visitAsync"),It.BREAK=ee,It.SKIP=Os,It.REMOVE=de;async function je(s,e,t,n){const i=await Ls(s,e,t,n);if(q(i)||j(i))return Ds(s,n,i),je(s,i,t,n);if(typeof i!="symbol"){if(U(e)){n=Object.freeze(n.concat(e));for(let r=0;r<e.items.length;++r){const o=await je(r,e.items[r],t,n);if(typeof o=="number")r=o-1;else{if(o===ee)return ee;o===de&&(e.items.splice(r,1),r-=1)}}}else if(j(e)){n=Object.freeze(n.concat(e));const r=await je("key",e.key,t,n);if(r===ee)return ee;r===de&&(e.key=null);const o=await je("value",e.value,t,n);if(o===ee)return ee;o===de&&(e.value=null)}}return i}c(je,"visitAsync_");function $s(s){return typeof s=="object"&&(s.Collection||s.Node||s.Value)?Object.assign({Alias:s.Node,Map:s.Node,Scalar:s.Node,Seq:s.Node},s.Value&&{Map:s.Value,Scalar:s.Value,Seq:s.Value},s.Collection&&{Map:s.Collection,Seq:s.Collection},s):s}c($s,"initVisitor");function Ls(s,e,t,n){if(typeof t=="function")return t(s,e,n);if(Re(e))return t.Map?.(s,e,n);if(Ke(e))return t.Seq?.(s,e,n);if(j(e))return t.Pair?.(s,e,n);if(K(e))return t.Scalar?.(s,e,n);if(Se(e))return t.Alias?.(s,e,n)}c(Ls,"callVisitor");function Ds(s,e,t){const n=e[e.length-1];if(U(n))n.items[s]=t;else if(j(n))s==="key"?n.key=t:n.value=t;else if(Te(n))n.contents=t;else{const i=Se(n)?"alias":"scalar";throw new Error(`Cannot replace node with ${i} parent`)}}c(Ds,"replaceNode");const po={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},mo=c(s=>s.replace(/[!,[\]{}]/g,e=>po[e]),"escapeTagName");class Z{static{c(this,"Directives")}constructor(e,t){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},Z.defaultYaml,e),this.tags=Object.assign({},Z.defaultTags,t)}clone(){const e=new Z(this.yaml,this.tags);return e.docStart=this.docStart,e}atDocument(){const e=new Z(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:Z.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},Z.defaultTags);break}return e}add(e,t){this.atNextDocument&&(this.yaml={explicit:Z.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},Z.defaultTags),this.atNextDocument=!1);const n=e.trim().split(/[ \t]+/),i=n.shift();switch(i){case"%TAG":{if(n.length!==2&&(t(0,"%TAG directive should contain exactly two parts"),n.length<2))return!1;const[r,o]=n;return this.tags[r]=o,!0}case"%YAML":{if(this.yaml.explicit=!0,n.length!==1)return t(0,"%YAML directive should contain exactly one part"),!1;const[r]=n;if(r==="1.1"||r==="1.2")return this.yaml.version=r,!0;{const o=/^\d+\.\d+$/.test(r);return t(6,`Unsupported YAML version ${r}`,o),!1}}default:return t(0,`Unknown directive ${i}`,!0),!1}}tagName(e,t){if(e==="!")return"!";if(e[0]!=="!")return t(`Not a valid tag: ${e}`),null;if(e[1]==="<"){const o=e.slice(2,-1);return o==="!"||o==="!!"?(t(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==">"&&t("Verbatim tags must end with a >"),o)}const[,n,i]=e.match(/^(.*!)([^!]*)$/s);i||t(`The ${e} tag has no suffix`);const r=this.tags[n];if(r)try{return r+decodeURIComponent(i)}catch(o){return t(String(o)),null}return n==="!"?e:(t(`Could not resolve tag: ${e}`),null)}tagString(e){for(const[t,n]of Object.entries(this.tags))if(e.startsWith(n))return t+mo(e.substring(n.length));return e[0]==="!"?e:`!<${e}>`}toString(e){const t=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],n=Object.entries(this.tags);let i;if(e&&n.length>0&&q(e.contents)){const r={};Ne(e.contents,(o,a)=>{q(a)&&a.tag&&(r[a.tag]=!0)}),i=Object.keys(r)}else i=[];for(const[r,o]of n)r==="!!"&&o==="tag:yaml.org,2002:"||(!e||i.some(a=>a.startsWith(o)))&&t.push(`%TAG ${r} ${o}`);return t.join(`
3
3
  `)}}Z.defaultYaml={explicit:!1,version:"1.2"},Z.defaultTags={"!!":"tag:yaml.org,2002:"};function xs(s){if(/[\x00-\x19\s,[\]{}]/.test(s)){const t=`Anchor must not contain whitespace or control characters: ${JSON.stringify(s)}`;throw new Error(t)}return!0}c(xs,"anchorIsValid");function Ps(s){const e=new Set;return Ne(s,{Value(t,n){n.anchor&&e.add(n.anchor)}}),e}c(Ps,"anchorNames");function Ms(s,e){for(let t=1;;++t){const n=`${s}${t}`;if(!e.has(n))return n}}c(Ms,"findNewAnchor");function go(s,e){const t=[],n=new Map;let i=null;return{onAnchor:c(r=>{t.push(r),i??(i=Ps(s));const o=Ms(e,i);return i.add(o),o},"onAnchor"),setAnchors:c(()=>{for(const r of t){const o=n.get(r);if(typeof o=="object"&&o.anchor&&(K(o.node)||U(o.node)))o.node.anchor=o.anchor;else{const a=new Error("Failed to resolve repeated object (this should not happen)");throw a.source=r,a}}},"setAnchors"),sourceObjects:n}}c(go,"createNodeAnchors");function Fe(s,e,t,n){if(n&&typeof n=="object")if(Array.isArray(n))for(let i=0,r=n.length;i<r;++i){const o=n[i],a=Fe(s,n,String(i),o);a===void 0?delete n[i]:a!==o&&(n[i]=a)}else if(n instanceof Map)for(const i of Array.from(n.keys())){const r=n.get(i),o=Fe(s,n,i,r);o===void 0?n.delete(i):o!==r&&n.set(i,o)}else if(n instanceof Set)for(const i of Array.from(n)){const r=Fe(s,n,i,i);r===void 0?n.delete(i):r!==i&&(n.delete(i),n.add(r))}else for(const[i,r]of Object.entries(n)){const o=Fe(s,n,i,r);o===void 0?delete n[i]:o!==r&&(n[i]=o)}return s.call(e,t,n)}c(Fe,"applyReviver");function re(s,e,t){if(Array.isArray(s))return s.map((n,i)=>re(n,String(i),t));if(s&&typeof s.toJSON=="function"){if(!t||!As(s))return s.toJSON(e,t);const n={aliasCount:0,count:1,res:void 0};t.anchors.set(s,n),t.onCreate=r=>{n.res=r,delete t.onCreate};const i=s.toJSON(e,t);return t.onCreate&&t.onCreate(i),i}return typeof s=="bigint"&&!t?.keep?Number(s):s}c(re,"toJS");class En{static{c(this,"NodeBase")}constructor(e){Object.defineProperty(this,ie,{value:e})}clone(){const e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:t,maxAliasCount:n,onAnchor:i,reviver:r}={}){if(!Te(e))throw new TypeError("A document argument is required");const o={anchors:new Map,doc:e,keep:!0,mapAsMap:t===!0,mapKeyWarned:!1,maxAliasCount:typeof n=="number"?n:100},a=re(this,"",o);if(typeof i=="function")for(const{count:l,res:u}of o.anchors.values())i(u,l);return typeof r=="function"?Fe(r,{"":a},"",a):a}}class Tt extends En{static{c(this,"Alias")}constructor(e){super(kn),this.source=e,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(e,t){let n;t?.aliasResolveCache?n=t.aliasResolveCache:(n=[],Ne(e,{Node:c((r,o)=>{(Se(o)||As(o))&&n.push(o)},"Node")}),t&&(t.aliasResolveCache=n));let i;for(const r of n){if(r===this)break;r.anchor===this.source&&(i=r)}return i}toJSON(e,t){if(!t)return{source:this.source};const{anchors:n,doc:i,maxAliasCount:r}=t,o=this.resolve(i,t);if(!o){const l=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(l)}let a=n.get(o);if(a||(re(o,null,t),a=n.get(o)),!a||a.res===void 0){const l="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(l)}if(r>=0&&(a.count+=1,a.aliasCount===0&&(a.aliasCount=Nt(i,o,n)),a.count*a.aliasCount>r)){const l="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(l)}return a.res}toString(e,t,n){const i=`*${this.source}`;if(e){if(xs(this.source),e.options.verifyAliasOrder&&!e.anchors.has(this.source)){const r=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(r)}if(e.implicitKey)return`${i} `}return i}}function Nt(s,e,t){if(Se(e)){const n=e.resolve(s),i=t&&n&&t.get(n);return i?i.count*i.aliasCount:0}else if(U(e)){let n=0;for(const i of e.items){const r=Nt(s,i,t);r>n&&(n=r)}return n}else if(j(e)){const n=Nt(s,e.key,t),i=Nt(s,e.value,t);return Math.max(n,i)}return 1}c(Nt,"getAliasCount");const Rs=c(s=>!s||typeof s!="function"&&typeof s!="object","isScalarValue");class L extends En{static{c(this,"Scalar")}constructor(e){super(he),this.value=e}toJSON(e,t){return t?.keep?this.value:re(this.value,e,t)}toString(){return String(this.value)}}L.BLOCK_FOLDED="BLOCK_FOLDED",L.BLOCK_LITERAL="BLOCK_LITERAL",L.PLAIN="PLAIN",L.QUOTE_DOUBLE="QUOTE_DOUBLE",L.QUOTE_SINGLE="QUOTE_SINGLE";const yo="tag:yaml.org,2002:";function wo(s,e,t){if(e){const n=t.filter(r=>r.tag===e),i=n.find(r=>!r.format)??n[0];if(!i)throw new Error(`Tag ${e} not found`);return i}return t.find(n=>n.identify?.(s)&&!n.format)}c(wo,"findTagObject");function it(s,e,t){if(Te(s)&&(s=s.contents),q(s))return s;if(j(s)){const d=t.schema[be].createNode?.(t.schema,null,t);return d.items.push(s),d}(s instanceof String||s instanceof Number||s instanceof Boolean||typeof BigInt<"u"&&s instanceof BigInt)&&(s=s.valueOf());const{aliasDuplicateObjects:n,onAnchor:i,onTagObj:r,schema:o,sourceObjects:a}=t;let l;if(n&&s&&typeof s=="object"){if(l=a.get(s),l)return l.anchor??(l.anchor=i(s)),new Tt(l.anchor);l={anchor:null,node:null},a.set(s,l)}e?.startsWith("!!")&&(e=yo+e.slice(2));let u=wo(s,e,o.tags);if(!u){if(s&&typeof s.toJSON=="function"&&(s=s.toJSON()),!s||typeof s!="object"){const d=new L(s);return l&&(l.node=d),d}u=s instanceof Map?o[be]:Symbol.iterator in Object(s)?o[Me]:o[be]}r&&(r(u),delete t.onTagObj);const p=u?.createNode?u.createNode(t.schema,s,t):typeof u?.nodeClass?.from=="function"?u.nodeClass.from(t.schema,s,t):new L(s);return e?p.tag=e:u.default||(p.tag=u.tag),l&&(l.node=p),p}c(it,"createNode");function At(s,e,t){let n=t;for(let i=e.length-1;i>=0;--i){const r=e[i];if(typeof r=="number"&&Number.isInteger(r)&&r>=0){const o=[];o[r]=n,n=o}else n=new Map([[r,n]])}return it(n,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:c(()=>{throw new Error("This should not happen, please report a bug.")},"onAnchor"),schema:s,sourceObjects:new Map})}c(At,"collectionFromPath");const rt=c(s=>s==null||typeof s=="object"&&!!s[Symbol.iterator]().next().done,"isEmptyPath");class Ks extends En{static{c(this,"Collection")}constructor(e,t){super(e),Object.defineProperty(this,"schema",{value:t,configurable:!0,enumerable:!1,writable:!0})}clone(e){const t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return e&&(t.schema=e),t.items=t.items.map(n=>q(n)||j(n)?n.clone(e):n),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(rt(e))this.add(t);else{const[n,...i]=e,r=this.get(n,!0);if(U(r))r.addIn(i,t);else if(r===void 0&&this.schema)this.set(n,At(this.schema,i,t));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${i}`)}}deleteIn(e){const[t,...n]=e;if(n.length===0)return this.delete(t);const i=this.get(t,!0);if(U(i))return i.deleteIn(n);throw new Error(`Expected YAML collection at ${t}. Remaining path: ${n}`)}getIn(e,t){const[n,...i]=e,r=this.get(n,!0);return i.length===0?!t&&K(r)?r.value:r:U(r)?r.getIn(i,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!j(t))return!1;const n=t.value;return n==null||e&&K(n)&&n.value==null&&!n.commentBefore&&!n.comment&&!n.tag})}hasIn(e){const[t,...n]=e;if(n.length===0)return this.has(t);const i=this.get(t,!0);return U(i)?i.hasIn(n):!1}setIn(e,t){const[n,...i]=e;if(i.length===0)this.set(n,t);else{const r=this.get(n,!0);if(U(r))r.setIn(i,t);else if(r===void 0&&this.schema)this.set(n,At(this.schema,i,t));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${i}`)}}}const bo=c(s=>s.replace(/^(?!$)(?: $)?/gm,"#"),"stringifyComment");function pe(s,e){return/^\n+$/.test(s)?s.substring(1):e?s.replace(/^(?! *$)/gm,e):s}c(pe,"indentComment");const Ae=c((s,e,t)=>s.endsWith(`
4
4
  `)?pe(t,e):t.includes(`
5
5
  `)?`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@membranehq/cli",
3
- "version": "0.10.4",
3
+ "version": "0.10.6",
4
4
  "keywords": [
5
5
  "cli",
6
6
  "integration",
@@ -33,7 +33,7 @@
33
33
  "@buildwithlayer/openapi-to-tools": "^1.3.3",
34
34
  "@faker-js/faker": "^9.8.0",
35
35
  "@inkjs/ui": "^2.0.0",
36
- "@membranehq/sdk": "^0.7.0",
36
+ "@membranehq/sdk": "^0.7.3",
37
37
  "@types/jsonwebtoken": "^9.0.10",
38
38
  "archiver": "^7.0.1",
39
39
  "axios": "^1.10.0",