@membranehq/cli 0.10.0 → 0.10.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -53,6 +53,7 @@ The CLI uses a configuration file at `membrane.config.yml`:
53
53
  ```yaml
54
54
  workspaceKey: <your-workspace-key>
55
55
  workspaceSecret: <your-workspace-secret>
56
+ # Optional
56
57
  apiUri: https://api.integration.app # Set it to work with a self-hosted version of Membrane
57
58
  testCustomerId: test-customer # Internal id of the customer to be used for testing integrations.
58
59
  ```
@@ -65,6 +66,46 @@ testCustomerId: test-customer # Internal id of the customer to be used for testi
65
66
 
66
67
  `membrane` folder can and should be stored in version control to keep your integration configurations versioned.
67
68
 
69
+ ## Syncing between workspaces with `pull` and `push`
70
+
71
+ The CLI provides a `pull` and `push` command to sync elements between your workspaces. You'd typically use this to sync elements between your development and production workspaces.
72
+
73
+ **Usage**
74
+
75
+ ```bash
76
+ membrane pull
77
+
78
+ # Change workspace credentials in membrane.config.yml / environment variables
79
+
80
+ membrane push
81
+ ```
82
+
83
+ **Sample workspace sync script**
84
+
85
+ ```bash
86
+
87
+ echo "🚀 Starting Membrane workspace sync workflow..."
88
+
89
+ # Step 1: Set up environment variables for development workspace
90
+ echo "📝 Setting up development workspace credentials..."
91
+ export MEMBRANE_WORKSPACE_KEY="dev-workspace-key-123"
92
+ export MEMBRANE_WORKSPACE_SECRET="dev-workspace-secret-456"
93
+
94
+ # Step 2: Pull latest changes from development workspace
95
+ echo "⬇️ Pulling latest changes from development workspace..."
96
+ membrane pull
97
+
98
+ # Step 3: Switch to production workspace credentials
99
+ echo "🔄 Switching to production workspace credentials..."
100
+ export MEMBRANE_WORKSPACE_KEY="prod-workspace-key-789"
101
+ export MEMBRANE_WORKSPACE_SECRET="prod-workspace-secret-012"
102
+
103
+ # Step 4: Push changes to production workspace
104
+ echo "⬆️ Pushing changes to production workspace..."
105
+ membrane push
106
+ ```
107
+
108
+
68
109
  ## License
69
110
 
70
111
  MIT
package/dist/index.js CHANGED
@@ -1,6 +1,5 @@
1
1
  #!/usr/bin/env node
2
- #!/usr/bin/env node
3
- var qi=Object.defineProperty;var c=(s,e)=>qi(s,"name",{value:e,configurable:!0});import{jsx as m,jsxs as E,Fragment as en}from"react/jsx-runtime";import*as x from"node:path";import{resolve as Wi,dirname as Ji,join as Gi}from"node:path";import{useInput as Pe,Box as b,Text as S,Newline as Vi,render as mt}from"ink";import Hi from"minimist";import{SWRConfig as Yi}from"swr";import xe,{createContext as ss,useState as j,useEffect as Ie,useContext as is,useMemo as zi,useRef as Qi}from"react";import rs from"swr/immutable";import os from"os";import B from"path";import Xi from"conf";import{exec as Zi}from"node:child_process";import*as P from"node:fs";import{readFileSync as er}from"node:fs";import{EventEmitter as tr}from"events";import{IntegrationAppClient as as,WorkspaceElementType as K,extractIntegrationAppErrorData as te,WorkspaceElementSpecs as we,setValueAtLocator as tn,getDataCollectionCreateFields as nn,excludeWriteOnlyFieldsFromSchema as cs,valueToSchema as gt,getRequiredFieldsFromSchema as nr,getValueAtLocator as sr,walkSchema as ls,makeDataLocationPath as us,getDataCollectionUpdateFields as sn}from"@membranehq/sdk";import rn from"jsonwebtoken";import pe from"js-yaml";import{z as W}from"zod";import{Spinner as ir,TextInput as rr,Select as or}from"@inkjs/ui";import yt from"ink-spinner";import ar from"ink-text-input";import*as cr from"node:crypto";import{createHash as lr}from"node:crypto";import*as ur from"node:os";import M from"fs";import fr from"archiver";import hr from"form-data";import dr from"unzipper";import pr from"lodash/isEqual.js";import mr from"chokidar";import{fileURLToPath as gr}from"node:url";import k from"chalk";import{Command as yr}from"commander";import on from"axios";import{FastMCP as wr}from"fastmcp";import an from"lodash/merge.js";import br from"@anthropic-ai/sdk";import{faker as Xe}from"@faker-js/faker";import Sr from"lodash/template.js";import Cr 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"},fs=ss(null);function kr({children:s,membraneCLIService:e}){const{data:t}=rs("/account"),[n,i]=j(D.NOT_INITIALIZED),[r,o]=j([]),[a,l]=j({}),[u,p]=j([]),[d,h]=j(null),w=t?.workspaces?.find(f=>f.workspaceKey===d?.workspaceKey)||null;return Ie(()=>{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(fs.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(kr,"MembraneCLIServiceProvider");function oe(){const s=is(fs);if(!s)throw new Error("useMembraneCLIService must be used within MembraneCLIServiceProvider");return s}c(oe,"useMembraneCLIService");const vr="membrane",Er="membrane.config.yml",cn="https://api.integration.app";function ln(){const s=process.cwd(),e=x.join(s,vr),t=x.join(s,Er),n=e,i=x.join(n,"workspace.yaml");return{membraneDirPath:e,configPath:t,payloadDirPath:n,workspaceDataFilePath:i}}c(ln,"getPaths");function Ir(){return ln().membraneDirPath}c(Ir,"getBasePath");const Tr={pat:{type:"string"},workspace:{type:"object"}},hs=new Xi({schema:Tr,configName:"config",cwd:B.join(os.homedir(),".membrane")}),Nr=c(s=>{hs.set("pat",s)},"setPat"),ds=c(()=>hs.get("pat"),"getPat");class ps{static{c(this,"AccountApiClient")}constructor(e=cn){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=ds();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 Ar=c(s=>{const e=new ps(cn);return t=>e.get(t)},"createAccountApiFetcher"),ms=ss(process.cwd());function Or({cwd:s,children:e}){return m(ms.Provider,{value:s,children:e})}c(Or,"CwdProvider");function $r(){return is(ms)}c($r,"useCwd");function wt({cwd:s,children:e,membraneCLIService:t}){const n=s||process.cwd();return m(Or,{cwd:n,children:m(Yi,{value:{fetcher:Ar()},children:m(kr,{membraneCLIService:t,children:e})})})}c(wt,"Layout");const un=[{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=x.join(process.cwd(),".mcp.json"),e={mcpServers:{membrane:{command:"membrane",args:["mcp"],env:{AGENT_NAME:"Claude Code"}}}};let t={};if(P.existsSync(s))try{t=JSON.parse(P.readFileSync(s,"utf8"))}catch{t={}}const n={...t,mcpServers:{...t.mcpServers,...e.mcpServers}};return P.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=x.join(process.cwd(),".cursor"),e=x.join(s,"mcp.json");P.existsSync(s)||P.mkdirSync(s);const t={mcpServers:{membrane:{command:"membrane",args:["mcp"],env:{AGENT_NAME:"Cursor"}}}};let n={};if(P.existsSync(e))try{n=JSON.parse(P.readFileSync(e,"utf8"))}catch{n={}}const i={...n,mcpServers:{...n.mcpServers,...t.mcpServers}};return P.writeFileSync(e,JSON.stringify(i,null,2)),`MCP server configuration added to ${e}`},"addConfig")}];function Lr({onExit:s,onComplete:e}){const[t,n]=j(0),[i,r]=j(!1),[o,a]=j(null),[l,u]=j(""),[p,d]=j("");Pe((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(un.length-1,t+1));else if(f.return||w===" "){const y=un[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:un.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(Lr,"AddMcpServerScreen");class gs extends tr{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)}}const ys="membrane.config.yml",bt=W.object({workspaceKey:W.string(),workspaceSecret:W.string(),apiUri:W.string().optional(),testCustomerId:W.string().optional(),anthropicApiKey:W.string().optional()});class He{static{c(this,"ConfigLoader")}static instance=null;cachedConfig=null;lastCwd=null;constructor(){}static getInstance(){return He.instance||(He.instance=new He),He.instance}loadConfig(e){const t=e??process.cwd();if(this.cachedConfig&&this.lastCwd===t)return this.cachedConfig;this.lastCwd=t;const n=this.loadFromFile(t),i=this.loadFromEnv(),r={...n,...i},o=bt.safeParse(r);return o.success?(this.cachedConfig=o.data,o.data):(this.cachedConfig=null,null)}clearCache(){this.cachedConfig=null,this.lastCwd=null}updateConfig(e){const t={...this.cachedConfig??{},...e},n=bt.safeParse(t),i=this.lastCwd??process.cwd();return this.saveToFile(e,i),n.success?(this.cachedConfig=n.data,this.cachedConfig):(this.cachedConfig=null,null)}isCacheDefined(e){return bt.safeParse(e).success}loadFromFile(e){const t=x.join(e,ys);try{const n=P.readFileSync(t,"utf8"),i=pe.load(n),r=bt.safeParse(i);return r.success?r.data:{}}catch{return{}}}loadFromEnv(){const e={};return process.env.MEMBRANE_WORKSPACE_KEY&&(e.workspaceKey=process.env.MEMBRANE_WORKSPACE_KEY),process.env.MEMBRANE_WORKSPACE_SECRET&&(e.workspaceSecret=process.env.MEMBRANE_WORKSPACE_SECRET),process.env.MEMBRANE_API_URI&&(e.apiUri=process.env.MEMBRANE_API_URI),process.env.MEMBRANE_TEST_CUSTOMER_ID&&(e.testCustomerId=process.env.MEMBRANE_TEST_CUSTOMER_ID),e}saveToFile(e,t){const n=t??process.cwd(),i=x.join(n,ys),o={...this.loadFromFile(n),...e},a=this.loadFromEnv();for(const l of Object.keys(a))a[l]===o[l]&&delete o[l];try{return P.writeFileSync(i,pe.dump(o)),!0}catch{return!1}}}const Ze=He.getInstance();function St(s){return Ze.loadConfig(s)}c(St,"readProjectConfig");class Dr{static{c(this,"MembraneClient")}client=null;currentConfig=null;tokenExpiry=0;async generateAccessToken(e,t){return rn.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=St(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 as({token:t,apiUri:e.apiUri})}async getClient(e=process.cwd()){const t=this.getCurrentConfig(e);if(!t)throw new Error("Unable to create IntegrationAppClient: 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 Dr;async function ws(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(ws,"getWorkspaceId");class Pr extends gs{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:os.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 Pr({heartbeatIntervalMs:15e3});function xr(){const[s,e]=j(null),[t,n]=j([]),[i,r]=j(null);return Ie(()=>{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 Mr(){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(Vi,{}),"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(Mr,"Agent");const Ct=c(s=>{switch(s){case"error":return"red";case"success":return"green";case"warning":return"yellow";default:return}},"getLogColor");function bs(s,e){return e<3?s.slice(0,Math.max(0,e)):s.length<=e?s:`${s.slice(0,e-3)}...`}c(bs,"truncateText");function fn({children:s}){const{state:e,logs:t}=oe();if(!e||e===D.NOT_INITIALIZED)return E(b,{gap:1,flexDirection:"row",children:[m(ir,{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:Ct(i.type),children:i.message},i.timestamp+r))})}return s}c(fn,"EnsureInitialized");function Ss({onExit:s,showEscOption:e=!0}){const[t,n]=j(""),{data:i,error:r,isLoading:o}=rs("/account"),{updateConfig:a}=oe(),l=i?.workspaces,u=o;if(Pe((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{workspaceKey:C,workspaceSecret: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(rr,{placeholder:"Enter a search query...",onChange:n})]}),g>5&&E(S,{children:["Showing ",h," of ",g," workspaces."]}),m(b,{marginTop:1,children:m(or,{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(Ss,"SelectWorkspace");function Rr({currentPat:s,onSubmit:e}){const[t,n]=j(""),[i,r]=j(!1),[o,a]=j(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(ar,{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(Rr,"PersonalAccessTokenInput");var et=(s=>(s[s.Authenticate=0]="Authenticate",s[s.ConnectWorkspace=1]="ConnectWorkspace",s))(et||{});const _r={0:"Authenticate in Membrane",1:"Connect a Membrane Workspace"},hn=[et.Authenticate,et.ConnectWorkspace];function Cs({onComplete:s}){const{config:e}=oe(),[t,n]=j(!1),[i,r]=j(0),o=!!(e?.workspaceKey&&e?.workspaceSecret),a=ds(),l=hn[i],u=i+1,p=hn.length,d=hn.map((w,f)=>{let y="pending";return f<i?y="done":f===i&&(y="current"),{id:w,label:_r[w],status:y}});async function h(w){const f=a&&w===""?a:w,y=new ps;try{await y.request("/account",{headers:{Authorization:`Bearer ${f}`}}),Nr(f),r(C=>C+1)}catch(C){console.error(C)}}c(h,"handlePatSubmit");function g(){n(!0),s&&s()}return c(g,"handleWorkspaceSelected"),Pe((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(Rr,{currentPat:a,onSubmit:h}),l===et.ConnectWorkspace&&m(Ss,{onExit:g,showEscOption:!1})]})}c(Cs,"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 dn(){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(dn,"ElementStats");const pn=5,Fr=6;function jr(){const{logs:s}=oe(),[e,t]=j(0),n=Math.min(100,process.stdout.columns||100),i=pn,r=Math.max(0,s.length-i-e),o=s.length-e,a=s.slice(r,o),l=n-Fr,u=e<s.length-i,p=e>0;return Pe((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>pn&&m(S,{color:"grey",children:" [arrows: scroll] [g: end]"})]}),a.map((d,h)=>m(b,{marginLeft:1,children:m(S,{color:Ct(d.type),children:bs(d.message,l)})},d.timestamp+h)),s.length>pn&&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"},kt=[{value:"sync",label:"Continue (overwrite/delete)",key:""},{value:"exit",label:"Cancel",key:""}];function Br(){const{state:s,resolveConflicts:e,exit:t}=oe(),[n,i]=j(0),[r,o]=j(!1);return Pe((a,l)=>{r||(l.upArrow?i(u=>u>0?u-1:kt.length-1):l.downArrow?i(u=>u<kt.length-1?u+1:0):a.toLowerCase()==="y"?i(0):a.toLowerCase()==="n"?i(1):(l.return||a===" ")&&(o(!0),kt[n].value==="sync"?e({watch:!0}):t()))}),Ie(()=>{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(mn,{})}),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:kt.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(Br,"ResolveChangesUI");const Ur={[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 mn(){const{conflicts:s}=oe(),e=zi(()=>{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=Ur[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(mn,"Conflicts");function qr(){const{config:s,state:e,logs:t,currentWorkspace:n,pull:i}=oe(),r=n?.name,o=r?bs(r,30):s?.workspaceKey,a=Math.min(100,process.stdout.columns||100);return Ie(()=>{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:[" [",Wr(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(Br,{}):E(en,{children:[m(b,{paddingTop:1,children:m(dn,{})}),t.length>0&&m(jr,{})]})]})}c(qr,"Workspace");function Wr(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(Wr,"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 Gr="https://console.integration.app/w";function Vr(){const s=$r(),e=Qi(!0),{exit:t,state:n}=oe(),[i,r]=j(null),o=i??(n===D.SETTING_UP?"setup":"main");Pe(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 ws(s),u=`${Gr}/${l}`,p=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";Zi(`${p} "${u}"`)}catch(l){console.error("Failed to open workspace:",l),t()}}return c(a,"handleOpenWorkspace"),Ie(()=>(e.current=!0,()=>{e.current=!1}),[]),o==="workspace-selection"?m(Ss,{onExit:c(()=>r(null),"onExit")}):o==="add-mcp-server"?m(Lr,{onExit:c(()=>r(null),"onExit"),onComplete:c(()=>r(null),"onComplete")}):o==="setup"?m(Cs,{onComplete:c(()=>r(null),"onComplete")},Date.now()):m(fn,{children:E(b,{flexDirection:"column",children:[m(b,{flexGrow:1,children:m(Mr,{})}),m(qr,{}),m(b,{paddingLeft:2,children:m(S,{color:"grey",children:"[s: (re-)setup]"})})]})})}c(Vr,"Main");class Hr{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 Hr,be=x.join(ur.tmpdir(),"membrane-mcp-status"),ks=3e4;class Yr{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=vt(void 0,e),n=vs(e);t&&ue.setMcpStatus(t),await ue.setMcpServers(n)}catch{T.error("Failed to check MCP status")}}}function vt(s,e){try{const t=e||process.cwd();if(!s){const i=vs(t);return i.length===0?null:i[0]}const n=wn(s,t);if(P.existsSync(n)){const i=P.statSync(n),r=new Date;if(r.getTime()-i.mtime.getTime()>ks)return tt(s,t),null;const a=P.readFileSync(n,"utf8"),l=JSON.parse(a);if(l.isRunning){const u=new Date(l.lastActivity).getTime();if(r.getTime()-u>ks)return tt(s,t),null}return l}}catch{s&&e&&tt(s,e)}return null}c(vt,"getMcpStatus");function vs(s){try{const e=s||process.cwd(),t=yn(e);if(!P.existsSync(be))return[];const n=P.readdirSync(be),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=vt(a,e);l&&i.push(l)}}return i.sort((r,o)=>new Date(o.startTime).getTime()-new Date(r.startTime).getTime())}catch{return[]}}c(vs,"getAllMcpStatusFiles");function gn(s){try{const t={...vt(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};P.existsSync(be)||P.mkdirSync(be,{recursive:!0});const n=wn(s.processId,s.cwd);P.writeFileSync(n,JSON.stringify(t,null,2))}catch{}}c(gn,"updateMcpStatus");function tt(s,e){try{const t=e||process.cwd();if(s){const n=wn(s,t);P.existsSync(n)&&P.unlinkSync(n)}else{const n=yn(t);if(P.existsSync(be)){const i=P.readdirSync(be);for(const r of i)r.match(new RegExp(`^mcp-${n}-\\d+\\.json$`))&&P.unlinkSync(x.join(be,r))}}}catch{}}c(tt,"clearMcpStatus");function zr(s,e){const t=vt(s,e);t&&gn({processId:s,cwd:e,totalRequests:t.totalRequests+1,lastRequestTime:new Date().toISOString(),lastActivity:new Date().toISOString()})}c(zr,"trackToolExecution");function yn(s){return lr("md5").update(s).digest("hex").slice(0,8)}c(yn,"getCwdHash");function wn(s,e){const t=yn(e);return x.join(be,`mcp-${t}-${s}.json`)}c(wn,"getStatusFilePath");const se={[K.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")},[K.Connector]:{element:"connector",elements:"connectors",exportable:!1},[K.Action]:{element:"action",elements:"actions",integrationSpecific:!0,exportCleanup:c(s=>(delete s.integration,s),"exportCleanup")},[K.AppDataSchema]:{element:"appDataSchema",elements:"appDataSchemas"},[K.AppEventType]:{element:"appEventType",elements:"appEventTypes"},[K.DataLinkTable]:{element:"dataLinkTable",elements:"dataLinkTables"},[K.DataSource]:{element:"dataSource",elements:"dataSources",parentKey:"universalDataSourceId",integrationSpecific:!0},[K.FieldMapping]:{element:"fieldMapping",elements:"fieldMappings",integrationSpecific:!0,parentKey:"universalFieldMappingId",exportCleanup:c(s=>(delete s.dataSourceId,s),"exportCleanup")},[K.Flow]:{element:"flow",elements:"flows",integrationSpecific:!0,parentKey:"universalFlowId"}};function Qr(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(Qr,"baseExportCleanup");class Es{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 Is{static{c(this,"ElementsManager")}cache;handler;connectorsMapping;constructor(e){this.cache=new Es,this.handler=e}async refresh(){try{const e=new Es,t=await this.handler.getIntegrations();e.addAll(t);const n=[K.Integration,K.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 Xr(s,e="full"){const t={};T.info("[connectors] Getting remote workspace data");const n=await s.integrations.findAll();t.integration=n.map(i=>bn("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=>bn(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,bn(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(Xr,"getWorkspaceData");function bn(s,e){return e=Qr(e),se[s].exportCleanup?se[s].exportCleanup(e):e}c(bn,"cleanUpForExport");const nt="connectors",st="development",Sn={};async function Zr({integrations:s,allConnectors:e=!1}){const t=Ir(),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 Ts({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 io({basePath:t,connector:u}),i.add(a)),r[a]||(r[a]=new Set),r[a].has(l)||(await ro({client:n,connector:u,connectorVersion:l,basePath:t}),r[a].add(l)))}}}c(Zr,"pullConnectors");async function eo(){const s=await le.getClient(process.cwd()),e=await Xr(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=Cn(),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 kn(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 Ts({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 so({client:s,connector:h,version:w,connectorId:i[h.id]})}return i}c(eo,"pushConnectors");function Cn(){const s=ln();return B.join(s.membraneDirPath,nt)}c(Cn,"getConnectorsPath");async function kn(s){return pe.load(M.readFileSync(B.join(Cn(),s,`${s}.yml`),"utf8"))}c(kn,"readConnector");async function to(s,e){return T.info(`[connectors] Zipping ${s} into ${e}`),new Promise((t,n)=>{const i=M.createWriteStream(e),r=fr("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(to,"createZipArchive");async function no(s,e){return T.info(`[connectors] Unzipping into ${e}`),new Promise((t,n)=>{const i=dr.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(no,"extractZipArchive");async function so({client:s,connector:e,version:t,connectorId:n}){const i=B.join(Cn(),Et(e),Ns(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 to(r,o)),!M.existsSync(o)){T.warning(`[connectors] No source code found for ${e.name} version ${t}`);return}try{const l=new hr;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(so,"pushConnectorVersion");async function Ts({client:s,connectorId:e}){if(Sn[e])return Sn[e];const t=await s.get(`connectors/${e}`);return Sn[e]=t,t}c(Ts,"getConnector");async function io({basePath:s,connector:e}){const t=Et(e),n=B.join(s,nt,t);M.mkdirSync(n,{recursive:!0});const i=B.join(n,`${Et(e)}.yml`);M.writeFileSync(i,pe.dump(e)),T.info(`[connectors] Pulled connector ${e.name}`)}c(io,"pullConnector");async function ro({client:s,connector:e,connectorVersion:t,basePath:n}){const i=Et(e),r=Ns(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 no(a,u)}T.info(`[connectors] Pulled connector version: ${e.name} (${r})`)}c(ro,"pullConnectorVersion");function Et(s){return s.key}c(Et,"getConnectorDirName");function Ns(s){return s??st}c(Ns,"getConnectorVersionDirName");function oo(s){return s.match(`${nt}/[^/]+/${st}/src/.*`)!==null}c(oo,"isConnectorSourceFile");async function ao(s){const e=s.match(`${nt}/([^/]+)/${st}/src/(.*)`);if(!e)return;const t=e[1],n=e[2],i=await kn(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(ao,"putConnectorFile");async function co(s){const e=s.match(`${nt}/([^/]+)/${st}/src/(.*)`);if(!e)return;const t=e[1],n=e[2],i=await kn(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(co,"deleteConnectorFile");const lo="membrane",uo=["**/node_modules/**","**/.git/**","**/.DS_Store","**/Thumbs.db","**/*.tmp","**/*.swp","**/*.swo","**/*.log","**/*.lock","**/.cache/**","**/.next/**","**/.vscode/**","**/.idea/**"];function It(s){return x.join(s,lo)}c(It,"getMembraneDir");const fo=["id","workspaceId","integrationId","createdAt","updatedAt","revision","parentRevision","archivedAt","baseUri","state"],As=[K.Action,K.FieldMapping,K.Flow,K.DataSource];class V{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||V.extractIntegrationKey(i)}get id(){return V.makeId(this.type,this.key,this.integrationKey)}get dirPath(){const e=we[this.type].apiPath;if(this.integrationKey){const t=we[K.Integration].apiPath;return x.join(t,this.integrationKey,e,this.key)}return x.join(e,this.key)}get path(){return x.join(this.dirPath,"spec.yaml")}get relativePath(){return x.relative(It(process.cwd()),this.path)}isEqual(e){if(this.id!==e.id)return!1;const t=this.clean(),n=e.clean();return pr(t,n)}hasParent(){const e=this.getParentKey();return!!e&&!!this.data?.[e]}clean(){const e={...this.data};return fo.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 V(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 V(e,t.key,n,t)}static fromPathAndData(e,t){const n=V.parsePath(e);if(!t)return;const i=t?.key||n?.key;return n?V.new(n.type,i,n.integrationKey,t):void 0}static fromElement(e){return new V(e.type,e.key,e.integrationKey,{...e.data})}static idFromPath(e){const t=V.parsePath(e);if(t)return V.makeId(t.type,t.key,t.integrationKey)}static makeId(e,t,n){return e===K.Integration?`${e}:${t}`:V.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(we).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(K).find(t=>we[t].apiPath===e)}static getRelativePath(e){return x.relative(It(process.cwd()),e)}static isIntegrationSpecific(e){return As.includes(e)}static canBeIntegrationSpecific(e){return As.includes(e)}}class ho{static{c(this,"LocalElementsHandler")}basePath;constructor(){this.basePath=It(process.cwd())}async getElementsByType(e,t){const n=[],i=x.join(this.basePath,we[e].apiPath),r=await this.readElementsInDir(i);n.push(...r);for(const o of t){const a=x.join(this.basePath,we[K.Integration].apiPath,o.key,we[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=x.join(this.basePath,t.dirPath),i=x.join(this.basePath,t.path);return P.existsSync(n)||P.mkdirSync(n,{recursive:!0}),P.writeFileSync(i,pe.dump(e.data)),T.info(`[local] Written ${t.relativePath}`),t}async deleteElement(e){const t=x.join(this.basePath,e.path),n=x.join(this.basePath,e.dirPath);P.existsSync(t)&&P.rmSync(t,{force:!0}),this.pruneEmptyDir(n),T.info(`[local] Deleted ${e.relativePath}`)}async getIntegrations(){const e=x.join(this.basePath,we[K.Integration].apiPath);return this.readElementsInDir(e)}async readElement(e){if(!P.existsSync(e))return;const t=P.readFileSync(e,"utf8"),n=pe.load(t);if(n)return V.fromPathAndData(e,n)}async readElementsInDir(e){const t=[];if(!P.existsSync(e))return t;const n=P.readdirSync(e);if(n.length===0)return t;const i=n.map(async o=>{const a=x.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||!P.existsSync(e)||P.readdirSync(e).length>0)return;P.rmdirSync(e),this.pruneEmptyDir(x.dirname(e))}catch(t){console.warn(`Failed to prune empty directory ${e}:`,t)}}}class po{static{c(this,"RemoteElementsHandler")}client;async getElementsByType(e,t){const n=await this.findAll(e);if(!V.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 V.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=V.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=V.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=>V.fromData(K.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===K.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===K.Integration).map(r=>r.key).join(", ")}`)}if(e.type===K.Integration){const i=n.connectorsMapping?.[t.connectorId];i&&(t.connectorId=i)}}transformElementForUpdate(e,t,n){if(e.type===K.Integration){const i=n.connectorsMapping?.[t.connectorId];i&&(t.connectorId=i)}}async findAll(e,t={}){return(await(await this.getClient())[se[e].elements].findAll(t)).filter(r=>r.key).map(r=>V.fromData(e,r))}async getClient(){return this.client||(this.client=await le.getClient(process.cwd())),this.client}}const vn=Symbol.for("yaml.alias"),En=Symbol.for("yaml.document"),Se=Symbol.for("yaml.map"),Os=Symbol.for("yaml.pair"),he=Symbol.for("yaml.scalar"),Me=Symbol.for("yaml.seq"),ie=Symbol.for("yaml.node.type"),Ce=c(s=>!!s&&typeof s=="object"&&s[ie]===vn,"isAlias"),Te=c(s=>!!s&&typeof s=="object"&&s[ie]===En,"isDocument"),Re=c(s=>!!s&&typeof s=="object"&&s[ie]===Se,"isMap"),F=c(s=>!!s&&typeof s=="object"&&s[ie]===Os,"isPair"),R=c(s=>!!s&&typeof s=="object"&&s[ie]===he,"isScalar$1"),_e=c(s=>!!s&&typeof s=="object"&&s[ie]===Me,"isSeq");function U(s){if(s&&typeof s=="object")switch(s[ie]){case Se:case Me:return!0}return!1}c(U,"isCollection$1");function q(s){if(s&&typeof s=="object")switch(s[ie]){case vn:case Se:case he:case Me:return!0}return!1}c(q,"isNode");const $s=c(s=>(R(s)||U(s))&&!!s.anchor,"hasAnchor"),ee=Symbol("break visit"),Ls=Symbol("skip children"),de=Symbol("remove node");function Ne(s,e){const t=Ds(e);Te(s)?Ke(null,s.contents,t,Object.freeze([s]))===de&&(s.contents=null):Ke(null,s,t,Object.freeze([]))}c(Ne,"visit$1"),Ne.BREAK=ee,Ne.SKIP=Ls,Ne.REMOVE=de;function Ke(s,e,t,n){const i=Ps(s,e,t,n);if(q(i)||F(i))return xs(s,n,i),Ke(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=Ke(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(F(e)){n=Object.freeze(n.concat(e));const r=Ke("key",e.key,t,n);if(r===ee)return ee;r===de&&(e.key=null);const o=Ke("value",e.value,t,n);if(o===ee)return ee;o===de&&(e.value=null)}}return i}c(Ke,"visit_");async function Tt(s,e){const t=Ds(e);Te(s)?await Fe(null,s.contents,t,Object.freeze([s]))===de&&(s.contents=null):await Fe(null,s,t,Object.freeze([]))}c(Tt,"visitAsync"),Tt.BREAK=ee,Tt.SKIP=Ls,Tt.REMOVE=de;async function Fe(s,e,t,n){const i=await Ps(s,e,t,n);if(q(i)||F(i))return xs(s,n,i),Fe(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 Fe(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(F(e)){n=Object.freeze(n.concat(e));const r=await Fe("key",e.key,t,n);if(r===ee)return ee;r===de&&(e.key=null);const o=await Fe("value",e.value,t,n);if(o===ee)return ee;o===de&&(e.value=null)}}return i}c(Fe,"visitAsync_");function Ds(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(Ds,"initVisitor");function Ps(s,e,t,n){if(typeof t=="function")return t(s,e,n);if(Re(e))return t.Map?.(s,e,n);if(_e(e))return t.Seq?.(s,e,n);if(F(e))return t.Pair?.(s,e,n);if(R(e))return t.Scalar?.(s,e,n);if(Ce(e))return t.Alias?.(s,e,n)}c(Ps,"callVisitor");function xs(s,e,t){const n=e[e.length-1];if(U(n))n.items[s]=t;else if(F(n))s==="key"?n.key=t:n.value=t;else if(Te(n))n.contents=t;else{const i=Ce(n)?"alias":"scalar";throw new Error(`Cannot replace node with ${i} parent`)}}c(xs,"replaceNode");const mo={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},go=c(s=>s.replace(/[!,[\]{}]/g,e=>mo[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+go(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 qi=Object.defineProperty;var c=(s,e)=>qi(s,"name",{value:e,configurable:!0});import{jsx as m,jsxs as E,Fragment as en}from"react/jsx-runtime";import*as x from"node:path";import{resolve as Wi,dirname as Ji,join as Gi}from"node:path";import{useInput as Pe,Box as b,Text as S,Newline as Vi,render as mt}from"ink";import Hi from"minimist";import{SWRConfig as Yi}from"swr";import xe,{createContext as ss,useState as j,useEffect as Ie,useContext as is,useMemo as zi,useRef as Qi}from"react";import rs from"swr/immutable";import os from"os";import B from"path";import Xi from"conf";import{exec as Zi}from"node:child_process";import*as P from"node:fs";import{readFileSync as er}from"node:fs";import{EventEmitter as tr}from"events";import{MembraneClient as as,WorkspaceElementType as K,extractMembraneErrorData as te,WorkspaceElementSpecs as we,setValueAtLocator as tn,getDataCollectionCreateFields as nn,excludeWriteOnlyFieldsFromSchema as cs,valueToSchema as gt,getRequiredFieldsFromSchema as nr,getValueAtLocator as sr,walkSchema as ls,makeDataLocationPath as us,getDataCollectionUpdateFields as sn}from"@membranehq/sdk";import rn from"jsonwebtoken";import pe from"js-yaml";import{z as W}from"zod";import{Spinner as ir,TextInput as rr,Select as or}from"@inkjs/ui";import yt from"ink-spinner";import ar from"ink-text-input";import*as cr from"node:crypto";import{createHash as lr}from"node:crypto";import*as ur from"node:os";import M from"fs";import fr from"archiver";import hr from"form-data";import dr from"unzipper";import pr from"lodash/isEqual.js";import mr from"chokidar";import{fileURLToPath as gr}from"node:url";import k from"chalk";import{Command as yr}from"commander";import on from"axios";import{FastMCP as wr}from"fastmcp";import an from"lodash/merge.js";import br from"@anthropic-ai/sdk";import{faker as Xe}from"@faker-js/faker";import Sr from"lodash/template.js";import Cr 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"},fs=ss(null);function kr({children:s,membraneCLIService:e}){const{data:t}=rs("/account"),[n,i]=j(D.NOT_INITIALIZED),[r,o]=j([]),[a,l]=j({}),[u,p]=j([]),[d,h]=j(null),w=t?.workspaces?.find(f=>f.workspaceKey===d?.workspaceKey)||null;return Ie(()=>{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(fs.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(kr,"MembraneCLIServiceProvider");function oe(){const s=is(fs);if(!s)throw new Error("useMembraneCLIService must be used within MembraneCLIServiceProvider");return s}c(oe,"useMembraneCLIService");const vr="membrane",Er="membrane.config.yml",cn="https://api.integration.app";function ln(){const s=process.cwd(),e=x.join(s,vr),t=x.join(s,Er),n=e,i=x.join(n,"workspace.yaml");return{membraneDirPath:e,configPath:t,payloadDirPath:n,workspaceDataFilePath:i}}c(ln,"getPaths");function Ir(){return ln().membraneDirPath}c(Ir,"getBasePath");const Tr={pat:{type:"string"},workspace:{type:"object"}},hs=new Xi({schema:Tr,configName:"config",cwd:B.join(os.homedir(),".membrane")}),Nr=c(s=>{hs.set("pat",s)},"setPat"),ds=c(()=>hs.get("pat"),"getPat");class ps{static{c(this,"AccountApiClient")}constructor(e=cn){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=ds();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 Ar=c(s=>{const e=new ps(cn);return t=>e.get(t)},"createAccountApiFetcher"),ms=ss(process.cwd());function Or({cwd:s,children:e}){return m(ms.Provider,{value:s,children:e})}c(Or,"CwdProvider");function $r(){return is(ms)}c($r,"useCwd");function wt({cwd:s,children:e,membraneCLIService:t}){const n=s||process.cwd();return m(Or,{cwd:n,children:m(Yi,{value:{fetcher:Ar()},children:m(kr,{membraneCLIService:t,children:e})})})}c(wt,"Layout");const un=[{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=x.join(process.cwd(),".mcp.json"),e={mcpServers:{membrane:{command:"membrane",args:["mcp"],env:{AGENT_NAME:"Claude Code"}}}};let t={};if(P.existsSync(s))try{t=JSON.parse(P.readFileSync(s,"utf8"))}catch{t={}}const n={...t,mcpServers:{...t.mcpServers,...e.mcpServers}};return P.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=x.join(process.cwd(),".cursor"),e=x.join(s,"mcp.json");P.existsSync(s)||P.mkdirSync(s);const t={mcpServers:{membrane:{command:"membrane",args:["mcp"],env:{AGENT_NAME:"Cursor"}}}};let n={};if(P.existsSync(e))try{n=JSON.parse(P.readFileSync(e,"utf8"))}catch{n={}}const i={...n,mcpServers:{...n.mcpServers,...t.mcpServers}};return P.writeFileSync(e,JSON.stringify(i,null,2)),`MCP server configuration added to ${e}`},"addConfig")}];function Lr({onExit:s,onComplete:e}){const[t,n]=j(0),[i,r]=j(!1),[o,a]=j(null),[l,u]=j(""),[p,d]=j("");Pe((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(un.length-1,t+1));else if(f.return||w===" "){const y=un[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:un.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(Lr,"AddMcpServerScreen");class gs extends tr{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)}}const ys="membrane.config.yml",bt=W.object({workspaceKey:W.string(),workspaceSecret:W.string(),apiUri:W.string().optional(),testCustomerId:W.string().optional(),anthropicApiKey:W.string().optional()});class He{static{c(this,"ConfigLoader")}static instance=null;cachedConfig=null;lastCwd=null;constructor(){}static getInstance(){return He.instance||(He.instance=new He),He.instance}loadConfig(e){const t=e??process.cwd();if(this.cachedConfig&&this.lastCwd===t)return this.cachedConfig;this.lastCwd=t;const n=this.loadFromFile(t),i=this.loadFromEnv(),r={...n,...i},o=bt.safeParse(r);return o.success?(this.cachedConfig=o.data,o.data):(this.cachedConfig=null,null)}clearCache(){this.cachedConfig=null,this.lastCwd=null}updateConfig(e){const t={...this.cachedConfig??{},...e},n=bt.safeParse(t),i=this.lastCwd??process.cwd();return this.saveToFile(e,i),n.success?(this.cachedConfig=n.data,this.cachedConfig):(this.cachedConfig=null,null)}isCacheDefined(e){return bt.safeParse(e).success}loadFromFile(e){const t=x.join(e,ys);try{const n=P.readFileSync(t,"utf8"),i=pe.load(n),r=bt.safeParse(i);return r.success?r.data:{}}catch{return{}}}loadFromEnv(){const e={};return process.env.MEMBRANE_WORKSPACE_KEY&&(e.workspaceKey=process.env.MEMBRANE_WORKSPACE_KEY),process.env.MEMBRANE_WORKSPACE_SECRET&&(e.workspaceSecret=process.env.MEMBRANE_WORKSPACE_SECRET),process.env.MEMBRANE_API_URI&&(e.apiUri=process.env.MEMBRANE_API_URI),process.env.MEMBRANE_TEST_CUSTOMER_ID&&(e.testCustomerId=process.env.MEMBRANE_TEST_CUSTOMER_ID),e}saveToFile(e,t){const n=t??process.cwd(),i=x.join(n,ys),o={...this.loadFromFile(n),...e},a=this.loadFromEnv();for(const l of Object.keys(a))a[l]===o[l]&&delete o[l];try{return P.writeFileSync(i,pe.dump(o)),!0}catch{return!1}}}const Ze=He.getInstance();function St(s){return Ze.loadConfig(s)}c(St,"readProjectConfig");class Dr{static{c(this,"MembraneClientManager")}client=null;currentConfig=null;tokenExpiry=0;async generateAccessToken(e,t){return rn.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=St(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 as({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 Dr;async function ws(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(ws,"getWorkspaceId");class Pr extends gs{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:os.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 Pr({heartbeatIntervalMs:15e3});function xr(){const[s,e]=j(null),[t,n]=j([]),[i,r]=j(null);return Ie(()=>{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 Mr(){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(Vi,{}),"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(Mr,"Agent");const Ct=c(s=>{switch(s){case"error":return"red";case"success":return"green";case"warning":return"yellow";default:return}},"getLogColor");function bs(s,e){return e<3?s.slice(0,Math.max(0,e)):s.length<=e?s:`${s.slice(0,e-3)}...`}c(bs,"truncateText");function fn({children:s}){const{state:e,logs:t}=oe();if(!e||e===D.NOT_INITIALIZED)return E(b,{gap:1,flexDirection:"row",children:[m(ir,{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:Ct(i.type),children:i.message},i.timestamp+r))})}return s}c(fn,"EnsureInitialized");function Ss({onExit:s,showEscOption:e=!0}){const[t,n]=j(""),{data:i,error:r,isLoading:o}=rs("/account"),{updateConfig:a}=oe(),l=i?.workspaces,u=o;if(Pe((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{workspaceKey:C,workspaceSecret: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(rr,{placeholder:"Enter a search query...",onChange:n})]}),g>5&&E(S,{children:["Showing ",h," of ",g," workspaces."]}),m(b,{marginTop:1,children:m(or,{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(Ss,"SelectWorkspace");function Rr({currentPat:s,onSubmit:e}){const[t,n]=j(""),[i,r]=j(!1),[o,a]=j(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(ar,{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(Rr,"PersonalAccessTokenInput");var et=(s=>(s[s.Authenticate=0]="Authenticate",s[s.ConnectWorkspace=1]="ConnectWorkspace",s))(et||{});const _r={0:"Authenticate in Membrane",1:"Connect a Membrane Workspace"},hn=[et.Authenticate,et.ConnectWorkspace];function Cs({onComplete:s}){const{config:e}=oe(),[t,n]=j(!1),[i,r]=j(0),o=!!(e?.workspaceKey&&e?.workspaceSecret),a=ds(),l=hn[i],u=i+1,p=hn.length,d=hn.map((w,f)=>{let y="pending";return f<i?y="done":f===i&&(y="current"),{id:w,label:_r[w],status:y}});async function h(w){const f=a&&w===""?a:w,y=new ps;try{await y.request("/account",{headers:{Authorization:`Bearer ${f}`}}),Nr(f),r(C=>C+1)}catch(C){console.error(C)}}c(h,"handlePatSubmit");function g(){n(!0),s&&s()}return c(g,"handleWorkspaceSelected"),Pe((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(Rr,{currentPat:a,onSubmit:h}),l===et.ConnectWorkspace&&m(Ss,{onExit:g,showEscOption:!1})]})}c(Cs,"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 dn(){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(dn,"ElementStats");const pn=5,Fr=6;function jr(){const{logs:s}=oe(),[e,t]=j(0),n=Math.min(100,process.stdout.columns||100),i=pn,r=Math.max(0,s.length-i-e),o=s.length-e,a=s.slice(r,o),l=n-Fr,u=e<s.length-i,p=e>0;return Pe((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>pn&&m(S,{color:"grey",children:" [arrows: scroll] [g: end]"})]}),a.map((d,h)=>m(b,{marginLeft:1,children:m(S,{color:Ct(d.type),children:bs(d.message,l)})},d.timestamp+h)),s.length>pn&&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"},kt=[{value:"sync",label:"Continue (overwrite/delete)",key:""},{value:"exit",label:"Cancel",key:""}];function Br(){const{state:s,resolveConflicts:e,exit:t}=oe(),[n,i]=j(0),[r,o]=j(!1);return Pe((a,l)=>{r||(l.upArrow?i(u=>u>0?u-1:kt.length-1):l.downArrow?i(u=>u<kt.length-1?u+1:0):a.toLowerCase()==="y"?i(0):a.toLowerCase()==="n"?i(1):(l.return||a===" ")&&(o(!0),kt[n].value==="sync"?e({watch:!0}):t()))}),Ie(()=>{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(mn,{})}),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:kt.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(Br,"ResolveChangesUI");const Ur={[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 mn(){const{conflicts:s}=oe(),e=zi(()=>{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=Ur[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(mn,"Conflicts");function qr(){const{config:s,state:e,logs:t,currentWorkspace:n,pull:i}=oe(),r=n?.name,o=r?bs(r,30):s?.workspaceKey,a=Math.min(100,process.stdout.columns||100);return Ie(()=>{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:[" [",Wr(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(Br,{}):E(en,{children:[m(b,{paddingTop:1,children:m(dn,{})}),t.length>0&&m(jr,{})]})]})}c(qr,"Workspace");function Wr(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(Wr,"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 Gr="https://console.integration.app/w";function Vr(){const s=$r(),e=Qi(!0),{exit:t,state:n}=oe(),[i,r]=j(null),o=i??(n===D.SETTING_UP?"setup":"main");Pe(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 ws(s),u=`${Gr}/${l}`,p=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";Zi(`${p} "${u}"`)}catch(l){console.error("Failed to open workspace:",l),t()}}return c(a,"handleOpenWorkspace"),Ie(()=>(e.current=!0,()=>{e.current=!1}),[]),o==="workspace-selection"?m(Ss,{onExit:c(()=>r(null),"onExit")}):o==="add-mcp-server"?m(Lr,{onExit:c(()=>r(null),"onExit"),onComplete:c(()=>r(null),"onComplete")}):o==="setup"?m(Cs,{onComplete:c(()=>r(null),"onComplete")},Date.now()):m(fn,{children:E(b,{flexDirection:"column",children:[m(b,{flexGrow:1,children:m(Mr,{})}),m(qr,{}),m(b,{paddingLeft:2,children:m(S,{color:"grey",children:"[s: (re-)setup]"})})]})})}c(Vr,"Main");class Hr{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 Hr,be=x.join(ur.tmpdir(),"membrane-mcp-status"),ks=3e4;class Yr{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=vt(void 0,e),n=vs(e);t&&ue.setMcpStatus(t),await ue.setMcpServers(n)}catch{T.error("Failed to check MCP status")}}}function vt(s,e){try{const t=e||process.cwd();if(!s){const i=vs(t);return i.length===0?null:i[0]}const n=wn(s,t);if(P.existsSync(n)){const i=P.statSync(n),r=new Date;if(r.getTime()-i.mtime.getTime()>ks)return tt(s,t),null;const a=P.readFileSync(n,"utf8"),l=JSON.parse(a);if(l.isRunning){const u=new Date(l.lastActivity).getTime();if(r.getTime()-u>ks)return tt(s,t),null}return l}}catch{s&&e&&tt(s,e)}return null}c(vt,"getMcpStatus");function vs(s){try{const e=s||process.cwd(),t=yn(e);if(!P.existsSync(be))return[];const n=P.readdirSync(be),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=vt(a,e);l&&i.push(l)}}return i.sort((r,o)=>new Date(o.startTime).getTime()-new Date(r.startTime).getTime())}catch{return[]}}c(vs,"getAllMcpStatusFiles");function gn(s){try{const t={...vt(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};P.existsSync(be)||P.mkdirSync(be,{recursive:!0});const n=wn(s.processId,s.cwd);P.writeFileSync(n,JSON.stringify(t,null,2))}catch{}}c(gn,"updateMcpStatus");function tt(s,e){try{const t=e||process.cwd();if(s){const n=wn(s,t);P.existsSync(n)&&P.unlinkSync(n)}else{const n=yn(t);if(P.existsSync(be)){const i=P.readdirSync(be);for(const r of i)r.match(new RegExp(`^mcp-${n}-\\d+\\.json$`))&&P.unlinkSync(x.join(be,r))}}}catch{}}c(tt,"clearMcpStatus");function zr(s,e){const t=vt(s,e);t&&gn({processId:s,cwd:e,totalRequests:t.totalRequests+1,lastRequestTime:new Date().toISOString(),lastActivity:new Date().toISOString()})}c(zr,"trackToolExecution");function yn(s){return lr("md5").update(s).digest("hex").slice(0,8)}c(yn,"getCwdHash");function wn(s,e){const t=yn(e);return x.join(be,`mcp-${t}-${s}.json`)}c(wn,"getStatusFilePath");const se={[K.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")},[K.Connector]:{element:"connector",elements:"connectors",exportable:!1},[K.Action]:{element:"action",elements:"actions",integrationSpecific:!0,exportCleanup:c(s=>(delete s.integration,s),"exportCleanup")},[K.AppDataSchema]:{element:"appDataSchema",elements:"appDataSchemas"},[K.AppEventType]:{element:"appEventType",elements:"appEventTypes"},[K.DataLinkTable]:{element:"dataLinkTable",elements:"dataLinkTables"},[K.DataSource]:{element:"dataSource",elements:"dataSources",parentKey:"universalDataSourceId",integrationSpecific:!0},[K.FieldMapping]:{element:"fieldMapping",elements:"fieldMappings",integrationSpecific:!0,parentKey:"universalFieldMappingId",exportCleanup:c(s=>(delete s.dataSourceId,s),"exportCleanup")},[K.Flow]:{element:"flow",elements:"flows",integrationSpecific:!0,parentKey:"universalFlowId"}};function Qr(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(Qr,"baseExportCleanup");class Es{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 Is{static{c(this,"ElementsManager")}cache;handler;connectorsMapping;constructor(e){this.cache=new Es,this.handler=e}async refresh(){try{const e=new Es,t=await this.handler.getIntegrations();e.addAll(t);const n=[K.Integration,K.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 Xr(s,e="full"){const t={};T.info("[connectors] Getting remote workspace data");const n=await s.integrations.findAll();t.integration=n.map(i=>bn("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=>bn(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,bn(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(Xr,"getWorkspaceData");function bn(s,e){return e=Qr(e),se[s].exportCleanup?se[s].exportCleanup(e):e}c(bn,"cleanUpForExport");const nt="connectors",st="development",Sn={};async function Zr({integrations:s,allConnectors:e=!1}){const t=Ir(),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 Ts({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 io({basePath:t,connector:u}),i.add(a)),r[a]||(r[a]=new Set),r[a].has(l)||(await ro({client:n,connector:u,connectorVersion:l,basePath:t}),r[a].add(l)))}}}c(Zr,"pullConnectors");async function eo(){const s=await le.getClient(process.cwd()),e=await Xr(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=Cn(),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 kn(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 Ts({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 so({client:s,connector:h,version:w,connectorId:i[h.id]})}return i}c(eo,"pushConnectors");function Cn(){const s=ln();return B.join(s.membraneDirPath,nt)}c(Cn,"getConnectorsPath");async function kn(s){return pe.load(M.readFileSync(B.join(Cn(),s,`${s}.yml`),"utf8"))}c(kn,"readConnector");async function to(s,e){return T.info(`[connectors] Zipping ${s} into ${e}`),new Promise((t,n)=>{const i=M.createWriteStream(e),r=fr("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(to,"createZipArchive");async function no(s,e){return T.info(`[connectors] Unzipping into ${e}`),new Promise((t,n)=>{const i=dr.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(no,"extractZipArchive");async function so({client:s,connector:e,version:t,connectorId:n}){const i=B.join(Cn(),Et(e),Ns(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 to(r,o)),!M.existsSync(o)){T.warning(`[connectors] No source code found for ${e.name} version ${t}`);return}try{const l=new hr;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(so,"pushConnectorVersion");async function Ts({client:s,connectorId:e}){if(Sn[e])return Sn[e];const t=await s.get(`connectors/${e}`);return Sn[e]=t,t}c(Ts,"getConnector");async function io({basePath:s,connector:e}){const t=Et(e),n=B.join(s,nt,t);M.mkdirSync(n,{recursive:!0});const i=B.join(n,`${Et(e)}.yml`);M.writeFileSync(i,pe.dump(e)),T.info(`[connectors] Pulled connector ${e.name}`)}c(io,"pullConnector");async function ro({client:s,connector:e,connectorVersion:t,basePath:n}){const i=Et(e),r=Ns(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 no(a,u)}T.info(`[connectors] Pulled connector version: ${e.name} (${r})`)}c(ro,"pullConnectorVersion");function Et(s){return s.key}c(Et,"getConnectorDirName");function Ns(s){return s??st}c(Ns,"getConnectorVersionDirName");function oo(s){return s.match(`${nt}/[^/]+/${st}/src/.*`)!==null}c(oo,"isConnectorSourceFile");async function ao(s){const e=s.match(`${nt}/([^/]+)/${st}/src/(.*)`);if(!e)return;const t=e[1],n=e[2],i=await kn(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(ao,"putConnectorFile");async function co(s){const e=s.match(`${nt}/([^/]+)/${st}/src/(.*)`);if(!e)return;const t=e[1],n=e[2],i=await kn(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(co,"deleteConnectorFile");const lo="membrane",uo=["**/node_modules/**","**/.git/**","**/.DS_Store","**/Thumbs.db","**/*.tmp","**/*.swp","**/*.swo","**/*.log","**/*.lock","**/.cache/**","**/.next/**","**/.vscode/**","**/.idea/**"];function It(s){return x.join(s,lo)}c(It,"getMembraneDir");const fo=["id","workspaceId","integrationId","createdAt","updatedAt","revision","parentRevision","archivedAt","baseUri","state"],As=[K.Action,K.FieldMapping,K.Flow,K.DataSource];class V{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||V.extractIntegrationKey(i)}get id(){return V.makeId(this.type,this.key,this.integrationKey)}get dirPath(){const e=we[this.type].apiPath;if(this.integrationKey){const t=we[K.Integration].apiPath;return x.join(t,this.integrationKey,e,this.key)}return x.join(e,this.key)}get path(){return x.join(this.dirPath,"spec.yaml")}get relativePath(){return x.relative(It(process.cwd()),this.path)}isEqual(e){if(this.id!==e.id)return!1;const t=this.clean(),n=e.clean();return pr(t,n)}hasParent(){const e=this.getParentKey();return!!e&&!!this.data?.[e]}clean(){const e={...this.data};return fo.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 V(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 V(e,t.key,n,t)}static fromPathAndData(e,t){const n=V.parsePath(e);if(!t)return;const i=t?.key||n?.key;return n?V.new(n.type,i,n.integrationKey,t):void 0}static fromElement(e){return new V(e.type,e.key,e.integrationKey,{...e.data})}static idFromPath(e){const t=V.parsePath(e);if(t)return V.makeId(t.type,t.key,t.integrationKey)}static makeId(e,t,n){return e===K.Integration?`${e}:${t}`:V.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(we).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(K).find(t=>we[t].apiPath===e)}static getRelativePath(e){return x.relative(It(process.cwd()),e)}static isIntegrationSpecific(e){return As.includes(e)}static canBeIntegrationSpecific(e){return As.includes(e)}}class ho{static{c(this,"LocalElementsHandler")}basePath;constructor(){this.basePath=It(process.cwd())}async getElementsByType(e,t){const n=[],i=x.join(this.basePath,we[e].apiPath),r=await this.readElementsInDir(i);n.push(...r);for(const o of t){const a=x.join(this.basePath,we[K.Integration].apiPath,o.key,we[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=x.join(this.basePath,t.dirPath),i=x.join(this.basePath,t.path);return P.existsSync(n)||P.mkdirSync(n,{recursive:!0}),P.writeFileSync(i,pe.dump(e.data)),T.info(`[local] Written ${t.relativePath}`),t}async deleteElement(e){const t=x.join(this.basePath,e.path),n=x.join(this.basePath,e.dirPath);P.existsSync(t)&&P.rmSync(t,{force:!0}),this.pruneEmptyDir(n),T.info(`[local] Deleted ${e.relativePath}`)}async getIntegrations(){const e=x.join(this.basePath,we[K.Integration].apiPath);return this.readElementsInDir(e)}async readElement(e){if(!P.existsSync(e))return;const t=P.readFileSync(e,"utf8"),n=pe.load(t);if(n)return V.fromPathAndData(e,n)}async readElementsInDir(e){const t=[];if(!P.existsSync(e))return t;const n=P.readdirSync(e);if(n.length===0)return t;const i=n.map(async o=>{const a=x.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||!P.existsSync(e)||P.readdirSync(e).length>0)return;P.rmdirSync(e),this.pruneEmptyDir(x.dirname(e))}catch(t){console.warn(`Failed to prune empty directory ${e}:`,t)}}}class po{static{c(this,"RemoteElementsHandler")}client;async getElementsByType(e,t){const n=await this.findAll(e);if(!V.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 V.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=V.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=V.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=>V.fromData(K.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===K.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===K.Integration).map(r=>r.key).join(", ")}`)}if(e.type===K.Integration){const i=n.connectorsMapping?.[t.connectorId];i&&(t.connectorId=i)}}transformElementForUpdate(e,t,n){if(e.type===K.Integration){const i=n.connectorsMapping?.[t.connectorId];i&&(t.connectorId=i)}}async findAll(e,t={}){return(await(await this.getClient())[se[e].elements].findAll(t)).filter(r=>r.key).map(r=>V.fromData(e,r))}async getClient(){return this.client||(this.client=await le.getClient(process.cwd())),this.client}}const vn=Symbol.for("yaml.alias"),En=Symbol.for("yaml.document"),Se=Symbol.for("yaml.map"),Os=Symbol.for("yaml.pair"),he=Symbol.for("yaml.scalar"),Me=Symbol.for("yaml.seq"),ie=Symbol.for("yaml.node.type"),Ce=c(s=>!!s&&typeof s=="object"&&s[ie]===vn,"isAlias"),Te=c(s=>!!s&&typeof s=="object"&&s[ie]===En,"isDocument"),Re=c(s=>!!s&&typeof s=="object"&&s[ie]===Se,"isMap"),F=c(s=>!!s&&typeof s=="object"&&s[ie]===Os,"isPair"),R=c(s=>!!s&&typeof s=="object"&&s[ie]===he,"isScalar$1"),_e=c(s=>!!s&&typeof s=="object"&&s[ie]===Me,"isSeq");function U(s){if(s&&typeof s=="object")switch(s[ie]){case Se:case Me:return!0}return!1}c(U,"isCollection$1");function q(s){if(s&&typeof s=="object")switch(s[ie]){case vn:case Se:case he:case Me:return!0}return!1}c(q,"isNode");const $s=c(s=>(R(s)||U(s))&&!!s.anchor,"hasAnchor"),ee=Symbol("break visit"),Ls=Symbol("skip children"),de=Symbol("remove node");function Ne(s,e){const t=Ds(e);Te(s)?Ke(null,s.contents,t,Object.freeze([s]))===de&&(s.contents=null):Ke(null,s,t,Object.freeze([]))}c(Ne,"visit$1"),Ne.BREAK=ee,Ne.SKIP=Ls,Ne.REMOVE=de;function Ke(s,e,t,n){const i=Ps(s,e,t,n);if(q(i)||F(i))return xs(s,n,i),Ke(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=Ke(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(F(e)){n=Object.freeze(n.concat(e));const r=Ke("key",e.key,t,n);if(r===ee)return ee;r===de&&(e.key=null);const o=Ke("value",e.value,t,n);if(o===ee)return ee;o===de&&(e.value=null)}}return i}c(Ke,"visit_");async function Tt(s,e){const t=Ds(e);Te(s)?await Fe(null,s.contents,t,Object.freeze([s]))===de&&(s.contents=null):await Fe(null,s,t,Object.freeze([]))}c(Tt,"visitAsync"),Tt.BREAK=ee,Tt.SKIP=Ls,Tt.REMOVE=de;async function Fe(s,e,t,n){const i=await Ps(s,e,t,n);if(q(i)||F(i))return xs(s,n,i),Fe(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 Fe(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(F(e)){n=Object.freeze(n.concat(e));const r=await Fe("key",e.key,t,n);if(r===ee)return ee;r===de&&(e.key=null);const o=await Fe("value",e.value,t,n);if(o===ee)return ee;o===de&&(e.value=null)}}return i}c(Fe,"visitAsync_");function Ds(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(Ds,"initVisitor");function Ps(s,e,t,n){if(typeof t=="function")return t(s,e,n);if(Re(e))return t.Map?.(s,e,n);if(_e(e))return t.Seq?.(s,e,n);if(F(e))return t.Pair?.(s,e,n);if(R(e))return t.Scalar?.(s,e,n);if(Ce(e))return t.Alias?.(s,e,n)}c(Ps,"callVisitor");function xs(s,e,t){const n=e[e.length-1];if(U(n))n.items[s]=t;else if(F(n))s==="key"?n.key=t:n.value=t;else if(Te(n))n.contents=t;else{const i=Ce(n)?"alias":"scalar";throw new Error(`Cannot replace node with ${i} parent`)}}c(xs,"replaceNode");const mo={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},go=c(s=>s.replace(/[!,[\]{}]/g,e=>mo[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+go(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(`
4
3
  `)}}Z.defaultYaml={explicit:!1,version:"1.2"},Z.defaultTags={"!!":"tag:yaml.org,2002:"};function Ms(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(Ms,"anchorIsValid");function Rs(s){const e=new Set;return Ne(s,{Value(t,n){n.anchor&&e.add(n.anchor)}}),e}c(Rs,"anchorNames");function _s(s,e){for(let t=1;;++t){const n=`${s}${t}`;if(!e.has(n))return n}}c(_s,"findNewAnchor");function yo(s,e){const t=[],n=new Map;let i=null;return{onAnchor:c(r=>{t.push(r),i??(i=Rs(s));const o=_s(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&&(R(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(yo,"createNodeAnchors");function je(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=je(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=je(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=je(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=je(s,n,i,r);o===void 0?delete n[i]:o!==r&&(n[i]=o)}return s.call(e,t,n)}c(je,"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||!$s(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 In{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"?je(r,{"":a},"",a):a}}class Nt extends In{static{c(this,"Alias")}constructor(e){super(vn),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)=>{(Ce(o)||$s(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=At(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(Ms(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 At(s,e,t){if(Ce(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=At(s,i,t);r>n&&(n=r)}return n}else if(F(e)){const n=At(s,e.key,t),i=At(s,e.value,t);return Math.max(n,i)}return 1}c(At,"getAliasCount");const Ks=c(s=>!s||typeof s!="function"&&typeof s!="object","isScalarValue");class L extends In{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 wo="tag:yaml.org,2002:";function bo(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(bo,"findTagObject");function it(s,e,t){if(Te(s)&&(s=s.contents),q(s))return s;if(F(s)){const d=t.schema[Se].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 Nt(l.anchor);l={anchor:null,node:null},a.set(s,l)}e?.startsWith("!!")&&(e=wo+e.slice(2));let u=bo(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[Se]:Symbol.iterator in Object(s)?o[Me]:o[Se]}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 Ot(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(Ot,"collectionFromPath");const rt=c(s=>s==null||typeof s=="object"&&!!s[Symbol.iterator]().next().done,"isEmptyPath");class Fs extends In{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)||F(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,Ot(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&&R(r)?r.value:r:U(r)?r.getIn(i,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!F(t))return!1;const n=t.value;return n==null||e&&R(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,Ot(this.schema,i,t));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${i}`)}}}const So=c(s=>s.replace(/^(?!$)(?: $)?/gm,"#"),"stringifyComment");function me(s,e){return/^\n+$/.test(s)?s.substring(1):e?s.replace(/^(?! *$)/gm,e):s}c(me,"indentComment");const Ae=c((s,e,t)=>s.endsWith(`
5
4
  `)?me(t,e):t.includes(`
6
5
  `)?`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@membranehq/cli",
3
- "version": "0.10.0",
3
+ "version": "0.10.1",
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.6.0",
36
+ "@membranehq/sdk": "^0.7.0",
37
37
  "@types/jsonwebtoken": "^9.0.10",
38
38
  "archiver": "^7.0.1",
39
39
  "axios": "^1.10.0",