@membranehq/cli 1.10.1 → 1.11.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/dist/index.js +50 -50
- package/package.json +3 -3
package/dist/index.js
CHANGED
|
@@ -1,58 +1,58 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var go=Object.defineProperty;var l=(o,e)=>go(o,"name",{value:e,configurable:!0});import
|
|
3
|
-
`)}}function
|
|
4
|
-
`,"utf8")}l(gr,"patchProjectConfig");function wn(){try{const o=$.join($.resolve(gn),yn);if(!
|
|
5
|
-
${
|
|
6
|
-
${
|
|
7
|
-
`);else{const u=c.items??[];if(u.length===0)console.error(
|
|
2
|
+
var go=Object.defineProperty;var l=(o,e)=>go(o,"name",{value:e,configurable:!0});import h from"chalk";import{Command as yo}from"commander";import*as T from"node:fs";import{mkdirSync as wo,writeFileSync as Co,readFileSync as So}from"node:fs";import*as k from"node:path";import{join as Ve,dirname as bo}from"node:path";import{URL as vo,fileURLToPath as To}from"node:url";import{MembraneConfigLoader as Io}from"@membranehq/sdk/config";import P,{existsSync as je,readFileSync as Zt,mkdirSync as Xt,writeFileSync as Eo,statSync as ko,chmodSync as xo}from"fs";import $ from"path";import $o from"conf";import Ye from"os";import{AgentName as Qt,WorkspaceElementType as x,MembraneAxiosInstance as Oo,MembraneClient as en,extractMembraneErrorData as V,WorkspaceElementSpecs as Q,WorkspaceSyncEventType as Ao,ConnectorFileUpdateType as Ze,NotFoundError as Po,parseMembraneElementPath as de,getConnectorSpecPath as No,getConnectorVersionPath as tn,CONNECTOR_VERSION_DEVELOPMENT as Xe,getMembraneElementPath as Ro,compareWorkspaceExports as nn,CONSOLE_ACCOUNT_API_TOKEN_PATH as Do,OAUTH_SCOPE_TENANT as on,OAUTH_SCOPE_PLATFORM_USER as rn,MEMBRANE_CLI_CLIENT_ID as Me,WorkspaceElementChangeType as ee,HttpRequestMethod as Lo,getDataCollectionCreateFields as Qe,excludeWriteOnlyFieldsFromSchema as sn,valueToSchema as Fe,getRequiredFieldsFromSchema as jo,getValueAtLocator as Mo,setValueAtLocator as et,walkSchema as an,makeDataLocationPath as cn,getDataCollectionUpdateFields as tt}from"@membranehq/sdk";import nt from"lodash/camelCase.js";import ot from"lodash/upperFirst.js";import Fo from"code-block-writer";import Uo from"lodash/uniqBy.js";import{Box as w,Text as C,useInput as pe,render as rt,Newline as Ko}from"ink";import he,{createContext as it,useContext as st,useId as _o,useRef as at,useState as L,useLayoutEffect as Ue,useEffect as Ce,useMemo as qo}from"react";import{jsxs as v,Fragment as Ke,jsx as d}from"react/jsx-runtime";import"node:events";import ln from"ink-text-input";import{SWRConfig as Bo}from"swr";import un from"swr/immutable";import Ee,{isAxiosError as Jo}from"axios";import ct from"jsonwebtoken";import lt from"semver";import{AsyncLocalStorage as Wo}from"async_hooks";import{toSentenceCase as zo}from"js-convert-case";import Go from"lodash/isEqual.js";import Y from"js-yaml";import Ho from"chokidar";import*as Vo from"node:crypto";import{createHash as Yo}from"node:crypto";import Zo from"yaml";import{EventEmitter as Xo}from"events";import{EventSource as Qo}from"eventsource";import ut from"archiver";import dn from"form-data";import _e from"unzipper";import*as er from"node:os";import{randomUUID as tr,randomBytes as pn,createHash as nr}from"crypto";import{createServer as hn}from"http";import Se from"ora";import fn from"jszip";import{minimatch as or}from"minimatch";import qe from"ink-spinner";import{TextInput as rr,Select as ir,Spinner as sr}from"@inkjs/ui";import{FastMCP as ar}from"fastmcp";import{z as D}from"zod";import{exec as cr}from"node:child_process";import dt from"lodash/merge.js";import lr from"@anthropic-ai/sdk";import{faker as ke}from"@faker-js/faker";import ur from"lodash/template.js";import dr from"lodash/templateSettings.js";class pt extends Error{static{l(this,"ApiError")}statusCode;errorType;errorKey;data;constructor(e,t){const n=pr(t);if(n){const{message:r,type:i,key:s,...a}=n,c=typeof r=="string"?r:`API request failed (${e})`;super(c),this.errorType=typeof i=="string"?i:void 0,this.errorKey=typeof s=="string"?s:void 0,this.data=Object.keys(a).length>0?a:void 0}else super(t||`API request failed (${e})`);this.statusCode=e,this.name="ApiError"}format(){const e=[this.message];return this.data&&Object.keys(this.data).length>0&&e.push(JSON.stringify(this.data,null,2)),e.join(`
|
|
3
|
+
`)}}function pr(o){try{const e=JSON.parse(o);return typeof e=="object"&&e!==null?e:null}catch{return null}}l(pr,"tryParseJson");class Ie{static{l(this,"ConfigLoader")}static instance=null;sdkLoader;constructor(){this.sdkLoader=new Io}static getInstance(){return Ie.instance||(Ie.instance=new Ie),Ie.instance}loadConfig(e){e&&e!==this.sdkLoader.getCwd()&&this.sdkLoader.setCwd(e);try{return this.sdkLoader.loadConfig({validate:!0})}catch(t){if(t.message?.includes("Failed to parse"))throw t;return null}}clearCache(){this.sdkLoader.clearCache()}updateConfig(e){return this.sdkLoader.updateConfig(e)}saveToFile(e){return this.sdkLoader.saveToFile(e)}isCacheDefined(){return this.sdkLoader.hasValidConfig()}}const fe=Ie.getInstance();function xe(o){return fe.loadConfig(o)}l(xe,"readProjectConfig");const hr="membrane",fr="membrane.config.yml",te="https://api.getmembrane.com",mr="https://console.getmembrane.com";function ht(o){const t=xe()?.consoleUri||mr;return o?new vo(o,t).toString():t}l(ht,"getConsoleUrl");function ft(){const o=process.cwd(),e=k.join(o,hr),t=k.join(o,fr),n=e,r=k.join(n,"workspace.yaml");return{membraneDirPath:e,configPath:t,payloadDirPath:n,workspaceDataFilePath:r}}l(ft,"getPaths");function mn(){return ft().membraneDirPath}l(mn,"getBasePath");const gn=".membrane",yn="config.json";function gr(o){const e=$.resolve(gn),t=$.join(e,yn);let n={};je(t)&&(n=JSON.parse(Zt(t,"utf8")));const r={...n,...o};for(const[i,s]of Object.entries(r))s===void 0&&delete r[i];je(e)||Xt(e,{recursive:!0}),Eo(t,JSON.stringify(r,null,2)+`
|
|
4
|
+
`,"utf8")}l(gr,"patchProjectConfig");function wn(){try{const o=$.join($.resolve(gn),yn);if(!je(o))return{};const e=JSON.parse(Zt(o,"utf8"));return{defaultWorkspaceKey:e.defaultWorkspaceKey,defaultTenantKey:e.defaultTenantKey}}catch{return{}}}l(wn,"readProjectDefaults");const Be=$.join(Ye.homedir(),".membrane");je(Be)?(ko(Be).mode&511)!==448&&xo(Be,448):Xt(Be,{mode:448});const yr={pat:{type:"string"},workspace:{type:"object"},accessToken:{type:"string"},refreshToken:{type:"string"},expiresAt:{type:"number"},apiUri:{type:"string"},tokenScope:{type:"string",enum:["platform-user","tenant"]},pendingLoginScope:{type:"string",enum:["platform-user","tenant"]},pendingLoginCodeVerifier:{type:"string"},pendingLoginClientId:{type:"string"},pendingLoginCreatedAt:{type:"number"}},j=new $o({schema:yr,configName:"credentials",cwd:$.join(Ye.homedir(),".membrane"),configFileMode:384}),wr=l(o=>{j.set("pat",o)},"setPat"),Cn=l(()=>j.get("pat"),"getPat"),Cr=l(()=>{j.delete("pat")},"clearPat"),Sn=l((o,e,t)=>{j.set({accessToken:o,refreshToken:e}),t!=null?j.set("expiresAt",Date.now()+t*1e3):j.delete("expiresAt")},"setTokens"),Sr=l(()=>j.get("accessToken"),"getAccessToken"),be=l(()=>j.get("refreshToken"),"getRefreshToken"),mt=l(()=>{const o=j.get("expiresAt");return o?Date.now()>=o-6e4:!0},"isTokenExpired"),br=l(()=>{j.delete("accessToken"),j.delete("refreshToken"),j.delete("expiresAt"),j.delete("apiUri"),j.delete("tokenScope"),$e()},"clearTokens"),me=l(()=>j.get("apiUri"),"getApiUri"),bn=l(o=>{j.set("apiUri",o)},"setApiUri"),vr=l(o=>{j.set("tokenScope",o)},"setTokenScope"),gt=l(()=>j.get("tokenScope"),"getTokenScope"),Tr=l(o=>{j.set({pendingLoginScope:o.scope,pendingLoginCodeVerifier:o.codeVerifier,pendingLoginClientId:o.clientId,pendingLoginCreatedAt:Date.now()})},"setPendingLogin"),Ir=600*1e3,Er=l(()=>{const o=j.get("pendingLoginScope"),e=j.get("pendingLoginCodeVerifier"),t=j.get("pendingLoginClientId");if(!o||!e||!t)return;const n=j.get("pendingLoginCreatedAt");if(n&&Date.now()-n>Ir){$e();return}return{scope:o,codeVerifier:e,clientId:t}},"getPendingLogin"),$e=l(()=>{j.delete("pendingLoginScope"),j.delete("pendingLoginCodeVerifier"),j.delete("pendingLoginClientId"),j.delete("pendingLoginCreatedAt")},"clearPendingLogin"),yt=l(()=>!!(j.get("accessToken")||j.get("pat")),"hasStoredCredentials");class Oe{static{l(this,"AccountApiClient")}refreshPromise=null;explicitBaseUrl;constructor(e){this.explicitBaseUrl=e}get apiBaseUrl(){return this.explicitBaseUrl||me()||te}async refreshAccessToken(){const e=be();if(!e)throw new Error("No refresh token available. Please run `membrane login`.");const t=await fetch(`${this.apiBaseUrl}/oauth/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({grant_type:"refresh_token",refresh_token:e})});if(!t.ok)throw new Error("Failed to refresh access token. Please run `membrane login` again.");const n=await t.json(),r=n.refresh_token??e;return Sn(n.access_token,r,n.expires_in),n.access_token}async getAuthToken(){const e=Sr();if(e&&!mt())return e;if(be())return this.refreshPromise??=this.refreshAccessToken().finally(()=>{this.refreshPromise=null});const t=Cn();if(t)return t;throw new Error("Not authenticated. Run `membrane login` first.")}async getValidAccessToken(){return this.getAuthToken()}async forceRefreshAccessToken(){return this.refreshPromise??=this.refreshAccessToken().finally(()=>{this.refreshPromise=null})}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 s=await this.getAuthToken();n.set("Authorization",`Bearer ${s}`)}t.body&&!n.has("Content-Type")&&n.set("Content-Type","application/json");let r=await fetch(`${this.apiBaseUrl}${e}`,{...t,headers:n});if(r.status===401&&be()){const s=await(this.refreshPromise??=this.refreshAccessToken().finally(()=>{this.refreshPromise=null}));n.set("Authorization",`Bearer ${s}`),r=await fetch(`${this.apiBaseUrl}${e}`,{...t,headers:n})}if(!r.ok){const s=await r.text();throw new pt(r.status,s)}if(r.status===204)return{};const i=await r.text();return JSON.parse(i)}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 kr=l(o=>{const e=new Oe(o);return t=>e.get(t)},"createAccountApiFetcher");class B{static{l(this,"TenantApiClient")}derivedToken=null;apiUri;directToken;workspaceKey;tenantKey;accountClient;constructor(e){this.apiUri=me()||te,this.accountClient=new Oe,this.directToken=process.env.MEMBRANE_TOKEN||null;const t=wn();this.workspaceKey=e.workspaceKey||t.defaultWorkspaceKey||"",this.tenantKey=e.tenantKey||t.defaultTenantKey||""}async fetchToken(){const{token:e}=await this.accountClient.post(`/workspaces/${encodeURIComponent(this.workspaceKey)}/access-token`,{tenantKey:this.tenantKey});return this.derivedToken=e,e}async getToken(){if(this.directToken)return this.directToken;if(gt()==="tenant")return this.accountClient.getValidAccessToken();if(!yt()||mt()&&!be())throw new Error("Not authenticated. Run `membrane login` first.");if(!this.workspaceKey)throw new Error("No workspace specified. Use --workspaceKey or run `membrane login` to set a default.");if(!this.tenantKey)throw new Error("No tenant specified. Use --tenantKey or run `membrane login` to set a default.");return this.derivedToken?this.derivedToken:this.fetchToken()}async request(e,t){const n=await this.getToken(),r={};t?.headers&&new Headers(t.headers).forEach((c,u)=>{r[u]=c});const i={Authorization:`Bearer ${n}`,...r};t?.body&&(i["Content-Type"]=i["Content-Type"]??"application/json");let s=await fetch(`${this.apiUri}${e}`,{...t,headers:i});if(s.status===401&&!this.directToken){const a=gt()==="tenant"?await this.accountClient.forceRefreshAccessToken():await this.fetchToken();i.Authorization=`Bearer ${a}`,s=await fetch(`${this.apiUri}${e}`,{...t,headers:i})}if(!s.ok){const a=await s.text();throw new pt(s.status,a)}return s.status===204?{}:s.json()}get(e){return this.request(e,{method:"GET"})}post(e,t){return this.request(e,{method:"POST",body:t!==void 0?JSON.stringify(t):void 0})}}const xr={info:"\u{1F4DD}",success:"\u2728",warning:"\u26A0\uFE0F",error:"\u274C",debug:"\u{1F50D}"},$r={info:h.white,success:h.green,warning:h.yellow,error:h.red,debug:h.gray};class b{static{l(this,"Logger")}static formatMessage(e,t,n={icon:!1}){const r=n.timestamp?`${h.gray(new Date().toISOString())} `:"",i=n.prefix?`${h.gray(n.prefix)} `:"",s=n.suffix?` ${h.gray(n.suffix)}`:"",a=xr[t],c=$r[t];return`${r}${n.icon?a:""} ${i}${c(e)}${s}`}static info(e,t){let n=h.white;if(t?.color&&(n=h[t.color.toLowerCase()]||h.white),t?.timestamp){const r=new Date().toLocaleTimeString();console.debug(`${h.gray(`[${r}]`)} ${n(e)}`)}else console.debug(n(e))}static group(e,t){}static groupEnd(){}static newLine(){}static success(e,t){console.debug(this.formatMessage(e,"success",t))}static warning(e,t){console.debug(this.formatMessage(e,"warning",t))}static error(e,t){console.info(this.formatMessage(e,"error",t))}static debug(e,t){t?.prefix?console.debug(h.gray(`[${t.prefix}] ${e}`),t.error?`
|
|
5
|
+
${h.red(t.error)}`:""):console.debug(h.gray(e),t?.error?`
|
|
6
|
+
${h.red(t.error)}`:"")}static step(e,t){}static header(e){console.debug(),console.debug(h.bold.cyan(`\u25B6 ${e}`)),console.debug()}static table(e,t){if(e.length===0)return;const n=t||Object.keys(e[0]),r=e.map(i=>{const s={};return n.forEach(a=>{s[a]=i[a]}),s});console.table(r,n)}static divider(){}}function U(o){o instanceof pt?b.error(o.format()):o instanceof Error?b.error(o.message):b.error("An unknown error occurred"),process.exit(1)}l(U,"handleCommandError");function E(o,e,t=14){console.error(` ${h.gray(o.padEnd(t))} ${e}`)}l(E,"printField");function Or(o){const e=o.command("action").description("List and run actions (tools) on connections").option("--workspaceKey <key>","Workspace key").option("--tenantKey <key>","Tenant key (customer internalId)");e.command("list").description("List available actions").option("--connectionId <id>","Filter by connection ID").option("--intent <text>","Search by natural language intent").option("--limit <n>","Max results").option("--cursor <cursor>","Pagination cursor").option("--json","Output as JSON").action(async t=>{try{const r={...e.opts(),...t},i=new B(r),s=new URLSearchParams;t.connectionId&&s.set("connectionId",t.connectionId),t.intent&&s.set("intent",t.intent),t.limit&&s.set("limit",t.limit),t.cursor&&s.set("cursor",t.cursor);const a=s.toString(),c=await i.get(`/actions${a?`?${a}`:""}`);if(r.json)process.stdout.write(JSON.stringify(c,null,2)+`
|
|
7
|
+
`);else{const u=c.items??[];if(u.length===0)console.error(h.gray(" No actions found."));else for(const p of u){const m=p.description?h.gray(` \u2014 ${p.description}`):"";console.error(` ${h.cyan(p.id)} ${p.name||p.key||"(unnamed)"}${m}`)}c.cursor&&console.error(h.gray(` Returned ${u.length} elements. Run with --cursor ${c.cursor} to get the next page.`)),console.error()}}catch(n){U(n)}}),e.command("get <id>").description("Get an action by ID").option("--wait","Long-poll until action is no longer in BUILDING state").option("--timeout <seconds>","Timeout in seconds for --wait (1-60, default 30)").option("--json","Output as JSON").action(async(t,n)=>{try{const i={...e.opts(),...n},s=new B(i),a=new URLSearchParams;n.wait&&(a.set("wait","true"),n.timeout&&a.set("timeout",n.timeout));const c=a.toString(),u=await s.get(`/actions/${encodeURIComponent(t)}${c?`?${c}`:""}`);i.json?process.stdout.write(JSON.stringify(u,null,2)+`
|
|
8
8
|
`):(console.error(),E("ID",u.id),u.name&&E("Name",u.name),u.key&&E("Key",u.key),u.state&&E("State",u.state),u.type&&E("Type",u.type),u.integrationId&&E("Integration",u.integrationId),u.connectionId&&E("Connection",u.connectionId),console.error())}catch(r){U(r)}}),e.command("create [intent]").description('Create a new action (e.g. "send a Slack message")').option("--connectionId <id>","Target connection ID").option("--name <name>","Custom action name").option("--data <json>",`Additional fields as JSON (e.g. '{"type":"ConnectorOperation"}')`).option("--json","Output as JSON").action(async(t,n)=>{try{const i={...e.opts(),...n},s=new B(i);let a={};if(n.data)try{a=JSON.parse(n.data)}catch{throw new Error("--data must be valid JSON")}const c={...a};t&&(c.intent=t),n.name&&(c.name=n.name),n.connectionId&&(c.connectionId=n.connectionId);const u=await s.post("/actions",c);i.json?process.stdout.write(JSON.stringify(u,null,2)+`
|
|
9
|
-
`):(console.error(),E("ID",u.id),u.name&&E("Name",u.name),u.state&&E("State",u.state),console.error(
|
|
10
|
-
`):(console.error(),console.error(
|
|
11
|
-
`))}catch(r){U(r)}})}l(Or,"setupActionCommand");const Ar=Object.values(
|
|
12
|
-
`);else{const s=i.items??[];if(s.length===0)console.error(
|
|
9
|
+
`):(console.error(),E("ID",u.id),u.name&&E("Name",u.name),u.state&&E("State",u.state),console.error(h.gray(" Use `action get <id> --wait --json` to poll until ready.")),console.error())}catch(r){U(r)}}),e.command("run <actionId>").description("Run an action on a connection").option("--connectionId <id>","Connection ID to run the action on").option("--input <json>","Action input as JSON string").option("--json","Output as JSON").action(async(t,n)=>{try{const i={...e.opts(),...n},s=n.connectionId;if(!s)throw new Error("--connectionId is required");const a=new B(i);let c={};if(n.input)try{c=JSON.parse(n.input)}catch{throw new Error("--input must be valid JSON")}const u=new URLSearchParams({connectionId:s}),p=await a.post(`/actions/${encodeURIComponent(t)}/run?${u}`,{input:c});i.json?process.stdout.write(JSON.stringify(p,null,2)+`
|
|
10
|
+
`):(console.error(),console.error(h.green(" Action executed successfully.")),console.error(),process.stdout.write(JSON.stringify(p.output??p,null,2)+`
|
|
11
|
+
`))}catch(r){U(r)}})}l(Or,"setupActionCommand");const Ar=Object.values(Qt),wt=Ar.filter(o=>o!==Qt.UNIVERSE);function Pr(o){const e=o.command("agent-session").description("Manage Membrane Agent sessions (build connectors and actions)").option("--workspaceKey <key>","Workspace key").option("--tenantKey <key>","Tenant key (customer internalId)");e.command("list").description("List agent sessions").option("--json","Output as JSON").action(async t=>{try{const n={...e.opts(),...t},i=await new B(n).get("/agent/sessions");if(n.json)process.stdout.write(JSON.stringify(i,null,2)+`
|
|
12
|
+
`);else{const s=i.items??[];if(s.length===0)console.error(h.gray(" No agent sessions found."));else for(const a of s){const c=h.gray(`[${a.status}]`);console.error(` ${h.cyan(a.id)} ${c} ${a.prompt||""}`)}console.error()}}catch(n){U(n)}}),e.command("create").description("Create a new agent session").requiredOption("--message <text>","Task description for the agent").option("--agent <name>",`Agent to run the session (${wt.join(", ")})`).option("--json","Output as JSON").action(async t=>{try{if(t.agent&&!wt.includes(t.agent))throw new Error(`Invalid agent name "${t.agent}". Must be one of: ${wt.join(", ")}`);const n={...e.opts(),...t},i=await new B(n).post("/agent/sessions",{prompt:t.message,...t.agent&&{agentName:t.agent}});n.json?process.stdout.write(JSON.stringify(i,null,2)+`
|
|
13
13
|
`):(console.error(),E("Session ID",i.id),E("Status",i.status),E("State",i.state),console.error())}catch(n){U(n)}}),e.command("get <sessionId>").description("Get agent session status").option("--wait","Long-poll until session is idle or completed").option("--timeout <seconds>","Timeout in seconds for --wait (1-60, default 30)").option("--json","Output as JSON").action(async(t,n)=>{try{const r={...e.opts(),...n},i=new B(r),s=new URLSearchParams;n.wait&&(s.set("wait","true"),n.timeout&&s.set("timeout",n.timeout));const a=s.toString(),c=await i.get(`/agent/sessions/${encodeURIComponent(t)}${a?`?${a}`:""}`);r.json?process.stdout.write(JSON.stringify(c,null,2)+`
|
|
14
14
|
`):(console.error(),E("Session ID",c.id),c.agentName&&E("Agent",c.agentName),E("State",c.state),c.prompt&&E("Prompt",c.prompt),c.summary&&E("Summary",c.summary),c.error&&E("Error",typeof c.error=="string"?c.error:JSON.stringify(c.error)),console.error())}catch(r){U(r)}}),e.command("send <sessionId>").description("Send a follow-up message to an active agent session").requiredOption("--message <text>","Message to send").option("--json","Output as JSON").action(async(t,n)=>{try{const r={...e.opts(),...n},s=await new B(r).post(`/agent/sessions/${encodeURIComponent(t)}/message`,{input:n.message});r.json?process.stdout.write(JSON.stringify(s,null,2)+`
|
|
15
15
|
`):(console.error(),E("Session ID",s.id),E("Status",s.status),E("State",s.state),console.error())}catch(r){U(r)}}),e.command("abort <sessionId>").description("Abort an active agent session").option("--json","Output as JSON").action(async(t,n)=>{try{const r={...e.opts(),...n},s=await new B(r).post(`/agent/sessions/${encodeURIComponent(t)}/interrupt`);r.json?process.stdout.write(JSON.stringify(s,null,2)+`
|
|
16
|
-
`):(console.error(),console.error(
|
|
17
|
-
`);else{const a=s.items??(Array.isArray(s)?s:[]);if(a.length===0)console.error(
|
|
18
|
-
`});return n.writeLine("// Generated TypeScript definitions for Membrane actions"),n.newLine(),n.writeLine("import type {"),n.writeLine(" ActionAccessor,"),n.writeLine(" ConnectionLevelActionAccessor,"),n.writeLine('} from "@membranehq/sdk";'),n.newLine(),Lr(n,t),n.toString()}l(Dr,"generateTypeScriptContent");function Lr(o,e){o.writeLine('declare module "@membranehq/sdk" {'),o.indent(()=>{e.forEach(t=>{const n=St(t),r=t?.inputSchema;Je(o,{interfaceName:n,properties:r?.properties,required:r?.required||[]});const i=bt(t),s=t?.customOutputSchema||t?.outputSchema;Je(o,{interfaceName:i,properties:s?.properties,required:s?.required||[],fallbackContent:"result: unknown"}),o.newLine()}),Je(o,{interfaceName:"MembraneClient",methods:e.map(t=>{const n=St(t),r=bt(t);return{name:"action",parameters:`selector: "${t.key}"`,returnType:`ActionAccessor<${n}, ${r}>`}})}),o.newLine(),Je(o,{interfaceName:"ConnectionAccessor",methods:e.map(t=>{const n=St(t),r=bt(t);return{name:"action",parameters:`selector: "${t.key}"`,returnType:`ConnectionLevelActionAccessor<${n}, ${r}>`}})})}),o.writeLine("}")}l(Lr,"generateModuleAugmentation");function Je(o,e){const{interfaceName:t,properties:n,required:r=[],methods:i,fallbackContent:s}=e;o.writeLine(`interface ${t} {`),o.indent(()=>{n&&Object.keys(n).length>0&&
|
|
19
|
-
`),"createExperimentalWarning$2");function Fr(o,e){o.command("codegen").description("\u26A0\uFE0F EXPERIMENTAL: Generate code for easy integration within projects - This feature is experimental and will be changing rapidly. Use at your own risk.").requiredOption("--actions <actions>",'Comma-separated list of action names (e.g., "list-files,get-file-by-id")').requiredOption("--out <path>","Output directory for generated files").requiredOption("--target <type>","Target format: openapi or typescript").requiredOption("--schemasOnly","Generate only schemas without implementation").addHelpText("after",Tt()).addHelpText("after",["",
|
|
20
|
-
`)).action(async t=>{try{console.warn(Tt()),console.error(p.cyan("\u{1F527} Membrane Codegen")),console.error("Status: Loading membrane interfaces...");const n=await Ur(e,t),r={out:t.out,target:t.target,schemasOnly:t.schemasOnly,membraneInterfaces:n};console.error(`Output: ${r.out}`),console.error(`Target: ${r.target}`),console.error(`Schemas Only: ${r.schemasOnly?"Yes":"No"}`),console.error(`Loaded ${n.actions.length} membrane interfaces`),console.error("Status: Generating code..."),await vt(r),console.error(p.green("\u2705 Code generation completed successfully!")),process.exit(0)}catch(n){console.error(p.red("\u274C Code generation failed:")),console.error(n instanceof Error?n.message:"Unknown error occurred"),process.exit(1)}})}l(Fr,"setupCodegenCommand");async function Ur(o,e){return await o.fetchElements(),{actions:[...o.getSyncedElementsByType(x.Action).map(t=>t.data)].filter(t=>e.actions.includes(t.key||""))}}l(Ur,"loadMembraneInterfaces");const vn=it(null);function Z(){const o=st(vn);if(!o)throw new Error("useMembraneCLIService must be used within MembraneCLIServiceProvider");return o}l(Z,"useMembraneCLIService");const It=it(null),Tn=l(()=>{const o=st(It);if(!o)throw new Error("useTree must be used within TreeView");return o},"useTree"),Kr=l(o=>pe.Children.count(o)>0,"hasChildren");function _r(o){const e=Tn(),{label:t,value:n,isInitiallyExpanded:r}=o,i=_o(),s=at(e.registerChildItem(t)).current,a=e.isActiveByRef(s),[c,u]=L(r??!1),h={props:o,ref:s,id:i,active:a,expanded:c,setExpanded:u,label:t,value:n,isInitiallyExpanded:r,isParent:!1},{children:m}=o,f=typeof m=="function"?m(h):m;return{...h,props:{...o,children:f},isParent:Kr(f)}}l(_r,"useTreeItem");function ve(o){const e=Tn(),t=_r(o),{expanded:n,isParent:r,props:{children:i},setExpanded:s}=t,{renderValue:a=Br}=o,c=t.ref;Ue(()=>{function f(y){return o.onInput?.(y)?!0:y.active&&y.key.rightArrow&&!n?(s(!0),!0):y.active&&y.key.leftArrow&&n?(s(!1),!0):!1}l(f,"onInput"),c.onInput=f},[c,o.onInput,n,s]),c.firstChild??={parent:c,index:0};let u=c.firstChild;function h(f){const y=u;return y.nextSibling||(y.nextSibling={parent:c,prevSibling:y,index:y.index+1}),u=y.nextSibling,y.label=f,y}l(h,"registerChildItem");function m(){c.lastRenderedChild=u.prevSibling}return l(m,"commitChildren"),Ue(()=>{m()}),v(Ke,{children:[v(w,{marginLeft:e.depth*2,children:[d(w,{width:2,children:r&&d(C,{children:n?"\u25BC":"\u25B6"})}),qr(t),a(t)]}),n&&d(It.Provider,{value:{...e,depth:e.depth+1,registerChildItem:h},children:i})]})}l(ve,"TreeItem");function qr({active:o,label:e}){return d(w,{width:32,children:d(C,{inverse:o,children:e})})}l(qr,"defaultRenderLabel");function Br(o){return d(C,{})}l(Br,"defaultRenderValue");const ye=l(({label:o,onPress:e,hotkey:t})=>d(ve,{label:o,onInput:l(({input:n,key:r,active:i})=>i&&r.return||t&&t in r&&r[t]||n===t?(e(),!0):!1,"onInput"),renderValue:l(()=>d(w,{children:d(C,{children:`${t?` (${t})`:""}`})}),"renderValue")}),"ActionTreeItem"),In=l(({label:o,value:e,onChange:t,disabled:n=!1,mask:r,...i})=>{const[s,a]=L(e),[c,u]=L(!1);return Ue(()=>{c||a(e)},[c,e]),d(ve,{label:o,value:e,onInput:l(({key:h,active:m})=>n?!1:c?(h.escape&&u(!1),h.return&&(t(s),u(!1)),!0):m&&h.return?(u(!0),a(e),!0):!1,"onInput"),renderValue:l(()=>{const h=s,m=r?r.repeat(h.length):h;return d(w,{children:n||!c?d(C,{dimColor:!0,children:m}):v(Ke,{children:[d(w,{width:m.length+1,children:d(ln,{...i,focus:c,value:h,onChange:a})}),d(C,{dimColor:!0,children:" \u241B cancel"})]})})},"renderValue")})},"TreeTextField"),Jr=l(o=>d(In,{...o,mask:"*"}),"SecretField"),H=l(({children:o,showHelp:e=!1})=>{const t=at({parent:void 0,label:"<<ROOT>>",index:0}),[n,r]=L(t.current),i={depth:0,isActiveByRef:l(a=>n===a,"isActiveByRef"),registerChildItem:l(()=>t.current,"registerChildItem"),activeItemRef:n};Ue(()=>{r(a=>a.parent?a.parent.lastRenderedChild&&a.index>a.parent.lastRenderedChild.index?a.parent.lastRenderedChild:a:t.current.firstChild??t.current)});function*s(a){a&&(yield a,yield*s(a.firstChild),a.nextSibling&&a!==a.parent?.lastRenderedChild&&(yield*s(a.nextSibling)))}return l(s,"walkTree"),he((a,c)=>{if(n.onInput?.({input:a,key:c,active:!0}))return;let u,h;for(const m of s(t.current))if(m.label!=null){if(u===n&&(h=m),m&&m.onInput?.({input:a,key:c,active:m===n}))return;u=m}c.upArrow?r(m=>m.prevSibling?.lastRenderedChild??m.prevSibling??m.parent??t.current):c.downArrow?r(m=>h??m):c.pageUp?r(()=>t.current.firstChild??t.current):c.pageDown?r(()=>t.current.lastRenderedChild??t.current):c.tab?console.debug({label:n.label,nextSibling:n.nextSibling?.label,prevSibling:n.prevSibling?.label,parent:n.parent?.label,firstChild:n.firstChild?.label,lastRenderedChild:n.lastRenderedChild?.label}):c.leftArrow?r(m=>m.parent??t.current):c.rightArrow&&r(m=>m.lastRenderedChild?m.firstChild:m)}),d(It.Provider,{value:i,children:v(w,{flexDirection:"column",children:[d(ve,{isInitiallyExpanded:!0,label:"rootItem",children:o}),e&&d(w,{marginTop:1,flexDirection:"column",children:d(C,{dimColor:!0,children:"\u2191/\u2193 move \u2022 \u2190 collapse \u2022 \u2192 expand \u2022 Enter/Space select/edit \u2022 Esc exit"})})]})})},"TreeView");H.Item=ve,H.TextField=In;function we({label:o,elementType:e,isActionExcluded:t,toggleAction:n,generateCode:r}){const[i,s]=L([]),{fetchElements:a,getSyncedElementsByType:c}=Z();return Ce(()=>{l(async()=>{try{await a();const h=c(e);s(h.map(m=>m.data))}catch(h){console.error(String(h))}},"loadElements")()},[e,a,c,s]),d(ve,{label:o,children:i.map(u=>d(ve,{label:u.name,children:e===x.Action&&v(Ke,{children:[t&&n&&d(ye,{label:`Toggle ${t(u)?"":"(excluded)"}`,onPress:l(()=>{n(u)},"onPress")}),r&&d(ye,{label:"Generate code",onPress:l(()=>{r?.(u)},"onPress")})]})},u.id))})}l(we,"WorkspaceElementsTreeItem");function Wr({onComplete:o}){const{config:e,updateConfig:t,fetchElements:n,getSyncedElementsByType:r}=Z(),[i,s]=L(""),a=e,c=l(f=>{s(f),setTimeout(()=>s(""),2e3)},"setFlash"),u=l(async(f,y)=>{try{await t({[f]:y}),c("\u2705 Configuration updated!")}catch{c("\u274C Error updating configuration")}},"updateField"),h=l(async()=>{try{if(e){const f=fe.saveToFile(e);c(f?"\u2705 Configuration saved successfully!":"\u274C Failed to save configuration"),await n();const y=r(x.Action);await vt({out:a?.outputDir??"",target:a?.projectType??"typescript",schemasOnly:!1,membraneInterfaces:{actions:y.filter(I=>!a?.excludedActionKeys?.includes(I.key)).map(I=>I.data)}}),c("\u2705 Code generated successfully!")}}catch{c("\u274C Error saving configuration")}},"handleSaveConfig"),m=l(async()=>{try{const f=fe.loadConfig();f?(await t(f),c("\u2705 Configuration reloaded successfully!")):c("\u274C No configuration found to reload")}catch{c("\u274C Error reloading configuration")}},"handleReloadConfig");return v(w,{flexDirection:"column",gap:1,children:[d(C,{bold:!0,color:"cyan",children:"\u2699\uFE0F Membrane Configuration Manager"}),d(w,{paddingX:2,children:v(H,{showHelp:!0,children:[v(H.Item,{label:"Configuration",isInitiallyExpanded:!0,children:[v(H.Item,{label:"Project",children:[d(H.TextField,{label:"Workspace Key",value:a?.workspaceKey??"",onChange:l(f=>u("workspaceKey",f),"onChange"),disabled:!0}),d(Jr,{label:"Workspace Secret",value:a?.workspaceSecret??"",onChange:l(f=>u("workspaceSecret",f),"onChange"),disabled:!0}),d(H.TextField,{label:"API URI",value:a?.apiUri??"",onChange:l(f=>u("apiUri",f),"onChange")}),d(H.TextField,{label:"Test Customer ID",value:a?.testCustomerId??"",onChange:l(f=>u("testCustomerId",f),"onChange")})]}),v(H.Item,{label:"Code Generation",isInitiallyExpanded:!0,children:[v(H.Item,{label:"Project Type",isInitiallyExpanded:!0,value:a?.projectType,renderValue:l(({value:f})=>d(C,{children:f==="typescript"?"TypeScript":f==="openapi"?"OpenAPI":"(Not set)"}),"renderValue"),children:[d(ye,{label:"Update to TypeScript",onPress:l(()=>u("projectType","typescript"),"onPress")}),d(ye,{label:"Update to OpenAPI",onPress:l(()=>u("projectType","openapi"),"onPress")})]}),d(H.TextField,{label:"Project dir",value:a?.outputDir??"",onChange:l(f=>u("outputDir",f),"onChange")})]}),v(H.Item,{label:"Workspace Elements",children:[d(we,{label:"Actions",elementType:x.Action,isActionExcluded:l(f=>a?.excludedActionKeys?.includes(f.key)??!1,"isActionExcluded"),toggleAction:l(f=>u("excludedActionKeys",[...a?.excludedActionKeys??[],f.key]),"toggleAction"),generateCode:l(f=>{(async()=>{try{await vt({out:a?.outputDir??"",target:a?.projectType??"typescript",schemasOnly:!1,membraneInterfaces:{actions:[f]}}),c("\u2705 Code generated successfully!")}catch{c("\u274C Error generating code")}})()},"generateCode")}),d(we,{label:"Flows",elementType:x.Flow}),d(we,{label:"Data Sources",elementType:x.DataSource}),d(we,{label:"Field Mappings",elementType:x.FieldMapping}),d(we,{label:"Packages",elementType:x.Package}),d(we,{label:"App Data Schemas",elementType:x.AppDataSchema}),d(we,{label:"App Event Types",elementType:x.AppEventType})]})]}),d(ye,{label:"Save Configuration",onPress:h,hotkey:"s"}),d(ye,{label:"Reload Configuration",onPress:m,hotkey:"r"}),d(ye,{label:"Exit",onPress:l(()=>o?.(),"onPress"),hotkey:"escape"})]})}),i&&d(w,{paddingX:2,children:d(C,{color:i.includes("\u2705")?"green":"red",children:i})})]})}l(Wr,"ConfigManager");const zr="membrane",Gr=["**/node_modules/**","**/.git/**","**/.DS_Store","**/Thumbs.db","**/*.tmp","**/*.swp","**/*.swo","**/*.log","**/*.lock","**/.cache/**","**/.next/**","**/.vscode/**","**/.idea/**","**/.logs/**"];function W(o){return k.join(o,zr)}l(W,"getMembraneDir");const En=Ve(W(process.cwd()),".logs");class Hr{static{l(this,"WorkspaceLogger")}_logs;verboseMode=!1;notificationHandler=null;constructor(){this._logs=[]}setNotificationHandler(e){this.notificationHandler=e}setVerboseMode(e){this.verboseMode=e}getVerboseMode(){return this.verboseMode}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),(t!=="debug"||this.verboseMode)&&this.notificationHandler&&this.notificationHandler.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")}debug(e){this.log(e,"debug")}clear(){this._logs=[]}saveLogsToFile(e){if(this._logs.length===0)return null;try{const t=new Date().toISOString().replace(/[:.]/g,"_"),n=e?`-${e}`:"",r=`${t}${n}.txt`;wo(En,{recursive:!0});const i=Ve(En,r),s=this._logs.map(a=>`[${a.timestamp}] ${a.type?.toUpperCase()||"INFO"}: ${a.message}`).join(`
|
|
21
|
-
`);return Co(i,s,"utf-8"),i}catch(t){return console.error("Failed to save logs:",t),null}}}const g=new Hr,kn=new Wo;class xn{static{l(this,"RequestLogger")}constructor(e=
|
|
16
|
+
`):(console.error(),console.error(h.green(" Session aborted.")),console.error())}catch(r){U(r)}}),e.command("messages <sessionId>").description("Get messages from an agent session").option("--json","Output as JSON").action(async(t,n)=>{try{const r={...e.opts(),...n},s=await new B(r).get(`/agent/sessions/${encodeURIComponent(t)}/messages`);if(r.json)process.stdout.write(JSON.stringify(s,null,2)+`
|
|
17
|
+
`);else{const a=s.items??(Array.isArray(s)?s:[]);if(a.length===0)console.error(h.gray(" No messages found."));else for(const c of a){const u=h.cyan(String(c.role??"unknown")),p=c.content??c.text??JSON.stringify(c);console.error(` ${u}: ${p}`)}console.error()}}catch(r){U(r)}})}l(Pr,"setupAgentSessionCommand");function ge(o){if(o.type){if(Array.isArray(o.type))return{anyOf:o.type.map(t=>ge({...o,type:t}))};if(o.type==="array"){const t={type:"array",items:o.items?ge(o.items):{type:"object"}};return o.title&&(t.title=o.title),o.description&&(t.description=o.description),o.minItems!==void 0&&(t.minItems=o.minItems),o.maxItems!==void 0&&(t.maxItems=o.maxItems),o.uniqueItems!==void 0&&(t.uniqueItems=o.uniqueItems),t}}const e={};if(o.type&&!Array.isArray(o.type)&&(e.type=o.type),o.title&&(e.title=o.title),o.description&&(e.description=o.description),o.format&&(e.format=o.format),o.enum&&(e.enum=o.enum),o.default!==void 0&&(e.default=o.default),o.minimum!==void 0&&(e.minimum=o.minimum),o.maximum!==void 0&&(e.maximum=o.maximum),o.minLength!==void 0&&(e.minLength=o.minLength),o.maxLength!==void 0&&(e.maxLength=o.maxLength),o.maxItems!==void 0&&(e.maxItems=o.maxItems),o.readOnly!==void 0&&(e.readOnly=o.readOnly),o.writeOnly!==void 0&&(e.writeOnly=o.writeOnly),o.examples&&o.examples.length>0&&(e.example=o.examples[0]),o.properties){e.properties={};for(const[t,n]of Object.entries(o.properties))e.properties[t]=ge(n)}return o.anyOf&&(e.anyOf=o.anyOf.map(ge)),o.additionalProperties!==void 0&&(typeof o.additionalProperties=="boolean"?e.additionalProperties=o.additionalProperties:e.additionalProperties=ge(o.additionalProperties)),o.required&&(e.required=o.required),e}l(ge,"convertDataSchemaToOpenAPI");function Nr(o){const{membraneInterfaces:{actions:e}}=o,t=Rr(e);return JSON.stringify({openapi:"3.0.0",info:{title:"Membrane Actions API",version:"1.0.0",description:"Generated OpenAPI specification for Membrane actions"},paths:{},components:{schemas:t}},null,2)}l(Nr,"generateOpenAPIContent");function Rr(o){const e={};return o.forEach(t=>{const n=ot(nt(t.key)),r={type:"object",properties:{id:{type:"string",description:"Request ID"},action:{type:"string",enum:[t.key]}},required:["id","action"]};if(t?.inputSchema){const a=ge(t.inputSchema);a.properties&&(r.properties={...r.properties,...a.properties}),a.required&&(r.required=[...r.required||[],...a.required])}e[`${n}Request`]=r;const i={type:"object",properties:{id:{type:"string",description:"Response ID"},success:{type:"boolean"},data:{type:"object"}},required:["id","success"]},s=t?.customOutputSchema||t?.outputSchema;if(s){const a=ge(s);i.properties={...i.properties,data:a}}e[`${n}Response`]=i}),e}l(Rr,"generateOpenAPISchemas");function Dr(o){const{membraneInterfaces:{actions:e}}=o,t=Uo(e,"key"),n=new Fo({indentNumberOfSpaces:2,newLine:`
|
|
18
|
+
`});return n.writeLine("// Generated TypeScript definitions for Membrane actions"),n.newLine(),n.writeLine("import type {"),n.writeLine(" ActionAccessor,"),n.writeLine(" ConnectionLevelActionAccessor,"),n.writeLine('} from "@membranehq/sdk";'),n.newLine(),Lr(n,t),n.toString()}l(Dr,"generateTypeScriptContent");function Lr(o,e){o.writeLine('declare module "@membranehq/sdk" {'),o.indent(()=>{e.forEach(t=>{const n=St(t),r=t?.inputSchema;Je(o,{interfaceName:n,properties:r?.properties,required:r?.required||[]});const i=bt(t),s=t?.customOutputSchema||t?.outputSchema;Je(o,{interfaceName:i,properties:s?.properties,required:s?.required||[],fallbackContent:"result: unknown"}),o.newLine()}),Je(o,{interfaceName:"MembraneClient",methods:e.map(t=>{const n=St(t),r=bt(t);return{name:"action",parameters:`selector: "${t.key}"`,returnType:`ActionAccessor<${n}, ${r}>`}})}),o.newLine(),Je(o,{interfaceName:"ConnectionAccessor",methods:e.map(t=>{const n=St(t),r=bt(t);return{name:"action",parameters:`selector: "${t.key}"`,returnType:`ConnectionLevelActionAccessor<${n}, ${r}>`}})})}),o.writeLine("}")}l(Lr,"generateModuleAugmentation");function Je(o,e){const{interfaceName:t,properties:n,required:r=[],methods:i,fallbackContent:s}=e;o.writeLine(`interface ${t} {`),o.indent(()=>{n&&Object.keys(n).length>0&&jr(o,n,r),i&&i.length>0&&(n&&Object.keys(n).length>0&&o.newLine(),i.forEach((a,c)=>{o.writeLine(`${a.name}(${a.parameters}): ${a.returnType};`),c<i.length-1&&o.newLine()})),s&&(!n||Object.keys(n).length===0)&&(!i||i.length===0)&&o.writeLine(s)}),o.writeLine("}")}l(Je,"generateTypeScriptInterface");function jr(o,e,t){Object.entries(e).forEach(([n,r])=>{const s=t.includes(n)?"":"?",a=Ct(r);o.writeLine(`readonly ${n}${s}: ${a}`)})}l(jr,"generateTypeScriptProperties");function Ct(o){return o.type==="string"?o.enum?o.enum.map(e=>`'${e}'`).join(" | "):"string":o.type==="number"||o.type==="integer"?"number":o.type==="boolean"?"boolean":o.type==="array"?`${o.items?Ct(o.items):"unknown"}[]`:o.type==="object"?o.properties?`{ ${Object.entries(o.properties).map(([t,n])=>{const i=(o.required||[]).includes(t)?"":"?",s=Ct(n);return`readonly ${t}${i}: ${s}`}).join("; ")} }`:"Record<string, unknown>":"unknown"}l(Ct,"convertJsonSchemaToTypeScript");function St(o){return`${ot(nt(o.key))}Input`}l(St,"getInputTypeName");function bt(o){return`${ot(nt(o.key))}Output`}l(bt,"getOutputTypeName");async function vt(o){const{out:e}=o;await T.promises.mkdir(e,{recursive:!0});const t=Mr(o);for(const[n,r]of Object.entries(t)){const i=k.join(e,n);await T.promises.writeFile(i,r,"utf-8")}}l(vt,"generateCode");function Mr(o){switch(o.target){case"openapi":return{"openapi.json":Nr(o)};case"typescript":return{"generated.d.ts":Dr(o)};default:throw new Error(`Unsupported target: ${o.target}`)}}l(Mr,"generateContent");const Tt=l(()=>[h.yellow("\u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510"),h.yellow("\u2502 \u26A0\uFE0F EXPERIMENTAL FEATURE WARNING \u2502"),h.yellow("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524"),h.yellow("\u2502 The codegen command is experimental and subject to rapid changes.\u2502"),h.yellow("\u2502 Features, APIs, and file structures may change without notice. \u2502"),h.yellow("\u2502 Use in production environments is not recommended. \u2502"),h.yellow("\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518"),""].join(`
|
|
19
|
+
`),"createExperimentalWarning$2");function Fr(o,e){o.command("codegen").description("\u26A0\uFE0F EXPERIMENTAL: Generate code for easy integration within projects - This feature is experimental and will be changing rapidly. Use at your own risk.").requiredOption("--actions <actions>",'Comma-separated list of action names (e.g., "list-files,get-file-by-id")').requiredOption("--out <path>","Output directory for generated files").requiredOption("--target <type>","Target format: openapi or typescript").requiredOption("--schemasOnly","Generate only schemas without implementation").addHelpText("after",Tt()).addHelpText("after",["",h.bold("Examples:"),` ${h.gray("\u25B8")} ${h.cyan("membrane codegen --actions list-files,get-file-by-id --out src/generated --target openapi --schemasOnly")}`,` ${h.gray("\u25B8")} ${h.cyan("membrane install --actions delete-file --out src/generated --target typescript --schemasOnly")}`,"",Tt()].join(`
|
|
20
|
+
`)).action(async t=>{try{console.warn(Tt()),console.error(h.cyan("\u{1F527} Membrane Codegen")),console.error("Status: Loading membrane interfaces...");const n=await Ur(e,t),r={out:t.out,target:t.target,schemasOnly:t.schemasOnly,membraneInterfaces:n};console.error(`Output: ${r.out}`),console.error(`Target: ${r.target}`),console.error(`Schemas Only: ${r.schemasOnly?"Yes":"No"}`),console.error(`Loaded ${n.actions.length} membrane interfaces`),console.error("Status: Generating code..."),await vt(r),console.error(h.green("\u2705 Code generation completed successfully!")),process.exit(0)}catch(n){console.error(h.red("\u274C Code generation failed:")),console.error(n instanceof Error?n.message:"Unknown error occurred"),process.exit(1)}})}l(Fr,"setupCodegenCommand");async function Ur(o,e){return await o.fetchElements(),{actions:[...o.getSyncedElementsByType(x.Action).map(t=>t.data)].filter(t=>e.actions.includes(t.key||""))}}l(Ur,"loadMembraneInterfaces");const vn=it(null);function Z(){const o=st(vn);if(!o)throw new Error("useMembraneCLIService must be used within MembraneCLIServiceProvider");return o}l(Z,"useMembraneCLIService");const It=it(null),Tn=l(()=>{const o=st(It);if(!o)throw new Error("useTree must be used within TreeView");return o},"useTree"),Kr=l(o=>he.Children.count(o)>0,"hasChildren");function _r(o){const e=Tn(),{label:t,value:n,isInitiallyExpanded:r}=o,i=_o(),s=at(e.registerChildItem(t)).current,a=e.isActiveByRef(s),[c,u]=L(r??!1),p={props:o,ref:s,id:i,active:a,expanded:c,setExpanded:u,label:t,value:n,isInitiallyExpanded:r,isParent:!1},{children:m}=o,f=typeof m=="function"?m(p):m;return{...p,props:{...o,children:f},isParent:Kr(f)}}l(_r,"useTreeItem");function ve(o){const e=Tn(),t=_r(o),{expanded:n,isParent:r,props:{children:i},setExpanded:s}=t,{renderValue:a=Br}=o,c=t.ref;Ue(()=>{function f(y){return o.onInput?.(y)?!0:y.active&&y.key.rightArrow&&!n?(s(!0),!0):y.active&&y.key.leftArrow&&n?(s(!1),!0):!1}l(f,"onInput"),c.onInput=f},[c,o.onInput,n,s]),c.firstChild??={parent:c,index:0};let u=c.firstChild;function p(f){const y=u;return y.nextSibling||(y.nextSibling={parent:c,prevSibling:y,index:y.index+1}),u=y.nextSibling,y.label=f,y}l(p,"registerChildItem");function m(){c.lastRenderedChild=u.prevSibling}return l(m,"commitChildren"),Ue(()=>{m()}),v(Ke,{children:[v(w,{marginLeft:e.depth*2,children:[d(w,{width:2,children:r&&d(C,{children:n?"\u25BC":"\u25B6"})}),qr(t),a(t)]}),n&&d(It.Provider,{value:{...e,depth:e.depth+1,registerChildItem:p},children:i})]})}l(ve,"TreeItem");function qr({active:o,label:e}){return d(w,{width:32,children:d(C,{inverse:o,children:e})})}l(qr,"defaultRenderLabel");function Br(o){return d(C,{})}l(Br,"defaultRenderValue");const ye=l(({label:o,onPress:e,hotkey:t})=>d(ve,{label:o,onInput:l(({input:n,key:r,active:i})=>i&&r.return||t&&t in r&&r[t]||n===t?(e(),!0):!1,"onInput"),renderValue:l(()=>d(w,{children:d(C,{children:`${t?` (${t})`:""}`})}),"renderValue")}),"ActionTreeItem"),In=l(({label:o,value:e,onChange:t,disabled:n=!1,mask:r,...i})=>{const[s,a]=L(e),[c,u]=L(!1);return Ue(()=>{c||a(e)},[c,e]),d(ve,{label:o,value:e,onInput:l(({key:p,active:m})=>n?!1:c?(p.escape&&u(!1),p.return&&(t(s),u(!1)),!0):m&&p.return?(u(!0),a(e),!0):!1,"onInput"),renderValue:l(()=>{const p=s,m=r?r.repeat(p.length):p;return d(w,{children:n||!c?d(C,{dimColor:!0,children:m}):v(Ke,{children:[d(w,{width:m.length+1,children:d(ln,{...i,focus:c,value:p,onChange:a})}),d(C,{dimColor:!0,children:" \u241B cancel"})]})})},"renderValue")})},"TreeTextField"),Jr=l(o=>d(In,{...o,mask:"*"}),"SecretField"),H=l(({children:o,showHelp:e=!1})=>{const t=at({parent:void 0,label:"<<ROOT>>",index:0}),[n,r]=L(t.current),i={depth:0,isActiveByRef:l(a=>n===a,"isActiveByRef"),registerChildItem:l(()=>t.current,"registerChildItem"),activeItemRef:n};Ue(()=>{r(a=>a.parent?a.parent.lastRenderedChild&&a.index>a.parent.lastRenderedChild.index?a.parent.lastRenderedChild:a:t.current.firstChild??t.current)});function*s(a){a&&(yield a,yield*s(a.firstChild),a.nextSibling&&a!==a.parent?.lastRenderedChild&&(yield*s(a.nextSibling)))}return l(s,"walkTree"),pe((a,c)=>{if(n.onInput?.({input:a,key:c,active:!0}))return;let u,p;for(const m of s(t.current))if(m.label!=null){if(u===n&&(p=m),m&&m.onInput?.({input:a,key:c,active:m===n}))return;u=m}c.upArrow?r(m=>m.prevSibling?.lastRenderedChild??m.prevSibling??m.parent??t.current):c.downArrow?r(m=>p??m):c.pageUp?r(()=>t.current.firstChild??t.current):c.pageDown?r(()=>t.current.lastRenderedChild??t.current):c.tab?console.debug({label:n.label,nextSibling:n.nextSibling?.label,prevSibling:n.prevSibling?.label,parent:n.parent?.label,firstChild:n.firstChild?.label,lastRenderedChild:n.lastRenderedChild?.label}):c.leftArrow?r(m=>m.parent??t.current):c.rightArrow&&r(m=>m.lastRenderedChild?m.firstChild:m)}),d(It.Provider,{value:i,children:v(w,{flexDirection:"column",children:[d(ve,{isInitiallyExpanded:!0,label:"rootItem",children:o}),e&&d(w,{marginTop:1,flexDirection:"column",children:d(C,{dimColor:!0,children:"\u2191/\u2193 move \u2022 \u2190 collapse \u2022 \u2192 expand \u2022 Enter/Space select/edit \u2022 Esc exit"})})]})})},"TreeView");H.Item=ve,H.TextField=In;function we({label:o,elementType:e,isActionExcluded:t,toggleAction:n,generateCode:r}){const[i,s]=L([]),{fetchElements:a,getSyncedElementsByType:c}=Z();return Ce(()=>{l(async()=>{try{await a();const p=c(e);s(p.map(m=>m.data))}catch(p){console.error(String(p))}},"loadElements")()},[e,a,c,s]),d(ve,{label:o,children:i.map(u=>d(ve,{label:u.name,children:e===x.Action&&v(Ke,{children:[t&&n&&d(ye,{label:`Toggle ${t(u)?"":"(excluded)"}`,onPress:l(()=>{n(u)},"onPress")}),r&&d(ye,{label:"Generate code",onPress:l(()=>{r?.(u)},"onPress")})]})},u.id))})}l(we,"WorkspaceElementsTreeItem");function Wr({onComplete:o}){const{config:e,updateConfig:t,fetchElements:n,getSyncedElementsByType:r}=Z(),[i,s]=L(""),a=e,c=l(f=>{s(f),setTimeout(()=>s(""),2e3)},"setFlash"),u=l(async(f,y)=>{try{await t({[f]:y}),c("\u2705 Configuration updated!")}catch{c("\u274C Error updating configuration")}},"updateField"),p=l(async()=>{try{if(e){const f=fe.saveToFile(e);c(f?"\u2705 Configuration saved successfully!":"\u274C Failed to save configuration"),await n();const y=r(x.Action);await vt({out:a?.outputDir??"",target:a?.projectType??"typescript",schemasOnly:!1,membraneInterfaces:{actions:y.filter(I=>!a?.excludedActionKeys?.includes(I.key)).map(I=>I.data)}}),c("\u2705 Code generated successfully!")}}catch{c("\u274C Error saving configuration")}},"handleSaveConfig"),m=l(async()=>{try{const f=fe.loadConfig();f?(await t(f),c("\u2705 Configuration reloaded successfully!")):c("\u274C No configuration found to reload")}catch{c("\u274C Error reloading configuration")}},"handleReloadConfig");return v(w,{flexDirection:"column",gap:1,children:[d(C,{bold:!0,color:"cyan",children:"\u2699\uFE0F Membrane Configuration Manager"}),d(w,{paddingX:2,children:v(H,{showHelp:!0,children:[v(H.Item,{label:"Configuration",isInitiallyExpanded:!0,children:[v(H.Item,{label:"Project",children:[d(H.TextField,{label:"Workspace Key",value:a?.workspaceKey??"",onChange:l(f=>u("workspaceKey",f),"onChange"),disabled:!0}),d(Jr,{label:"Workspace Secret",value:a?.workspaceSecret??"",onChange:l(f=>u("workspaceSecret",f),"onChange"),disabled:!0}),d(H.TextField,{label:"API URI",value:a?.apiUri??"",onChange:l(f=>u("apiUri",f),"onChange")}),d(H.TextField,{label:"Test Customer ID",value:a?.testCustomerId??"",onChange:l(f=>u("testCustomerId",f),"onChange")})]}),v(H.Item,{label:"Code Generation",isInitiallyExpanded:!0,children:[v(H.Item,{label:"Project Type",isInitiallyExpanded:!0,value:a?.projectType,renderValue:l(({value:f})=>d(C,{children:f==="typescript"?"TypeScript":f==="openapi"?"OpenAPI":"(Not set)"}),"renderValue"),children:[d(ye,{label:"Update to TypeScript",onPress:l(()=>u("projectType","typescript"),"onPress")}),d(ye,{label:"Update to OpenAPI",onPress:l(()=>u("projectType","openapi"),"onPress")})]}),d(H.TextField,{label:"Project dir",value:a?.outputDir??"",onChange:l(f=>u("outputDir",f),"onChange")})]}),v(H.Item,{label:"Workspace Elements",children:[d(we,{label:"Actions",elementType:x.Action,isActionExcluded:l(f=>a?.excludedActionKeys?.includes(f.key)??!1,"isActionExcluded"),toggleAction:l(f=>u("excludedActionKeys",[...a?.excludedActionKeys??[],f.key]),"toggleAction"),generateCode:l(f=>{(async()=>{try{await vt({out:a?.outputDir??"",target:a?.projectType??"typescript",schemasOnly:!1,membraneInterfaces:{actions:[f]}}),c("\u2705 Code generated successfully!")}catch{c("\u274C Error generating code")}})()},"generateCode")}),d(we,{label:"Flows",elementType:x.Flow}),d(we,{label:"Data Sources",elementType:x.DataSource}),d(we,{label:"Field Mappings",elementType:x.FieldMapping}),d(we,{label:"Packages",elementType:x.Package}),d(we,{label:"App Data Schemas",elementType:x.AppDataSchema}),d(we,{label:"App Event Types",elementType:x.AppEventType})]})]}),d(ye,{label:"Save Configuration",onPress:p,hotkey:"s"}),d(ye,{label:"Reload Configuration",onPress:m,hotkey:"r"}),d(ye,{label:"Exit",onPress:l(()=>o?.(),"onPress"),hotkey:"escape"})]})}),i&&d(w,{paddingX:2,children:d(C,{color:i.includes("\u2705")?"green":"red",children:i})})]})}l(Wr,"ConfigManager");const zr="membrane",Gr=["**/node_modules/**","**/.git/**","**/.DS_Store","**/Thumbs.db","**/*.tmp","**/*.swp","**/*.swo","**/*.log","**/*.lock","**/.cache/**","**/.next/**","**/.vscode/**","**/.idea/**","**/.logs/**"];function W(o){return k.join(o,zr)}l(W,"getMembraneDir");const En=Ve(W(process.cwd()),".logs");class Hr{static{l(this,"WorkspaceLogger")}_logs;verboseMode=!1;notificationHandler=null;constructor(){this._logs=[]}setNotificationHandler(e){this.notificationHandler=e}setVerboseMode(e){this.verboseMode=e}getVerboseMode(){return this.verboseMode}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),(t!=="debug"||this.verboseMode)&&this.notificationHandler&&this.notificationHandler.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")}debug(e){this.log(e,"debug")}clear(){this._logs=[]}saveLogsToFile(e){if(this._logs.length===0)return null;try{const t=new Date().toISOString().replace(/[:.]/g,"_"),n=e?`-${e}`:"",r=`${t}${n}.txt`;wo(En,{recursive:!0});const i=Ve(En,r),s=this._logs.map(a=>`[${a.timestamp}] ${a.type?.toUpperCase()||"INFO"}: ${a.message}`).join(`
|
|
21
|
+
`);return Co(i,s,"utf-8"),i}catch(t){return console.error("Failed to save logs:",t),null}}}const g=new Hr,kn=new Wo;class xn{static{l(this,"RequestLogger")}constructor(e=Oo){this.axiosInstance=e}interceptorsConfigured=!1;setup(){if(this.interceptorsConfigured)return;const e=l(t=>(this.logError(t),Promise.reject(t)),"errorHandler");this.axiosInstance.interceptors.request.use(t=>{const n=kn.getStore();t.metadata={startTime:Date.now(),skipErrorLog:n};const{method:r,url:i}=this.getRequestDetails(t);return g.debug(`[Request]: ${r} ${i}`),t},e),this.axiosInstance.interceptors.response.use(t=>{const{method:n,url:r}=this.getRequestDetails(t.config),i=this.getDuration(t.config),{status:s,statusText:a}=t;return g.debug(`[Response]: ${n} ${r} - ${s} ${a} (${i}ms)`),t},e),this.interceptorsConfigured=!0}static withSkipErrorLog(e){return kn.run(!0,e)}getRequestDetails(e){const t=e?.method?.toUpperCase()??"UNKNOWN";if(!e?.url)return{method:t,url:"unknown"};if(e.url.startsWith("http"))return{method:t,url:e.url};const r=`${e.baseURL??""}/${e.url}`.replace(/\/+/g,"/").replace(/:\//,"://");return{method:t,url:r}}getDuration(e){return Date.now()-(e?.metadata?.startTime??Date.now())}logError(e){if(e.config?.metadata?.skipErrorLog)return;const{method:t,url:n}=this.getRequestDetails(e.config),r=this.getDuration(e.config);if(e.response){const{status:i,statusText:s}=e.response;g.error(`[Response]: ${t} ${n} - ${i} ${s} (${r}ms)`),e.response.data&&g.error(`[Response Data]: ${JSON.stringify(e.response.data,null,2)}`)}}}function Vr(o,e){return new Proxy(o,{get(t,n){const r=t[n];return typeof r=="function"?(...i)=>(e.lastCall={method:String(n),args:i},r.apply(t,i)):r}})}l(Vr,"createTrackedClient");class Yr{static{l(this,"MembraneAPIManager")}client=null;currentConfig=null;tokenExpiry=0;requestTimes=[];maxRequestsPerSecond=80;windowSizeMs=1e3;semaphore=0;maxConcurrentRequests;maxRetries;retryDelay;requestTimeout;enableJitter;semaphoreQueue=[];rateLimitMutex=Promise.resolve();requestLogger=null;constructor(e={}){this.init(e)}init(e={}){this.windowSizeMs=e.windowSizeMs??1e3,this.maxRequestsPerSecond=e.maxRequestsPerSecond??80,this.maxConcurrentRequests=e.maxConcurrentRequests??Math.max(1,Math.min(Math.floor(this.maxRequestsPerSecond/4),20)),this.maxRetries=e.maxRetries??3,this.retryDelay=e.retryDelay??1e3,this.requestTimeout=e.requestTimeout??12e4,this.enableJitter=e.enableJitter!==!1,this.requestLogger=new xn,this.requestLogger.setup()}async withClient(e,t=!0,n=process.cwd()){const r={lastCall:null},i=l(async()=>{try{return await this.withRetry(async()=>{const s=await this.getClient(n),a=Vr(s,r);await this.acquireSemaphore();try{return await this.waitIfNeeded(),this.recordRequest(),await this.withTimeout(e(a),this.requestTimeout)}finally{this.releaseSemaphore()}},"API request")}catch(s){if(t){const a=r.lastCall?`Request: client.${r.lastCall.method}(${r.lastCall.args.map(c=>JSON.stringify(c)).join(", ")})`:null;throw s?.isMembraneError?(console.error(`
|
|
22
22
|
Membrane API Error:`),a&&console.error(a),console.error(JSON.stringify(V(s),null,2))):Jo(s)?(console.error(`
|
|
23
23
|
HTTP Error:`),a&&console.error(a),console.error(JSON.stringify({message:s.message,status:s.response?.status,statusText:s.response?.statusText,responseData:s.response?.data},null,2))):(console.error(`
|
|
24
|
-
Unexpected Error:`),a&&console.error(a),console.error(s)),s}return}},"executeRequest");return t?i():xn.withSkipErrorLog(i)}async generateAccessToken(e,t){return ct.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=xe(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 Xt({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,r=!this.isTokenValid()||this.tokenExpiry-Date.now()<3e5;return(!this.client||n||r)&&(this.client=await this.createClient(t)),this.client}clearClient(){this.client=null,this.currentConfig=null,this.tokenExpiry=0,this.requestTimes=[],this.semaphore=0,this.semaphoreQueue=[],this.rateLimitMutex=Promise.resolve()}getCurrentConfigInfo(){return this.currentConfig}async waitIfNeeded(){this.rateLimitMutex=this.rateLimitMutex.then(async()=>{for(this.cleanOldRequests();this.requestTimes.length>=this.maxRequestsPerSecond;){const t=this.requestTimes[0]+this.windowSizeMs-Date.now()+10;if(t>0)await new Promise(n=>setTimeout(n,t)),this.cleanOldRequests();else break}}),await this.rateLimitMutex}recordRequest(){this.requestTimes.push(Date.now())}cleanOldRequests(){const e=Date.now()-this.windowSizeMs;this.requestTimes=this.requestTimes.filter(t=>t>e)}getRequestCount(){return this.cleanOldRequests(),this.requestTimes.length}async acquireSemaphore(){if(this.semaphore<this.maxConcurrentRequests){this.semaphore++;return}return new Promise(e=>{this.semaphoreQueue.push(e)})}releaseSemaphore(){if(this.semaphore--,this.semaphoreQueue.length>0){const e=this.semaphoreQueue.shift();this.semaphore++,e()}}async withRetry(e,t="operation"){let n;for(let r=0;r<=this.maxRetries;r++)try{return await e()}catch(i){if(n=i,!this.isRetryableError(i)||r===this.maxRetries)throw i;const s=new Date().toISOString(),a=r+2;g.debug(`[${s}] Retrying ${t} (attempt ${a}/${this.maxRetries+1})`);let c=this.retryDelay*Math.pow(2,r);if(this.enableJitter){const u=c*.25*(Math.random()*2-1);c=Math.max(0,c+u)}await new Promise(u=>setTimeout(u,c))}throw n||new Error("Unknown error occurred during retry attempts")}isRetryableError(e){if(!e)return!1;const t=(e.message||e.toString()||"").toLowerCase(),n=e.code;return n&&["econnrefused","enotfound","econnreset","etimedout","ehostunreach","enetunreach"].includes(n.toLowerCase())?!0:["econnrefused","connection refused","network error","timeout","socket hang up","request timeout","dns lookup failed"].some(s=>t.includes(s))}async withTimeout(e,t){let n;const r=new Promise((i,s)=>{n=setTimeout(()=>s(new Error(`Request timeout after ${t}ms`)),t)});try{const i=await Promise.race([e,r]);return n&&clearTimeout(n),i}catch(i){throw n&&clearTimeout(n),i}}async getVersion(){try{return(await this.withClient(t=>t.get("version"),!1))?.version??null}catch{return null}}async isVersionAtLeast(e){const t=await this.getVersion(),n=t?lt.coerce(t):null,r=lt.coerce(e);return!!(n&&r&<.gte(n,r))}}const O=new Yr,X={[x.Integration]:{element:"integration",elements:"integrations",exportable:!1,exportCleanup:l(o=>({id:o.id,key:o.key,name:o.name,connectorId:o.connectorId,baseUri:o.baseUri,connectorVersion:o.connectorVersion}),"exportCleanup")},[x.Connector]:{element:"connector",elements:"connectors",exportable:!1},[x.Action]:{element:"action",elements:"actions",integrationSpecific:!0,exportCleanup:l(o=>(delete o.integration,o),"exportCleanup")},[x.AppDataSchema]:{element:"appDataSchema",elements:"appDataSchemas"},[x.AppEventType]:{element:"appEventType",elements:"appEventTypes"},[x.DataLinkTable]:{element:"dataLinkTable",elements:"dataLinkTables"},[x.DataSource]:{element:"dataSource",elements:"dataSources",parentKey:"universalDataSourceId",integrationSpecific:!0},[x.FieldMapping]:{element:"fieldMapping",elements:"fieldMappings",integrationSpecific:!0,parentKey:"universalFieldMappingId",exportCleanup:l(o=>(delete o.dataSourceId,o),"exportCleanup")},[x.Flow]:{element:"flow",elements:"flows",integrationSpecific:!0,parentKey:"universalFlowId"},[x.Package]:{element:"package",elements:"packages",integrationSpecific:!0}},Zr=["id","workspaceId","integrationId","createdAt","updatedAt","revision","archivedAt","baseUri","state","appliedToIntegrations","dependencies"],$n=[x.Action,x.FieldMapping,x.Flow,x.DataSource,x.Package];class _{static{l(this,"Element")}type;key;integrationKey;data;constructor(e,t,n,r){if(!r)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=r,this.integrationKey=n||_.extractIntegrationKey(r)}get id(){return _.makeId(this.type,this.key,this.integrationKey)}get dirPath(){const e=Q[this.type].apiPath;if(this.integrationKey){const t=Q[x.Integration].apiPath;return k.join(t,this.integrationKey,e,this.key)}return k.join(e,this.key)}get path(){return k.join(this.dirPath,"spec.yaml")}get relativePath(){return k.relative(W(process.cwd()),this.path)}get absolutePath(){return k.resolve(k.join(W(process.cwd()),this.path))}isEqual(e){if(this.id!==e.id)return!1;const t=this.clean(),n=e.clean();return Go(t,n)}hasParent(){if(this.data?.parentUuid)return!0;const e=this.getParentKey();return!!e&&!!this.data?.[e]}clean(){const e={...this.data};return Zr.forEach(t=>{delete e[t]}),Object.keys(e).forEach(t=>{t.match(/universal.*Revision/)&&delete e[t]}),e}getParentKey(){let e="parentId";return X?.[this.type]?.parentKey&&(e=X?.[this.type]?.parentKey),e}static new(e,t,n,r){return new _(e,t,n,r)}static fromData(e,t){if(!t?.key)throw new Error(`Element missing key: ${JSON.stringify(t)}`);const n=this.extractIntegrationKey(t);return new _(e,t.key,n,t)}static fromPathAndData(e,t){const n=_.parsePath(e);if(!t)return;const r=t?.key||n?.key;return n?_.new(n.type,r,n.integrationKey,t):void 0}static fromElement(e){return new _(e.type,e.key,e.integrationKey,{...e.data})}static idFromPath(e){const t=_.parsePath(e);if(t)return _.makeId(t.type,t.key,t.integrationKey)}static makeId(e,t,n){return e===x.Integration?`${e}:${t}`:_.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(Q).map(c=>c.apiPath).join("|"),r=new RegExp(`^(?<elementType>${n})/(?<elementKey>[^/]+)/spec\\.ya?ml$`),i=t.match(r);if(i?.groups){const{elementType:c,elementKey:u}=i.groups,h=this.getElementTypeFromPath(c);if(h)return{type:h,key:u}}const s=new RegExp(`^integrations/(?<integrationKey>[^/]+)/(?<elementType>${n})/(?<elementKey>[^/]+)/spec\\.ya?ml$`),a=t.match(s);if(a?.groups){const{integrationKey:c,elementType:u,elementKey:h}=a.groups,m=this.getElementTypeFromPath(u);if(m)return{type:m,key:h,integrationKey:c}}}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(x).find(t=>Q[t].apiPath===e)}static getRelativePath(e){return k.relative(W(process.cwd()),e)}static isIntegrationSpecific(e){return $n.includes(e)}static canBeIntegrationSpecific(e){return $n.includes(e)}}function Et(o,e=!0){if(T.existsSync(o))try{const t=T.readFileSync(o,"utf8");return Y.load(t)||void 0}catch(t){if(!e)return;if(t instanceof Error){const n=k.relative(process.cwd(),o);throw new Error(`Failed to parse YAML file "${n}": ${t.message}`)}throw t}}l(Et,"readYaml$1");function Xr(o,e,t){try{const n=Y.dump(e,t);T.writeFileSync(o,n,"utf8")}catch(n){if(n instanceof Error){const r=k.relative(process.cwd(),o);throw new Error(`Failed to write YAML file "${r}": ${n.message}`)}throw n}}l(Xr,"writeYaml$1");class On{static{l(this,"BaseWorkspaceElementsRepository")}constructor(e){this.cache=e}connectorsMapping;sourceCache;setConnectorsMapping(e){this.connectorsMapping=e}setSourceCache(e){this.sourceCache=e}async getElements(){const e=[];try{const t=await this.getIntegrations();e.push(...t);const n=[x.Integration,x.Connector],r=Object.keys(X),i=await Promise.all(r.filter(s=>!n.includes(s)).map(async s=>this.getElementsByType(s,t)));for(const s of i)e.push(...s)}catch(t){throw g.error(`Failed to get elements: ${t}`),t}return e}async putElement(e){let t=this.cache.get(e.id);return t&&!e.data.id&&t.data.id&&(e.data.id=t.data.id),!t&&e.data.id&&(t=await this.getByInternalId(e.data.id,e.type,!1)),e.data.id&&t?t=await this.updateElement(e,t,{elements:this.cache.getAll(),connectorsMapping:this.connectorsMapping,sourceElements:this.sourceCache?.getAll()}):t=await this.createElement(e,{elements:this.cache.getAll(),connectorsMapping:this.connectorsMapping,sourceElements:this.sourceCache?.getAll()}),t}async getElementsByType(e,t){return[]}async createElement(e,t){return e}async updateElement(e,t,n){return t}async getElement(e){}async getIntegrations(){return[]}async getByInternalId(e,t,n=!0){}async deleteElement(e,t){}}class Qr extends On{static{l(this,"LocalWorkspaceElementsRepository")}basePath;constructor(e){super(e),this.basePath=W(process.cwd())}async getElementsByType(e,t){const n=[],r=k.join(this.basePath,Q[e].apiPath),i=await this.readElementsInDir(r);n.push(...i);for(const s of t){const a=k.join(this.basePath,Q[x.Integration].apiPath,s.key,Q[e].apiPath),c=await this.readElementsInDir(a);n.push(...c)}return n.length>0&&g.debug(`[local] Fetched ${n.length} ${e}${n.length!==1?"s":""}`),n}async getElement(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=k.join(this.basePath,t.dirPath),r=k.join(this.basePath,t.path);return T.existsSync(n)||T.mkdirSync(n,{recursive:!0}),Xr(r,e.data),g.debug(`[local] Written ${t.relativePath}`),t}async deleteElement(e){const t=k.join(this.basePath,e.path),n=k.join(this.basePath,e.dirPath);T.existsSync(t)&&T.rmSync(t,{force:!0}),this.pruneEmptyDir(n),g.debug(`[local] Deleted ${e.relativePath}`)}async getIntegrations(){const e=k.join(this.basePath,Q[x.Integration].apiPath);return this.readElementsInDir(e)}async readElement(e){const t=Et(e);if(t)return _.fromPathAndData(e,t)}async readElementsInDir(e){const t=[];if(!T.existsSync(e))return t;const n=T.readdirSync(e);if(n.length===0)return t;const r=n.map(async s=>{const a=k.join(e,s,"spec.yaml");return this.readElement(a)});return(await Promise.all(r)).filter(s=>s!=null)}pruneEmptyDir(e){try{if(!e.startsWith(this.basePath)||e===this.basePath||!T.existsSync(e)||T.readdirSync(e).length>0)return;T.rmdirSync(e),this.pruneEmptyDir(k.dirname(e))}catch(t){console.warn(`Failed to prune empty directory ${e}:`,t)}}}class ei extends On{static{l(this,"RemoteWorkspaceElementsRepository")}async getElementsByType(e,t){const n=_.canBeIntegrationSpecific(e),r=await this.findAll(e,n?{layer:"universal"}:{});if(!_.canBeIntegrationSpecific(e))return r;for(const i of t){const s=i.key,a=i.data.id,c=await this.findAll(e,a?{integrationId:a}:{integrationKey:s},s);r.push(...c)}return r.length>0&&g.debug(`[remote] Fetched ${r.length} ${e}${r.length!==1?"s":""}`),r}async getElement(e){const t=await O.withClient(n=>n[X[e.type].element](e.data.id).get());return _.fromData(e.type,t)}async createElement(e,t){const n=e.clean();if(this.transformElementForCreate(e,n,t),e.hasParent()&&n.integrationId&&!n.isCustomized){const s=e.getParentKey(),a=new Set(["uuid","integrationId",s,"meta","integrationUuid","parentUuid"]);Object.keys(n).forEach(c=>{a.has(c)||delete n[c]})}const r=await O.withClient(s=>s[X[e.type].elements].create(n)),i=_.fromData(e.type,r);return g.debug(`[remote] Created ${i.id}`),i}async updateElement(e,t,n){if(!e.data.id)throw new Error("Element must have an id to update");t.data.archivedAt&&await O.withClient(a=>a[X[e.type].element](t.data.id).restore());const r=e.clean();if(this.transformElementForUpdate(e,r,n),e.hasParent()&&r.integrationId&&!r.isCustomized)return g.debug(`[remote] Skipped update for ${t.id} (non-customized)`),t;const i=await O.withClient(a=>a[X[e.type].element](t.data.id).put(r)),s=_.fromData(t.type,i);return g.debug(`[remote] Updated ${t.id}`),s}async deleteElement(e){if(!e.data.id)throw new Error("Element must have an id to delete");await O.withClient(t=>t[X[e.type].element](e.data.id).archive()),g.debug(`[remote] Deleted ${e.id}`)}async getIntegrations(){const e=await O.withClient(n=>n.integrations.findAll());if(!e)return[];const t=e.map(n=>_.fromData(x.Integration,n));return t.length>0&&g.debug(`[remote] Fetched ${t.length} integrations`),t}async getByInternalId(e,t){let n;if(n=await O.withClient(r=>r[X[t].element](e).get(),!1),!!n)return _.fromData(t,n)}transformElementForCreate(e,t,n){if(e.integrationKey){const r=n.elements.find(i=>i.type===x.Integration&&i.key===e.integrationKey);if(r)t.integrationId=r.data.id;else throw new Error(`Dependency integration ${e.integrationKey} not found for ${e.id}`)}if(e.type===x.Integration){const r=n.connectorsMapping?.[t.connectorId];r&&(t.connectorId=r)}this.transformPackageDependencies(e,t,n),this.transformParentDependency(e,t,n)}transformElementForUpdate(e,t,n){if(e.type===x.Integration){const r=n.connectorsMapping?.[t.connectorId];r&&(t.connectorId=r)}if(e.integrationKey){t.integrationKey=e.integrationKey;const r=n.elements.find(i=>i.type===x.Integration&&i.key===e.integrationKey);if(r)t.integrationId=r.data.id;else throw new Error(`Dependency integration ${e.integrationKey} not found for ${e.id}`)}this.transformPackageDependencies(e,t,n),this.transformParentDependency(e,t,n)}transformPackageDependencies(e,t,n){if(e.type!==x.Package||!t.elements)return;const r=t.elements.map(i=>{const a=(n.sourceElements||n.elements).find(u=>u.data.id===i.id&&u.type===i.type);if(!a)throw new Error(`Package element ${i.type} with id ${i.id} not found in source workspace for package ${e.id}`);const c=n.elements.find(u=>u.type===i.type&&u.key===a.key&&u.integrationKey===a.integrationKey);if(!c)throw new Error(`Package element ${i.type} with key ${a.key} not found in target workspace for package ${e.id}`);return{id:c.data.id,type:i.type}});t.elements=r}transformParentDependency(e,t,n){if(!e.hasParent())return;const r=e.getParentKey();if(!r)return;const i=n.elements.find(s=>s.type===e.type&&s.key===e.key&&!s.hasParent());if(i)t[r]=i.data.id;else throw new Error(`Parent ${e.getParentKey()} not found for ${e.id}`)}async findAll(e,t={},n){const r=await O.withClient(i=>i[X[e].elements].findAll(t));return r?r.filter(i=>i.key).map(i=>(n&&!i.integrationKey&&(i.integrationKey=n),_.fromData(e,i))):[]}}class kt extends Xo{static{l(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 G={Updated:"updated",Deleted:"deleted",Stopped:"stopped"},ti={ignored:Gr,persistent:!0,ignoreInitial:!0,followSymlinks:!1,depth:20,awaitWriteFinish:{stabilityThreshold:500,pollInterval:100},ignorePermissionErrors:!0,atomic:!0,usePolling:!1,alwaysStat:!1,interval:1e3,binaryInterval:300};class ni extends kt{static{l(this,"LocalElementWatcher")}constructor(e){super(),this.options=e,this.membraneDir=W(this.options.cwd),this.lockTimeoutMs=this.options.lockTimeoutMs??1e3}isWatching=!1;watcher;membraneDir;contentCache={};ignoredPaths=new Set;lockTimeoutMs;async start(){this.isWatching||(T.existsSync(this.membraneDir)||T.mkdirSync(this.membraneDir,{recursive:!0}),this.initializeContentCache(),this.watcher=Ho.watch(this.membraneDir,ti),this.watcher.on("add",e=>this.handleFileSystemEvent(G.Updated,e)).on("change",e=>this.handleFileSystemEvent(G.Updated,e)).on("unlink",e=>this.handleFileSystemEvent(G.Deleted,e)).on("ready",()=>this.isWatching=!0))}async stop(){!this.isWatching||!this.watcher||(await this.watcher.close(),this.isWatching=!1,this.watcher=void 0,this.clearCache(),this.clearAllLocks(),this.emit(G.Stopped))}getCwd(){return this.options.cwd}async executeWithPathLock(e,t){const n=k.resolve(e);this.ignoredPaths.add(n);try{await t()}finally{setTimeout(()=>{this.ignoredPaths.delete(n)},this.lockTimeoutMs)}}isPathLocked(e){const t=k.resolve(e);if(this.ignoredPaths.has(t))return!0;for(const n of this.ignoredPaths)if(t.startsWith(n+k.sep))return!0;return!1}clearAllLocks(){this.ignoredPaths.clear()}handleFileSystemEvent(e,t){const n=k.relative(this.membraneDir,t);if(this.isPathLocked(t))return;if(e===G.Deleted){this.removeFromCache(n);const a={filePath:t,relativePath:n,data:void 0};g.info(`[local] ${e}: ${a.relativePath}`),this.emit(e,a);return}const r=this.readFileContent(t);if(!this.hasContentChanged(n,r))return;const s=this.processFileEvent(t,r);this.updateCache(n,r),s&&(g.info(`[local] ${e}: ${s.relativePath}`),this.emit(e,s))}readFileContent(e){return T.readFileSync(e,"utf8")}processFileEvent(e,t){const n=k.relative(this.membraneDir,e);let r;try{r=t?Zo.parse(t):void 0}catch{r=void 0}return{filePath:e,relativePath:n,data:r}}hasContentChanged(e,t){if(!t)return this.contentCache[e]!==void 0;const n=this.getContentHash(t);return this.contentCache[e]!==n}getContentHash(e){return Vo.createHash("sha256").update(e).digest("hex")}updateCache(e,t){if(!t){delete this.contentCache[e];return}this.contentCache[e]=this.getContentHash(t)}removeFromCache(e){delete this.contentCache[e]}clearCache(){Object.keys(this.contentCache).forEach(e=>{delete this.contentCache[e]})}initializeContentCache(){T.existsSync(this.membraneDir)&&this.scanDirectoryForCache(this.membraneDir)}scanDirectoryForCache(e){const t=T.readdirSync(e,{withFileTypes:!0});for(const n of t){const r=k.join(e,n.name);if(n.isDirectory())this.scanDirectoryForCache(r);else if(n.isFile())try{const i=T.readFileSync(r,"utf8"),s=k.relative(this.membraneDir,r);this.updateCache(s,i)}catch{}}}}var xt=(o=>(o.Updated="updated",o.ConnectorFileUpdated="connector-file-updated",o.Connected="connected",o.Disconnected="disconnected",o.Error="error",o))(xt||{});const oi={debounceMs:2e3,reconnectIntervalMs:5e3,maxReconnectAttempts:1/0,maxBackoffMs:6e4,connectionTimeoutMs:3e5};class ri extends kt{static{l(this,"RemoteElementWatcher")}constructor(e=oi){super(),this.config=e}eventSource;debounceTimeouts=new Map;reconnectAttempts=0;reconnectTimeout;connectionTimeout;isStarted=!1;isConnected=!1;async start(){this.isStarted||(this.isStarted=!0,await this.connect())}async stop(){this.isStarted&&(this.isStarted=!1,this.isConnected=!1,this.clearReconnectTimeout(),this.clearConnectionTimeout(),this.clearAllDebounceTimeouts(),this.eventSource&&(this.eventSource.close(),this.eventSource=void 0))}async connect(){try{g.debug("[remote-events] Connecting to server"),this.eventSource&&(this.eventSource.close(),this.eventSource=void 0);const e=await O.getClient(process.cwd()),t=await e.getToken();if(!t)throw new Error("No auth token available");const n=`${e.apiUri}/sse/workspace?token=${encodeURIComponent(t)}`;g.debug("[remote-events] Subscribing to workspace events"),this.eventSource=new Qo(n),this.setupEventSourceHandlers()}catch(e){g.debug(`[remote-events] Failed to connect: ${e}`),this.emit("error",{error:e}),this.scheduleReconnect()}}setupEventSourceHandlers(){this.eventSource&&(this.eventSource.onopen=()=>{g.debug("[remote-events] Connected to server"),this.reconnectAttempts=0,this.isConnected=!0,this.resetConnectionTimeout(),this.emit("connected",{})},this.eventSource.onmessage=e=>{try{this.resetConnectionTimeout();const t=JSON.parse(e.data);this.handleElementUpdate(t)}catch(t){g.debug(`[remote-events] Failed to parse workspace event: ${t}`)}},this.eventSource.onerror=e=>{g.debug(`[remote-events] Connection error: ${JSON.stringify(e,null,2)}`),this.isConnected=!1,this.clearConnectionTimeout(),this.eventSource&&(this.eventSource.close(),this.eventSource=void 0),this.emit("disconnected",{}),this.isStarted&&this.scheduleReconnect()})}handleElementUpdate(e){if(e.type!==ko.ElementUpdate)return;const{elementId:t,elementType:n,data:r={}}=e;if(!(!t||!n)){if(n===x.Connector){const{filePath:i,eventType:s,newPath:a}=r;return g.debug(`[remote-watcher] Received connector event - elementId: ${t}, filePath: ${i}, eventType: ${s}`),this.scheduleConnectorFileUpdate(t,i,s,a)}return this.scheduleElementUpdate(t,n)}}scheduleElementUpdate(e,t){const n=this.debounceTimeouts.get(e);n&&clearTimeout(n);const r=setTimeout(()=>{this.debounceTimeouts.delete(e),this.emit("updated",{elementId:e,elementType:t})},this.config.debounceMs);this.debounceTimeouts.set(e,r)}scheduleConnectorFileUpdate(e,t,n,r){const i=JSON.stringify({connectorId:e,filePath:t}),s=this.debounceTimeouts.get(i);s&&clearTimeout(s);const a=setTimeout(()=>{this.debounceTimeouts.delete(i),this.emit("connector-file-updated",{connectorId:e,filePath:t,eventType:n,newPath:r})},this.config.debounceMs);this.debounceTimeouts.set(i,a)}scheduleReconnect(){if(!this.isStarted||this.reconnectAttempts>=this.config.maxReconnectAttempts){this.reconnectAttempts>=this.config.maxReconnectAttempts&&(g.error("[remote-events] Max reconnection attempts reached. Connection will not be retried."),this.emit("error",{error:new Error("Max reconnection attempts reached")}));return}this.reconnectTimeout&&clearTimeout(this.reconnectTimeout),this.reconnectAttempts++;const e=this.config.reconnectIntervalMs*Math.pow(2,this.reconnectAttempts-1),t=Math.random()*.3*e,n=Math.min(e+t,this.config.maxBackoffMs);g.debug(`[remote-events] Reconnecting in ${Math.round(n)}ms (attempt ${this.reconnectAttempts})`),this.reconnectTimeout=setTimeout(()=>{this.connect()},n)}clearReconnectTimeout(){this.reconnectTimeout&&(clearTimeout(this.reconnectTimeout),this.reconnectTimeout=void 0)}resetConnectionTimeout(){this.clearConnectionTimeout(),this.connectionTimeout=setTimeout(()=>{this.isConnected&&this.isStarted&&(g.debug("[remote-events] Connection timeout detected, reconnecting..."),this.isConnected=!1,this.eventSource&&(this.eventSource.close(),this.eventSource=void 0),this.scheduleReconnect())},this.config.connectionTimeoutMs)}clearConnectionTimeout(){this.connectionTimeout&&(clearTimeout(this.connectionTimeout),this.connectionTimeout=void 0)}clearAllDebounceTimeouts(){this.debounceTimeouts.forEach(e=>clearTimeout(e)),this.debounceTimeouts.clear()}}class An{static{l(this,"ElementsCache")}elements=new Map;typeIndex=new Map;internalIdIndex=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),e.data?.id&&this.internalIdIndex.set(e.data.id,t)}remove(e){const t=e.id,n=this.elements.delete(t);if(n){const r=this.typeIndex.get(e.type);r&&(r.delete(t),r.size===0&&this.typeIndex.delete(e.type)),e.data?.id&&this.internalIdIndex.delete(e.data.id)}return n}put(e){this.elements.has(e.id)&&this.remove(e),this.add(e)}get(e){return this.elements.get(e)}getByInternalId(e){const t=this.internalIdIndex.get(e);if(t)return this.elements.get(t)}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(),this.internalIdIndex.clear()}getAllIds(){return new Set(this.elements.keys())}}const Te="connectors",ne="development",$t={};async function Pn(o={}){const{onProgress:e}=o,t=new Set,r=(await O.withClient(u=>u.get("org-workspace-id"))).id,i={};g.info("[connectors] Loading custom connectors"),await O.withClient(u=>u.get(`/connectors?workspaceId=${r}`)),g.info("[connectors] Loading public connectors");const s=ie(),c=(P.existsSync(s)?P.readdirSync(s):[]).filter(u=>{if(u.startsWith("."))return!1;const h=$.join(s,u);try{return P.statSync(h).isDirectory()}catch{return!1}});for(const u of c){g.info(`[connectors] Loading connector from: ${u}`);const h=P.readdirSync($.join(s,u)),m=await Ot(u);if(!m)continue;e?.("pushing",m.name),"baseUri"in m&&delete m.baseUri;let f;m.uuid&&(f=await O.withClient(S=>S.get(`/connectors/${m.uuid}`),!1));const y=m.uuid;if(f)i[y]=f.id,g.info(`[connectors] Matched ${m.name} uuid: ${m.uuid}`),f.isPublic||(f.archivedAt&&(g.info(`[connectors] Restoring archived connector ${m.name}`),await O.withClient(S=>S.post(`connectors/${f.id}/restore`))),g.info(`[connectors] Updating connector ${m.name}`),await O.withClient(S=>S.patch(`connectors/${f.id}`,{...m,workspaceId:r})));else if(!i[y]&&!f?.isPublic){let S=!1;try{const R=await At({connectorId:y});R&&R.isPublic&&(S=!0)}catch{}if(!S){g.info(`[connectors] Creating custom connector ${m.name} (${m.key})`);const R=await O.withClient(N=>N.post("connectors",{...m,workspaceId:r}));i[y]=R.id}}const I=h.filter(S=>P.statSync($.join(s,u,S)).isDirectory());for(const S of I)await ai({connector:m,version:S,connectorId:i[y]}),t.add(y);e?.("pushed",m.name)}return{connectorsMapping:i,pushedConnectors:Array.from(t)}}l(Pn,"pushConnectors");async function Nn({connectorId:o,connectorVersion:e,allConnectors:t,pulledConnectors:n,pulledConnectorVersions:r}){if(!o||r[o]?.has(e))return;const i=mn(),s=await At({connectorId:o});if(!s.isPublic||t){if(!s?.key){console.error(`[connectors] Connector ${o} has no key. Skipping..`),g.error(`[connectors] Connector ${o} has no key. Skipping..`);return}n.has(o)||(await ci({basePath:i,connector:s}),n.add(o)),r[o]||(r[o]=new Set),r[o].has(e)||(await li({connector:s,connectorVersion:e,basePath:i}),r[o].add(e))}}l(Nn,"pullRemoteConnector");function ie(){const o=ft();return $.join(o.membraneDirPath,Te)}l(ie,"getConnectorsPath");async function Ot(o){const e=$.join(ie(),o,`${o}.yml`);return Et(e,!1)}l(Ot,"readConnector");async function ii(o,e){return g.info(`[connectors] Zipping ${o} into ${e}`),new Promise((t,n)=>{const r=P.createWriteStream(e),i=ut("zip",{zlib:{level:9}});r.on("close",()=>{g.success(`[connectors] Successfully created ${e}`),t()}),r.on("end",()=>{g.info("[connectors] Data has been drained")}),i.on("warning",a=>{a.code==="ENOENT"?console.warn(a):n(a)}),i.on("error",a=>{n(a)}),i.pipe(r);const s=P.readdirSync(o);for(const a of s){const c=$.join(o,a),u=P.statSync(c);u.isFile()?i.file(c,{name:a}):u.isDirectory()&&i.directory(c,a)}i.finalize()})}l(ii,"createZipArchive");async function si(o,e){return g.info(`[connectors] Unzipping into ${e}`),new Promise((t,n)=>{const r=_e.Parse();r.on("entry",i=>{const s=i.path;if(i.type==="Directory"){const c=$.join(e,s);P.mkdirSync(c,{recursive:!0}),i.autodrain()}else{const c=$.join(e,s),u=$.dirname(c);P.mkdirSync(u,{recursive:!0});const h=P.createWriteStream(c);i.pipe(h),h.on("finish",()=>{})}}),r.on("end",()=>{g.success(`[connectors] Successfully extracted to ${e}`),t()}),r.on("error",i=>{n(i)}),r.write(o),r.end()})}l(si,"extractZipArchive");async function ai({connector:o,version:e,connectorId:t}){const n=$.join(ie(),oe(o),Rn(e)),r=$.join(n,"src"),i=$.join(n,"src.zip"),s=P.existsSync(i);if(P.existsSync(r)&&(g.info(`[connectors] Archiving source code for ${o.name} version ${e}`),await ii(r,i)),!P.existsSync(i)){g.warning(`[connectors] No source code found for ${o.name} version ${e}`);return}try{const a=new dn;if(a.append("file",P.createReadStream(i),"file.zip"),g.info(`[connectors] Pushing connector version ${e} for ${o.name}`),e==ne)g.info(`[connectors] Uploading connector ${t}`),await O.withClient(c=>c.post(`connectors/${t}/upload`,a,{headers:{...a.getHeaders()}}));else{if(a.append("version",e),a.append("changelog","Imported Version"),(await O.withClient(u=>u.get(`/connectors/${t}/versions`))).find(u=>u.version==e)){g.info(`[connectors] Version ${e} already published`);return}g.info(`[connectors] Publishing version ${e} of connector ${t}`),await O.withClient(u=>u.post(`connectors/${t}/publish-version`,a,{headers:{...a.getHeaders()}}))}g.success(`Successfully pushed connector version ${e} for ${o.name}`)}catch(a){g.error(`Error pushing connector version ${e} for ${o.name}: ${a}`),console.error(`[connectors] Error pushing connector version ${e} for ${o.name}: ${a}`)}finally{!s&&P.existsSync(i)&&(g.info(`[connectors] Cleaning up temporary zip file for ${o.name} version ${e}`),P.unlinkSync(i))}}l(ai,"pushConnectorVersion");async function At({connectorId:o}){if(o){if($t[o])return $t[o];try{const e=await O.withClient(t=>t.get(`connectors/${o}`),!1);return $t[o]=e,e}catch(e){return g.error(`[connectors] Failed to get connector ${o}: ${e}`),console.error(`[connectors] Failed to get connector ${o}: ${e}`),null}}}l(At,"getConnector");async function ci({basePath:o,connector:e}){const t=oe(e),n=$.join(o,Te,t);P.mkdirSync(n,{recursive:!0});const r=$.join(n,`${oe(e)}.yml`);P.writeFileSync(r,Y.dump(e)),g.info(`[connectors] Pulled connector ${e.name}`)}l(ci,"pullConnector$1");async function li({connector:o,connectorVersion:e,basePath:t}){const n=oe(o),r=Rn(e),i=$.join(t,"connectors",n,r),s=await O.withClient(c=>c.get(`connectors/${o.id}/download`,{version:e},{responseType:"arraybuffer",headers:{Accept:"application/zip"},timeout:1e6}));P.mkdirSync(i,{recursive:!0});const a=$.join(i,"src.zip");if(P.writeFileSync(a,s),!e){const c=$.join(i,"src");P.mkdirSync(c,{recursive:!0}),await si(s,c)}g.info(`[connectors] Pulled connector version: ${o.name} (${r})`)}l(li,"pullConnectorVersion");function oe(o){return o.key}l(oe,"getConnectorDirName");function Rn(o){return o??ne}l(Rn,"getConnectorVersionDirName");function ui(o){const e=mn(),t=oe(o);return $.join(e,Te,t)}l(ui,"getConnectorDirPath");function di(o){return o.match(`${Te}/[^/]+/${ne}/src/.*`)!==null}l(di,"isConnectorSourceFile");async function hi(o){const e=o.match(`${Te}/([^/]+)/${ne}/src/(.*)`);if(!e)return;const t=e[1],n=e[2],r=await Ot(t);if(!r){g.warning(`[connectors] Connector ${t} not found. Ignoring file change`);return}const i=r.id,s=P.readFileSync(o,"utf-8");await O.withClient(a=>a.put(`connectors/${i}/files/${n}`,s,{headers:{"Content-Type":"text/plain"}})),g.info(`[connectors] Pushed file ${n} for connector ${r.name}`)}l(hi,"putConnectorFile");async function pi(o){const e=o.match(`${Te}/([^/]+)/${ne}/src/(.*)`);if(!e)return;const t=e[1],n=e[2],r=await Ot(t);if(!r){g.warning(`[connectors] Connector ${t} not found. Ignoring file change`);return}const i=r.id;await O.withClient(s=>s.delete(`connectors/${i}/files/${n}`)),g.info(`[connectors] Deleted file ${n} for connector ${r.name}`)}l(pi,"deleteConnectorFile");async function fi(o,e){try{const t=await O.withClient(s=>s.get(`connectors/${o}`));if(!t){g.warning(`[connectors] Connector ${o} not found`);return}const n=await O.withClient(s=>s.get(`connectors/${o}/files/${e}`)),r=oe(t),i=$.join(ie(),r,ne,"src",e);P.mkdirSync($.dirname(i),{recursive:!0}),n!=null?(P.writeFileSync(i,n),g.info(`[connectors] Pulled file ${e} for connector ${t.name}`)):P.existsSync(i)&&(P.unlinkSync(i),g.info(`[connectors] Deleted file ${e} for connector ${t.name}`))}catch(t){g.error(`[connectors] Failed to pull connector file ${e} for connector ${o}: ${t}`),console.error(`[connectors] Failed to pull connector file ${e} for connector ${o}: ${t}`)}}l(fi,"pullConnectorFile");async function mi(o,e){const t=await O.withClient(i=>i.get(`connectors/${o}`),!1);if(!t){g.warning(`[connectors] Connector ${o} not found`);return}const n=oe(t),r=$.join(ie(),n,ne,"src",e);P.existsSync(r)&&(P.unlinkSync(r),g.info(`[connectors] Deleted file ${e} for connector ${n}`))}l(mi,"deleteLocalConnectorFile");async function gi(o,e,t){if(t&&e!==t)try{const n=await O.withClient(c=>c.get(`connectors/${o}`),!1);if(!n){g.warning(`[connectors] Connector ${o} not found`);return}const r=oe(n),i=$.join(ie(),r,ne,"src"),s=$.join(i,e),a=$.join(i,t);P.existsSync(s)&&(P.mkdirSync($.dirname(a),{recursive:!0}),P.renameSync(s,a),g.info(`[connectors] Renamed directory from ${e} to ${t} for connector ${r}`))}catch(n){g.error(`[connectors] Failed to rename directory ${e} to ${t} for connector ${o}: ${n}`)}}l(gi,"renameLocalConnectorDirectory");async function yi(o,e){try{const t=await O.withClient(i=>i.get(`connectors/${o}`),!1);if(!t){g.warning(`[connectors] Connector ${o} not found`);return}const n=oe(t),r=$.join(ie(),n,ne,"src",e);if(P.existsSync(r)){const i=$.resolve(ie());if(!$.resolve(r).startsWith(i))return;P.rmSync(r,{recursive:!0,force:!0}),g.info(`[connectors] Deleted directory ${e} for connector ${n}`)}}catch(t){g.error(`[connectors] Failed to delete directory ${e} for connector ${o}: ${t}`)}}l(yi,"deleteLocalConnectorDirectory");const q={LogAdded:"logAdded",StateChanged:"stateChanged",StatsChanged:"statsChanged",ConflictsChanged:"conflictsChanged",McpStatusChanged:"mcpStatusChanged",McpServersChanged:"mcpServersChanged",ConfigChanged:"configChanged"};class wi extends kt{static{l(this,"WorkspaceNotifications")}constructor(e){super(),this.config=e,g.setNotificationHandler(this)}clientId;heartbeatInterval;isCleaningUp=!1;async connectToRemote(){await this.registerWithRemoteServer(),await this.startHeartbeatLoop()}async setState(e){this.emit(q.StateChanged,{state:e}),await this.emitRemote({status:e})}setConflicts(e){this.emit(q.ConflictsChanged,{conflicts:e})}setConfig(e){this.emit(q.ConfigChanged,{config:e})}setStats(e){this.emit(q.StatsChanged,{stats:e})}addLog(e){this.emit(q.LogAdded,{log:e})}setMcpStatus(e){this.emit(q.McpStatusChanged,{status:e})}async setMcpServers(e){this.emit(q.McpServersChanged,{servers:e}),await this.emitRemote({mcpServers:e.map(t=>({name:t.agentName,totalRequests:t.totalRequests}))})}async cleanup(){!this.clientId||this.isCleaningUp||(this.isCleaningUp=!0,this.heartbeatInterval&&(clearInterval(this.heartbeatInterval),this.heartbeatInterval=void 0),await this.withErrorHandling(async()=>{await O.withClient(e=>e.delete(`/local-clients/${this.clientId}`))}),this.clientId=void 0)}async registerWithRemoteServer(){if(this.clientId)return;const e=await this.withErrorHandling(async()=>await O.withClient(t=>t.post("/local-clients",{hostname:tt.hostname(),workingDirectory:process.cwd()})));e?.id?this.clientId=e.id:this.addLog({timestamp:new Date().toISOString(),message:"Failed to register with remote server",type:"error"})}async startHeartbeatLoop(){this.heartbeatInterval=setInterval(async()=>{this.clientId&&await this.sendHeartbeat()},this.config.heartbeatIntervalMs)}async sendHeartbeat(){this.clientId&&await this.withErrorHandling(async()=>{await O.withClient(e=>e.post(`/local-clients/${this.clientId}/keep-alive`,{}))})}async emitRemote(e){this.clientId&&await this.withErrorHandling(async()=>{await O.withClient(t=>t.patch(`/local-clients/${this.clientId}`,e))})}async withErrorHandling(e){try{return await e()}catch(t){const n=t instanceof Error?t.message:String(t);return this.addLog({timestamp:new Date().toISOString(),message:`Failed to connect to remote: ${n}`,type:"error"}),null}}}const se=new wi({heartbeatIntervalMs:15e3}),re={UPDATE:"update",DELETE:"delete",CREATE:"create"},z={INCOMING:"incoming",OUTGOING:"outgoing"},Dn=[x.AppDataSchema,x.AppEventType,x.DataLinkTable,x.DataSource,x.FieldMapping,x.Action,x.Flow,x.Package];class De{static{l(this,"ElementSyncService")}localWatcher=void 0;remoteWatcher=void 0;notifier;changes=[];localCache;remoteCache;localRepo;remoteRepo;pulledConnectors=new Set;pulledConnectorVersions={};constructor(){this.notifier=se,this.localCache=new An,this.remoteCache=new An,this.localRepo=new Qr(this.localCache),this.remoteRepo=new ei(this.remoteCache)}clear(){this.changes=[]}needsForcedSync(){return this.changes.some(e=>e.isConflict)}needsSync(){return this.changes.length>0}async getStats(){const e=this.localCache.getAll(),t={};return e.forEach(n=>{t[n.type]=(t[n.type]||0)+1}),t}async fetchElements(){const e=await this.localRepo.getElements(),t=await this.remoteRepo.getElements();this.localCache.addAll(e),this.remoteCache.addAll(t)}async updateElement(e,t){const n=this.getHandler(t),r=this.getCache(t);try{const i=await n.putElement(e);r.put(i)}catch(i){throw g.error(`Failed to update element ${e.id}: ${i}`),i}}async deleteElement(e,t){const n=this.getHandler(t),r=this.getCache(t);try{await n.deleteElement(e,{elements:n.cache.getAll(),connectorsMapping:n.connectorsMapping}),r.remove(e)}catch(i){throw g.error(`Failed to delete element ${e.id}: ${i}`),i}}async pullConnectors(e=!1){const t=this.remoteCache.getElementsByType(x.Integration).map(n=>n.data);for(const n of t){const r=n.connectorId,i=n.connectorVersion;r&&await Nn({connectorId:r,connectorVersion:i,allConnectors:e,pulledConnectors:this.pulledConnectors,pulledConnectorVersions:this.pulledConnectorVersions})}}async pushConnectors(){const{connectorsMapping:e}=await Pn();this.remoteRepo.setConnectorsMapping(e)}getHandler(e){return e===z.INCOMING?this.localRepo:(this.remoteRepo.setSourceCache(this.localCache),this.remoteRepo)}getCache(e){return e===z.INCOMING?this.localCache:this.remoteCache}async startWatching(){this.localWatcher=new ni({cwd:process.cwd(),lockTimeoutMs:1e3}),this.localWatcher.on(G.Updated,e=>this.handleLocalEvent(e,G.Updated)),this.localWatcher.on(G.Deleted,e=>this.handleLocalEvent(e,G.Deleted)),await this.localWatcher.start(),g.success("[local] Tracking changes.."),this.remoteWatcher=new ri,this.remoteWatcher.on(xt.Updated,({elementId:e,elementType:t})=>this.handleRemoteElementEvent(e,t)),this.remoteWatcher.on(xt.ConnectorFileUpdated,({connectorId:e,filePath:t,eventType:n,newPath:r})=>this.handleRemoteConnectorFileEvent(e,t,n,r)),await this.remoteWatcher.start(),g.success("[remote] Tracking changes..")}async stopWatching(){this.localWatcher&&(await this.localWatcher.stop(),this.localWatcher=void 0),this.remoteWatcher&&(await this.remoteWatcher.stop(),this.remoteWatcher=void 0)}async handleRemoteElementEvent(e,t){try{const n=await this.remoteRepo.getByInternalId(e,t),r=!!n?.data.archivedAt||!!n?.data.isDeactivated;if(!n||r){const s=n||this.remoteCache.getByInternalId(e);return s?(g.info(`[${this.getDirectionLabel(z.INCOMING)}] Deleted: ${s.id}`),this.localWatcher?.executeWithPathLock(s.absolutePath,()=>this.deleteElement(s,z.INCOMING))):void 0}if(g.info(`[${this.getDirectionLabel(z.INCOMING)}] Updated: ${n.id}`),await this.localWatcher?.executeWithPathLock(n.absolutePath,async()=>this.updateElement(n,z.INCOMING)),t===x.Integration){const s=n.data.connectorId,a=n.data.connectorVersion,c=await At({connectorId:s});if(!c?.key)return;const u=ui(c);await this.localWatcher?.executeWithPathLock(u,async()=>Nn({connectorId:s,connectorVersion:a,allConnectors:!1,pulledConnectors:this.pulledConnectors,pulledConnectorVersions:this.pulledConnectorVersions}))}}catch(n){g.error(`[sync] Error handling remote event: ${n}`)}}async handleRemoteConnectorFileEvent(e,t,n,r){try{switch(n){case Ye.ConnectorFileDeleted:await mi(e,t);break;case Ye.ConnectorDirectoryRenamed:await gi(e,t,r);break;case Ye.ConnectorDirectoryDeleted:await yi(e,t);break;default:await fi(e,t);break}}catch(i){g.error(`[sync] Error handling remote connector file event: ${i}`)}}async handleLocalEvent(e,t){try{if(di(e.filePath))switch(t){case G.Updated:await hi(e.filePath);break;case G.Deleted:await pi(e.filePath);break}else{let n=_.fromPathAndData(e.filePath,e.data);if(!n){const r=_.idFromPath(e.filePath);if(!r||(n=this.remoteCache.get(r),!n))return}switch(g.info(`[${this.getDirectionLabel(z.OUTGOING)}] ${zo(t)}: ${n.id}`),t){case G.Updated:await this.updateElement(n,z.OUTGOING);break;case G.Deleted:await this.deleteElement(n,z.OUTGOING);break}}}catch(n){g.error(`[sync] Error handling local event: ${n}`)}}detectIncomingChanges(){this.clearChanges();const e=De.getChanges(z.INCOMING,this.remoteCache,this.localCache);return this.updateChanges(e),e}detectOutgoingChanges(){this.clearChanges();const e=De.getChanges(z.OUTGOING,this.localCache,this.remoteCache);return this.updateChanges(e),e}async resolveChanges(){if(!this.needsSync())return;g.info("[resolver] Resolving changes.."),g.info("[resolver] Resolving integration elements");const e=this.changes.filter(r=>r.element.type===x.Integration);await Promise.all(e.map(async r=>this.resolveChange(r))),e.length>0&&(await this.fetchElements(),this.changes=this.changes.length>0&&this.changes[0]?.direction===z.INCOMING?this.detectIncomingChanges():this.detectOutgoingChanges(),this.changes=this.changes.filter(r=>r.element.type!==x.Integration)),g.info("[resolver] Resolving universal elements");const t=this.changes.filter(r=>!r.element.hasParent());for(const r of Dn){const i=t.filter(s=>s.element.type===r);g.info(`[resolver] Resolving ${r} elements`),await Promise.all(i.map(async s=>this.resolveChange(s)))}g.info("[resolver] Resolving integration level elements");const n=this.changes.filter(r=>r.element.hasParent());for(const r of Dn){const i=n.filter(s=>s.element.type===r);g.info(`[resolver] Resolving ${r} elements`),await Promise.all(i.map(async s=>this.resolveChange(s)))}g.success("[resolver] Resolved changes")}async resolveChange(e){switch(e.type){case re.DELETE:return this.deleteElement(e.element,e.direction);case re.CREATE:return this.updateElement(e.element,e.direction);case re.UPDATE:return this.updateElement(e.element,e.direction)}}static getChanges(e,t,n){const r=t.getAllIds(),i=n.getAllIds(),s=new Set([...r,...i]),a=[];for(const c of s){const u=t.get(c),h=n.get(c),m=De.detectChangeForElement(u,h,e);m&&a.push(m)}return a}updateChanges(e){if(this.changes=e,this.needsForcedSync()){const t=e.filter(n=>n.isConflict);g.warning("[resolver] Conflicts detected"),this.notifier.setConflicts(t)}}clearChanges(){this.changes=[]}getDirectionLabel(e){switch(e){case z.INCOMING:return"local\u2190remote";case z.OUTGOING:return"local\u2192remote"}}static detectChangeForElement(e,t,n){return e&&!t?{type:re.CREATE,element:e,direction:n,isConflict:!1}:!e&&t?{type:re.DELETE,element:t,direction:n,isConflict:!0}:e&&t&&!e.isEqual(t)?{type:re.UPDATE,element:e,direction:n,isConflict:!1}:null}}const ae=k.join(er.tmpdir(),"membrane-mcp-status"),Ln=3e4;class Ci{static{l(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=We(void 0,e),n=Mn(e);t&&se.setMcpStatus(t),await se.setMcpServers(n)}catch{g.error("Failed to check MCP status")}}}function We(o,e){try{const t=e||process.cwd();if(!o){const r=Mn(t);return r.length===0?null:r[0]}const n=Rt(o,t);if(T.existsSync(n)){const r=T.statSync(n),i=new Date;if(i.getTime()-r.mtime.getTime()>Ln)return Ae(o,t),null;const a=T.readFileSync(n,"utf8"),c=JSON.parse(a);if(c.isRunning){const u=new Date(c.lastActivity).getTime();if(i.getTime()-u>Ln)return Ae(o,t),null}return c}}catch{o&&e&&Ae(o,e)}return null}l(We,"getMcpStatus");function Mn(o){try{const e=o||process.cwd(),t=Nt(e);if(!T.existsSync(ae))return[];const n=T.readdirSync(ae),r=[];for(const i of n){const s=i.match(new RegExp(`^mcp-${t}-(\\d+)\\.json$`));if(s){const a=parseInt(s[1],10),c=We(a,e);c&&r.push(c)}}return r.sort((i,s)=>new Date(s.startTime).getTime()-new Date(i.startTime).getTime())}catch{return[]}}l(Mn,"getAllMcpStatusFiles");function Pt(o){try{const t={...We(o.processId,o.cwd)||{isRunning:!1,startTime:new Date().toISOString(),lastActivity:new Date().toISOString(),toolsCount:0,totalRequests:0,processId:o.processId,cwd:o.cwd,agentName:process.env.AGENT_NAME||"Unnamed Agent"},...o};T.existsSync(ae)||T.mkdirSync(ae,{recursive:!0});const n=Rt(o.processId,o.cwd);T.writeFileSync(n,JSON.stringify(t,null,2))}catch{}}l(Pt,"updateMcpStatus");function Ae(o,e){try{const t=e||process.cwd();if(o){const n=Rt(o,t);T.existsSync(n)&&T.unlinkSync(n)}else{const n=Nt(t);if(T.existsSync(ae)){const r=T.readdirSync(ae);for(const i of r)i.match(new RegExp(`^mcp-${n}-\\d+\\.json$`))&&T.unlinkSync(k.join(ae,i))}}}catch{}}l(Ae,"clearMcpStatus");function Si(o,e){const t=We(o,e);t&&Pt({processId:o,cwd:e,totalRequests:t.totalRequests+1,lastRequestTime:new Date().toISOString(),lastActivity:new Date().toISOString()})}l(Si,"trackToolExecution");function Nt(o){return Yo("md5").update(o).digest("hex").slice(0,8)}l(Nt,"getCwdHash");function Rt(o,e){const t=Nt(e);return k.join(ae,`mcp-${t}-${o}.json`)}l(Rt,"getStatusFilePath");const ze={Agent:"agent",Cli:"cli"},A={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"};class bi{static{l(this,"MembraneCLIService")}constructor(e,t,n=()=>process.exit(0)){this.mode=e,this.cwd=t,this.onShutdown=n,this.notifier=se,this.mcpStatusService=new Ci,this.syncService=new De,this.setupProcessCleanup()}initialized=!1;notifier;mcpStatusService;syncService;isShuttingDown=!1;currentConfig=null;get config(){return this.currentConfig}getSyncedElements(){return this.syncService.localCache.getAll()}getSyncedElementsByType(e){return this.syncService.localCache.getElementsByType(e)}async fetchElements(){await this.syncService.fetchElements()}async pullWorkspace(e={}){let t=!1;try{g.setVerboseMode(!!e.verbose),e.rps!==void 0&&O.init({maxRequestsPerSecond:e.rps}),await this.notifier.setState(A.PULLING),await this.syncService.fetchElements(),this.syncService.detectIncomingChanges(),this.syncService.needsForcedSync()&&!e.force?(await this.notifier.setState(A.CONFLICTS),e.watch||(t=!0)):(await this.syncService.pullConnectors(e.allConnectors),await this.syncWorkspaces(e))}catch(n){t=!0,g.error(`Failed to pull workspace: ${n}`),await this.notifier.setState(A.ERROR),g.saveLogsToFile("error")}finally{e.saveLogs&&g.saveLogsToFile()}t?process.exit(1):e?.onComplete?.()}async pushWorkspace(e={}){let t=!1;try{g.setVerboseMode(!!e.verbose),e.rps!==void 0&&O.init({maxRequestsPerSecond:e.rps}),await this.notifier.setState(A.PUSHING),await this.syncService.fetchElements(),this.syncService.detectOutgoingChanges(),this.syncService.needsForcedSync()&&!e.force?(await this.notifier.setState(A.CONFLICTS),e.watch||(t=!0)):(await this.syncService.pushConnectors(),await this.syncWorkspaces(e))}catch(n){t=!0,g.error(`Failed to push workspace: ${n}`),await this.notifier.setState(A.ERROR),g.saveLogsToFile("error")}finally{e.saveLogs&&g.saveLogsToFile()}t?process.exit(1):e?.onComplete?.()}async syncWorkspaces(e={}){try{e.verbose!==void 0&&g.setVerboseMode(!!e.verbose),await this.notifier.setState(A.RESOLVING),this.syncService.needsSync()&&await this.syncService.resolveChanges();const t=await this.syncService.getStats();this.notifier.setStats(t),await this.notifier.setState(A.SYNCED),e.watch&&(await this.notifier.setState(A.WATCHING),await this.syncService.startWatching())}catch(t){g.error(`Failed to sync local and remote workspaces: ${t}`),await this.notifier.setState(A.ERROR),g.saveLogsToFile("error")}}async init({force:e=!1}={}){if(!(this.initialized&&!e)){await this.notifier.setState(A.NOT_INITIALIZED);try{await this.loadConfig(),fe.isCacheDefined()?(await this.initServices(),this.initialized=!0,await this.notifier.setState(A.INITIALIZED)):(this.initialized=!1,await this.notifier.setState(A.SETTING_UP))}catch(t){g.error(`Failed to initialize services: ${t}`),await this.notifier.setState(A.ERROR),g.saveLogsToFile("error"),this.onShutdown()}}}async loadConfig(){this.currentConfig=fe.loadConfig(this.cwd),this.notifier.setConfig(this.currentConfig)}async updateConfig(e){const t={...this.currentConfig,...e};if(!(JSON.stringify(t)!==JSON.stringify(this.currentConfig)))return;await this.stopServices();const r=fe.updateConfig(t);this.currentConfig=r,await this.init({force:!0})}async shutdown(){!this.initialized||this.isShuttingDown||(this.isShuttingDown=!0,this.mode===ze.Agent&&(await this.notifier.cleanup(),await this.mcpStatusService.stop()),this.initialized=!1,this.onShutdown())}async initServices(){this.mode===ze.Agent&&(await this.notifier.connectToRemote(),await this.mcpStatusService.start()),this.syncService.clear()}async stopServices(){this.mode===ze.Agent&&(await this.notifier.cleanup(),await this.mcpStatusService.stop())}setupProcessCleanup(){["SIGINT","SIGTERM","uncaughtException","unhandledRejection"].forEach(t=>process.on(t,()=>this.shutdown())),process.on("beforeExit",t=>{t===0&&this.shutdown()})}}function vi({children:o,membraneCLIService:e}){const{data:t}=un("/account"),[n,r]=L(A.NOT_INITIALIZED),[i,s]=L([]),[a,c]=L({}),[u,h]=L([]),[m,f]=L(null),I=t?.workspaces?.find(S=>S.workspaceKey===m?.workspaceKey)||null;return Ce(()=>{const S=l(({state:F})=>r(F),"handleStateChanged"),R=l(({stats:F})=>c(F),"handleStatsChanged"),N=l(({log:F})=>h(Le=>[...Le,F]),"handleLogAdded"),j=l(({conflicts:F})=>s(F),"handleConflictsUpdated"),K=l(({config:F})=>f(F),"handleConfigChanged");return e.notifier.on(q.StateChanged,S),e.notifier.on(q.StatsChanged,R),e.notifier.on(q.LogAdded,N),e.notifier.on(q.ConflictsChanged,j),e.notifier.on(q.ConfigChanged,K),e.init(),()=>{e.notifier.off(q.StateChanged,S),e.notifier.off(q.StatsChanged,R),e.notifier.off(q.LogAdded,N),e.notifier.off(q.ConflictsChanged,j),e.notifier.off(q.ConfigChanged,K)}},[]),d(vn.Provider,{value:{state:n,stats:a,logs:u,currentWorkspace:I,conflicts:i,config:m,updateConfig:l(S=>e.updateConfig(S),"updateConfig"),resolveConflicts:l(S=>e.syncWorkspaces(S),"resolveConflicts"),pull:l(S=>e.pullWorkspace(S),"pull"),push:l(S=>e.pushWorkspace(S),"push"),exit:l(()=>e.shutdown(),"exit"),fetchElements:l(()=>e.fetchElements(),"fetchElements"),getSyncedElementsByType:l(S=>e.getSyncedElementsByType(S),"getSyncedElementsByType")},children:o})}l(vi,"MembraneCLIServiceProvider");const jn=it(process.cwd());function Ti(){return st(jn)}l(Ti,"useCwd");function Ii({cwd:o,children:e}){return d(jn.Provider,{value:o,children:e})}l(Ii,"CwdProvider");function Dt({cwd:o,children:e,membraneCLIService:t}){const n=o||process.cwd();return d(Ii,{cwd:n,children:d(Bo,{value:{fetcher:kr()},children:d(vi,{membraneCLIService:t,children:e})})})}l(Dt,"Layout");function Ei(o,e){o.command("config").alias("install").description("\u26A0\uFE0F EXPERIMENTAL: Manage local membrane configuration with interactive UI").addHelpText("after",["","Examples:"," membrane config # Open interactive config manager",""].join(`
|
|
25
|
-
`)).action(()=>{rt(
|
|
24
|
+
Unexpected Error:`),a&&console.error(a),console.error(s)),s}return}},"executeRequest");return t?i():xn.withSkipErrorLog(i)}async generateAccessToken(e,t){return ct.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=xe(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 en({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,r=!this.isTokenValid()||this.tokenExpiry-Date.now()<3e5;return(!this.client||n||r)&&(this.client=await this.createClient(t)),this.client}clearClient(){this.client=null,this.currentConfig=null,this.tokenExpiry=0,this.requestTimes=[],this.semaphore=0,this.semaphoreQueue=[],this.rateLimitMutex=Promise.resolve()}getCurrentConfigInfo(){return this.currentConfig}async waitIfNeeded(){this.rateLimitMutex=this.rateLimitMutex.then(async()=>{for(this.cleanOldRequests();this.requestTimes.length>=this.maxRequestsPerSecond;){const t=this.requestTimes[0]+this.windowSizeMs-Date.now()+10;if(t>0)await new Promise(n=>setTimeout(n,t)),this.cleanOldRequests();else break}}),await this.rateLimitMutex}recordRequest(){this.requestTimes.push(Date.now())}cleanOldRequests(){const e=Date.now()-this.windowSizeMs;this.requestTimes=this.requestTimes.filter(t=>t>e)}getRequestCount(){return this.cleanOldRequests(),this.requestTimes.length}async acquireSemaphore(){if(this.semaphore<this.maxConcurrentRequests){this.semaphore++;return}return new Promise(e=>{this.semaphoreQueue.push(e)})}releaseSemaphore(){if(this.semaphore--,this.semaphoreQueue.length>0){const e=this.semaphoreQueue.shift();this.semaphore++,e()}}async withRetry(e,t="operation"){let n;for(let r=0;r<=this.maxRetries;r++)try{return await e()}catch(i){if(n=i,!this.isRetryableError(i)||r===this.maxRetries)throw i;const s=new Date().toISOString(),a=r+2;g.debug(`[${s}] Retrying ${t} (attempt ${a}/${this.maxRetries+1})`);let c=this.retryDelay*Math.pow(2,r);if(this.enableJitter){const u=c*.25*(Math.random()*2-1);c=Math.max(0,c+u)}await new Promise(u=>setTimeout(u,c))}throw n||new Error("Unknown error occurred during retry attempts")}isRetryableError(e){if(!e)return!1;const t=(e.message||e.toString()||"").toLowerCase(),n=e.code;return n&&["econnrefused","enotfound","econnreset","etimedout","ehostunreach","enetunreach"].includes(n.toLowerCase())?!0:["econnrefused","connection refused","network error","timeout","socket hang up","request timeout","dns lookup failed"].some(s=>t.includes(s))}async withTimeout(e,t){let n;const r=new Promise((i,s)=>{n=setTimeout(()=>s(new Error(`Request timeout after ${t}ms`)),t)});try{const i=await Promise.race([e,r]);return n&&clearTimeout(n),i}catch(i){throw n&&clearTimeout(n),i}}async getVersion(){try{return(await this.withClient(t=>t.get("version"),!1))?.version??null}catch{return null}}async isVersionAtLeast(e){const t=await this.getVersion(),n=t?lt.coerce(t):null,r=lt.coerce(e);return!!(n&&r&<.gte(n,r))}}const O=new Yr,X={[x.Integration]:{element:"integration",elements:"integrations",exportable:!1,exportCleanup:l(o=>({id:o.id,key:o.key,name:o.name,connectorId:o.connectorId,baseUri:o.baseUri,connectorVersion:o.connectorVersion}),"exportCleanup")},[x.Connector]:{element:"connector",elements:"connectors",exportable:!1},[x.Action]:{element:"action",elements:"actions",integrationSpecific:!0,exportCleanup:l(o=>(delete o.integration,o),"exportCleanup")},[x.AppDataSchema]:{element:"appDataSchema",elements:"appDataSchemas"},[x.AppEventType]:{element:"appEventType",elements:"appEventTypes"},[x.DataLinkTable]:{element:"dataLinkTable",elements:"dataLinkTables"},[x.DataSource]:{element:"dataSource",elements:"dataSources",parentKey:"universalDataSourceId",integrationSpecific:!0},[x.FieldMapping]:{element:"fieldMapping",elements:"fieldMappings",integrationSpecific:!0,parentKey:"universalFieldMappingId",exportCleanup:l(o=>(delete o.dataSourceId,o),"exportCleanup")},[x.Flow]:{element:"flow",elements:"flows",integrationSpecific:!0,parentKey:"universalFlowId"},[x.Package]:{element:"package",elements:"packages",integrationSpecific:!0}},Zr=["id","workspaceId","integrationId","createdAt","updatedAt","revision","archivedAt","baseUri","state","appliedToIntegrations","dependencies"],$n=[x.Action,x.FieldMapping,x.Flow,x.DataSource,x.Package];class _{static{l(this,"Element")}type;key;integrationKey;data;constructor(e,t,n,r){if(!r)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=r,this.integrationKey=n||_.extractIntegrationKey(r)}get id(){return _.makeId(this.type,this.key,this.integrationKey)}get dirPath(){const e=Q[this.type].apiPath;if(this.integrationKey){const t=Q[x.Integration].apiPath;return k.join(t,this.integrationKey,e,this.key)}return k.join(e,this.key)}get path(){return k.join(this.dirPath,"spec.yaml")}get relativePath(){return k.relative(W(process.cwd()),this.path)}get absolutePath(){return k.resolve(k.join(W(process.cwd()),this.path))}isEqual(e){if(this.id!==e.id)return!1;const t=this.clean(),n=e.clean();return Go(t,n)}hasParent(){if(this.data?.parentUuid)return!0;const e=this.getParentKey();return!!e&&!!this.data?.[e]}clean(){const e={...this.data};return Zr.forEach(t=>{delete e[t]}),Object.keys(e).forEach(t=>{t.match(/universal.*Revision/)&&delete e[t]}),e}getParentKey(){let e="parentId";return X?.[this.type]?.parentKey&&(e=X?.[this.type]?.parentKey),e}static new(e,t,n,r){return new _(e,t,n,r)}static fromData(e,t){if(!t?.key)throw new Error(`Element missing key: ${JSON.stringify(t)}`);const n=this.extractIntegrationKey(t);return new _(e,t.key,n,t)}static fromPathAndData(e,t){const n=_.parsePath(e);if(!t)return;const r=t?.key||n?.key;return n?_.new(n.type,r,n.integrationKey,t):void 0}static fromElement(e){return new _(e.type,e.key,e.integrationKey,{...e.data})}static idFromPath(e){const t=_.parsePath(e);if(t)return _.makeId(t.type,t.key,t.integrationKey)}static makeId(e,t,n){return e===x.Integration?`${e}:${t}`:_.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(Q).map(c=>c.apiPath).join("|"),r=new RegExp(`^(?<elementType>${n})/(?<elementKey>[^/]+)/spec\\.ya?ml$`),i=t.match(r);if(i?.groups){const{elementType:c,elementKey:u}=i.groups,p=this.getElementTypeFromPath(c);if(p)return{type:p,key:u}}const s=new RegExp(`^integrations/(?<integrationKey>[^/]+)/(?<elementType>${n})/(?<elementKey>[^/]+)/spec\\.ya?ml$`),a=t.match(s);if(a?.groups){const{integrationKey:c,elementType:u,elementKey:p}=a.groups,m=this.getElementTypeFromPath(u);if(m)return{type:m,key:p,integrationKey:c}}}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(x).find(t=>Q[t].apiPath===e)}static getRelativePath(e){return k.relative(W(process.cwd()),e)}static isIntegrationSpecific(e){return $n.includes(e)}static canBeIntegrationSpecific(e){return $n.includes(e)}}function Et(o,e=!0){if(T.existsSync(o))try{const t=T.readFileSync(o,"utf8");return Y.load(t)||void 0}catch(t){if(!e)return;if(t instanceof Error){const n=k.relative(process.cwd(),o);throw new Error(`Failed to parse YAML file "${n}": ${t.message}`)}throw t}}l(Et,"readYaml$1");function Xr(o,e,t){try{const n=Y.dump(e,t);T.writeFileSync(o,n,"utf8")}catch(n){if(n instanceof Error){const r=k.relative(process.cwd(),o);throw new Error(`Failed to write YAML file "${r}": ${n.message}`)}throw n}}l(Xr,"writeYaml$1");class On{static{l(this,"BaseWorkspaceElementsRepository")}constructor(e){this.cache=e}connectorsMapping;sourceCache;setConnectorsMapping(e){this.connectorsMapping=e}setSourceCache(e){this.sourceCache=e}async getElements(){const e=[];try{const t=await this.getIntegrations();e.push(...t);const n=[x.Integration,x.Connector],r=Object.keys(X),i=await Promise.all(r.filter(s=>!n.includes(s)).map(async s=>this.getElementsByType(s,t)));for(const s of i)e.push(...s)}catch(t){throw g.error(`Failed to get elements: ${t}`),t}return e}async putElement(e){let t=this.cache.get(e.id);return t&&!e.data.id&&t.data.id&&(e.data.id=t.data.id),!t&&e.data.id&&(t=await this.getByInternalId(e.data.id,e.type,!1)),e.data.id&&t?t=await this.updateElement(e,t,{elements:this.cache.getAll(),connectorsMapping:this.connectorsMapping,sourceElements:this.sourceCache?.getAll()}):t=await this.createElement(e,{elements:this.cache.getAll(),connectorsMapping:this.connectorsMapping,sourceElements:this.sourceCache?.getAll()}),t}async getElementsByType(e,t){return[]}async createElement(e,t){return e}async updateElement(e,t,n){return t}async getElement(e){}async getIntegrations(){return[]}async getByInternalId(e,t,n=!0){}async deleteElement(e,t){}}class Qr extends On{static{l(this,"LocalWorkspaceElementsRepository")}basePath;constructor(e){super(e),this.basePath=W(process.cwd())}async getElementsByType(e,t){const n=[],r=k.join(this.basePath,Q[e].apiPath),i=await this.readElementsInDir(r);n.push(...i);for(const s of t){const a=k.join(this.basePath,Q[x.Integration].apiPath,s.key,Q[e].apiPath),c=await this.readElementsInDir(a);n.push(...c)}return n.length>0&&g.debug(`[local] Fetched ${n.length} ${e}${n.length!==1?"s":""}`),n}async getElement(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=k.join(this.basePath,t.dirPath),r=k.join(this.basePath,t.path);return T.existsSync(n)||T.mkdirSync(n,{recursive:!0}),Xr(r,e.data),g.debug(`[local] Written ${t.relativePath}`),t}async deleteElement(e){const t=k.join(this.basePath,e.path),n=k.join(this.basePath,e.dirPath);T.existsSync(t)&&T.rmSync(t,{force:!0}),this.pruneEmptyDir(n),g.debug(`[local] Deleted ${e.relativePath}`)}async getIntegrations(){const e=k.join(this.basePath,Q[x.Integration].apiPath);return this.readElementsInDir(e)}async readElement(e){const t=Et(e);if(t)return _.fromPathAndData(e,t)}async readElementsInDir(e){const t=[];if(!T.existsSync(e))return t;const n=T.readdirSync(e);if(n.length===0)return t;const r=n.map(async s=>{const a=k.join(e,s,"spec.yaml");return this.readElement(a)});return(await Promise.all(r)).filter(s=>s!=null)}pruneEmptyDir(e){try{if(!e.startsWith(this.basePath)||e===this.basePath||!T.existsSync(e)||T.readdirSync(e).length>0)return;T.rmdirSync(e),this.pruneEmptyDir(k.dirname(e))}catch(t){console.warn(`Failed to prune empty directory ${e}:`,t)}}}class ei extends On{static{l(this,"RemoteWorkspaceElementsRepository")}async getElementsByType(e,t){const n=_.canBeIntegrationSpecific(e),r=await this.findAll(e,n?{layer:"universal"}:{});if(!_.canBeIntegrationSpecific(e))return r;for(const i of t){const s=i.key,a=i.data.id,c=await this.findAll(e,a?{integrationId:a}:{integrationKey:s},s);r.push(...c)}return r.length>0&&g.debug(`[remote] Fetched ${r.length} ${e}${r.length!==1?"s":""}`),r}async getElement(e){const t=await O.withClient(n=>n[X[e.type].element](e.data.id).get());return _.fromData(e.type,t)}async createElement(e,t){const n=e.clean();if(this.transformElementForCreate(e,n,t),e.hasParent()&&n.integrationId&&!n.isCustomized){const s=e.getParentKey(),a=new Set(["uuid","integrationId",s,"meta","integrationUuid","parentUuid"]);Object.keys(n).forEach(c=>{a.has(c)||delete n[c]})}const r=await O.withClient(s=>s[X[e.type].elements].create(n)),i=_.fromData(e.type,r);return g.debug(`[remote] Created ${i.id}`),i}async updateElement(e,t,n){if(!e.data.id)throw new Error("Element must have an id to update");t.data.archivedAt&&await O.withClient(a=>a[X[e.type].element](t.data.id).restore());const r=e.clean();if(this.transformElementForUpdate(e,r,n),e.hasParent()&&r.integrationId&&!r.isCustomized)return g.debug(`[remote] Skipped update for ${t.id} (non-customized)`),t;const i=await O.withClient(a=>a[X[e.type].element](t.data.id).put(r)),s=_.fromData(t.type,i);return g.debug(`[remote] Updated ${t.id}`),s}async deleteElement(e){if(!e.data.id)throw new Error("Element must have an id to delete");await O.withClient(t=>t[X[e.type].element](e.data.id).archive()),g.debug(`[remote] Deleted ${e.id}`)}async getIntegrations(){const e=await O.withClient(n=>n.integrations.findAll());if(!e)return[];const t=e.map(n=>_.fromData(x.Integration,n));return t.length>0&&g.debug(`[remote] Fetched ${t.length} integrations`),t}async getByInternalId(e,t){let n;if(n=await O.withClient(r=>r[X[t].element](e).get(),!1),!!n)return _.fromData(t,n)}transformElementForCreate(e,t,n){if(e.integrationKey){const r=n.elements.find(i=>i.type===x.Integration&&i.key===e.integrationKey);if(r)t.integrationId=r.data.id;else throw new Error(`Dependency integration ${e.integrationKey} not found for ${e.id}`)}if(e.type===x.Integration){const r=n.connectorsMapping?.[t.connectorId];r&&(t.connectorId=r)}this.transformPackageDependencies(e,t,n),this.transformParentDependency(e,t,n)}transformElementForUpdate(e,t,n){if(e.type===x.Integration){const r=n.connectorsMapping?.[t.connectorId];r&&(t.connectorId=r)}if(e.integrationKey){t.integrationKey=e.integrationKey;const r=n.elements.find(i=>i.type===x.Integration&&i.key===e.integrationKey);if(r)t.integrationId=r.data.id;else throw new Error(`Dependency integration ${e.integrationKey} not found for ${e.id}`)}this.transformPackageDependencies(e,t,n),this.transformParentDependency(e,t,n)}transformPackageDependencies(e,t,n){if(e.type!==x.Package||!t.elements)return;const r=t.elements.map(i=>{const a=(n.sourceElements||n.elements).find(u=>u.data.id===i.id&&u.type===i.type);if(!a)throw new Error(`Package element ${i.type} with id ${i.id} not found in source workspace for package ${e.id}`);const c=n.elements.find(u=>u.type===i.type&&u.key===a.key&&u.integrationKey===a.integrationKey);if(!c)throw new Error(`Package element ${i.type} with key ${a.key} not found in target workspace for package ${e.id}`);return{id:c.data.id,type:i.type}});t.elements=r}transformParentDependency(e,t,n){if(!e.hasParent())return;const r=e.getParentKey();if(!r)return;const i=n.elements.find(s=>s.type===e.type&&s.key===e.key&&!s.hasParent());if(i)t[r]=i.data.id;else throw new Error(`Parent ${e.getParentKey()} not found for ${e.id}`)}async findAll(e,t={},n){const r=await O.withClient(i=>i[X[e].elements].findAll(t));return r?r.filter(i=>i.key).map(i=>(n&&!i.integrationKey&&(i.integrationKey=n),_.fromData(e,i))):[]}}class kt extends Xo{static{l(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 G={Updated:"updated",Deleted:"deleted",Stopped:"stopped"},ti={ignored:Gr,persistent:!0,ignoreInitial:!0,followSymlinks:!1,depth:20,awaitWriteFinish:{stabilityThreshold:500,pollInterval:100},ignorePermissionErrors:!0,atomic:!0,usePolling:!1,alwaysStat:!1,interval:1e3,binaryInterval:300};class ni extends kt{static{l(this,"LocalElementWatcher")}constructor(e){super(),this.options=e,this.membraneDir=W(this.options.cwd),this.lockTimeoutMs=this.options.lockTimeoutMs??1e3}isWatching=!1;watcher;membraneDir;contentCache={};ignoredPaths=new Set;lockTimeoutMs;async start(){this.isWatching||(T.existsSync(this.membraneDir)||T.mkdirSync(this.membraneDir,{recursive:!0}),this.initializeContentCache(),this.watcher=Ho.watch(this.membraneDir,ti),this.watcher.on("add",e=>this.handleFileSystemEvent(G.Updated,e)).on("change",e=>this.handleFileSystemEvent(G.Updated,e)).on("unlink",e=>this.handleFileSystemEvent(G.Deleted,e)).on("ready",()=>this.isWatching=!0))}async stop(){!this.isWatching||!this.watcher||(await this.watcher.close(),this.isWatching=!1,this.watcher=void 0,this.clearCache(),this.clearAllLocks(),this.emit(G.Stopped))}getCwd(){return this.options.cwd}async executeWithPathLock(e,t){const n=k.resolve(e);this.ignoredPaths.add(n);try{await t()}finally{setTimeout(()=>{this.ignoredPaths.delete(n)},this.lockTimeoutMs)}}isPathLocked(e){const t=k.resolve(e);if(this.ignoredPaths.has(t))return!0;for(const n of this.ignoredPaths)if(t.startsWith(n+k.sep))return!0;return!1}clearAllLocks(){this.ignoredPaths.clear()}handleFileSystemEvent(e,t){const n=k.relative(this.membraneDir,t);if(this.isPathLocked(t))return;if(e===G.Deleted){this.removeFromCache(n);const a={filePath:t,relativePath:n,data:void 0};g.info(`[local] ${e}: ${a.relativePath}`),this.emit(e,a);return}const r=this.readFileContent(t);if(!this.hasContentChanged(n,r))return;const s=this.processFileEvent(t,r);this.updateCache(n,r),s&&(g.info(`[local] ${e}: ${s.relativePath}`),this.emit(e,s))}readFileContent(e){return T.readFileSync(e,"utf8")}processFileEvent(e,t){const n=k.relative(this.membraneDir,e);let r;try{r=t?Zo.parse(t):void 0}catch{r=void 0}return{filePath:e,relativePath:n,data:r}}hasContentChanged(e,t){if(!t)return this.contentCache[e]!==void 0;const n=this.getContentHash(t);return this.contentCache[e]!==n}getContentHash(e){return Vo.createHash("sha256").update(e).digest("hex")}updateCache(e,t){if(!t){delete this.contentCache[e];return}this.contentCache[e]=this.getContentHash(t)}removeFromCache(e){delete this.contentCache[e]}clearCache(){Object.keys(this.contentCache).forEach(e=>{delete this.contentCache[e]})}initializeContentCache(){T.existsSync(this.membraneDir)&&this.scanDirectoryForCache(this.membraneDir)}scanDirectoryForCache(e){const t=T.readdirSync(e,{withFileTypes:!0});for(const n of t){const r=k.join(e,n.name);if(n.isDirectory())this.scanDirectoryForCache(r);else if(n.isFile())try{const i=T.readFileSync(r,"utf8"),s=k.relative(this.membraneDir,r);this.updateCache(s,i)}catch{}}}}var xt=(o=>(o.Updated="updated",o.ConnectorFileUpdated="connector-file-updated",o.Connected="connected",o.Disconnected="disconnected",o.Error="error",o))(xt||{});const oi={debounceMs:2e3,reconnectIntervalMs:5e3,maxReconnectAttempts:1/0,maxBackoffMs:6e4,connectionTimeoutMs:3e5};class ri extends kt{static{l(this,"RemoteElementWatcher")}constructor(e=oi){super(),this.config=e}eventSource;debounceTimeouts=new Map;reconnectAttempts=0;reconnectTimeout;connectionTimeout;isStarted=!1;isConnected=!1;async start(){this.isStarted||(this.isStarted=!0,await this.connect())}async stop(){this.isStarted&&(this.isStarted=!1,this.isConnected=!1,this.clearReconnectTimeout(),this.clearConnectionTimeout(),this.clearAllDebounceTimeouts(),this.eventSource&&(this.eventSource.close(),this.eventSource=void 0))}async connect(){try{g.debug("[remote-events] Connecting to server"),this.eventSource&&(this.eventSource.close(),this.eventSource=void 0);const e=await O.getClient(process.cwd()),t=await e.getToken();if(!t)throw new Error("No auth token available");const n=`${e.apiUri}/sse/workspace?token=${encodeURIComponent(t)}`;g.debug("[remote-events] Subscribing to workspace events"),this.eventSource=new Qo(n),this.setupEventSourceHandlers()}catch(e){g.debug(`[remote-events] Failed to connect: ${e}`),this.emit("error",{error:e}),this.scheduleReconnect()}}setupEventSourceHandlers(){this.eventSource&&(this.eventSource.onopen=()=>{g.debug("[remote-events] Connected to server"),this.reconnectAttempts=0,this.isConnected=!0,this.resetConnectionTimeout(),this.emit("connected",{})},this.eventSource.onmessage=e=>{try{this.resetConnectionTimeout();const t=JSON.parse(e.data);this.handleElementUpdate(t)}catch(t){g.debug(`[remote-events] Failed to parse workspace event: ${t}`)}},this.eventSource.onerror=e=>{g.debug(`[remote-events] Connection error: ${JSON.stringify(e,null,2)}`),this.isConnected=!1,this.clearConnectionTimeout(),this.eventSource&&(this.eventSource.close(),this.eventSource=void 0),this.emit("disconnected",{}),this.isStarted&&this.scheduleReconnect()})}handleElementUpdate(e){if(e.type!==Ao.ElementUpdate)return;const{elementId:t,elementType:n,data:r={}}=e;if(!(!t||!n)){if(n===x.Connector){const{filePath:i,eventType:s,newPath:a}=r;return g.debug(`[remote-watcher] Received connector event - elementId: ${t}, filePath: ${i}, eventType: ${s}`),this.scheduleConnectorFileUpdate(t,i,s,a)}return this.scheduleElementUpdate(t,n)}}scheduleElementUpdate(e,t){const n=this.debounceTimeouts.get(e);n&&clearTimeout(n);const r=setTimeout(()=>{this.debounceTimeouts.delete(e),this.emit("updated",{elementId:e,elementType:t})},this.config.debounceMs);this.debounceTimeouts.set(e,r)}scheduleConnectorFileUpdate(e,t,n,r){const i=JSON.stringify({connectorId:e,filePath:t}),s=this.debounceTimeouts.get(i);s&&clearTimeout(s);const a=setTimeout(()=>{this.debounceTimeouts.delete(i),this.emit("connector-file-updated",{connectorId:e,filePath:t,eventType:n,newPath:r})},this.config.debounceMs);this.debounceTimeouts.set(i,a)}scheduleReconnect(){if(!this.isStarted||this.reconnectAttempts>=this.config.maxReconnectAttempts){this.reconnectAttempts>=this.config.maxReconnectAttempts&&(g.error("[remote-events] Max reconnection attempts reached. Connection will not be retried."),this.emit("error",{error:new Error("Max reconnection attempts reached")}));return}this.reconnectTimeout&&clearTimeout(this.reconnectTimeout),this.reconnectAttempts++;const e=this.config.reconnectIntervalMs*Math.pow(2,this.reconnectAttempts-1),t=Math.random()*.3*e,n=Math.min(e+t,this.config.maxBackoffMs);g.debug(`[remote-events] Reconnecting in ${Math.round(n)}ms (attempt ${this.reconnectAttempts})`),this.reconnectTimeout=setTimeout(()=>{this.connect()},n)}clearReconnectTimeout(){this.reconnectTimeout&&(clearTimeout(this.reconnectTimeout),this.reconnectTimeout=void 0)}resetConnectionTimeout(){this.clearConnectionTimeout(),this.connectionTimeout=setTimeout(()=>{this.isConnected&&this.isStarted&&(g.debug("[remote-events] Connection timeout detected, reconnecting..."),this.isConnected=!1,this.eventSource&&(this.eventSource.close(),this.eventSource=void 0),this.scheduleReconnect())},this.config.connectionTimeoutMs)}clearConnectionTimeout(){this.connectionTimeout&&(clearTimeout(this.connectionTimeout),this.connectionTimeout=void 0)}clearAllDebounceTimeouts(){this.debounceTimeouts.forEach(e=>clearTimeout(e)),this.debounceTimeouts.clear()}}class An{static{l(this,"ElementsCache")}elements=new Map;typeIndex=new Map;internalIdIndex=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),e.data?.id&&this.internalIdIndex.set(e.data.id,t)}remove(e){const t=e.id,n=this.elements.delete(t);if(n){const r=this.typeIndex.get(e.type);r&&(r.delete(t),r.size===0&&this.typeIndex.delete(e.type)),e.data?.id&&this.internalIdIndex.delete(e.data.id)}return n}put(e){this.elements.has(e.id)&&this.remove(e),this.add(e)}get(e){return this.elements.get(e)}getByInternalId(e){const t=this.internalIdIndex.get(e);if(t)return this.elements.get(t)}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(),this.internalIdIndex.clear()}getAllIds(){return new Set(this.elements.keys())}}const Te="connectors",ne="development",$t={};async function Pn(o={}){const{onProgress:e}=o,t=new Set,r=(await O.withClient(u=>u.get("org-workspace-id"))).id,i={};g.info("[connectors] Loading custom connectors"),await O.withClient(u=>u.get(`/connectors?workspaceId=${r}`)),g.info("[connectors] Loading public connectors");const s=ie(),c=(P.existsSync(s)?P.readdirSync(s):[]).filter(u=>{if(u.startsWith("."))return!1;const p=$.join(s,u);try{return P.statSync(p).isDirectory()}catch{return!1}});for(const u of c){g.info(`[connectors] Loading connector from: ${u}`);const p=P.readdirSync($.join(s,u)),m=await Ot(u);if(!m)continue;e?.("pushing",m.name),"baseUri"in m&&delete m.baseUri;let f;m.uuid&&(f=await O.withClient(S=>S.get(`/connectors/${m.uuid}`),!1));const y=m.uuid;if(f)i[y]=f.id,g.info(`[connectors] Matched ${m.name} uuid: ${m.uuid}`),f.isPublic||(f.archivedAt&&(g.info(`[connectors] Restoring archived connector ${m.name}`),await O.withClient(S=>S.post(`connectors/${f.id}/restore`))),g.info(`[connectors] Updating connector ${m.name}`),await O.withClient(S=>S.patch(`connectors/${f.id}`,{...m,workspaceId:r})));else if(!i[y]&&!f?.isPublic){let S=!1;try{const R=await At({connectorId:y});R&&R.isPublic&&(S=!0)}catch{}if(!S){g.info(`[connectors] Creating custom connector ${m.name} (${m.key})`);const R=await O.withClient(N=>N.post("connectors",{...m,workspaceId:r}));i[y]=R.id}}const I=p.filter(S=>P.statSync($.join(s,u,S)).isDirectory());for(const S of I)await ai({connector:m,version:S,connectorId:i[y]}),t.add(y);e?.("pushed",m.name)}return{connectorsMapping:i,pushedConnectors:Array.from(t)}}l(Pn,"pushConnectors");async function Nn({connectorId:o,connectorVersion:e,allConnectors:t,pulledConnectors:n,pulledConnectorVersions:r}){if(!o||r[o]?.has(e))return;const i=mn(),s=await At({connectorId:o});if(!s.isPublic||t){if(!s?.key){console.error(`[connectors] Connector ${o} has no key. Skipping..`),g.error(`[connectors] Connector ${o} has no key. Skipping..`);return}n.has(o)||(await ci({basePath:i,connector:s}),n.add(o)),r[o]||(r[o]=new Set),r[o].has(e)||(await li({connector:s,connectorVersion:e,basePath:i}),r[o].add(e))}}l(Nn,"pullRemoteConnector");function ie(){const o=ft();return $.join(o.membraneDirPath,Te)}l(ie,"getConnectorsPath");async function Ot(o){const e=$.join(ie(),o,`${o}.yml`);return Et(e,!1)}l(Ot,"readConnector");async function ii(o,e){return g.info(`[connectors] Zipping ${o} into ${e}`),new Promise((t,n)=>{const r=P.createWriteStream(e),i=ut("zip",{zlib:{level:9}});r.on("close",()=>{g.success(`[connectors] Successfully created ${e}`),t()}),r.on("end",()=>{g.info("[connectors] Data has been drained")}),i.on("warning",a=>{a.code==="ENOENT"?console.warn(a):n(a)}),i.on("error",a=>{n(a)}),i.pipe(r);const s=P.readdirSync(o);for(const a of s){const c=$.join(o,a),u=P.statSync(c);u.isFile()?i.file(c,{name:a}):u.isDirectory()&&i.directory(c,a)}i.finalize()})}l(ii,"createZipArchive");async function si(o,e){return g.info(`[connectors] Unzipping into ${e}`),new Promise((t,n)=>{const r=_e.Parse();r.on("entry",i=>{const s=i.path;if(i.type==="Directory"){const c=$.join(e,s);P.mkdirSync(c,{recursive:!0}),i.autodrain()}else{const c=$.join(e,s),u=$.dirname(c);P.mkdirSync(u,{recursive:!0});const p=P.createWriteStream(c);i.pipe(p),p.on("finish",()=>{})}}),r.on("end",()=>{g.success(`[connectors] Successfully extracted to ${e}`),t()}),r.on("error",i=>{n(i)}),r.write(o),r.end()})}l(si,"extractZipArchive");async function ai({connector:o,version:e,connectorId:t}){const n=$.join(ie(),oe(o),Rn(e)),r=$.join(n,"src"),i=$.join(n,"src.zip"),s=P.existsSync(i);if(P.existsSync(r)&&(g.info(`[connectors] Archiving source code for ${o.name} version ${e}`),await ii(r,i)),!P.existsSync(i)){g.warning(`[connectors] No source code found for ${o.name} version ${e}`);return}try{const a=new dn;if(a.append("file",P.createReadStream(i),"file.zip"),g.info(`[connectors] Pushing connector version ${e} for ${o.name}`),e==ne)g.info(`[connectors] Uploading connector ${t}`),await O.withClient(c=>c.post(`connectors/${t}/upload`,a,{headers:{...a.getHeaders()}}));else{if(a.append("version",e),a.append("changelog","Imported Version"),(await O.withClient(u=>u.get(`/connectors/${t}/versions`))).find(u=>u.version==e)){g.info(`[connectors] Version ${e} already published`);return}g.info(`[connectors] Publishing version ${e} of connector ${t}`),await O.withClient(u=>u.post(`connectors/${t}/publish-version`,a,{headers:{...a.getHeaders()}}))}g.success(`Successfully pushed connector version ${e} for ${o.name}`)}catch(a){g.error(`Error pushing connector version ${e} for ${o.name}: ${a}`),console.error(`[connectors] Error pushing connector version ${e} for ${o.name}: ${a}`)}finally{!s&&P.existsSync(i)&&(g.info(`[connectors] Cleaning up temporary zip file for ${o.name} version ${e}`),P.unlinkSync(i))}}l(ai,"pushConnectorVersion");async function At({connectorId:o}){if(o){if($t[o])return $t[o];try{const e=await O.withClient(t=>t.get(`connectors/${o}`),!1);return $t[o]=e,e}catch(e){return g.error(`[connectors] Failed to get connector ${o}: ${e}`),console.error(`[connectors] Failed to get connector ${o}: ${e}`),null}}}l(At,"getConnector");async function ci({basePath:o,connector:e}){const t=oe(e),n=$.join(o,Te,t);P.mkdirSync(n,{recursive:!0});const r=$.join(n,`${oe(e)}.yml`);P.writeFileSync(r,Y.dump(e)),g.info(`[connectors] Pulled connector ${e.name}`)}l(ci,"pullConnector$1");async function li({connector:o,connectorVersion:e,basePath:t}){const n=oe(o),r=Rn(e),i=$.join(t,"connectors",n,r),s=await O.withClient(c=>c.get(`connectors/${o.id}/download`,{version:e},{responseType:"arraybuffer",headers:{Accept:"application/zip"},timeout:1e6}));P.mkdirSync(i,{recursive:!0});const a=$.join(i,"src.zip");if(P.writeFileSync(a,s),!e){const c=$.join(i,"src");P.mkdirSync(c,{recursive:!0}),await si(s,c)}g.info(`[connectors] Pulled connector version: ${o.name} (${r})`)}l(li,"pullConnectorVersion");function oe(o){return o.key}l(oe,"getConnectorDirName");function Rn(o){return o??ne}l(Rn,"getConnectorVersionDirName");function ui(o){const e=mn(),t=oe(o);return $.join(e,Te,t)}l(ui,"getConnectorDirPath");function di(o){return o.match(`${Te}/[^/]+/${ne}/src/.*`)!==null}l(di,"isConnectorSourceFile");async function pi(o){const e=o.match(`${Te}/([^/]+)/${ne}/src/(.*)`);if(!e)return;const t=e[1],n=e[2],r=await Ot(t);if(!r){g.warning(`[connectors] Connector ${t} not found. Ignoring file change`);return}const i=r.id,s=P.readFileSync(o,"utf-8");await O.withClient(a=>a.put(`connectors/${i}/files/${n}`,s,{headers:{"Content-Type":"text/plain"}})),g.info(`[connectors] Pushed file ${n} for connector ${r.name}`)}l(pi,"putConnectorFile");async function hi(o){const e=o.match(`${Te}/([^/]+)/${ne}/src/(.*)`);if(!e)return;const t=e[1],n=e[2],r=await Ot(t);if(!r){g.warning(`[connectors] Connector ${t} not found. Ignoring file change`);return}const i=r.id;await O.withClient(s=>s.delete(`connectors/${i}/files/${n}`)),g.info(`[connectors] Deleted file ${n} for connector ${r.name}`)}l(hi,"deleteConnectorFile");async function fi(o,e){try{const t=await O.withClient(s=>s.get(`connectors/${o}`));if(!t){g.warning(`[connectors] Connector ${o} not found`);return}const n=await O.withClient(s=>s.get(`connectors/${o}/files/${e}`)),r=oe(t),i=$.join(ie(),r,ne,"src",e);P.mkdirSync($.dirname(i),{recursive:!0}),n!=null?(P.writeFileSync(i,n),g.info(`[connectors] Pulled file ${e} for connector ${t.name}`)):P.existsSync(i)&&(P.unlinkSync(i),g.info(`[connectors] Deleted file ${e} for connector ${t.name}`))}catch(t){g.error(`[connectors] Failed to pull connector file ${e} for connector ${o}: ${t}`),console.error(`[connectors] Failed to pull connector file ${e} for connector ${o}: ${t}`)}}l(fi,"pullConnectorFile");async function mi(o,e){const t=await O.withClient(i=>i.get(`connectors/${o}`),!1);if(!t){g.warning(`[connectors] Connector ${o} not found`);return}const n=oe(t),r=$.join(ie(),n,ne,"src",e);P.existsSync(r)&&(P.unlinkSync(r),g.info(`[connectors] Deleted file ${e} for connector ${n}`))}l(mi,"deleteLocalConnectorFile");async function gi(o,e,t){if(t&&e!==t)try{const n=await O.withClient(c=>c.get(`connectors/${o}`),!1);if(!n){g.warning(`[connectors] Connector ${o} not found`);return}const r=oe(n),i=$.join(ie(),r,ne,"src"),s=$.join(i,e),a=$.join(i,t);P.existsSync(s)&&(P.mkdirSync($.dirname(a),{recursive:!0}),P.renameSync(s,a),g.info(`[connectors] Renamed directory from ${e} to ${t} for connector ${r}`))}catch(n){g.error(`[connectors] Failed to rename directory ${e} to ${t} for connector ${o}: ${n}`)}}l(gi,"renameLocalConnectorDirectory");async function yi(o,e){try{const t=await O.withClient(i=>i.get(`connectors/${o}`),!1);if(!t){g.warning(`[connectors] Connector ${o} not found`);return}const n=oe(t),r=$.join(ie(),n,ne,"src",e);if(P.existsSync(r)){const i=$.resolve(ie());if(!$.resolve(r).startsWith(i))return;P.rmSync(r,{recursive:!0,force:!0}),g.info(`[connectors] Deleted directory ${e} for connector ${n}`)}}catch(t){g.error(`[connectors] Failed to delete directory ${e} for connector ${o}: ${t}`)}}l(yi,"deleteLocalConnectorDirectory");const q={LogAdded:"logAdded",StateChanged:"stateChanged",StatsChanged:"statsChanged",ConflictsChanged:"conflictsChanged",McpStatusChanged:"mcpStatusChanged",McpServersChanged:"mcpServersChanged",ConfigChanged:"configChanged"};class wi extends kt{static{l(this,"WorkspaceNotifications")}constructor(e){super(),this.config=e,g.setNotificationHandler(this)}clientId;heartbeatInterval;isCleaningUp=!1;async connectToRemote(){await this.registerWithRemoteServer(),await this.startHeartbeatLoop()}async setState(e){this.emit(q.StateChanged,{state:e}),await this.emitRemote({status:e})}setConflicts(e){this.emit(q.ConflictsChanged,{conflicts:e})}setConfig(e){this.emit(q.ConfigChanged,{config:e})}setStats(e){this.emit(q.StatsChanged,{stats:e})}addLog(e){this.emit(q.LogAdded,{log:e})}setMcpStatus(e){this.emit(q.McpStatusChanged,{status:e})}async setMcpServers(e){this.emit(q.McpServersChanged,{servers:e}),await this.emitRemote({mcpServers:e.map(t=>({name:t.agentName,totalRequests:t.totalRequests}))})}async cleanup(){!this.clientId||this.isCleaningUp||(this.isCleaningUp=!0,this.heartbeatInterval&&(clearInterval(this.heartbeatInterval),this.heartbeatInterval=void 0),await this.withErrorHandling(async()=>{await O.withClient(e=>e.delete(`/local-clients/${this.clientId}`))}),this.clientId=void 0)}async registerWithRemoteServer(){if(this.clientId)return;const e=await this.withErrorHandling(async()=>await O.withClient(t=>t.post("/local-clients",{hostname:Ye.hostname(),workingDirectory:process.cwd()})));e?.id?this.clientId=e.id:this.addLog({timestamp:new Date().toISOString(),message:"Failed to register with remote server",type:"error"})}async startHeartbeatLoop(){this.heartbeatInterval=setInterval(async()=>{this.clientId&&await this.sendHeartbeat()},this.config.heartbeatIntervalMs)}async sendHeartbeat(){this.clientId&&await this.withErrorHandling(async()=>{await O.withClient(e=>e.post(`/local-clients/${this.clientId}/keep-alive`,{}))})}async emitRemote(e){this.clientId&&await this.withErrorHandling(async()=>{await O.withClient(t=>t.patch(`/local-clients/${this.clientId}`,e))})}async withErrorHandling(e){try{return await e()}catch(t){const n=t instanceof Error?t.message:String(t);return this.addLog({timestamp:new Date().toISOString(),message:`Failed to connect to remote: ${n}`,type:"error"}),null}}}const se=new wi({heartbeatIntervalMs:15e3}),re={UPDATE:"update",DELETE:"delete",CREATE:"create"},z={INCOMING:"incoming",OUTGOING:"outgoing"},Dn=[x.AppDataSchema,x.AppEventType,x.DataLinkTable,x.DataSource,x.FieldMapping,x.Action,x.Flow,x.Package];class De{static{l(this,"ElementSyncService")}localWatcher=void 0;remoteWatcher=void 0;notifier;changes=[];localCache;remoteCache;localRepo;remoteRepo;pulledConnectors=new Set;pulledConnectorVersions={};constructor(){this.notifier=se,this.localCache=new An,this.remoteCache=new An,this.localRepo=new Qr(this.localCache),this.remoteRepo=new ei(this.remoteCache)}clear(){this.changes=[]}needsForcedSync(){return this.changes.some(e=>e.isConflict)}needsSync(){return this.changes.length>0}async getStats(){const e=this.localCache.getAll(),t={};return e.forEach(n=>{t[n.type]=(t[n.type]||0)+1}),t}async fetchElements(){const e=await this.localRepo.getElements(),t=await this.remoteRepo.getElements();this.localCache.addAll(e),this.remoteCache.addAll(t)}async updateElement(e,t){const n=this.getHandler(t),r=this.getCache(t);try{const i=await n.putElement(e);r.put(i)}catch(i){throw g.error(`Failed to update element ${e.id}: ${i}`),i}}async deleteElement(e,t){const n=this.getHandler(t),r=this.getCache(t);try{await n.deleteElement(e,{elements:n.cache.getAll(),connectorsMapping:n.connectorsMapping}),r.remove(e)}catch(i){throw g.error(`Failed to delete element ${e.id}: ${i}`),i}}async pullConnectors(e=!1){const t=this.remoteCache.getElementsByType(x.Integration).map(n=>n.data);for(const n of t){const r=n.connectorId,i=n.connectorVersion;r&&await Nn({connectorId:r,connectorVersion:i,allConnectors:e,pulledConnectors:this.pulledConnectors,pulledConnectorVersions:this.pulledConnectorVersions})}}async pushConnectors(){const{connectorsMapping:e}=await Pn();this.remoteRepo.setConnectorsMapping(e)}getHandler(e){return e===z.INCOMING?this.localRepo:(this.remoteRepo.setSourceCache(this.localCache),this.remoteRepo)}getCache(e){return e===z.INCOMING?this.localCache:this.remoteCache}async startWatching(){this.localWatcher=new ni({cwd:process.cwd(),lockTimeoutMs:1e3}),this.localWatcher.on(G.Updated,e=>this.handleLocalEvent(e,G.Updated)),this.localWatcher.on(G.Deleted,e=>this.handleLocalEvent(e,G.Deleted)),await this.localWatcher.start(),g.success("[local] Tracking changes.."),this.remoteWatcher=new ri,this.remoteWatcher.on(xt.Updated,({elementId:e,elementType:t})=>this.handleRemoteElementEvent(e,t)),this.remoteWatcher.on(xt.ConnectorFileUpdated,({connectorId:e,filePath:t,eventType:n,newPath:r})=>this.handleRemoteConnectorFileEvent(e,t,n,r)),await this.remoteWatcher.start(),g.success("[remote] Tracking changes..")}async stopWatching(){this.localWatcher&&(await this.localWatcher.stop(),this.localWatcher=void 0),this.remoteWatcher&&(await this.remoteWatcher.stop(),this.remoteWatcher=void 0)}async handleRemoteElementEvent(e,t){try{const n=await this.remoteRepo.getByInternalId(e,t),r=!!n?.data.archivedAt||!!n?.data.isDeactivated;if(!n||r){const s=n||this.remoteCache.getByInternalId(e);return s?(g.info(`[${this.getDirectionLabel(z.INCOMING)}] Deleted: ${s.id}`),this.localWatcher?.executeWithPathLock(s.absolutePath,()=>this.deleteElement(s,z.INCOMING))):void 0}if(g.info(`[${this.getDirectionLabel(z.INCOMING)}] Updated: ${n.id}`),await this.localWatcher?.executeWithPathLock(n.absolutePath,async()=>this.updateElement(n,z.INCOMING)),t===x.Integration){const s=n.data.connectorId,a=n.data.connectorVersion,c=await At({connectorId:s});if(!c?.key)return;const u=ui(c);await this.localWatcher?.executeWithPathLock(u,async()=>Nn({connectorId:s,connectorVersion:a,allConnectors:!1,pulledConnectors:this.pulledConnectors,pulledConnectorVersions:this.pulledConnectorVersions}))}}catch(n){g.error(`[sync] Error handling remote event: ${n}`)}}async handleRemoteConnectorFileEvent(e,t,n,r){try{switch(n){case Ze.ConnectorFileDeleted:await mi(e,t);break;case Ze.ConnectorDirectoryRenamed:await gi(e,t,r);break;case Ze.ConnectorDirectoryDeleted:await yi(e,t);break;default:await fi(e,t);break}}catch(i){g.error(`[sync] Error handling remote connector file event: ${i}`)}}async handleLocalEvent(e,t){try{if(di(e.filePath))switch(t){case G.Updated:await pi(e.filePath);break;case G.Deleted:await hi(e.filePath);break}else{let n=_.fromPathAndData(e.filePath,e.data);if(!n){const r=_.idFromPath(e.filePath);if(!r||(n=this.remoteCache.get(r),!n))return}switch(g.info(`[${this.getDirectionLabel(z.OUTGOING)}] ${zo(t)}: ${n.id}`),t){case G.Updated:await this.updateElement(n,z.OUTGOING);break;case G.Deleted:await this.deleteElement(n,z.OUTGOING);break}}}catch(n){g.error(`[sync] Error handling local event: ${n}`)}}detectIncomingChanges(){this.clearChanges();const e=De.getChanges(z.INCOMING,this.remoteCache,this.localCache);return this.updateChanges(e),e}detectOutgoingChanges(){this.clearChanges();const e=De.getChanges(z.OUTGOING,this.localCache,this.remoteCache);return this.updateChanges(e),e}async resolveChanges(){if(!this.needsSync())return;g.info("[resolver] Resolving changes.."),g.info("[resolver] Resolving integration elements");const e=this.changes.filter(r=>r.element.type===x.Integration);await Promise.all(e.map(async r=>this.resolveChange(r))),e.length>0&&(await this.fetchElements(),this.changes=this.changes.length>0&&this.changes[0]?.direction===z.INCOMING?this.detectIncomingChanges():this.detectOutgoingChanges(),this.changes=this.changes.filter(r=>r.element.type!==x.Integration)),g.info("[resolver] Resolving universal elements");const t=this.changes.filter(r=>!r.element.hasParent());for(const r of Dn){const i=t.filter(s=>s.element.type===r);g.info(`[resolver] Resolving ${r} elements`),await Promise.all(i.map(async s=>this.resolveChange(s)))}g.info("[resolver] Resolving integration level elements");const n=this.changes.filter(r=>r.element.hasParent());for(const r of Dn){const i=n.filter(s=>s.element.type===r);g.info(`[resolver] Resolving ${r} elements`),await Promise.all(i.map(async s=>this.resolveChange(s)))}g.success("[resolver] Resolved changes")}async resolveChange(e){switch(e.type){case re.DELETE:return this.deleteElement(e.element,e.direction);case re.CREATE:return this.updateElement(e.element,e.direction);case re.UPDATE:return this.updateElement(e.element,e.direction)}}static getChanges(e,t,n){const r=t.getAllIds(),i=n.getAllIds(),s=new Set([...r,...i]),a=[];for(const c of s){const u=t.get(c),p=n.get(c),m=De.detectChangeForElement(u,p,e);m&&a.push(m)}return a}updateChanges(e){if(this.changes=e,this.needsForcedSync()){const t=e.filter(n=>n.isConflict);g.warning("[resolver] Conflicts detected"),this.notifier.setConflicts(t)}}clearChanges(){this.changes=[]}getDirectionLabel(e){switch(e){case z.INCOMING:return"local\u2190remote";case z.OUTGOING:return"local\u2192remote"}}static detectChangeForElement(e,t,n){return e&&!t?{type:re.CREATE,element:e,direction:n,isConflict:!1}:!e&&t?{type:re.DELETE,element:t,direction:n,isConflict:!0}:e&&t&&!e.isEqual(t)?{type:re.UPDATE,element:e,direction:n,isConflict:!1}:null}}const ae=k.join(er.tmpdir(),"membrane-mcp-status"),Ln=3e4;class Ci{static{l(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=We(void 0,e),n=jn(e);t&&se.setMcpStatus(t),await se.setMcpServers(n)}catch{g.error("Failed to check MCP status")}}}function We(o,e){try{const t=e||process.cwd();if(!o){const r=jn(t);return r.length===0?null:r[0]}const n=Rt(o,t);if(T.existsSync(n)){const r=T.statSync(n),i=new Date;if(i.getTime()-r.mtime.getTime()>Ln)return Ae(o,t),null;const a=T.readFileSync(n,"utf8"),c=JSON.parse(a);if(c.isRunning){const u=new Date(c.lastActivity).getTime();if(i.getTime()-u>Ln)return Ae(o,t),null}return c}}catch{o&&e&&Ae(o,e)}return null}l(We,"getMcpStatus");function jn(o){try{const e=o||process.cwd(),t=Nt(e);if(!T.existsSync(ae))return[];const n=T.readdirSync(ae),r=[];for(const i of n){const s=i.match(new RegExp(`^mcp-${t}-(\\d+)\\.json$`));if(s){const a=parseInt(s[1],10),c=We(a,e);c&&r.push(c)}}return r.sort((i,s)=>new Date(s.startTime).getTime()-new Date(i.startTime).getTime())}catch{return[]}}l(jn,"getAllMcpStatusFiles");function Pt(o){try{const t={...We(o.processId,o.cwd)||{isRunning:!1,startTime:new Date().toISOString(),lastActivity:new Date().toISOString(),toolsCount:0,totalRequests:0,processId:o.processId,cwd:o.cwd,agentName:process.env.AGENT_NAME||"Unnamed Agent"},...o};T.existsSync(ae)||T.mkdirSync(ae,{recursive:!0});const n=Rt(o.processId,o.cwd);T.writeFileSync(n,JSON.stringify(t,null,2))}catch{}}l(Pt,"updateMcpStatus");function Ae(o,e){try{const t=e||process.cwd();if(o){const n=Rt(o,t);T.existsSync(n)&&T.unlinkSync(n)}else{const n=Nt(t);if(T.existsSync(ae)){const r=T.readdirSync(ae);for(const i of r)i.match(new RegExp(`^mcp-${n}-\\d+\\.json$`))&&T.unlinkSync(k.join(ae,i))}}}catch{}}l(Ae,"clearMcpStatus");function Si(o,e){const t=We(o,e);t&&Pt({processId:o,cwd:e,totalRequests:t.totalRequests+1,lastRequestTime:new Date().toISOString(),lastActivity:new Date().toISOString()})}l(Si,"trackToolExecution");function Nt(o){return Yo("md5").update(o).digest("hex").slice(0,8)}l(Nt,"getCwdHash");function Rt(o,e){const t=Nt(e);return k.join(ae,`mcp-${t}-${o}.json`)}l(Rt,"getStatusFilePath");const ze={Agent:"agent",Cli:"cli"},A={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"};class bi{static{l(this,"MembraneCLIService")}constructor(e,t,n=()=>process.exit(0)){this.mode=e,this.cwd=t,this.onShutdown=n,this.notifier=se,this.mcpStatusService=new Ci,this.syncService=new De,this.setupProcessCleanup()}initialized=!1;notifier;mcpStatusService;syncService;isShuttingDown=!1;currentConfig=null;get config(){return this.currentConfig}getSyncedElements(){return this.syncService.localCache.getAll()}getSyncedElementsByType(e){return this.syncService.localCache.getElementsByType(e)}async fetchElements(){await this.syncService.fetchElements()}async pullWorkspace(e={}){let t=!1;try{g.setVerboseMode(!!e.verbose),e.rps!==void 0&&O.init({maxRequestsPerSecond:e.rps}),await this.notifier.setState(A.PULLING),await this.syncService.fetchElements(),this.syncService.detectIncomingChanges(),this.syncService.needsForcedSync()&&!e.force?(await this.notifier.setState(A.CONFLICTS),e.watch||(t=!0)):(await this.syncService.pullConnectors(e.allConnectors),await this.syncWorkspaces(e))}catch(n){t=!0,g.error(`Failed to pull workspace: ${n}`),await this.notifier.setState(A.ERROR),g.saveLogsToFile("error")}finally{e.saveLogs&&g.saveLogsToFile()}t?process.exit(1):e?.onComplete?.()}async pushWorkspace(e={}){let t=!1;try{g.setVerboseMode(!!e.verbose),e.rps!==void 0&&O.init({maxRequestsPerSecond:e.rps}),await this.notifier.setState(A.PUSHING),await this.syncService.fetchElements(),this.syncService.detectOutgoingChanges(),this.syncService.needsForcedSync()&&!e.force?(await this.notifier.setState(A.CONFLICTS),e.watch||(t=!0)):(await this.syncService.pushConnectors(),await this.syncWorkspaces(e))}catch(n){t=!0,g.error(`Failed to push workspace: ${n}`),await this.notifier.setState(A.ERROR),g.saveLogsToFile("error")}finally{e.saveLogs&&g.saveLogsToFile()}t?process.exit(1):e?.onComplete?.()}async syncWorkspaces(e={}){try{e.verbose!==void 0&&g.setVerboseMode(!!e.verbose),await this.notifier.setState(A.RESOLVING),this.syncService.needsSync()&&await this.syncService.resolveChanges();const t=await this.syncService.getStats();this.notifier.setStats(t),await this.notifier.setState(A.SYNCED),e.watch&&(await this.notifier.setState(A.WATCHING),await this.syncService.startWatching())}catch(t){g.error(`Failed to sync local and remote workspaces: ${t}`),await this.notifier.setState(A.ERROR),g.saveLogsToFile("error")}}async init({force:e=!1}={}){if(!(this.initialized&&!e)){await this.notifier.setState(A.NOT_INITIALIZED);try{await this.loadConfig(),fe.isCacheDefined()?(await this.initServices(),this.initialized=!0,await this.notifier.setState(A.INITIALIZED)):(this.initialized=!1,await this.notifier.setState(A.SETTING_UP))}catch(t){g.error(`Failed to initialize services: ${t}`),await this.notifier.setState(A.ERROR),g.saveLogsToFile("error"),this.onShutdown()}}}async loadConfig(){this.currentConfig=fe.loadConfig(this.cwd),this.notifier.setConfig(this.currentConfig)}async updateConfig(e){const t={...this.currentConfig,...e};if(!(JSON.stringify(t)!==JSON.stringify(this.currentConfig)))return;await this.stopServices();const r=fe.updateConfig(t);this.currentConfig=r,await this.init({force:!0})}async shutdown({skipExit:e=!1}={}){!this.initialized||this.isShuttingDown||(this.isShuttingDown=!0,this.mode===ze.Agent&&(await this.notifier.cleanup(),await this.mcpStatusService.stop()),this.initialized=!1,e||this.onShutdown())}async initServices(){this.mode===ze.Agent&&(await this.notifier.connectToRemote(),await this.mcpStatusService.start()),this.syncService.clear()}async stopServices(){this.mode===ze.Agent&&(await this.notifier.cleanup(),await this.mcpStatusService.stop())}setupProcessCleanup(){process.on("SIGINT",async()=>{try{await this.shutdown({skipExit:!0})}finally{process.exit(130)}}),process.on("SIGTERM",async()=>{try{await this.shutdown({skipExit:!0})}finally{process.exit(143)}}),process.on("uncaughtException",e=>{console.error("Uncaught exception:",e),this.shutdown({skipExit:!0}).finally(()=>process.exit(1))}),process.on("unhandledRejection",e=>{console.error("Unhandled rejection:",e),this.shutdown({skipExit:!0}).finally(()=>process.exit(1))}),process.on("beforeExit",e=>{e===0&&this.shutdown()})}}function vi({children:o,membraneCLIService:e}){const{data:t}=un("/account"),[n,r]=L(A.NOT_INITIALIZED),[i,s]=L([]),[a,c]=L({}),[u,p]=L([]),[m,f]=L(null),I=t?.workspaces?.find(S=>S.workspaceKey===m?.workspaceKey)||null;return Ce(()=>{const S=l(({state:F})=>r(F),"handleStateChanged"),R=l(({stats:F})=>c(F),"handleStatsChanged"),N=l(({log:F})=>p(Le=>[...Le,F]),"handleLogAdded"),M=l(({conflicts:F})=>s(F),"handleConflictsUpdated"),K=l(({config:F})=>f(F),"handleConfigChanged");return e.notifier.on(q.StateChanged,S),e.notifier.on(q.StatsChanged,R),e.notifier.on(q.LogAdded,N),e.notifier.on(q.ConflictsChanged,M),e.notifier.on(q.ConfigChanged,K),e.init(),()=>{e.notifier.off(q.StateChanged,S),e.notifier.off(q.StatsChanged,R),e.notifier.off(q.LogAdded,N),e.notifier.off(q.ConflictsChanged,M),e.notifier.off(q.ConfigChanged,K)}},[]),d(vn.Provider,{value:{state:n,stats:a,logs:u,currentWorkspace:I,conflicts:i,config:m,updateConfig:l(S=>e.updateConfig(S),"updateConfig"),resolveConflicts:l(S=>e.syncWorkspaces(S),"resolveConflicts"),pull:l(S=>e.pullWorkspace(S),"pull"),push:l(S=>e.pushWorkspace(S),"push"),exit:l(()=>e.shutdown(),"exit"),fetchElements:l(()=>e.fetchElements(),"fetchElements"),getSyncedElementsByType:l(S=>e.getSyncedElementsByType(S),"getSyncedElementsByType")},children:o})}l(vi,"MembraneCLIServiceProvider");const Mn=it(process.cwd());function Ti(){return st(Mn)}l(Ti,"useCwd");function Ii({cwd:o,children:e}){return d(Mn.Provider,{value:o,children:e})}l(Ii,"CwdProvider");function Dt({cwd:o,children:e,membraneCLIService:t}){const n=o||process.cwd();return d(Ii,{cwd:n,children:d(Bo,{value:{fetcher:kr()},children:d(vi,{membraneCLIService:t,children:e})})})}l(Dt,"Layout");function Ei(o,e){o.command("config").alias("install").description("\u26A0\uFE0F EXPERIMENTAL: Manage local membrane configuration with interactive UI").addHelpText("after",["","Examples:"," membrane config # Open interactive config manager",""].join(`
|
|
25
|
+
`)).action(async()=>{await rt(he.createElement(Dt,{membraneCLIService:e,children:he.createElement(Wr,{onComplete:l(()=>process.exit(0),"onComplete")})})).waitUntilExit(),process.exit(0)})}l(Ei,"setupConfigCommand");function Fn(o,e){return new Promise((t,n)=>{if(e.aborted){n(e.reason);return}const r=setTimeout(t,o);e.addEventListener("abort",()=>{clearTimeout(r),n(e.reason)},{once:!0})})}l(Fn,"sleep");function Un(o){return o.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}l(Un,"escapeHtml");const ki="font-family:system-ui;display:flex;justify-content:center;align-items:center;height:100vh;margin:0;background:#0a0a0a;color:#fff";function ce(o,e,t="#888"){const n=/^#[0-9a-fA-F]{3,6}$/.test(t)?t:"#888";return`<!DOCTYPE html><html><body style="${ki}">
|
|
26
26
|
<div style="text-align:center"><h1>${Un(o)}</h1><p style="color:${n}">${Un(e)}</p></div>
|
|
27
27
|
</body></html>`}l(ce,"htmlPage");async function Lt(o,e){return o.post("/connection-requests",e)}l(Lt,"createConnectionRequest");function Kn(o){console.info(),b.info("Open this URL in a browser to complete the connection:"),console.info(` ${o.url}`),console.info(),b.info("Then check the status with:"),console.info(` membrane connection-request get ${o.requestId}`),console.info()}l(Kn,"printConnectionRequestResult");const xi=3e3,$i=1800*1e3;function Oi(o){o.command("connect").description("Create a connection to a third-party service via browser-based OAuth").option("--integrationId <id>","Integration ID").option("--integrationKey <key>","Integration key").option("--connectorId <id>","Connector ID").option("--connectorKey <key>","Connector key").option("--connectorVersion <version>","Connector version").option("--connectionId <id>","Existing connection ID (for reconnect)").option("--name <name>","Connection name").option("--allowMultipleConnections","Allow multiple connections").option("--connectorParameters <json>","JSON string of connector parameters").option("--workspaceKey <key>","Workspace key").option("--tenantKey <key>","Tenant key (customer internalId)").option("--non-interactive","Print URL instead of opening browser").addHelpText("after",["","Examples:"," membrane connect --integrationKey hubspot"," membrane connect --integrationKey hubspot --tenantKey my-customer"," membrane connect --connectorId 123 --workspaceKey my-workspace"," membrane connect --connectorKey hubspot --workspaceKey my-workspace"," membrane connect --connectionId abc --non-interactive",""].join(`
|
|
28
|
-
`)).action(async e=>{try{await Ai(e)}catch(t){U(t)}})}l(Oi,"setupConnectCommand");async function Ai(o){b.header("Creating a connection");let e;if(o.connectorParameters){let
|
|
28
|
+
`)).action(async e=>{try{await Ai(e)}catch(t){U(t)}})}l(Oi,"setupConnectCommand");async function Ai(o){b.header("Creating a connection");let e;if(o.connectorParameters){let p;try{p=JSON.parse(o.connectorParameters)}catch{throw new Error("--connectorParameters must be valid JSON")}if(typeof p!="object"||p===null||Array.isArray(p))throw new Error("--connectorParameters must be a JSON object");e=p}const t=new B({workspaceKey:o.workspaceKey,tenantKey:o.tenantKey}),n=!!(process.stdin.isTTY&&!o.nonInteractive),r={integrationId:o.integrationId,integrationKey:o.integrationKey,connectorId:o.connectorId,connectorKey:o.connectorKey,connectorVersion:o.connectorVersion,connectionId:o.connectionId,name:o.name,allowMultipleConnections:o.allowMultipleConnections,connectorParameters:e};if(!n){const p=await Lt(t,r);Kn(p),process.exit(0);return}const i=tr(),{port:s,server:a,waitForCallback:c}=await Pi(i),u=`http://127.0.0.1:${s}/callback?nonce=${i}`;try{const p=await Lt(t,{...r,redirectUri:u}),m=p.url;try{const{default:K}=await import("open");await K(m),b.info("Opening browser to complete connection...")}catch{b.info("Could not open browser automatically.")}console.error(` If the browser doesn't open, visit:
|
|
29
29
|
${m}
|
|
30
|
-
`);const f=Se("Waiting for connection to complete...").start(),y=new AbortController,I=l(()=>{y.abort(),f.stop(),a.closeAllConnections(),a.close(),process.exit(130)},"onSigint");process.once("SIGINT",I);const S=c,R=Ni(t,
|
|
30
|
+
`);const f=Se({text:"Waiting for connection to complete...",discardStdin:!1}).start(),y=new AbortController,I=l(()=>{y.abort(),f.stop(),a.closeAllConnections(),a.close(),process.exit(130)},"onSigint");process.once("SIGINT",I);const S=c,R=Ni(t,p.requestId,y.signal);R.catch(()=>{});const N=await Promise.race([S,R]);if(y.abort(),f.stop(),process.removeListener("SIGINT",I),N.cancelled&&(b.warning("Connection was cancelled."),process.exit(0)),N.error)throw new Error(`Connection failed: ${N.error}`);if(!N.connectionId)throw new Error("Connection completed but no connection ID received");const M=await t.get(`/connections/${N.connectionId}`);b.success("Connection created successfully!"),console.error(),console.error(` Connection ID: ${M.id}`),M.name&&console.error(` Name: ${M.name}`),M.integrationId&&console.error(` Integration ID: ${M.integrationId}`),M.connectorId&&console.error(` Connector ID: ${M.connectorId}`),console.error(),process.exit(0)}finally{a.closeAllConnections(),a.close()}}l(Ai,"runConnect");function Pi(o){return new Promise(e=>{let t;const n=new Promise(i=>{t=i}),r=hn((i,s)=>{const a=new URL(i.url??"/","http://127.0.0.1");if(a.pathname!=="/callback"){s.writeHead(404),s.end("Not found");return}if(a.searchParams.get("nonce")!==o){s.writeHead(403),s.end("Invalid nonce");return}const c=a.searchParams.get("connectionId"),u=a.searchParams.get("cancelled"),p=a.searchParams.get("error");s.writeHead(200,{"Content-Type":"text/html"}),p?(s.end(ce("Connection failed",p,"#f87171")),t({error:p})):u?(s.end(ce("Connection cancelled","You can close this tab and return to your terminal.")),t({cancelled:!0})):c?(s.end(ce("Connection successful","You can close this tab and return to your terminal.")),t({connectionId:c})):(s.end(ce("Connection failed","Unknown callback state","#f87171")),t({error:"Unknown callback state"}))});r.listen(0,"127.0.0.1",()=>{const i=r.address(),s=typeof i=="object"&&i?i.port:0;if(!s)throw new Error("Failed to bind local callback server");e({port:s,server:r,waitForCallback:n})})})}l(Pi,"startConnectionCallbackServer");async function Ni(o,e,t){const n=Date.now()+$i;for(;Date.now()<n;){t.throwIfAborted(),await Fn(xi,t),t.throwIfAborted();const r=await o.request(`/connection-requests/${encodeURIComponent(e)}`,{signal:t});if(r.status==="success"&&r.resultConnectionId)return{connectionId:r.resultConnectionId};if(r.status==="cancelled")return{cancelled:!0};if(r.status==="error")return{error:r.resultError?.message??"Connection failed"}}throw new Error("Connection timed out after 30 minutes")}l(Ni,"pollConnectionRequest");function Ri(o){const e=o.command("connection-request").description("Manage connection requests (OAuth authentication flows)").option("--workspaceKey <key>","Workspace key").option("--tenantKey <key>","Tenant key (customer internalId)");e.command("create").description("Create a connection request for user authentication").option("--connectorId <id>","Connector ID").option("--integrationId <id>","Integration ID").option("--integrationKey <key>","Integration key").option("--connectionId <id>","Existing connection ID (for reconnecting)").option("--name <name>","Connection name").option("--json","Output as JSON").action(async t=>{try{const n={...e.opts(),...t},r=new B(n),i={};t.connectorId&&(i.connectorId=t.connectorId),t.integrationId&&(i.integrationId=t.integrationId),t.integrationKey&&(i.integrationKey=t.integrationKey),t.connectionId&&(i.connectionId=t.connectionId),t.name&&(i.name=t.name);const s=await Lt(r,i);n.json?process.stdout.write(JSON.stringify(s,null,2)+`
|
|
31
31
|
`):Kn(s)}catch(n){U(n)}}),e.command("get <requestId>").description("Check the status of a connection request").option("--json","Output as JSON").action(async(t,n)=>{try{const r={...e.opts(),...n},s=await new B(r).get(`/connection-requests/${encodeURIComponent(t)}`);r.json?process.stdout.write(JSON.stringify(s,null,2)+`
|
|
32
32
|
`):(console.error(),E("Request ID",s.requestId,16),E("Status",s.status,16),s.resultConnectionId&&E("Connection ID",s.resultConnectionId,16),s.resultError&&E("Error",typeof s.resultError=="string"?s.resultError:JSON.stringify(s.resultError),16),console.error())}catch(r){U(r)}})}l(Ri,"setupConnectionRequestCommand");function Di(o){const e=o.command("connection").description("Manage connections to external apps").option("--workspaceKey <key>","Workspace key").option("--tenantKey <key>","Tenant key (customer internalId)");e.command("list").description("List all connections").option("--limit <n>","Max results").option("--cursor <cursor>","Pagination cursor").option("--json","Output as JSON").action(async t=>{try{const r={...e.opts(),...t},i=new B(r),s=new URLSearchParams;t.limit&&s.set("limit",t.limit),t.cursor&&s.set("cursor",t.cursor);const a=s.toString(),c=await i.get(`/connections${a?`?${a}`:""}`);if(r.json)process.stdout.write(JSON.stringify(c,null,2)+`
|
|
33
|
-
`);else{const u=c.items??[];if(u.length===0)console.error(
|
|
34
|
-
`);else{if(console.error(),E("ID",u.id),u.name&&E("Name",u.name),E("State",u.state),u.connectorId&&E("Connector",u.connectorId),u.integrationId&&E("Integration",u.integrationId),u.disconnected&&E("Status",
|
|
35
|
-
`);else{if(console.error(),E("ID",c.id),c.name&&E("Name",c.name),E("State",c.state),c.connectorId&&E("Connector",c.connectorId),c.integrationId&&E("Integration",c.integrationId),c.disconnected&&E("Status",
|
|
36
|
-
`):(console.error(),E("ID",c.id),c.name&&E("Name",c.name),E("State",c.state),console.error(
|
|
33
|
+
`);else{const u=c.items??[];if(u.length===0)console.error(h.gray(" No connections found."));else for(const p of u){const m=p.disconnected?h.red("disconnected"):h.green("connected");console.error(` ${h.cyan(p.id)} ${p.name||h.gray("(unnamed)")} ${m}`)}c.cursor&&console.error(h.gray(` Returned ${u.length} elements. Run with --cursor ${c.cursor} to get the next page.`)),console.error()}}catch(n){U(n)}}),e.command("get <id>").description("Get a connection by ID").option("--wait","Long-poll until connection is no longer in BUILDING state").option("--timeout <seconds>","Timeout in seconds for --wait (1-60, default 30)").option("--json","Output as JSON").action(async(t,n)=>{try{const i={...e.opts(),...n},s=new B(i),a=new URLSearchParams;n.wait&&(a.set("wait","true"),n.timeout&&a.set("timeout",n.timeout));const c=a.toString(),u=await s.get(`/connections/${encodeURIComponent(t)}${c?`?${c}`:""}`);if(i.json)process.stdout.write(JSON.stringify(u,null,2)+`
|
|
34
|
+
`);else{if(console.error(),E("ID",u.id),u.name&&E("Name",u.name),E("State",u.state),u.connectorId&&E("Connector",u.connectorId),u.integrationId&&E("Integration",u.integrationId),u.disconnected&&E("Status",h.red("disconnected")),u.clientAction){const p=u.clientAction;E("Action Required",p.type),p.description&&E("Description",p.description),p.uiUrl&&E("URL",p.uiUrl)}console.error()}}catch(r){U(r)}}),e.command("ensure <intent>").description('Find or create a connection (e.g. "Slack")').option("--name <name>","Custom connection name").option("--json","Output as JSON").action(async(t,n)=>{try{const i={...e.opts(),...n},s=new B(i),a={intent:t};n.name&&(a.name=n.name);const c=await s.post("/connections/ensure",a);if(i.json)process.stdout.write(JSON.stringify(c,null,2)+`
|
|
35
|
+
`);else{if(console.error(),E("ID",c.id),c.name&&E("Name",c.name),E("State",c.state),c.connectorId&&E("Connector",c.connectorId),c.integrationId&&E("Integration",c.integrationId),c.disconnected&&E("Status",h.red("disconnected")),c.clientAction){const u=c.clientAction;E("Action Required",u.type),u.description&&E("Description",u.description),u.uiUrl&&E("URL",u.uiUrl)}console.error()}}catch(r){U(r)}}),e.command("create [intent]").description('Create a new connection (e.g. "Connect to Slack")').option("--name <name>","Custom connection name").option("--data <json>",`Additional fields as JSON (e.g. '{"connectorId":"..."}')`).option("--json","Output as JSON").action(async(t,n)=>{try{const i={...e.opts(),...n},s=new B(i),a={...n.data?JSON.parse(n.data):{}};t&&(a.intent=t),n.name&&(a.name=n.name);const c=await s.post("/connections",a);i.json?process.stdout.write(JSON.stringify(c,null,2)+`
|
|
36
|
+
`):(console.error(),E("ID",c.id),c.name&&E("Name",c.name),E("State",c.state),console.error(h.gray(" Use `connection get <id> --wait --json` to poll until ready.")),console.error())}catch(r){U(r)}})}l(Di,"setupConnectionCommand");async function jt(o,e,t={}){const{jobId:n,accessKey:r}=await e(),i=`${n}:${r}`;g.debug(`[background-job] Started job ${n}`);const s=Date.now(),{pollIntervalMs:a=1e3,timeoutMs:c=3e5,maxRetries:u=3}=t;let p=0;for(;;){if(Date.now()-s>c)throw new Error(`Background job ${n} timed out after ${c}ms`);await new Promise(y=>setTimeout(y,a));let f;try{f=await o.get(`background-jobs/${i}`),p=0}catch(y){if(y instanceof Po&&p<u){p++,g.debug(`[background-job] Job ${n} not found, retrying (${p}/${u})`);continue}throw y}if(f.status==="completed"){if(g.debug(`[background-job] Completed job ${n}`),!f.result)throw new Error(`Background job ${n} completed but returned no result`);return f.result}if(f.status==="failed"){const y=f.error?.message||"Unknown error";throw g.error(`[background-job] Failed job ${n}: ${y}`),f.error?.stack&&g.error(`Stacktrace: ${f.error.stack}`),new Error(`Background job ${n} failed: ${y}`)}g.debug(`[background-job] Polling job ${n} (status: ${f.status})`)}}l(jt,"pollBackgroundJob");const _n=1e3,qn=12e4;async function Bn(){const o=await O.withClient(async t=>jt(t,()=>t.get("export"),{pollIntervalMs:_n,timeoutMs:qn}));if(!o)throw new Error("Failed to export workspace");const e=await Ee.get(o.downloadUrl,{responseType:"arraybuffer"});return Buffer.from(e.data)}l(Bn,"downloadWorkspaceExport");async function Jn(o,e={}){const t=new dn;t.append("file",o,{filename:"membrane.zip",contentType:"application/zip"});const n=await O.withClient(async i=>{const s=`import?dryRun=${e.dryRun??!1}&partial=${e.partial??!1}`,{jobId:a,accessKey:c}=await i.post(s,t,{headers:t.getHeaders()});return jt(i,()=>Promise.resolve({jobId:a,accessKey:c}),{pollIntervalMs:1e3,timeoutMs:3e5})});if(!n)throw new Error("Failed to import workspace");return await O.isVersionAtLeast("1.10")?{create:new Set(n.comparison.create||[]),update:new Set(n.comparison.update||[]),delete:new Set(n.comparison.delete||[])}:{create:new Set(n.create||[]),update:new Set(n.update||[]),delete:new Set(n.delete||[])}}l(Jn,"importWorkspace");async function Li(o,e){const t=await O.withClient(async r=>jt(r,()=>r.get(`connectors/${o}/export-files`,{version:e}),{pollIntervalMs:_n,timeoutMs:qn}));if(!t)throw new Error("Failed to export connector version");const n=await Ee.get(t.downloadUrl,{responseType:"arraybuffer"});return Buffer.from(n.data)}l(Li,"exportConnector");function Wn(o,e){Pe(k.dirname(o)),T.writeFileSync(o,e)}l(Wn,"writeFile");function ji(o){T.existsSync(o)&&T.rmSync(o)}l(ji,"deleteFile");function Mt(o){T.existsSync(o)&&T.rmSync(o,{recursive:!0,force:!0})}l(Mt,"deleteDir");function Mi(o,e=!0){if(T.existsSync(o))try{const t=T.readFileSync(o,"utf8");return Y.load(t)||void 0}catch(t){if(!e)return;if(t instanceof Error){const n=k.relative(process.cwd(),o);throw new Error(`Failed to parse YAML file "${n}": ${t.message}`)}throw t}}l(Mi,"readYaml");function zn(o,e,t){try{Pe(k.dirname(o));const n=Y.dump(e,t);T.writeFileSync(o,n,"utf8")}catch(n){if(n instanceof Error){const r=k.relative(process.cwd(),o);throw new Error(`Failed to write YAML file "${r}": ${n.message}`)}throw n}return e}l(zn,"writeYaml");function Pe(o){T.existsSync(o)||T.mkdirSync(o,{recursive:!0})}l(Pe,"ensureDirExists");function Gn(o,e=!0){if(!T.existsSync(o)||!T.statSync(o).isDirectory())return;let t=T.readdirSync(o);t.length>0&&(t.forEach(n=>Gn(k.join(o,n),!1)),t=T.readdirSync(o)),t.length===0&&!e&&T.rmdirSync(o)}l(Gn,"cleanupEmptyFolders");function Fi(o){const e=o.split(/[\\/]/).join("/");return e.endsWith("/")?e+"**":e}l(Fi,"normalizePattern");async function Hn(o,e,t){const n=(e??[]).map(Fi),r=[];if(t){const i=k.join(W(process.cwd()),"connectors");for(const s of Object.values(t)){const a=s.key,c=k.join(i,a),u=k.join(c,`${a}.yml`);T.existsSync(u)&&r.push({name:No(a),content:T.readFileSync(u,"utf-8")});const p=[...s.versions];T.existsSync(k.join(c,"development"))&&!p.includes("")&&p.push("");for(const m of p){const f=m===""?"development":m,y=k.join(c,f,"src"),I=k.join(c,f,"src.zip"),S=m===""?Xe:m;T.existsSync(y)?r.push({name:tn(a,S),content:await Ui(y)}):T.existsSync(I)&&r.push({name:tn(a,S),content:T.readFileSync(I)})}}}return new Promise((i,s)=>{const a=ut("zip",{zlib:{level:9}}),c=[];a.on("data",p=>c.push(p)),a.on("end",()=>i(Buffer.concat(c))),a.on("error",p=>s(p));const u=new Map;for(const p of o[x.Integration]||[])u.set(p.uuid,p.key);for(const[p,m]of Object.entries(o))for(const f of m){const y=u.get(f.integrationUuid),I=Ro(p,f.key,y);n.length>0&&!n.some(S=>or(I,S))||a.append(Y.dump(f),{name:I})}for(const{name:p,content:m}of r)a.append(m,{name:p});a.finalize()})}l(Hn,"createMembraneZip");async function Ui(o){return new Promise((e,t)=>{const n=ut("zip",{zlib:{level:9}}),r=[];n.on("data",i=>r.push(i)),n.on("end",()=>e(Buffer.concat(r))),n.on("error",i=>t(i)),n.directory(o,!1),n.finalize()})}l(Ui,"createConnectorVersionZip");async function Ft(o,e){const t=await fn.loadAsync(o),n=[];for(const[r,i]of Object.entries(t.files)){if(i.dir)continue;const s=de(r);if(!s)continue;const a=await i.async("string"),c=Y.load(a);if(!c)continue;const u=await e(r,c,s);u!==void 0&&n.push(u)}return n}l(Ft,"iterateZipItems");async function Vn(o){const e=await fn.loadAsync(o),t={};for(const[n,r]of Object.entries(e.files)){if(r.dir)continue;const i=de(n);if(!i)continue;const s=await r.async("string"),a=Y.load(s);t[i.type]||(t[i.type]=[]),t[i.type].push(a)}return t}l(Vn,"readMembraneZip");async function Ut(o=process.cwd()){const e=await Yn(W(o)),t={};for(const{data:n,type:r}of e)t[r]||(t[r]=[]),t[r].push(n);return t}l(Ut,"readMembraneDir");async function Yn(o){const e=Zn(o),t=[];for(const n of e){if(n.isDirectory())continue;const r=de(n.path);if(!r)continue;const i=await n.readContent(),s=Y.load(i),a=k.join(o,n.path);t.push({filePath:a,data:s,type:r.type})}return t}l(Yn,"iterateMembraneFiles");function Zn(o,e){const t=[];if(e||(e=o),!T.existsSync(e)||e.startsWith(k.join(o,"connectors")))return t;const n=T.readdirSync(e,{withFileTypes:!0});for(const r of n){const i=k.join(e,r.name),s=k.relative(o,i);r.isDirectory()?t.push(...Zn(o,i)):r.isFile()&&de(s)&&t.push({path:s,isDirectory:l(()=>!1,"isDirectory"),readContent:l(async()=>T.readFileSync(i,"utf8"),"readContent")})}return t}l(Zn,"getMembraneFiles");function Xn(){const o={},e=k.join(W(process.cwd()),"connectors");if(!T.existsSync(e))return o;const t=T.readdirSync(e);for(const n of t){const r=k.join(e,n);if(!T.statSync(r).isDirectory())continue;const i=k.join(r,`${n}.yml`),s=Mi(i,!1);if(!s?.uuid)continue;const a=new Set,c=T.readdirSync(r);for(const u of c){if(u.endsWith(".yml"))continue;const p=k.join(r,u);T.statSync(p).isDirectory()&&a.add(u=="development"?"":u)}o[s.uuid]={key:n,id:s.id,versions:Array.from(a)}}return o}l(Xn,"readConnectorsDir");function Ne(o,e){const t=k.join(W(process.cwd()),"connectors",o);return e==""||e===Xe?k.join(t,"development"):e?k.join(t,e):t}l(Ne,"getConnectorPath");function Ki(o){o.command("diff").description("Show what would change on push without applying anything").action(async()=>{const e=Se({text:"Comparing workspace",color:"white",discardStdin:!1}).start();try{const t=await Ut();e.text="Downloading remote workspace";const n=await Bn(),r=await Vn(n);e.stop();const{changes:i,diff:s}=nn(r,t,{includeDiff:!0}),a=Object.keys(i).length;if(a===0){b.info("No changes detected");return}b.info(`\u25CF Diff \xB7 ${a} change(s)
|
|
37
37
|
`),s&&b.info(_i(s))}catch(t){e.stop(),b.error("\u25A0 Error"),b.error(`\u2514\u2500\u2500 ${t.message}`),process.exit(1)}})}l(Ki,"setupDiffCommand");function _i(o){return o.split(`
|
|
38
|
-
`).map(e=>e.startsWith("diff ")?
|
|
39
|
-
`)}l(_i,"colorizePatch");var Re=(o=>(o[o.Authenticate=0]="Authenticate",o[o.ConnectWorkspace=1]="ConnectWorkspace",o))(Re||{});const qi={0:"Authenticate in Membrane",1:"Connect a Membrane Workspace"};function Bi({currentPat:o,onSubmit:e}){const[t,n]=L(""),[r,i]=L(!1),[s,a]=L(null),c=
|
|
40
|
-
`)).action(t=>{t.key&&t.secret?fe.saveToFile({workspaceKey:t.key,workspaceSecret:t.secret})?(console.error("\u2705 Configuration saved to membrane.config.yml"),process.exit(0)):(console.error("Error writing configuration file"),process.exit(1)):t.key||t.secret?(console.error("Error: Both --key and --secret must be provided for non-interactive mode"),process.exit(1)):rt(
|
|
41
|
-
`)).action(async t=>{try{if(t.apiUri=t.apiUri.replace(/\/+$/,""),!!!(process.stdin.isTTY&&!t.nonInteractive)){await no(t);return}b.header("Logging in to Membrane");const r=t.tenant?
|
|
38
|
+
`).map(e=>e.startsWith("diff ")?h.bold(e):e.startsWith("index ")||e.startsWith("===")?h.dim(e):e.startsWith("---")?h.bold.red(e):e.startsWith("+++")?h.bold.green(e):e.startsWith("@@")?h.cyan(e):e.startsWith("+")?h.green(e):e.startsWith("-")?h.red(e):e).join(`
|
|
39
|
+
`)}l(_i,"colorizePatch");var Re=(o=>(o[o.Authenticate=0]="Authenticate",o[o.ConnectWorkspace=1]="ConnectWorkspace",o))(Re||{});const qi={0:"Authenticate in Membrane",1:"Connect a Membrane Workspace"};function Bi({currentPat:o,onSubmit:e}){const[t,n]=L(""),[r,i]=L(!1),[s,a]=L(null),c=ht(`/w/0/${Do}`);return v(w,{flexDirection:"column",borderStyle:"round",borderTop:!0,width:70,paddingX:1,children:[d(w,{marginTop:-1,marginBottom:1,children:d(C,{bold:!0,children:"\u{1F511} Enter your Personal Access Token"})}),d(C,{children:"Please provide your Personal Access Token. You can find it here:"}),d(w,{marginTop:1,marginBottom:1,children:d(C,{color:"yellow",children:c})}),o&&d(C,{dimColor:!0,children:"Press Enter to keep your current token or type a new one."}),d(ln,{mask:"*",placeholder:`${o?"******":"Enter your token here..."}`,value:t,onChange:n,onSubmit:l(async p=>{a(null),i(!0);try{await e(p),n("")}catch{a("Invalid token. Please try again.")}finally{i(!1)}},"handleSubmit")}),r&&d(w,{marginTop:1,children:v(C,{children:[d(qe,{type:"dots"})," Validating token..."]})}),s&&d(C,{color:"red",children:s})]})}l(Bi,"PersonalAccessTokenInput");function Qn({onExit:o,showEscOption:e=!0}){const[t,n]=L(""),{data:r,error:i,isLoading:s}=un("/account"),{updateConfig:a}=Z(),c=r?.workspaces,u=s;if(pe((S,R)=>{R.escape&&o?.()}),u)return v(w,{children:[d(qe,{}),d(C,{children:" Fetching workspaces..."})]});if(i)return v(w,{flexDirection:"column",children:[v(C,{color:"red",children:["Error: ",i.message]}),d(w,{marginTop:1,children:d(C,{color:"grey",children:"Press ESC to go back"})})]});const p=c?.filter(S=>S.name.toLowerCase().includes(t.toLowerCase()))??[],m=p.map(S=>({label:S.name,value:S.id})),f=m.length,y=c?.length??0;async function I(S){const R=p.find(K=>K.id===S);if(!R)return;const{key:N,secret:M}=R;!N||!M||(await a({workspaceKey:N,workspaceSecret:M}),o?.())}return l(I,"handleSelect"),v(w,{flexDirection:"column",borderStyle:"round",borderTop:!0,width:70,paddingX:1,children:[d(w,{marginTop:-1,children:d(C,{bold:!0,children:"\u{1F4C1} Select your workspace"})}),v(w,{marginTop:1,children:[d(C,{children:"Search: "}),d(rr,{placeholder:"Enter a search query...",onChange:n})]}),y>5&&v(C,{children:["Showing ",f," of ",y," workspaces."]}),d(w,{marginTop:1,children:d(ir,{options:m,onChange:l(S=>{S&&I(S)},"onChange")})}),e&&d(w,{marginTop:1,children:d(C,{color:"grey",children:"Press ESC to go back"})})]})}l(Qn,"SelectWorkspace");const Kt=[Re.Authenticate,Re.ConnectWorkspace];function eo({onComplete:o}){const{config:e}=Z(),[t,n]=L(!1),[r,i]=L(0),s=!!(e?.workspaceKey&&e?.workspaceSecret),a=Cn(),c=Kt[r],u=r+1,p=Kt.length,m=Kt.map((I,S)=>{let R="pending";return S<r?R="done":S===r&&(R="current"),{id:I,label:qi[I],status:R}});async function f(I){const S=a&&I===""?a:I,R=new Oe;try{await R.request("/account",{headers:{Authorization:`Bearer ${S}`}}),wr(S),i(N=>N+1)}catch(N){console.error(N)}}l(f,"handlePatSubmit");function y(){n(!0),o&&o()}return l(y,"handleWorkspaceSelected"),pe((I,S)=>{s&&S.escape&&o&&o()}),t?d(w,{children:d(C,{children:"\u2705 Setup complete. You are ready to go!"})}):v(w,{flexDirection:"column",alignSelf:"flex-start",gap:1,children:[v(w,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:70,children:[d(w,{marginTop:-1,marginBottom:1,children:v(C,{bold:!0,children:["\u{1F6E0}\uFE0F Setup \u2014"," ",v(C,{color:"cyan",children:["Step ",u," of ",p]}),s&&d(C,{color:"grey",children:" [esc: go back]"})]})}),d(w,{flexDirection:"column",paddingLeft:2,children:m.map(I=>d(Ji,{status:I.status,label:I.label},I.id))})]}),c===Re.Authenticate&&d(Bi,{currentPat:a,onSubmit:f}),c===Re.ConnectWorkspace&&d(Qn,{onExit:y,showEscOption:!1})]})}l(eo,"Setup");function Ji({status:o,label:e}){return v(w,{children:[v(w,{width:2,children:[o==="current"&&d(qe,{type:"dots"}),o==="done"&&d(C,{children:"\u2705"})]}),d(C,{dimColor:o!=="current",children:e})]})}l(Ji,"StepDisplay");function Wi(o,e){o.command("init").description("Run interactive setup for Membrane project").option("--key <key>","Workspace key for non-interactive setup").option("--secret <secret>","Workspace secret for non-interactive setup").addHelpText("after",["","Examples:"," membrane init # Run interactive setup"," membrane init --key KEY --secret SEC # Non-interactive setup with key and secret",""].join(`
|
|
40
|
+
`)).action(async t=>{t.key&&t.secret?fe.saveToFile({workspaceKey:t.key,workspaceSecret:t.secret})?(console.error("\u2705 Configuration saved to membrane.config.yml"),process.exit(0)):(console.error("Error writing configuration file"),process.exit(1)):t.key||t.secret?(console.error("Error: Both --key and --secret must be provided for non-interactive mode"),process.exit(1)):(await rt(he.createElement(Dt,{membraneCLIService:e,children:he.createElement(eo,{onComplete:l(()=>process.exit(0),"onComplete")})})).waitUntilExit(),process.exit(0))})}l(Wi,"setupInitCommand");function zi(o){const e=o.command("login").description("Log in to Membrane").option("--apiUri <uri>","API base URI",te).option("--non-interactive","Print the authorization URL instead of opening a browser").option("--tenant","Log in with tenant-scoped tokens (for workspace/tenant-level access)",!1).addHelpText("after",["","Examples:"," membrane login # Interactive browser login"," membrane login --tenant # Interactive browser login with tenant scope"," membrane login start # Non-interactive: get auth URL"," membrane login complete <code> # Non-interactive: complete with code",""].join(`
|
|
41
|
+
`)).action(async t=>{try{if(t.apiUri=t.apiUri.replace(/\/+$/,""),!!!(process.stdin.isTTY&&!t.nonInteractive)){await no(t);return}b.header("Logging in to Membrane");const r=t.tenant?on:rn,i=await Vi(t.apiUri,r);to(i,t),b.success("Authentication successful!"),process.exit(0)}catch(n){U(n)}});e.command("start").description("Start non-interactive login (outputs auth URL)").action(async()=>{try{const t=e.opts();await no(t)}catch(t){U(t)}}),e.command("complete <code>").description("Complete login with an authorization code from the consent page").action(async t=>{try{await Hi(t)}catch(n){U(n)}})}l(zi,"setupLoginCommand");function to(o,e){Cr(),Sn(o.accessToken,o.refreshToken,o.expiresIn),bn(e.apiUri),vr(e.tenant?"tenant":"platform-user"),o.defaultWorkspaceKey&&gr({defaultWorkspaceKey:o.defaultWorkspaceKey,defaultTenantKey:o.defaultTenantKey})}l(to,"storeTokens");async function no(o){b.header("Starting non-interactive login");const e=o.tenant?on:rn,{consentUrl:t,codeVerifier:n,clientId:r}=await Gi(o.apiUri,e);bn(o.apiUri),Tr({scope:o.tenant?"tenant":"platform-user",codeVerifier:n,clientId:r}),console.info(),b.info("Open this URL in your browser to authorize:"),console.info(` ${t}`),console.info(),b.info("After approving, copy the authorization code and run:"),console.info(" membrane login complete <code>"),console.info(),process.exit(0)}l(no,"performLoginStart");async function Gi(o,e){const t=oo(),n=ro(t),r=Me,i=new URLSearchParams({response_type:"code",client_id:r,code_challenge:n,code_challenge_method:"S256",scope:e,show_code:"true"}),s=`${o}/oauth/authorize?${i}`,c=(await fetch(s,{redirect:"manual"})).headers.get("location");if(!c)throw new Error("No redirect from authorization endpoint");return{consentUrl:c,codeVerifier:t,clientId:r}}l(Gi,"prepareNonInteractiveLogin");async function Hi(o){const e=me()||te,t=Er();if(!t){b.error("No pending login found. Run `membrane login start` first."),process.exit(1);return}b.header("Completing login");const n=Se({text:"Exchanging authorization code...",discardStdin:!1}).start();try{const r=await fetch(`${e}/oauth/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({grant_type:"authorization_code",code:o,client_id:t.clientId,code_verifier:t.codeVerifier})});if(r.ok){const i=await r.json(),s=_t(i);n.stop(),to(s,{apiUri:e,nonInteractive:!1,tenant:t.scope==="tenant"}),$e(),b.success("Authentication successful!"),process.exit(0);return}n.stop(),$e(),b.error("Invalid authorization code. Make sure you copied the full code from the consent page.")}catch(r){n.stop(),$e();const i=r instanceof Error?r.message:String(r);b.error(`Login failed: ${i}`)}b.info("To start the login flow, run: membrane login start"),process.exit(1)}l(Hi,"performLoginComplete");async function Vi(o,e){const t=oo(),n=ro(t),{port:r,waitForCode:i,state:s,server:a}=await Yi(),c=`http://127.0.0.1:${r}/callback`,u=new URLSearchParams({response_type:"code",client_id:Me,redirect_uri:c,code_challenge:n,code_challenge_method:"S256",scope:e,state:s}),p=`${o}/oauth/authorize?${u}`,f=(await fetch(p,{redirect:"manual"})).headers.get("location");if(!f)throw a.close(),new Error("No redirect from authorization endpoint");const y=new URL(f).searchParams.get("authorizationId");if(!y)throw a.close(),new Error("No authorizationId in authorization redirect");try{const{default:K}=await import("open");await K(f),b.info("Opening browser for authentication...")}catch{b.info("Could not open browser automatically.")}console.error(` If the browser doesn't open, visit:
|
|
42
42
|
${f}
|
|
43
|
-
`);const I=Se("Waiting for authorization...").start(),S=new AbortController,R=l(()=>{S.abort(),I.stop(),a.closeAllConnections(),a.close(),process.exit(130)},"onSigint");process.once("SIGINT",R);const N=i.then(async K=>{I.text="Exchanging authorization code...";const F=await fetch(`${o}/oauth/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({grant_type:"authorization_code",code:K,redirect_uri:c,client_id:Me,code_verifier:t})});if(!F.ok)throw new Error(`Token exchange failed: ${F.status} ${await F.text()}`);return _t(await F.json())}),
|
|
44
|
-
`)).action(async()=>{try{process.env.FASTMCP_SUPPRESS_WARNINGS="true";const e=xe(),t=process.env.MEMBRANE_ACCESS_TOKEN||e?.accessToken,n=process.env.MEMBRANE_WORKSPACE_KEY||e?.workspaceKey,r=process.env.MEMBRANE_WORKSPACE_SECRET||e?.workspaceSecret,i=process.env.MEMBRANE_TEST_CUSTOMER_ID||e?.testCustomerId,s=process.env.MEMBRANE_API_URI||e?.apiUri||me()||te;!t&&(!n||!r)&&(e||(console.error("No configuration found. Please set MEMBRANE_ACCESS_TOKEN, or MEMBRANE_WORKSPACE_KEY and MEMBRANE_WORKSPACE_SECRET environment variables, or run `membrane init` first to create a configuration file."),process.exit(1)),console.error("Missing credentials. Please provide MEMBRANE_ACCESS_TOKEN or workspace key/secret in the configuration file, command line, or environment variables."),process.exit(1));const a=t||await ns(n,r,i),c=await os(s,a),u=is(c,s,a),
|
|
43
|
+
`);const I=Se({text:"Waiting for authorization...",discardStdin:!1}).start(),S=new AbortController,R=l(()=>{S.abort(),I.stop(),a.closeAllConnections(),a.close(),process.exit(130)},"onSigint");process.once("SIGINT",R);const N=i.then(async K=>{I.text="Exchanging authorization code...";const F=await fetch(`${o}/oauth/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({grant_type:"authorization_code",code:K,redirect_uri:c,client_id:Me,code_verifier:t})});if(!F.ok)throw new Error(`Token exchange failed: ${F.status} ${await F.text()}`);return _t(await F.json())}),M=Qi(o,y,t,S.signal);M.catch(()=>{});try{const K=await Promise.race([N,M]);return S.abort(),I.stop(),process.removeListener("SIGINT",R),K}finally{a.closeAllConnections(),a.close()}}l(Vi,"performInteractiveLogin");function oo(){return pn(32).toString("base64url")}l(oo,"generateCodeVerifier");function ro(o){return nr("sha256").update(o).digest("base64url")}l(ro,"generateCodeChallenge");function _t(o){if(!o.refresh_token)throw new Error("Server did not return a refresh token. The server may be misconfigured.");return{accessToken:o.access_token,refreshToken:o.refresh_token,expiresIn:o.expires_in,defaultWorkspaceKey:o.default_workspace_key,defaultTenantKey:o.default_tenant_key}}l(_t,"parseTokenResponse");function Yi(){const o=pn(16).toString("base64url");return new Promise(e=>{let t,n;const r=new Promise((s,a)=>{t=s,n=a}),i=hn((s,a)=>{const c=new URL(s.url??"/","http://127.0.0.1");if(c.pathname!=="/callback"){a.writeHead(404),a.end("Not found");return}if(c.searchParams.get("error")){const f=c.searchParams.get("error_description")??"Authorization was denied";a.writeHead(200,{"Content-Type":"text/html"}),a.end(ce("Authorization failed",f,"#f87171")),n(new Error(f));return}const p=c.searchParams.get("code");if(c.searchParams.get("state")!==o){a.writeHead(200,{"Content-Type":"text/html"}),a.end(ce("Authorization failed","State mismatch \u2014 possible CSRF attack. Please try again.","#f87171")),n(new Error("State mismatch"));return}if(!p){a.writeHead(200,{"Content-Type":"text/html"}),a.end(ce("Authorization failed","No authorization code received.","#f87171")),n(new Error("No authorization code received"));return}a.writeHead(200,{"Content-Type":"text/html"}),a.end(ce("Authorization successful","You can close this tab and return to your terminal.")),t(p)});i.listen(0,"127.0.0.1",()=>{const s=i.address(),a=typeof s=="object"&&s?s.port:0;if(!a)throw new Error("Failed to bind local callback server");e({port:a,waitForCode:r,state:o,server:i})})})}l(Yi,"startCallbackServer");const Zi=900*1e3,Xi=5;async function Qi(o,e,t,n){const r=Date.now()+Zi;let i=Xi;for(;Date.now()<r;){n.throwIfAborted(),await Fn(i*1e3,n),n.throwIfAborted();const s=await fetch(`${o}/oauth/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({grant_type:"authorization_code",authorization_id:e,client_id:Me,code_verifier:t})});if(s.ok)return _t(await s.json());let a;try{a=await s.json()}catch{throw new Error(`Token request failed with status ${s.status}`)}const c=a.error??a.message??"";if(c!=="authorization_pending")if(c==="slow_down"){i+=5;continue}else throw c==="expired_token"?new Error("Authorization has expired. Please try again."):new Error(`Token exchange failed: ${s.status} ${c}`)}throw new Error("Authorization has expired. Please try again.")}l(Qi,"pollForTokens");function es(o){o.command("logout").description("Log out of Membrane and revoke tokens").option("--apiUri <uri>","API base URI").action(async e=>{try{yt()||(b.info("You are not logged in."),process.exit(0));const t=be(),n=e.apiUri||me()||te;if(t)try{const r=await fetch(`${n}/oauth/revoke`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:t})});r.ok||b.debug(`Server revocation returned ${r.status}`)}catch{b.warning("Could not reach server to revoke token. Local tokens cleared, but the session may still be active on the server. You can revoke it from the console.")}br(),b.success("Logged out successfully."),process.exit(0)}catch(t){t instanceof Error?b.error(t.message):b.error("An unknown error occurred"),process.exit(1)}})}l(es,"setupLogoutCommand");const ts=86400;async function ns(o,e,t,n){const r={iss:o,isAdmin:!0};return t&&(r.id=t),ct.sign(r,e,{expiresIn:ts})}l(ns,"generateMcpAccessToken");async function os(o,e){return(await Ee.get(`${o}/docs-json`,{headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}})).data}l(os,"fetchOpenApiSchema");function le(o,e=!0,t,n=new Set){if(!o)return e?D.string():D.string().optional();if(Object.keys(o).length===0)return e?D.any():D.any().optional();if(o.$ref){const i=o.$ref.replace("#/components/schemas/","");if(n.has(i))return D.any();if(n.add(i),t?.schemas?.[i]){const s=t.schemas[i];return le(s,e,t,n)}return D.any()}let r;if(o.type==="object"||o.properties){const i={};if(o.properties)for(const[s,a]of Object.entries(o.properties)){const c=o.required?.includes(s)??!1;i[s]=le(a,c,t,n)}if(Object.keys(i).length>0){if(r=D.object(i),o.additionalProperties)if(typeof o.additionalProperties=="object"){const s=le(o.additionalProperties,!1,t,n);r=r.catchall(s)}else o.additionalProperties===!0&&(r=r.passthrough())}else if(o.additionalProperties&&typeof o.additionalProperties=="object"){const s=le(o.additionalProperties,!1,t,n);r=D.record(D.string(),s)}else r=D.record(D.string(),D.any())}else if(o.type==="array"){const i=o.items?le(o.items,!0,t,n):D.any();r=D.array(i)}else if(o.anyOf)r=D.any();else{switch(o.type){case"integer":r=D.coerce.number().int();break;case"number":r=D.coerce.number();break;case"boolean":r=D.coerce.boolean();break;case"string":default:r=D.string();break}o.format==="uuid"?r=D.string().uuid():o.format==="email"?r=D.string().email():o.format==="date"?r=D.string().regex(/^\d{4}-\d{2}-\d{2}$/):o.format==="date-time"&&(r=D.string().datetime()),o.enum&&(r=D.enum(o.enum)),(o.type==="integer"||o.type==="number")&&(o.minimum!==void 0&&(r=r.min(o.minimum)),o.maximum!==void 0&&(r=r.max(o.maximum))),o.type==="string"&&(o.minLength!==void 0&&(r=r.min(o.minLength)),o.maxLength!==void 0&&(r=r.max(o.maxLength)))}return e?r:r.optional()}l(le,"convertOpenApiSchemaToZod");function io(o){const e=o.match(/\{([^}]+)\}/g);return e?e.map(t=>t.slice(1,-1)):[]}l(io,"extractPathParameters");function rs(o,e,t,n,r,i){const s=o.operationId||`${t}_${e.replace(/[^a-zA-Z0-9]/g,"_")}`,a=o.description||o.summary||`${t.toUpperCase()} ${e}`,c={},u={},p={};if(o.parameters){for(const f of o.parameters)if(f.in==="path")u[f.name]=le(f.schema,!0,r).describe(f.description||`Path parameter: ${f.name}`);else if(f.in==="query"){const y=f.required===!0;p[f.name]=le(f.schema,y,r).describe(f.description||`Query parameter: ${f.name}`)}}if(Object.keys(u).length>0&&(c.params=D.object(u).describe("Path parameters")),Object.keys(p).length>0&&(c.query=D.object(p).describe("Query parameters")),o.requestBody&&o.requestBody.content){const f=o.requestBody.required===!0;if(o.requestBody.content["application/json"]){const y=o.requestBody.content["application/json"].schema;y?c.body=le(y,f,r).describe("Request body (JSON)"):c.body=D.any().describe("Request body (JSON)")}else o.requestBody.content["application/octet-stream"]||o.requestBody.content["text/plain"]?c.body=f?D.string().describe("Request body (binary/text)"):D.string().optional().describe("Request body (binary/text)"):c.body=D.any().describe("Request body")}const m=Object.keys(c).length>0?D.object(c):D.object({});return{name:s,description:a,parameters:m,async execute(f){try{const y=io(e);if(y.length>0){if(!f.params)throw new Error(`Missing required path parameters: ${y.join(", ")}`);const K=y.filter(F=>!(F in f.params));if(K.length>0)throw new Error(`Missing required path parameters: ${K.join(", ")}`)}let I=`${n}${e}`;if(f.params)for(const[K,F]of Object.entries(f.params)){const Le=`{${K}}`;I.includes(Le)&&(I=I.replace(Le,String(F)))}const S=io(I);if(S.length>0)throw new Error(`Unresolved path parameters: ${S.join(", ")}`);const R=new URLSearchParams;if(f.query)for(const[K,F]of Object.entries(f.query))F!=null&&R.append(K,String(F));R.toString()&&(I+=`?${R.toString()}`);const N={method:t.toUpperCase(),headers:{Authorization:`Bearer ${i}`}};f.body&&t.toLowerCase()!=="get"&&(o.requestBody?.content?.["application/json"]?(N.headers["Content-Type"]="application/json",N.data=f.body):o.requestBody?.content?.["application/octet-stream"]?(N.headers["Content-Type"]="application/octet-stream",N.data=f.body):o.requestBody?.content?.["text/plain"]?(N.headers["Content-Type"]="text/plain",N.data=f.body):(N.headers["Content-Type"]="application/json",N.data=f.body));const M=await Ee.request({url:I,...N});return{content:[{type:"text",text:M.data===""?"":JSON.stringify(M.data,null,2)}]}}catch(y){return Ee.isAxiosError(y)?{content:[{type:"text",text:`Error: ${y.response?.data?`HTTP ${y.response.status}: ${y.response.statusText} - ${JSON.stringify(y.response.data)}`:`HTTP ${y.response?.status||"unknown"}: ${y.message}`}`}],isError:!0}:y instanceof Error?{content:[{type:"text",text:`Error: API call failed: ${y.message}`}],isError:!0}:{content:[{type:"text",text:"Error: API call failed with unknown error"}],isError:!0}}}}}l(rs,"createApiTool");function is(o,e,t){const n=[];if(!o.paths)return n;const r=o.components||{};for(const[i,s]of Object.entries(o.paths))if(typeof s=="object"&&s!==null){for(const[a,c]of Object.entries(s))if(["get","post","put","delete","patch"].includes(a)&&c&&typeof c=="object"){const u=rs(c,i,a,e,r,t);n.push(u)}}return n}l(is,"convertOpenApiToTools");function ss(o){o.command("mcp").description("Launch MCP server with OpenAPI endpoints as tools (API URI is read from environment variables or membrane.config.yml)").addHelpText("after",["","Examples:"," membrane mcp # Launch MCP server using API URI from env vars or membrane.config.yml",""].join(`
|
|
44
|
+
`)).action(async()=>{try{process.env.FASTMCP_SUPPRESS_WARNINGS="true";const e=xe(),t=process.env.MEMBRANE_ACCESS_TOKEN||e?.accessToken,n=process.env.MEMBRANE_WORKSPACE_KEY||e?.workspaceKey,r=process.env.MEMBRANE_WORKSPACE_SECRET||e?.workspaceSecret,i=process.env.MEMBRANE_TEST_CUSTOMER_ID||e?.testCustomerId,s=process.env.MEMBRANE_API_URI||e?.apiUri||me()||te;!t&&(!n||!r)&&(e||(console.error("No configuration found. Please set MEMBRANE_ACCESS_TOKEN, or MEMBRANE_WORKSPACE_KEY and MEMBRANE_WORKSPACE_SECRET environment variables, or run `membrane init` first to create a configuration file."),process.exit(1)),console.error("Missing credentials. Please provide MEMBRANE_ACCESS_TOKEN or workspace key/secret in the configuration file, command line, or environment variables."),process.exit(1));const a=t||await ns(n,r,i),c=await os(s,a),u=is(c,s,a),p=new ar({name:"Membrane API",instructions:`This MCP server lets you interact with Membrane to configure, run, and troubleshoot integrations.
|
|
45
45
|
Use it for anything related to Membrane or integrations.
|
|
46
|
-
`,version:"1.0.0"});for(const y of u){const I=y.execute;y.execute=async S=>(Si(process.pid,process.cwd()),I(S)),
|
|
47
|
-
`)).action(async()=>{try{b.header("Opening Workspace in Browser"),b.info("Loading configuration...");const e=xe();if(!e)throw new Error("No configuration found. Please set MEMBRANE_WORKSPACE_KEY and MEMBRANE_WORKSPACE_SECRET environment variables, or run `membrane init` first.");if(!e.workspaceKey||!e.workspaceSecret)throw new Error("Missing workspace credentials");b.info("Retrieving workspace ID...");const t=await so(process.cwd()),n=
|
|
48
|
-
`)).action(async e=>{const t=Se({text:"Pulling workspace",color:"white"}).start();try{const n=await ls(e,t);t.stop(),fs(n.workspaceExport,n.connectors)}catch(n){t.stop(),gs(n),process.exit(1)}})}l(cs,"setupPullCommand");async function ls(o,e){const t=await Ut(),n=await Hn(t),r=await Bn(),i=await Vn(r),{comparison:s}=
|
|
49
|
-
`)).action(async(e,t)=>{const n=Se({text:"Pushing workspace",color:"white"}).start();try{await Ts(e,t,n)}catch(r){n.stop(),Ns(r),process.exit(1)}})}l(vs,"setupPushCommand");async function Ts(o,e,t){const n=o.length>0,r=await Ut(),i=Xn(),s=ks(r,i),a=await O.isVersionAtLeast("1.9"),c=await Hn(s,n?o:void 0,a?i:void 0);e.force||(t.text="Comparing workspace",await Is(c,n)&&(t.stop(),process.exit(1)));const u=a?Object.keys(i):await Es(t);t.start("Pushing workspace..."),await Jn(c,{partial:n}),t.stop(),As(s,u),process.exit(0)}l(Ts,"pushWorkspace");async function Is(o,e){const t=await Jn(o,{dryRun:!0,partial:e}),n=t[ee.DELETE].size>0;return n&&(await Ps(t,o),b.error("Use --force to delete remote elements")),n}l(Is,"checkForConflicts");async function Es(o){return(await Pn({onProgress:l((t,n)=>{t==="pushing"?o.start(`Pushing connector ${n}...`):o.succeed(`Pushed connector ${n}`)},"onProgress")})).pushedConnectors??[]}l(Es,"pushConnectorsLegacy");function ks(o,e){const t=$s(o),n=Os(t,e),r={};for(const[i,s]of Object.entries(t)){const a=i;r[a]=(s||[]).map(c=>xs(c,a,n))}return r}l(ks,"resolveLegacyIdReferences");function xs(o,e,t){const n={...o},r=Q[e]?.parentFieldKey||"parentId";if(n.integrationId&&!n.integrationUuid&&(n.integrationUuid=t.get(n.integrationId.toString())||n.integrationId,delete n.integrationId),n.connectorId){if(!n.connectorUuid){const i=t.get(n.connectorId.toString());i&&(n.connectorUuid=i)}delete n.connectorId}if(n[r]){const i=t.get(n[r].toString());i&&(n.parentUuid=i)}return e===x.Package&&n.elements&&(n.elements=n.elements.map(i=>{if(i.id&&!i.uuid){const s=t.get(i.id.toString());if(s)return{uuid:s,type:i.type}}return i})),delete n.id,n}l(xs,"resolveElementIds");function $s(o){const e={};for(const[t,n]of Object.entries(o))e[t]=(n||[]).map(r=>r.uuid?r:{...r,uuid:bs()});return e}l($s,"generateMissingUuids");function Os(o,e){const t=new Map;for(const n of Object.values(o))for(const r of n||[])r.id&&r.uuid&&t.set(r.id.toString(),r.uuid);for(const[n,r]of Object.entries(e))r.id&&t.set(r.id.toString(),n);return t}l(Os,"buildIdToUuidLookup");function As(o,e=[]){const t=Object.values(o).reduce((n,r)=>n+(r?.length??0),0)+e.length;b.info(`\u25CF Pushed workspace elements \xB7 ${t}`);for(const n of Object.keys(o).sort()){const r=o[n];b.info(`\u2514\u2500\u2500 ${n}s \xB7 ${r?.length??0}`)}e.length>0&&b.info(`\u2514\u2500\u2500 connectors \xB7 ${e.length}`)}l(As,"showStats");async function Ps(o,e){const t=o[ee.DELETE].size;b.info(`\u2299 Push: conflicts detected \xB7 ${t}`),await Ft(e,(n,r)=>{de(n)&&o[ee.DELETE].has(r.uuid)&&b.info(`\u2514\u2500\u2500 ./membrane/${n} (deleted locally)`)})}l(Ps,"showConflicts");function Ns(o){b.error("\u25A0 Error"),b.error(`\u2514\u2500\u2500 ${o.message}`),b.error(` ${o.stack}`)}l(Ns,"showError");const lo=new Set(Object.values(
|
|
46
|
+
`,version:"1.0.0"});for(const y of u){const I=y.execute;y.execute=async S=>(Si(process.pid,process.cwd()),I(S)),p.addTool(y)}Pt({isRunning:!0,startTime:new Date().toISOString(),toolsCount:u.length,lastActivity:new Date().toISOString(),processId:process.pid,cwd:process.cwd(),agentName:process.env.AGENT_NAME||"Unnamed Agent"});const m=setInterval(()=>{Pt({processId:process.pid,cwd:process.cwd(),lastActivity:new Date().toISOString()})},5e3),f=l(async()=>{clearInterval(m),Ae(process.pid,process.cwd());try{await p.stop()}catch{}},"cleanup");await p.start({transportType:"stdio"}),process.on("SIGINT",async()=>{await f(),process.exit(0)}),process.on("SIGTERM",async()=>{await f(),process.exit(0)}),process.on("exit",()=>{Ae(process.pid,process.cwd())}),process.on("uncaughtException",async y=>{console.error("Uncaught exception:",y.message),await f(),process.exit(1)}),process.on("unhandledRejection",async y=>{console.error("Unhandled rejection:",y),await f(),process.exit(1)})}catch(e){e instanceof Error&&(console.error(e.message),process.exit(1)),console.error("An unknown error occurred"),process.exit(1)}})}l(ss,"setupMcpCommand");async function so(o){const e=await O.withClient(t=>t.get("org-workspace-id"),!0,o);if(!e)throw new Error("Failed to get workspace ID");return e.id}l(so,"getWorkspaceId");function as(o){o.command("open").description("Open the workspace in the browser").addHelpText("after",["","Examples:"," membrane open # Open workspace in browser",""].join(`
|
|
47
|
+
`)).action(async()=>{try{b.header("Opening Workspace in Browser"),b.info("Loading configuration...");const e=xe();if(!e)throw new Error("No configuration found. Please set MEMBRANE_WORKSPACE_KEY and MEMBRANE_WORKSPACE_SECRET environment variables, or run `membrane init` first.");if(!e.workspaceKey||!e.workspaceSecret)throw new Error("Missing workspace credentials");b.info("Retrieving workspace ID...");const t=await so(process.cwd()),n=ht(`/w/${t}`);b.info(`Opening ${n}...`);const{default:r}=await import("open");await r(n),b.success("Browser opened successfully")}catch(e){e instanceof Error&&(b.error(e.message),process.exit(1)),b.error("An unknown error occurred"),process.exit(1)}})}l(as,"setupOpenCommand");const ao=5;function cs(o){o.command("pull").description("Pull workspace data from specified workspace").option("--force","Overwrite conflicts with remote data",!1).addHelpText("after",["","Examples:"," membrane pull # Pull from default workspace"," membrane pull --force # Overwrite conflicts with remote data",""].join(`
|
|
48
|
+
`)).action(async e=>{const t=Se({text:"Pulling workspace",color:"white",discardStdin:!1}).start();try{const n=await ls(e,t);t.stop(),fs(n.workspaceExport,n.connectors)}catch(n){t.stop(),gs(n),process.exit(1)}})}l(cs,"setupPullCommand");async function ls(o,e){const t=await Ut(),n=await Hn(t),r=await Bn(),i=await Vn(r),{comparison:s}=nn(t,i);s[ee.DELETE].size>0&&!o.force&&(await ms(s,n),b.error("Use --force to delete local elements"),process.exit(1));const c=await Yn(W(process.cwd()));for(const{filePath:m,data:f}of c)s[ee.DELETE].has(f.uuid)&&ji(m);return Gn(W(process.cwd())),await Ft(r,(m,f)=>{if(de(m)&&(s[ee.CREATE].has(f.uuid)||s[ee.UPDATE].has(f.uuid))){const I=$.join(W(process.cwd()),m);zn(I,f)}}),{connectors:await O.isVersionAtLeast("1.8")?await us(r,e):await ps(i[x.Integration],e),workspaceExport:i}}l(ls,"pullWorkspace");async function us(o,e){e.text="Extracting connectors",Mt($.join(W(process.cwd()),"connectors"));const t=new Set,n=await _e.Open.buffer(o);for(const r of n.files){if(!r.path.startsWith("connectors/")||r.type==="Directory")continue;const i=$.join(W(process.cwd()),r.path);Pe($.dirname(i));const s=await r.buffer();if(Wn(i,s),t.add(r.path.split("/")[1]),r.path.endsWith("/development/src.zip")){const a=$.join($.dirname(i),"src");Pe(a),await(await _e.Open.buffer(s)).extract({path:a})}}return Array.from(t)}l(us,"extractConnectorsFromExport");async function ds(o,e,t){if(Wn($.join(Ne(o,e),"src.zip"),t),!e||e===Xe){const n=$.join(Ne(o,e),"src");Pe(n),await(await _e.Open.buffer(t)).extract({path:n})}}l(ds,"writeConnectorVersion");async function ps(o,e){e.text="Pulling connectors";const t=new Map,{id:n}=await O.withClient(c=>c.get("org-workspace-id")),{items:r=[]}=await O.withClient(c=>c.get(`/connectors?workspaceId=${n}`));for(const c of r){const u=c.uuid??c.id;!c.isPublic&&u&&t.set(u,new Set([""]))}for(const c of o??[]){const{connectorUuid:u,connectorVersion:p}=c;u&&(t.has(u)||t.set(u,new Set),t.get(u).add(p??""))}const i=Xn();for(const[c,{key:u,versions:p}]of Object.entries(i)){if(!t.has(c)){const f=Ne(u);Mt(f);continue}const m=t.get(c);for(const f of p)if(!m.has(f)){const y=Ne(u,f);Mt(y)}}const s=Array.from(t.entries()),a=l((c,u)=>{c==="pulling"?e.start(`Pulling connector ${u}...`):e.succeed(`Pulled connector ${u}`)},"onProgress");for(let c=0;c<s.length;c+=ao){const u=s.slice(c,c+ao);await Promise.all(u.map(([p,m])=>hs(p,Array.from(m),a)))}return Array.from(t.keys())}l(ps,"pullConnectorsLegacy");async function hs(o,e,t){const n=await O.withClient(u=>u.get(`connectors/${o}/export-json`),!1),r=await O.withClient(u=>u.get(`connectors/${o}`),!1);if(!n||!r||!n.key||!r.key)return;const i=r.name||n.key;t?.("pulling",i);const s={...n,id:r.id,uuid:r.uuid},a=Ne(n.key),c=$.join(a,`${n.key}.yml`);zn(c,s);for(const u of e){const p=await Li(o,u);await ds(n.key,u,p)}t?.("pulled",i)}l(hs,"pullConnector");function fs(o,e=[]){const t=Object.values(o).reduce((n,r)=>n+(r?.length??0),0)+e.length;b.info(`\u25CF Pulled workspace elements \xB7 ${t}`);for(const n of Object.keys(o).sort()){const r=o[n];b.info(`\u2514\u2500\u2500 ${n}s \xB7 ${r?.length??0}`)}e.length>0&&b.info(`\u2514\u2500\u2500 connectors \xB7 ${e.length}`)}l(fs,"showStats$1");async function ms(o,e){const t=o[ee.DELETE].size;b.info(`\u2299 Pull: conflicts detected \xB7 ${t}`),await Ft(e,(n,r)=>{de(n)&&o[ee.DELETE].has(r.uuid)&&b.info(`\u2514\u2500\u2500 ./membrane/${n} (deleted in remote)`)})}l(ms,"showConflicts$1");async function gs(o){b.error("\u25A0 Error"),b.error(`\u2514\u2500\u2500 ${o.message}`),b.error(` ${o.stack}`)}l(gs,"showError$1");const J=[];for(let o=0;o<256;++o)J.push((o+256).toString(16).slice(1));function ys(o,e=0){return(J[o[e+0]]+J[o[e+1]]+J[o[e+2]]+J[o[e+3]]+"-"+J[o[e+4]]+J[o[e+5]]+"-"+J[o[e+6]]+J[o[e+7]]+"-"+J[o[e+8]]+J[o[e+9]]+"-"+J[o[e+10]]+J[o[e+11]]+J[o[e+12]]+J[o[e+13]]+J[o[e+14]]+J[o[e+15]]).toLowerCase()}l(ys,"unsafeStringify");let qt;const ws=new Uint8Array(16);function Cs(){if(!qt){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");qt=crypto.getRandomValues.bind(crypto)}return qt(ws)}l(Cs,"rng");const Ss=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto);var co={randomUUID:Ss};function bs(o,e,t){if(co.randomUUID&&!o)return co.randomUUID();o=o||{};const n=o.random??o.rng?.()??Cs();if(n.length<16)throw new Error("Random bytes length must be >= 16");return n[6]=n[6]&15|64,n[8]=n[8]&63|128,ys(n)}l(bs,"v4");function vs(o){o.command("push").description("Push workspace data to specified workspace").argument("[files...]","Files, directories, or glob patterns to push").option("--force","Overwrite conflicts with local data",!1).addHelpText("after",["","Examples:"," membrane push # Push all workspace elements"," membrane push data-sources/ # Push all data-sources"," membrane push actions/my-action/spec.yaml # Push specific action"," membrane push flows/*-test/spec.yaml # Push flows matching pattern"," membrane push --force # Overwrite conflicts with local data",""].join(`
|
|
49
|
+
`)).action(async(e,t)=>{const n=Se({text:"Pushing workspace",color:"white",discardStdin:!1}).start();try{await Ts(e,t,n)}catch(r){n.stop(),Ns(r),process.exit(1)}})}l(vs,"setupPushCommand");async function Ts(o,e,t){const n=o.length>0,r=await Ut(),i=Xn(),s=ks(r,i),a=await O.isVersionAtLeast("1.9"),c=await Hn(s,n?o:void 0,a?i:void 0);e.force||(t.text="Comparing workspace",await Is(c,n)&&(t.stop(),process.exit(1)));const u=a?Object.keys(i):await Es(t);t.start("Pushing workspace..."),await Jn(c,{partial:n}),t.stop(),As(s,u),process.exit(0)}l(Ts,"pushWorkspace");async function Is(o,e){const t=await Jn(o,{dryRun:!0,partial:e}),n=t[ee.DELETE].size>0;return n&&(await Ps(t,o),b.error("Use --force to delete remote elements")),n}l(Is,"checkForConflicts");async function Es(o){return(await Pn({onProgress:l((t,n)=>{t==="pushing"?o.start(`Pushing connector ${n}...`):o.succeed(`Pushed connector ${n}`)},"onProgress")})).pushedConnectors??[]}l(Es,"pushConnectorsLegacy");function ks(o,e){const t=$s(o),n=Os(t,e),r={};for(const[i,s]of Object.entries(t)){const a=i;r[a]=(s||[]).map(c=>xs(c,a,n))}return r}l(ks,"resolveLegacyIdReferences");function xs(o,e,t){const n={...o},r=Q[e]?.parentFieldKey||"parentId";if(n.integrationId&&!n.integrationUuid&&(n.integrationUuid=t.get(n.integrationId.toString())||n.integrationId,delete n.integrationId),n.connectorId){if(!n.connectorUuid){const i=t.get(n.connectorId.toString());i&&(n.connectorUuid=i)}delete n.connectorId}if(n[r]){const i=t.get(n[r].toString());i&&(n.parentUuid=i)}return e===x.Package&&n.elements&&(n.elements=n.elements.map(i=>{if(i.id&&!i.uuid){const s=t.get(i.id.toString());if(s)return{uuid:s,type:i.type}}return i})),delete n.id,n}l(xs,"resolveElementIds");function $s(o){const e={};for(const[t,n]of Object.entries(o))e[t]=(n||[]).map(r=>r.uuid?r:{...r,uuid:bs()});return e}l($s,"generateMissingUuids");function Os(o,e){const t=new Map;for(const n of Object.values(o))for(const r of n||[])r.id&&r.uuid&&t.set(r.id.toString(),r.uuid);for(const[n,r]of Object.entries(e))r.id&&t.set(r.id.toString(),n);return t}l(Os,"buildIdToUuidLookup");function As(o,e=[]){const t=Object.values(o).reduce((n,r)=>n+(r?.length??0),0)+e.length;b.info(`\u25CF Pushed workspace elements \xB7 ${t}`);for(const n of Object.keys(o).sort()){const r=o[n];b.info(`\u2514\u2500\u2500 ${n}s \xB7 ${r?.length??0}`)}e.length>0&&b.info(`\u2514\u2500\u2500 connectors \xB7 ${e.length}`)}l(As,"showStats");async function Ps(o,e){const t=o[ee.DELETE].size;b.info(`\u2299 Push: conflicts detected \xB7 ${t}`),await Ft(e,(n,r)=>{de(n)&&o[ee.DELETE].has(r.uuid)&&b.info(`\u2514\u2500\u2500 ./membrane/${n} (deleted locally)`)})}l(Ps,"showConflicts");function Ns(o){b.error("\u25A0 Error"),b.error(`\u2514\u2500\u2500 ${o.message}`),b.error(` ${o.stack}`)}l(Ns,"showError");const lo=new Set(Object.values(Lo));function Bt(o,e=[]){return e.push(o),e}l(Bt,"collectOption");function uo(o,e,t){for(const n of e){const r=o.indexOf(n);if(r>0)return{key:o.slice(0,r).trim(),value:o.slice(r+n.length).trim()}}throw new Error(`${t} must be in key=value format`)}l(uo,"parseKeyValue");function Rs(o=[]){const e={};for(const t of o){const{key:n,value:r}=uo(t,[":","="],"--header");if(!n)throw new Error("--header key cannot be empty");e[n]=r}return e}l(Rs,"parseHeaderEntries");function po(o=[],e){const t={};for(const n of o){const{key:r,value:i}=uo(n,["="],e);if(!r)throw new Error(`${e} key cannot be empty`);t[r]=i}return t}l(po,"parseMapEntries");function Ds(o,e){if(o!==void 0){if(e)return o;try{return JSON.parse(o)}catch{return o}}}l(Ds,"parseData");function Ls(o){const[e,t=""]=o.split("?",2),n={},r=new URLSearchParams(t);for(const[i,s]of r.entries())n[i]=s;return{path:e,query:n}}l(Ls,"parsePathAndQuery");function js(o){o.command("request <connectionId> <path>").description("Make a curl-like HTTP request through a connection").option("--workspaceKey <key>","Workspace key").option("--tenantKey <key>","Tenant key (customer internalId)").option("-X, --method <method>","HTTP method (GET, POST, PUT, PATCH, DELETE)","GET").option("-H, --header <key:value>","Request header (repeatable)",Bt,[]).option("--query <key=value>","Query parameter (repeatable)",Bt,[]).option("--pathParam <key=value>","Path parameter replacement (repeatable)",Bt,[]).option("-d, --data <value>","Request body (JSON auto-parsed unless --rawData)").option("--rawData","Send --data as raw string").option("--json","Output full response object as JSON").action(async(e,t,n)=>{try{const r=(n.method||"GET").toUpperCase();if(!lo.has(r))throw new Error(`--method must be one of ${Array.from(lo).join(", ")}`);const i=new B(n),s=Ls(t),a=po(n.query,"--query"),c={...s.query,...a},u=po(n.pathParam,"--pathParam"),p=Rs(n.header),m=Ds(n.data,n.rawData),f={path:s.path,method:r};Object.keys(c).length>0&&(f.query=c),Object.keys(u).length>0&&(f.pathParameters=u),Object.keys(p).length>0&&(f.headers=p),m!==void 0&&(f.data=m);const y=await i.post(`/connections/${encodeURIComponent(e)}/request`,f);if(n.json){process.stdout.write(JSON.stringify(y,null,2)+`
|
|
50
50
|
`);return}const I=Object.prototype.hasOwnProperty.call(y,"data")?y.data:y;if(typeof I=="string"){process.stdout.write(`${I}
|
|
51
51
|
`);return}process.stdout.write(JSON.stringify(I,null,2)+`
|
|
52
|
-
`)}catch(r){U(r)}})}l(
|
|
53
|
-
`);else{const s=i.items??[];if(s.length===0)console.error(p.gray(" No results found."));else for(const a of s){const c=a.element,u=p.gray(`[${a.elementType}]`),h=c?.name||c?.key||"(unnamed)",m=p.cyan(String(c?.id??a.id??"(no id)"));console.error(` ${u} ${m} ${h}`)}console.error()}}catch(n){U(n)}})}l(js,"setupSearchCommand");const Fs="0";function Us(o){o.command("status").description("Show current login status, project settings, and resolved environment").action(async()=>{try{await Ks()}catch(e){U(e)}})}l(Us,"setupStatusCommand");async function Ks(){const o=me()||te,e=wn(),t=yt();if(console.error(),console.error(p.bold.cyan("\u25B6 Membrane CLI Status")),console.error(),E("API",o),!t)E("Auth",p.red("Not logged in"));else{const n=mt(),r=!!be(),i=gt();if(n&&!r)E("Auth",p.yellow("Token expired (no refresh token)"));else if(i==="tenant"){E("Auth",p.green("Logged in")+p.gray(" (tenant scope)"));try{const a=await new Oe().get("/self"),c=a.workspaceKey??e.defaultWorkspaceKey;c&&E("Workspace",c);const u=a.internalId??e.defaultTenantKey;a.name&&u?E("Tenant",`${a.name} (${u})`):a.name?E("Tenant",a.name):u&&E("Tenant",u)}catch{e.defaultWorkspaceKey&&E("Workspace",e.defaultWorkspaceKey),e.defaultTenantKey&&E("Tenant",e.defaultTenantKey)}}else{try{const a=await new Oe().get(`/account?workspaceId=${Fs}`);if(a.user?(E("Auth",p.green("Logged in")),E("User",`${a.user.name} (${a.user.email})`)):E("Auth",p.green("Logged in")),a.orgs?.length){const c=a.orgs.map(u=>u.name).join(", ");E("Orgs",c)}}catch{E("Auth",p.yellow("Logged in (could not fetch account details)"))}e.defaultWorkspaceKey&&E("Workspace",`${e.defaultWorkspaceKey} ${p.gray("(default)")}`),e.defaultTenantKey&&E("Tenant",`${e.defaultTenantKey} ${p.gray("(default)")}`),!e.defaultWorkspaceKey&&!e.defaultTenantKey&&E("Project",p.gray("No project defaults configured"))}}console.error()}l(Ks,"runStatus");const Jt=[{id:"claude-code",name:"Claude Code",description:"Anthropic Claude Code agent",actionDescription:"Adding membrane MCP to .mcp.json in the current directory",addConfig:l(()=>{const o=k.join(process.cwd(),".mcp.json"),e={mcpServers:{membrane:{command:"membrane",args:["mcp"],env:{AGENT_NAME:"Claude Code"}}}};let t={};if(T.existsSync(o))try{t=JSON.parse(T.readFileSync(o,"utf8"))}catch{t={}}const n={...t,mcpServers:{...t.mcpServers,...e.mcpServers}};return T.writeFileSync(o,JSON.stringify(n,null,2)),`MCP server configuration added to ${o}`},"addConfig")},{id:"cursor",name:"Cursor",description:"Cursor AI editor",actionDescription:"Adding membrane MCP to .cursor/mcp.json in the current directory",addConfig:l(()=>{const o=k.join(process.cwd(),".cursor"),e=k.join(o,"mcp.json");T.existsSync(o)||T.mkdirSync(o);const t={mcpServers:{membrane:{command:"membrane",args:["mcp"],env:{AGENT_NAME:"Cursor"}}}};let n={};if(T.existsSync(e))try{n=JSON.parse(T.readFileSync(e,"utf8"))}catch{n={}}const r={...n,mcpServers:{...n.mcpServers,...t.mcpServers}};return T.writeFileSync(e,JSON.stringify(r,null,2)),`MCP server configuration added to ${e}`},"addConfig")}];function _s({onExit:o,onComplete:e}){const[t,n]=L(0),[r,i]=L(!1),[s,a]=L(null),[c,u]=L(""),[h,m]=L("");he((I,S)=>{if(c||h){(S.escape||I==="q"||S.return)&&e();return}if(r)S.return||I===" "?f(s):S.escape&&(i(!1),a(null));else if(S.escape)o();else if(S.upArrow||I==="k")n(Math.max(0,t-1));else if(S.downArrow||I==="j")n(Math.min(Jt.length-1,t+1));else if(S.return||I===" "){const R=Jt[t];a(R),i(!0)}});const f=l(I=>{try{const S=I.addConfig();u(S)}catch(S){m(`Failed to write configuration: ${S.message||S}`)}},"addMcpConfiguration"),y=Math.min(80,process.stdout.columns||80);return c?v(w,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:y,children:[d(w,{marginTop:-1,marginBottom:1,children:v(C,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",d(C,{color:"green",children:"Success"})]})}),v(w,{flexDirection:"column",paddingLeft:2,children:[d(C,{color:"green",children:c}),d(w,{marginTop:1,children:d(C,{color:"grey",children:"The agent will now be able to use Membrane's integration capabilities."})})]}),d(w,{marginTop:1,paddingLeft:2,children:d(C,{color:"white",children:"[esc/q/enter: exit]"})})]}):h?v(w,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:y,children:[d(w,{marginTop:-1,marginBottom:1,children:v(C,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",d(C,{color:"red",children:"Error"})]})}),d(w,{flexDirection:"column",paddingLeft:2,children:d(C,{color:"red",children:h})}),d(w,{marginTop:1,children:d(C,{color:"grey",children:"[esc/q/enter: exit]"})})]}):r&&s?v(w,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:y,children:[d(w,{marginTop:-1,marginBottom:1,children:v(C,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",d(C,{color:"cyan",children:"Confirmation"})]})}),v(w,{flexDirection:"column",paddingLeft:2,children:[v(C,{children:["Connect ",d(C,{bold:!0,children:s.name})," to Membrane via MCP?"]}),d(w,{marginTop:1,children:d(C,{color:"grey",children:"This will add an MCP server configuration that allows the agent to use Membrane's integration capabilities."})}),d(w,{marginTop:1,children:d(C,{color:"yellow",bold:!0,children:s.actionDescription})}),d(w,{marginTop:2,marginBottom:1,children:v(C,{children:[d(C,{color:"white",bold:!0,children:"[Enter] Confirm"})," ",d(C,{color:"gray",children:"[Esc] Cancel"})]})})]})]}):v(w,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:y,children:[d(w,{marginTop:-1,marginBottom:1,children:v(C,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",d(C,{color:"cyan",children:"Select Agent"})]})}),v(w,{flexDirection:"column",paddingLeft:2,children:[d(C,{color:"grey",children:"Choose an agent to connect to Membrane via MCP:"}),d(w,{marginTop:1,children:d(C,{color:"grey",children:"This will add an MCP server configuration that allows the agent to use Membrane's integration capabilities."})}),d(w,{marginTop:1,flexDirection:"column",children:Jt.map((I,S)=>v(w,{children:[v(C,{color:t===S?"cyan":"white",children:[t===S?"\u25B6 ":" ",I.name]}),v(C,{color:"grey",children:[" \u2014 ",I.description]})]},I.id))})]}),d(w,{marginTop:1,children:d(C,{color:"grey",children:"[\u2191\u2193: select] [enter: choose] [esc: exit]"})})]})}l(_s,"AddMcpServerScreen");function qs(){const[o,e]=L(null),[t,n]=L([]),[r,i]=L(null);return Ce(()=>{const s=l(({status:c})=>{e(c),i(null)},"handleMcpStatusChanged"),a=l(({servers:c})=>{n(c),i(null)},"handleMcpServersChanged");return se.on(q.McpStatusChanged,s),se.on(q.McpServersChanged,a),()=>{se.off(q.McpStatusChanged,s),se.off(q.McpServersChanged,a)}},[]),{mcpStatus:o,allMcpServers:t,error:r,isRunning:o?.isRunning||!1,toolsCount:o?.toolsCount||0,totalRequests:o?.totalRequests||0,lastActivity:o?.lastActivity,processId:o?.processId,serverCount:t.length}}l(qs,"useMcpStatus");function Bs(){const{error:o,serverCount:e,allMcpServers:t}=qs(),n=Math.min(100,process.stdout.columns||100);return v(w,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:n,children:[d(w,{marginTop:-1,marginBottom:0,flexDirection:"column",children:v(C,{bold:!0,children:["\u{1F916} Connected AI Agents:"," ",o?d(C,{color:"red",children:"error reading status"}):e===0?d(C,{color:"yellow",children:"none"}):d(C,{color:"green",children:e})]})}),!o&&e===0&&d(w,{marginTop:1,children:v(C,{color:"grey",children:["Connect your AI agents to Membrane.",d(Ko,{}),"It will give them tools and context to build integrations."]})}),t.length>0&&d(w,{flexDirection:"column",paddingLeft:2,marginTop:1,children:t.map((r,i)=>d(w,{children:v(C,{color:"grey",children:["#",i+1," ",r.agentName,": ",r.totalRequests," calls"]})},r.processId))}),d(w,{marginTop:1,children:d(C,{color:"grey",children:"[a: connect an agent]"})})]})}l(Bs,"Agent");const po=l(o=>{switch(o){case"error":return"red";case"success":return"green";case"warning":return"yellow";default:return}},"getLogColor");function fo(o,e){return e<3?o.slice(0,Math.max(0,e)):o.length<=e?o:`${o.slice(0,e-3)}...`}l(fo,"truncateText");function Js({children:o}){const{state:e,logs:t}=Z();return!e||e===A.NOT_INITIALIZED?v(w,{gap:1,flexDirection:"row",children:[d(sr,{type:"dots"}),d(C,{children:"Initializing..."})]}):e===A.SETTING_UP?d(w,{gap:1,flexDirection:"row",children:d(C,{children:"No workspace selected. Please run `membrane init` to select a workspace."})}):e===A.ERROR?d(w,{flexDirection:"column",children:t.slice().map((n,r)=>d(C,{color:po(n.type),children:n.message},n.timestamp+r))}):o}l(Js,"EnsureInitialized");function Ws(){const{stats:o}=Z(),e=Object.entries(o).filter(([t,n])=>n>0);return e.length===0?null:v(w,{flexDirection:"column",children:[d(w,{children:d(w,{width:12,children:d(C,{color:"grey",children:"Elements:"})})}),d(w,{flexDirection:"column",marginLeft:1,children:e.map(([t,n])=>v(w,{children:[d(w,{width:20,children:v(C,{children:[t,":"]})}),d(C,{color:"green",children:n})]},t))})]})}l(Ws,"ElementStats");const Wt=5,zs=6;function Gs(){const{logs:o}=Z(),[e,t]=L(0),n=Math.min(100,process.stdout.columns||100),r=Wt,i=Math.max(0,o.length-r-e),s=o.length-e,a=o.slice(i,s),c=n-zs,u=e<o.length-r,h=e>0;return he((m,f)=>{if(o.length!==0)if(f.upArrow){const y=Math.max(0,o.length-r);t(I=>Math.min(y,I+1))}else f.downArrow?t(y=>Math.max(0,y-1)):(m==="G"||m==="g")&&t(0)}),v(w,{flexDirection:"column",paddingTop:1,children:[v(C,{color:"grey",children:["Recent Activity (",i+1,"-",s," of ",o.length,"):",o.length>Wt&&d(C,{color:"grey",children:" [arrows: scroll] [g: end]"})]}),a.map((m,f)=>d(w,{marginLeft:1,children:d(C,{color:po(m.type),children:fo(m.message,c)})},m.timestamp+f)),o.length>Wt&&v(w,{marginLeft:1,flexDirection:"row",children:[u&&d(C,{color:"grey",children:"\u2191 "}),h&&d(C,{color:"grey",children:"\u2193 "})]})]})}l(Gs,"Logs");const Ge=[{value:"sync",label:"Continue (overwrite/delete)",key:""},{value:"exit",label:"Cancel",key:""}];function Hs(){const{state:o,resolveConflicts:e,exit:t}=Z(),[n,r]=L(0),[i,s]=L(!1),[a,c]=L(!1);return he((u,h)=>{if(!i){if(h.ctrl&&u.toLowerCase()==="r"){c(!a);return}h.upArrow?r(m=>m>0?m-1:Ge.length-1):h.downArrow?r(m=>m<Ge.length-1?m+1:0):u.toLowerCase()==="y"?r(0):u.toLowerCase()==="n"?r(1):(h.return||u===" ")&&(s(!0),Ge[n].value==="sync"?e({watch:!0}):t())}}),Ce(()=>{o!==A.CONFLICTS&&i&&s(!1)},[o,i]),v(w,{flexDirection:"column",paddingTop:1,children:[d(w,{children:d(w,{flexDirection:"row",gap:2,children:d(C,{bold:!0,color:"white",children:"Conflicts with remote"})})}),d(w,{children:d(C,{color:"grey",children:"The remote workspace has changes that aren't in your local workspace:"})}),d(w,{marginTop:1,marginLeft:2,children:d(Ys,{isExpanded:a})}),v(w,{marginTop:2,flexDirection:"row",gap:1,children:[d(C,{color:"white",bold:!0,children:"What would you like to do?"}),d(C,{color:"grey",children:"[up/down, enter]"})]}),d(w,{children:i?v(w,{flexDirection:"row",gap:1,children:[d(qe,{type:"dots"}),d(C,{color:"blue",bold:!0,children:"Syncing with remote..."})]}):d(w,{flexDirection:"column",children:Ge.map((u,h)=>d(w,{flexDirection:"column",children:v(w,{flexDirection:"row",gap:1,children:[d(C,{color:n===h?"cyan":"grey",children:n===h?"\u25B6":" "}),d(C,{color:n===h?"cyan":"grey",bold:n===h,children:u.label})]})},u.value))})})]})}l(Hs,"ResolveChangesUI");const Vs={[re.UPDATE]:{incoming:{label:"Elements updated in remote",description:"(to be overwritten from remote)"},outgoing:{label:"Elements updated locally",description:"(to be pushed to remote)"}},[re.DELETE]:{incoming:{label:"Elements not existing in remote",description:"(to be deleted locally)"},outgoing:{label:"Elements deleted locally",description:"(to be deleted from remote)"}},[re.CREATE]:{incoming:{label:"Elements created in remote",description:"(to be created locally)"},outgoing:{label:"Elements created locally",description:"(to be created in remote)"}}};function Ys({isExpanded:o,showControls:e=!0}){const{conflicts:t}=Z(),n=5,r=qo(()=>{const i={};return t.forEach(s=>{const a=`${s.type}-${s.direction}`;i[a]||(i[a]=[]),i[a].push(s)}),i},[t]);return d(w,{flexDirection:"column",children:Object.entries(r).map(([i,s])=>{if(s.length===0)return null;const[a,c]=i.split("-"),u=Vs[a][c];return v(w,{flexDirection:"column",children:[v(w,{flexDirection:"row",gap:1,children:[v(C,{color:"yellow",children:[u.label," (",s.length,")"]}),d(C,{color:"white",children:u.description})]}),(o?s:s.slice(0,n)).map(h=>d(w,{marginLeft:2,children:v(C,{color:"grey",children:["\u2022 ",h.element.id," (",h.element.relativePath,")"]})},h.element.id)),!o&&s.length>n&&d(w,{marginLeft:2,children:v(C,{color:"cyan",children:["... and ",s.length-n," more",e?" (press Ctrl+R to show all)":""]})}),o&&s.length>n&&e&&d(w,{marginLeft:2,children:d(C,{color:"cyan",children:"(press Ctrl+R to collapse)"})})]},i)})})}l(Ys,"Conflicts");function Zs(){const{config:o,state:e,logs:t,currentWorkspace:n,pull:r}=Z(),i=n?.name,s=i?fo(i,30):o?.workspaceKey,a=Math.min(100,process.stdout.columns||100);return Ce(()=>{r({watch:!0})},[]),v(w,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:a,children:[d(w,{marginTop:-1,marginBottom:1,children:v(w,{flexDirection:"row",gap:1,children:[d(C,{bold:!0,children:"\u{1F504} Workspace"}),v(C,{color:Qs(e),children:[" [",Xs(e),"] "]})]})}),v(w,{children:[d(w,{width:12,children:d(C,{color:"grey",children:"Local:"})}),d(C,{color:"grey",children:process.cwd()})]}),v(w,{children:[d(w,{width:12,children:d(C,{color:"grey",children:"Remote:"})}),o?.workspaceKey?v(C,{color:"grey",children:[s," [o: open in console] [w: change]"]}):v(C,{children:[d(C,{color:"yellow",children:"not selected"})," [w: select]"]})]}),e===A.CONFLICTS?d(Hs,{}):v(Ke,{children:[d(w,{paddingTop:1,children:d(Ws,{})}),t.length>0&&d(Gs,{})]})]})}l(Zs,"Workspace");function Xs(o){switch(o){case A.PULLING:return"pulling";case A.PUSHING:return"pushing";case A.CONFLICTS:return"conflicts";case A.SYNCED:return"synced";case A.ERROR:return"error";case A.WATCHING:return"tracking changes";case A.RESOLVING:return"resolving";case A.NOT_SYNCED:return"not synced";case A.INITIALIZED:return"initialized";case A.SETTING_UP:return"setup required";default:return"unknown"}}l(Xs,"getStatusDisplay");function Qs(o){switch(o){case A.PULLING:return"yellow";case A.PUSHING:return"yellow";case A.CONFLICTS:return"red";case A.SYNCED:return"green";case A.ERROR:return"red";case A.WATCHING:return"green";case A.RESOLVING:return"yellow";case A.NOT_SYNCED:return"grey";case A.SETTING_UP:return"yellow";default:return"grey"}}l(Qs,"getStatusColor");function ea(){const o=Ti(),e=at(!0),{exit:t,state:n}=Z(),[r,i]=L(null),s=r??(n===A.SETTING_UP?"setup":"main");he(c=>{s==="main"&&(c==="w"&&i("workspace-selection"),c==="a"&&i("add-mcp-server"),c==="o"&&n===A.INITIALIZED&&a(),c==="s"&&i("setup"))});async function a(){try{const c=await so(o),u=pt(`/w/${c}`),h=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";cr(`${h} "${u}"`)}catch(c){console.error("Failed to open workspace:",c),t()}}return l(a,"handleOpenWorkspace"),Ce(()=>(e.current=!0,()=>{e.current=!1}),[]),s==="workspace-selection"?d(Qn,{onExit:l(()=>i(null),"onExit")}):s==="add-mcp-server"?d(_s,{onExit:l(()=>i(null),"onExit"),onComplete:l(()=>i(null),"onComplete")}):s==="setup"?d(eo,{onComplete:l(()=>i(null),"onComplete")},Date.now()):d(Js,{children:v(w,{flexDirection:"column",children:[d(w,{flexGrow:1,children:d(Bs,{})}),d(Zs,{}),d(w,{paddingLeft:2,children:d(C,{color:"grey",children:"[s: (re-)setup]"})})]})})}l(ea,"Main");const ta=l(()=>[p.yellow("\u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510"),p.yellow("\u2502 \u26A0\uFE0F EXPERIMENTAL FEATURE WARNING \u2502"),p.yellow("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524"),p.yellow("\u2502 Real-time agent mode is experimental and subject to changes. \u2502"),p.yellow("\u2502 Use in production environments is not recommended. \u2502"),p.yellow("\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518"),""].join(`
|
|
52
|
+
`)}catch(r){U(r)}})}l(js,"setupRequestCommand");function Ms(o){o.command("search <query>").description("Search workspace elements (connectors, integrations, actions, etc.)").option("--elementType <type>","Filter by element type (e.g. connector, integration)").option("--limit <n>","Max results").option("--workspaceKey <key>","Workspace key").option("--tenantKey <key>","Tenant key (customer internalId)").option("--json","Output as JSON").action(async(e,t)=>{try{const n=new B(t),r=new URLSearchParams({q:e});t.elementType&&r.set("elementType",t.elementType),t.limit&&r.set("limit",t.limit);const i=await n.get(`/search?${r}`);if(t.json)process.stdout.write(JSON.stringify(i,null,2)+`
|
|
53
|
+
`);else{const s=i.items??[];if(s.length===0)console.error(h.gray(" No results found."));else for(const a of s){const c=a.element,u=h.gray(`[${a.elementType}]`),p=c?.name||c?.key||"(unnamed)",m=h.cyan(String(c?.id??a.id??"(no id)"));console.error(` ${u} ${m} ${p}`)}console.error()}}catch(n){U(n)}})}l(Ms,"setupSearchCommand");const Fs="0";function Us(o){o.command("status").description("Show current login status, project settings, and resolved environment").action(async()=>{try{await Ks()}catch(e){U(e)}})}l(Us,"setupStatusCommand");async function Ks(){const o=me()||te,e=wn(),t=yt();if(console.error(),console.error(h.bold.cyan("\u25B6 Membrane CLI Status")),console.error(),E("API",o),!t)E("Auth",h.red("Not logged in"));else{const n=mt(),r=!!be(),i=gt();if(n&&!r)E("Auth",h.yellow("Token expired (no refresh token)"));else if(i==="tenant"){E("Auth",h.green("Logged in")+h.gray(" (tenant scope)"));try{const a=await new Oe().get("/self"),c=a.workspaceKey??e.defaultWorkspaceKey;c&&E("Workspace",c);const u=a.internalId??e.defaultTenantKey;a.name&&u?E("Tenant",`${a.name} (${u})`):a.name?E("Tenant",a.name):u&&E("Tenant",u)}catch{e.defaultWorkspaceKey&&E("Workspace",e.defaultWorkspaceKey),e.defaultTenantKey&&E("Tenant",e.defaultTenantKey)}}else{try{const a=await new Oe().get(`/account?workspaceId=${Fs}`);if(a.user?(E("Auth",h.green("Logged in")),E("User",`${a.user.name} (${a.user.email})`)):E("Auth",h.green("Logged in")),a.orgs?.length){const c=a.orgs.map(u=>u.name).join(", ");E("Orgs",c)}}catch{E("Auth",h.yellow("Logged in (could not fetch account details)"))}e.defaultWorkspaceKey&&E("Workspace",`${e.defaultWorkspaceKey} ${h.gray("(default)")}`),e.defaultTenantKey&&E("Tenant",`${e.defaultTenantKey} ${h.gray("(default)")}`),!e.defaultWorkspaceKey&&!e.defaultTenantKey&&E("Project",h.gray("No project defaults configured"))}}console.error()}l(Ks,"runStatus");const Jt=[{id:"claude-code",name:"Claude Code",description:"Anthropic Claude Code agent",actionDescription:"Adding membrane MCP to .mcp.json in the current directory",addConfig:l(()=>{const o=k.join(process.cwd(),".mcp.json"),e={mcpServers:{membrane:{command:"membrane",args:["mcp"],env:{AGENT_NAME:"Claude Code"}}}};let t={};if(T.existsSync(o))try{t=JSON.parse(T.readFileSync(o,"utf8"))}catch{t={}}const n={...t,mcpServers:{...t.mcpServers,...e.mcpServers}};return T.writeFileSync(o,JSON.stringify(n,null,2)),`MCP server configuration added to ${o}`},"addConfig")},{id:"cursor",name:"Cursor",description:"Cursor AI editor",actionDescription:"Adding membrane MCP to .cursor/mcp.json in the current directory",addConfig:l(()=>{const o=k.join(process.cwd(),".cursor"),e=k.join(o,"mcp.json");T.existsSync(o)||T.mkdirSync(o);const t={mcpServers:{membrane:{command:"membrane",args:["mcp"],env:{AGENT_NAME:"Cursor"}}}};let n={};if(T.existsSync(e))try{n=JSON.parse(T.readFileSync(e,"utf8"))}catch{n={}}const r={...n,mcpServers:{...n.mcpServers,...t.mcpServers}};return T.writeFileSync(e,JSON.stringify(r,null,2)),`MCP server configuration added to ${e}`},"addConfig")}];function _s({onExit:o,onComplete:e}){const[t,n]=L(0),[r,i]=L(!1),[s,a]=L(null),[c,u]=L(""),[p,m]=L("");pe((I,S)=>{if(c||p){(S.escape||I==="q"||S.return)&&e();return}if(r)S.return||I===" "?f(s):S.escape&&(i(!1),a(null));else if(S.escape)o();else if(S.upArrow||I==="k")n(Math.max(0,t-1));else if(S.downArrow||I==="j")n(Math.min(Jt.length-1,t+1));else if(S.return||I===" "){const R=Jt[t];a(R),i(!0)}});const f=l(I=>{try{const S=I.addConfig();u(S)}catch(S){m(`Failed to write configuration: ${S.message||S}`)}},"addMcpConfiguration"),y=Math.min(80,process.stdout.columns||80);return c?v(w,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:y,children:[d(w,{marginTop:-1,marginBottom:1,children:v(C,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",d(C,{color:"green",children:"Success"})]})}),v(w,{flexDirection:"column",paddingLeft:2,children:[d(C,{color:"green",children:c}),d(w,{marginTop:1,children:d(C,{color:"grey",children:"The agent will now be able to use Membrane's integration capabilities."})})]}),d(w,{marginTop:1,paddingLeft:2,children:d(C,{color:"white",children:"[esc/q/enter: exit]"})})]}):p?v(w,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:y,children:[d(w,{marginTop:-1,marginBottom:1,children:v(C,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",d(C,{color:"red",children:"Error"})]})}),d(w,{flexDirection:"column",paddingLeft:2,children:d(C,{color:"red",children:p})}),d(w,{marginTop:1,children:d(C,{color:"grey",children:"[esc/q/enter: exit]"})})]}):r&&s?v(w,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:y,children:[d(w,{marginTop:-1,marginBottom:1,children:v(C,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",d(C,{color:"cyan",children:"Confirmation"})]})}),v(w,{flexDirection:"column",paddingLeft:2,children:[v(C,{children:["Connect ",d(C,{bold:!0,children:s.name})," to Membrane via MCP?"]}),d(w,{marginTop:1,children:d(C,{color:"grey",children:"This will add an MCP server configuration that allows the agent to use Membrane's integration capabilities."})}),d(w,{marginTop:1,children:d(C,{color:"yellow",bold:!0,children:s.actionDescription})}),d(w,{marginTop:2,marginBottom:1,children:v(C,{children:[d(C,{color:"white",bold:!0,children:"[Enter] Confirm"})," ",d(C,{color:"gray",children:"[Esc] Cancel"})]})})]})]}):v(w,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:y,children:[d(w,{marginTop:-1,marginBottom:1,children:v(C,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",d(C,{color:"cyan",children:"Select Agent"})]})}),v(w,{flexDirection:"column",paddingLeft:2,children:[d(C,{color:"grey",children:"Choose an agent to connect to Membrane via MCP:"}),d(w,{marginTop:1,children:d(C,{color:"grey",children:"This will add an MCP server configuration that allows the agent to use Membrane's integration capabilities."})}),d(w,{marginTop:1,flexDirection:"column",children:Jt.map((I,S)=>v(w,{children:[v(C,{color:t===S?"cyan":"white",children:[t===S?"\u25B6 ":" ",I.name]}),v(C,{color:"grey",children:[" \u2014 ",I.description]})]},I.id))})]}),d(w,{marginTop:1,children:d(C,{color:"grey",children:"[\u2191\u2193: select] [enter: choose] [esc: exit]"})})]})}l(_s,"AddMcpServerScreen");function qs(){const[o,e]=L(null),[t,n]=L([]),[r,i]=L(null);return Ce(()=>{const s=l(({status:c})=>{e(c),i(null)},"handleMcpStatusChanged"),a=l(({servers:c})=>{n(c),i(null)},"handleMcpServersChanged");return se.on(q.McpStatusChanged,s),se.on(q.McpServersChanged,a),()=>{se.off(q.McpStatusChanged,s),se.off(q.McpServersChanged,a)}},[]),{mcpStatus:o,allMcpServers:t,error:r,isRunning:o?.isRunning||!1,toolsCount:o?.toolsCount||0,totalRequests:o?.totalRequests||0,lastActivity:o?.lastActivity,processId:o?.processId,serverCount:t.length}}l(qs,"useMcpStatus");function Bs(){const{error:o,serverCount:e,allMcpServers:t}=qs(),n=Math.min(100,process.stdout.columns||100);return v(w,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:n,children:[d(w,{marginTop:-1,marginBottom:0,flexDirection:"column",children:v(C,{bold:!0,children:["\u{1F916} Connected AI Agents:"," ",o?d(C,{color:"red",children:"error reading status"}):e===0?d(C,{color:"yellow",children:"none"}):d(C,{color:"green",children:e})]})}),!o&&e===0&&d(w,{marginTop:1,children:v(C,{color:"grey",children:["Connect your AI agents to Membrane.",d(Ko,{}),"It will give them tools and context to build integrations."]})}),t.length>0&&d(w,{flexDirection:"column",paddingLeft:2,marginTop:1,children:t.map((r,i)=>d(w,{children:v(C,{color:"grey",children:["#",i+1," ",r.agentName,": ",r.totalRequests," calls"]})},r.processId))}),d(w,{marginTop:1,children:d(C,{color:"grey",children:"[a: connect an agent]"})})]})}l(Bs,"Agent");const ho=l(o=>{switch(o){case"error":return"red";case"success":return"green";case"warning":return"yellow";default:return}},"getLogColor");function fo(o,e){return e<3?o.slice(0,Math.max(0,e)):o.length<=e?o:`${o.slice(0,e-3)}...`}l(fo,"truncateText");function Js({children:o}){const{state:e,logs:t}=Z();return!e||e===A.NOT_INITIALIZED?v(w,{gap:1,flexDirection:"row",children:[d(sr,{type:"dots"}),d(C,{children:"Initializing..."})]}):e===A.SETTING_UP?d(w,{gap:1,flexDirection:"row",children:d(C,{children:"No workspace selected. Please run `membrane init` to select a workspace."})}):e===A.ERROR?d(w,{flexDirection:"column",children:t.slice().map((n,r)=>d(C,{color:ho(n.type),children:n.message},n.timestamp+r))}):o}l(Js,"EnsureInitialized");function Ws(){const{stats:o}=Z(),e=Object.entries(o).filter(([t,n])=>n>0);return e.length===0?null:v(w,{flexDirection:"column",children:[d(w,{children:d(w,{width:12,children:d(C,{color:"grey",children:"Elements:"})})}),d(w,{flexDirection:"column",marginLeft:1,children:e.map(([t,n])=>v(w,{children:[d(w,{width:20,children:v(C,{children:[t,":"]})}),d(C,{color:"green",children:n})]},t))})]})}l(Ws,"ElementStats");const Wt=5,zs=6;function Gs(){const{logs:o}=Z(),[e,t]=L(0),n=Math.min(100,process.stdout.columns||100),r=Wt,i=Math.max(0,o.length-r-e),s=o.length-e,a=o.slice(i,s),c=n-zs,u=e<o.length-r,p=e>0;return pe((m,f)=>{if(o.length!==0)if(f.upArrow){const y=Math.max(0,o.length-r);t(I=>Math.min(y,I+1))}else f.downArrow?t(y=>Math.max(0,y-1)):(m==="G"||m==="g")&&t(0)}),v(w,{flexDirection:"column",paddingTop:1,children:[v(C,{color:"grey",children:["Recent Activity (",i+1,"-",s," of ",o.length,"):",o.length>Wt&&d(C,{color:"grey",children:" [arrows: scroll] [g: end]"})]}),a.map((m,f)=>d(w,{marginLeft:1,children:d(C,{color:ho(m.type),children:fo(m.message,c)})},m.timestamp+f)),o.length>Wt&&v(w,{marginLeft:1,flexDirection:"row",children:[u&&d(C,{color:"grey",children:"\u2191 "}),p&&d(C,{color:"grey",children:"\u2193 "})]})]})}l(Gs,"Logs");const Ge=[{value:"sync",label:"Continue (overwrite/delete)",key:""},{value:"exit",label:"Cancel",key:""}];function Hs(){const{state:o,resolveConflicts:e,exit:t}=Z(),[n,r]=L(0),[i,s]=L(!1),[a,c]=L(!1);return pe((u,p)=>{if(!i){if(p.ctrl&&u.toLowerCase()==="r"){c(!a);return}p.upArrow?r(m=>m>0?m-1:Ge.length-1):p.downArrow?r(m=>m<Ge.length-1?m+1:0):u.toLowerCase()==="y"?r(0):u.toLowerCase()==="n"?r(1):(p.return||u===" ")&&(s(!0),Ge[n].value==="sync"?e({watch:!0}):t())}}),Ce(()=>{o!==A.CONFLICTS&&i&&s(!1)},[o,i]),v(w,{flexDirection:"column",paddingTop:1,children:[d(w,{children:d(w,{flexDirection:"row",gap:2,children:d(C,{bold:!0,color:"white",children:"Conflicts with remote"})})}),d(w,{children:d(C,{color:"grey",children:"The remote workspace has changes that aren't in your local workspace:"})}),d(w,{marginTop:1,marginLeft:2,children:d(Ys,{isExpanded:a})}),v(w,{marginTop:2,flexDirection:"row",gap:1,children:[d(C,{color:"white",bold:!0,children:"What would you like to do?"}),d(C,{color:"grey",children:"[up/down, enter]"})]}),d(w,{children:i?v(w,{flexDirection:"row",gap:1,children:[d(qe,{type:"dots"}),d(C,{color:"blue",bold:!0,children:"Syncing with remote..."})]}):d(w,{flexDirection:"column",children:Ge.map((u,p)=>d(w,{flexDirection:"column",children:v(w,{flexDirection:"row",gap:1,children:[d(C,{color:n===p?"cyan":"grey",children:n===p?"\u25B6":" "}),d(C,{color:n===p?"cyan":"grey",bold:n===p,children:u.label})]})},u.value))})})]})}l(Hs,"ResolveChangesUI");const Vs={[re.UPDATE]:{incoming:{label:"Elements updated in remote",description:"(to be overwritten from remote)"},outgoing:{label:"Elements updated locally",description:"(to be pushed to remote)"}},[re.DELETE]:{incoming:{label:"Elements not existing in remote",description:"(to be deleted locally)"},outgoing:{label:"Elements deleted locally",description:"(to be deleted from remote)"}},[re.CREATE]:{incoming:{label:"Elements created in remote",description:"(to be created locally)"},outgoing:{label:"Elements created locally",description:"(to be created in remote)"}}};function Ys({isExpanded:o,showControls:e=!0}){const{conflicts:t}=Z(),n=5,r=qo(()=>{const i={};return t.forEach(s=>{const a=`${s.type}-${s.direction}`;i[a]||(i[a]=[]),i[a].push(s)}),i},[t]);return d(w,{flexDirection:"column",children:Object.entries(r).map(([i,s])=>{if(s.length===0)return null;const[a,c]=i.split("-"),u=Vs[a][c];return v(w,{flexDirection:"column",children:[v(w,{flexDirection:"row",gap:1,children:[v(C,{color:"yellow",children:[u.label," (",s.length,")"]}),d(C,{color:"white",children:u.description})]}),(o?s:s.slice(0,n)).map(p=>d(w,{marginLeft:2,children:v(C,{color:"grey",children:["\u2022 ",p.element.id," (",p.element.relativePath,")"]})},p.element.id)),!o&&s.length>n&&d(w,{marginLeft:2,children:v(C,{color:"cyan",children:["... and ",s.length-n," more",e?" (press Ctrl+R to show all)":""]})}),o&&s.length>n&&e&&d(w,{marginLeft:2,children:d(C,{color:"cyan",children:"(press Ctrl+R to collapse)"})})]},i)})})}l(Ys,"Conflicts");function Zs(){const{config:o,state:e,logs:t,currentWorkspace:n,pull:r}=Z(),i=n?.name,s=i?fo(i,30):o?.workspaceKey,a=Math.min(100,process.stdout.columns||100);return Ce(()=>{r({watch:!0})},[]),v(w,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:a,children:[d(w,{marginTop:-1,marginBottom:1,children:v(w,{flexDirection:"row",gap:1,children:[d(C,{bold:!0,children:"\u{1F504} Workspace"}),v(C,{color:Qs(e),children:[" [",Xs(e),"] "]})]})}),v(w,{children:[d(w,{width:12,children:d(C,{color:"grey",children:"Local:"})}),d(C,{color:"grey",children:process.cwd()})]}),v(w,{children:[d(w,{width:12,children:d(C,{color:"grey",children:"Remote:"})}),o?.workspaceKey?v(C,{color:"grey",children:[s," [o: open in console] [w: change]"]}):v(C,{children:[d(C,{color:"yellow",children:"not selected"})," [w: select]"]})]}),e===A.CONFLICTS?d(Hs,{}):v(Ke,{children:[d(w,{paddingTop:1,children:d(Ws,{})}),t.length>0&&d(Gs,{})]})]})}l(Zs,"Workspace");function Xs(o){switch(o){case A.PULLING:return"pulling";case A.PUSHING:return"pushing";case A.CONFLICTS:return"conflicts";case A.SYNCED:return"synced";case A.ERROR:return"error";case A.WATCHING:return"tracking changes";case A.RESOLVING:return"resolving";case A.NOT_SYNCED:return"not synced";case A.INITIALIZED:return"initialized";case A.SETTING_UP:return"setup required";default:return"unknown"}}l(Xs,"getStatusDisplay");function Qs(o){switch(o){case A.PULLING:return"yellow";case A.PUSHING:return"yellow";case A.CONFLICTS:return"red";case A.SYNCED:return"green";case A.ERROR:return"red";case A.WATCHING:return"green";case A.RESOLVING:return"yellow";case A.NOT_SYNCED:return"grey";case A.SETTING_UP:return"yellow";default:return"grey"}}l(Qs,"getStatusColor");function ea(){const o=Ti(),e=at(!0),{exit:t,state:n}=Z(),[r,i]=L(null),s=r??(n===A.SETTING_UP?"setup":"main");pe(c=>{s==="main"&&(c==="w"&&i("workspace-selection"),c==="a"&&i("add-mcp-server"),c==="o"&&n===A.INITIALIZED&&a(),c==="s"&&i("setup"))});async function a(){try{const c=await so(o),u=ht(`/w/${c}`),p=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";cr(`${p} "${u}"`)}catch(c){console.error("Failed to open workspace:",c),t()}}return l(a,"handleOpenWorkspace"),Ce(()=>(e.current=!0,()=>{e.current=!1}),[]),s==="workspace-selection"?d(Qn,{onExit:l(()=>i(null),"onExit")}):s==="add-mcp-server"?d(_s,{onExit:l(()=>i(null),"onExit"),onComplete:l(()=>i(null),"onComplete")}):s==="setup"?d(eo,{onComplete:l(()=>i(null),"onComplete")},Date.now()):d(Js,{children:v(w,{flexDirection:"column",children:[d(w,{flexGrow:1,children:d(Bs,{})}),d(Zs,{}),d(w,{paddingLeft:2,children:d(C,{color:"grey",children:"[s: (re-)setup]"})})]})})}l(ea,"Main");const ta=l(()=>[h.yellow("\u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510"),h.yellow("\u2502 \u26A0\uFE0F EXPERIMENTAL FEATURE WARNING \u2502"),h.yellow("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524"),h.yellow("\u2502 Real-time agent mode is experimental and subject to changes. \u2502"),h.yellow("\u2502 Use in production environments is not recommended. \u2502"),h.yellow("\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518"),""].join(`
|
|
54
54
|
`),"createExperimentalWarning$1");function na(o,e){o.command("sync").description("\u26A0\uFE0F EXPERIMENTAL: Sync workspace data in real-time - This feature is experimental and subject to changes. Use in production environments is not recommended.").option("--watch","Watch for changes and sync automatically",!1).option("--rps <number>","Maximum requests per second (default: 80)",t=>parseInt(t,10)).addHelpText("after",["","Examples:"," membrane sync --watch # Start real-time sync with watch mode"," membrane sync --watch --rps 5 # Limit to 5 requests per second",""].join(`
|
|
55
|
-
`)).action(async t=>{if(t.watch||(console.error("Error: The sync command requires the --watch flag"),console.error("Usage: membrane sync --watch"),process.exit(1)),t.rps!==void 0){const
|
|
55
|
+
`)).action(async t=>{if(t.watch||(console.error("Error: The sync command requires the --watch flag"),console.error("Usage: membrane sync --watch"),process.exit(1)),t.rps!==void 0){const r=t.rps;!isNaN(r)&&r>0&&r<=1e3?O.init({maxRequestsPerSecond:r}):(g.error(`Invalid RPS value: ${r}. Must be between 1 and 1000.`),process.exit(1))}console.warn(ta()),await rt(he.createElement(Dt,{cwd:process.cwd(),membraneCLIService:e,children:he.createElement(ea)})).waitUntilExit(),process.exit(0)})}l(na,"setupSyncCommand");const oa="claude-sonnet-4-20250514";class Yt{static{l(this,"TestEnvironment")}client;connectionId;testsDir;testBasePath;options;llm;state={};constructor({connectionId:e,testsDir:t,testBasePath:n,client:r,options:i,llm:s}){this.client=r,this.connectionId=e,this.testsDir=t,this.testBasePath=n,this.llm=s,this.options=i}static async create({connectionId:e,testBasePath:t,options:n}){const r=xe();if(!r)throw new Error("No configuration found. Please set MEMBRANE_WORKSPACE_KEY and MEMBRANE_WORKSPACE_SECRET environment variables, or run `membrane init` first.");if(!r.workspaceKey||!r.workspaceSecret)throw new Error("Missing workspace credentials");if(!r.anthropicApiKey)throw new Error("Anthropic API key not configured. Run `membrane init` to set up testing.");const i=new en({token:await this.createMembraneToken(r),apiUri:r.apiUri}),s=new lr({apiKey:r.anthropicApiKey}),a={complete:l(async({prompt:c,maxTokens:u})=>{const p=await s.messages.create({model:oa,max_tokens:u,messages:[{role:"user",content:c}]});return p.content[0].type==="text"?p.content[0].text:""},"complete")};return new Yt({client:i,options:n,connectionId:e,testsDir:"src/testing/tests",testBasePath:t,llm:a})}async run(e){this.state={};const t={};for(const n of e)await n.run(),dt(t,n.getResult());this.writeResults(t)}async readYaml(e){const t=$.join(this.testsDir,this.testBasePath,this.connectionId,e);return Et(t)}async writeYaml(e,t){const n=$.join(this.testsDir,this.testBasePath,this.connectionId,e);P.mkdirSync($.dirname(n),{recursive:!0}),P.writeFileSync(n,Y.dump(t,{noRefs:!0}))}writeResults(e){const t=$.join(this.testsDir,this.testBasePath,this.connectionId);P.mkdirSync(t,{recursive:!0});const n=$.join(t,"test-results.yaml");P.writeFileSync(n,Y.dump(e,{noRefs:!0})),console.debug(`[TestRunner] Results written to: ${n}`)}static async createMembraneToken(e){const t=e.testCustomerId||"test-customer",n={id:t,name:t},r={issuer:e.workspaceKey,expiresIn:7200,algorithm:"HS512"};return ct.sign(n,e.workspaceSecret,r)}}function zt(o,e){const t={};for(const n in e){if(!(n in o)){t[n]=e[n];continue}const r=o[n],i=e[n];if(r&&i&&typeof r=="object"&&typeof i=="object"){if(Array.isArray(r)&&Array.isArray(i)){const s=i.filter(a=>!r.some(c=>{if(typeof c=="object"&&typeof a=="object"&&c!==null&&a!==null&&!Array.isArray(c)&&!Array.isArray(a)){for(const u in a)if(!(u in c)||!Gt(c[u],a[u]))return!1;return!0}else return JSON.stringify(c)===JSON.stringify(a)}));s.length>0&&(t[n]=s)}else if(!Array.isArray(r)&&!Array.isArray(i)){const s=zt(r,i);s!==null&&(t[n]=s)}else t[n]=i;continue}Gt(r,i)||(t[n]=i)}return Object.keys(t).length===0?null:t}l(zt,"getNotMatchingSubFields");function Gt(o,e){if(o==e||o?.toString?.()===e?.toString?.())return!0;const t=new Date(o),n=new Date(e);return!isNaN(t.getTime())&&!isNaN(n.getTime())?t.getTime()===n.getTime():!1}l(Gt,"softCompare");class ue{static{l(this,"BaseTester")}environment;level;logs;assertions;resultsLocator;path;constructor({environment:e,path:t}){this.environment=e,this.logs=[],this.assertions=[],this.path=t,this.level=0,this.resultsLocator=""}async fix(e){const t=await this.readTestCase();if(!t)throw new Error(`No config found for test ${this.path}`);const n=await this.fixTestCase({config:t,error:e});console.debug(h.bold.yellow("[auto-fix]"),this.path),await this.environment.writeYaml(this.getTestCasePath(),n)}async readTestCase(){const e=this.getTestCasePath();return this.environment.readYaml(e)}async generateConfig(){return{}}async fixTestCase(e){throw new Error(`Auto-fix is not implemented for test ${this.path}`)}getResult(){return{logs:this.logs,assertions:this.assertions}}async assert(e,t,n){try{const r=await e();r?(this.logMsg(`\u2705 ${t}`),this.assertions.push({message:t,result:r})):(this.logMsg(`\u274C ${t}`),this.assertions.push({message:t,result:!1,details:n}))}catch(r){this.assertions.push({message:t,result:!1,details:V(r)}),this.logMsg(`\u274C ${t}: ${r.message}`)}}logMsg(e){console.debug(`${" ".repeat(this.level*2)}${e}`)}getTestCasePath(){return`${this.path}.test.yml`}}class ra extends ue{static{l(this,"DataCollectionCreateTester")}dataCollectionKey;dataCollection;constructor({environment:e,dataCollectionKey:t,dataCollection:n}){super({environment:e,path:`data/${t}/create`}),this.dataCollectionKey=t,this.dataCollection=n}async run(e){const t=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).create(e.input);await this.assert(()=>!!t.id,"Returned ID of a created record"),t.id&&(this.environment.state[this.dataCollectionKey]={createdRecordId:t.id});const n=Qe(this.dataCollection);if(this.dataCollection.findById){const i=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).findById({id:t.id});await this.assert(()=>!!i.record,"Record is returned from findById"),i.record&&(this.environment.state[this.dataCollectionKey]={createdRecordId:t.id,createdRecord:i.record.fields});const s=sn(n),a=Fe(e.input.fields,s,{skipUnknownFields:!0}),c=Fe(i.record.fields,s),u=zt(c,a);await this.assert(()=>!u,"Returned fields match created fields",{difference:u,sentFields:a,receivedFields:c})}const r=jo(n??{});if(r.length>0){const i={};r.forEach(a=>{const c=Mo(e.input.fields,a);typeof c<"u"&&et(i,a,c)});const s=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).create({fields:i});await this.assert(()=>!!s.id,"Record can be created with schema-defined required fields only")}}async generateConfig(){const e=Qe(this.dataCollection);if(!e?.properties)throw new Error("No fields schema found for data collection");return{input:{fields:await this.generateFieldsWithLLM(e)}}}async fixTestCase({config:e,error:t}){const n=V(t),r=Qe(this.dataCollection),i=await this.getExampleRecordsForSchema(r),s=`I'm trying to create a data record in a data collection with the following fields schema:
|
|
56
56
|
|
|
57
57
|
${JSON.stringify(r,null,2)}
|
|
58
58
|
|
|
@@ -76,7 +76,7 @@ Format your response as a JSON object with two fields:
|
|
|
76
76
|
"fields": { ... fixed fields ... }
|
|
77
77
|
}.
|
|
78
78
|
|
|
79
|
-
Only return the JSON object, no other text or wrapping (like \`\`\`json or \`\`\`).`,a=await this.environment.llm.complete({prompt:s,maxTokens:1e4}),c=JSON.parse(a.trim());return console.warn(
|
|
79
|
+
Only return the JSON object, no other text or wrapping (like \`\`\`json or \`\`\`).`,a=await this.environment.llm.complete({prompt:s,maxTokens:1e4}),c=JSON.parse(a.trim());return console.warn(h.bold.yellow("[auto-fix]"),`${this.path}:`,c.explanation),{input:{fields:c.fields}}}async generateFieldsWithLLM(e){const t=await this.getExampleRecordsForSchema(e),n=`Generate a valid JSON object that matches this JSONSchema. Return only the JSON object, no other text.
|
|
80
80
|
|
|
81
81
|
${this.getExampleRecordsPrompt(t)}
|
|
82
82
|
|
|
@@ -92,7 +92,7 @@ ${JSON.stringify(r,null,2)}`).join(`
|
|
|
92
92
|
|
|
93
93
|
`)}.
|
|
94
94
|
|
|
95
|
-
If you don't have an example for a given collection, leave the field empty instead of coming up with a fake record id.`}async findReferenceCollections(e){const t=new Set,n=[];return
|
|
95
|
+
If you don't have an example for a given collection, leave the field empty instead of coming up with a fake record id.`}async findReferenceCollections(e){const t=new Set,n=[];return an(e,r=>{if(r.referenceCollection){const i=r.referenceCollection.key,s=r.referenceCollection.parameters,a=`${i}:${JSON.stringify(s||{})}`;t.has(a)||(t.add(a),n.push({key:i,parameters:s}))}return r}),n}async fetchExampleRecords(e){return(await this.environment.client.connection(this.environment.connectionId).dataCollection(e.key).list({parameters:e.parameters})).records.map(n=>({id:n.id,fields:n.fields??{}}))}async getExampleRecordsForSchema(e){const t=await this.findReferenceCollections(e),n={};for(const r of t){const i=cn(r);n[i]=await this.fetchExampleRecords(r)}return n}}class ia extends ue{static{l(this,"DataCollectionDeleteTester")}dataCollectionKey;dataCollection;constructor({environment:e,dataCollectionKey:t,dataCollection:n}){super({environment:e,path:`data/${t}/delete`}),this.dataCollectionKey=t,this.dataCollection=n}async run(e){const t=this.environment.state[this.dataCollectionKey]?.createdRecordId||e?.input?.id;if(!t)throw new Error(`No ID found in state or config for ${this.dataCollectionKey} delete`);if(await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).delete({id:t}),this.dataCollection.findById)try{await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).findById({id:t})}catch(n){if(n?.data?.data?.response?.status===404){await this.assert(()=>!0,"Record is not found after deletion");return}throw n}else await this.assert(()=>!0,"No findById capability, skipping verification")}async generateConfig(){let e=this.environment.state[this.dataCollectionKey]?.createdRecordId;if(!e){if(!this.dataCollection.list)throw new Error(`Can't find a record to test delete operation for ${this.dataCollectionKey}. List operation is not implemented for this data collection`);const t=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).list({});if(!t?.records?.length)throw new Error(`No records found to test delete for ${this.dataCollectionKey}`);e=t.records[0].id}return{input:{id:e}}}async fixTestCase({config:e,error:t}){const n=V(t),r=`I'm trying to delete a record from a data collection.
|
|
96
96
|
|
|
97
97
|
I tried to delete a record with this ID:
|
|
98
98
|
|
|
@@ -112,7 +112,7 @@ Format your response as a JSON object with two fields:
|
|
|
112
112
|
"id": "fixed id"
|
|
113
113
|
}.
|
|
114
114
|
|
|
115
|
-
Only return the JSON object, no other text or wrapping (like \`\`\`json or \`\`\`).`,i=await this.environment.llm.complete({prompt:r,maxTokens:1e3}),s=JSON.parse(i.trim());return console.warn(
|
|
115
|
+
Only return the JSON object, no other text or wrapping (like \`\`\`json or \`\`\`).`,i=await this.environment.llm.complete({prompt:r,maxTokens:1e3}),s=JSON.parse(i.trim());return console.warn(h.bold.yellow("[auto-fix]"),`${this.path}:`,s.explanation),{input:{id:s.id}}}}class sa extends ue{static{l(this,"DataCollectionFindByIdTester")}dataCollectionKey;dataCollection;constructor({environment:e,dataCollectionKey:t,dataCollection:n}){super({environment:e,path:`data/${t}/find-by-id`}),this.dataCollectionKey=t,this.dataCollection=n}async run(e){const t=this.environment.state[this.dataCollectionKey]?.createdRecordId||e?.input?.id;if(!t)throw new Error(`No ID found in state or config for ${this.dataCollectionKey} find-by-id`);const n=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).findById({id:t});await this.assert(()=>!!n.record,"Record is returned from findById"),await this.assert(()=>n.record.id===t,"Returned record ID matches requested ID")}async generateConfig(){let e=this.environment.state[this.dataCollectionKey]?.createdRecordId;if(!e){if(!this.dataCollection.list)throw new Error(`Can't find a record to test findById operation for ${this.dataCollectionKey}. List operation is not implemented for this data collection`);const t=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).list({});if(!t?.records?.length)throw new Error(`No records found to test findById for ${this.dataCollectionKey}`);e=t.records[0].id}return{input:{id:e}}}async fixTestCase({config:e,error:t}){const n=V(t),r=`I'm trying to find a record by ID in a data collection.
|
|
116
116
|
|
|
117
117
|
I tried to find a record with this ID:
|
|
118
118
|
|
|
@@ -132,7 +132,7 @@ Format your response as a JSON object with two fields:
|
|
|
132
132
|
"id": "fixed id"
|
|
133
133
|
}.
|
|
134
134
|
|
|
135
|
-
Only return the JSON object, no other text or wrapping (like \`\`\`json or \`\`\`).`,i=await this.environment.llm.complete({prompt:r,maxTokens:1e3}),s=JSON.parse(i.trim());return console.warn(
|
|
135
|
+
Only return the JSON object, no other text or wrapping (like \`\`\`json or \`\`\`).`,i=await this.environment.llm.complete({prompt:r,maxTokens:1e3}),s=JSON.parse(i.trim());return console.warn(h.bold.yellow("[auto-fix]"),`${this.path}:`,s.explanation),{input:{id:s.id}}}}class aa extends ue{static{l(this,"DataCollectionListTester")}dataCollectionKey;constructor({environment:e,dataCollectionKey:t}){super({environment:e,path:`data/${t}/list`}),this.dataCollectionKey=t}async run(e){const t=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).list(e.input);if(await this.assert(()=>Array.isArray(t.records),"Response has records field as array"),e.input.sort){const{field:n,direction:r}=e.input.sort,i=t.records;if(i.length>1)for(let s=1;s<i.length;s++){const a=i[s-1].fields?.[n],c=i[s].fields?.[n];a==null||c==null||(r==="asc"?await this.assert(()=>a<=c,`Records are sorted by ${n} in ascending order`):await this.assert(()=>a>=c,`Records are sorted by ${n} in descending order`))}}}async generateConfig(){return{input:{}}}async fixTestCase({config:e,error:t}){const n=V(t),r=`I'm trying to list records from a data collection.
|
|
136
136
|
|
|
137
137
|
I tried to list records with these parameters:
|
|
138
138
|
|
|
@@ -152,7 +152,7 @@ Format your response as a JSON object with two fields:
|
|
|
152
152
|
"input": { ... fixed parameters ... }
|
|
153
153
|
}.
|
|
154
154
|
|
|
155
|
-
Only return the JSON object, no other text or wrapping (like \`\`\`json or \`\`\`).`,i=await this.environment.llm.complete({prompt:r,maxTokens:1e3}),s=JSON.parse(i.trim());return console.warn(
|
|
155
|
+
Only return the JSON object, no other text or wrapping (like \`\`\`json or \`\`\`).`,i=await this.environment.llm.complete({prompt:r,maxTokens:1e3}),s=JSON.parse(i.trim());return console.warn(h.bold.yellow("[auto-fix]"),`${this.path}:`,s.explanation),{input:s.input}}}class ca extends ue{static{l(this,"DataCollectionMatchTester")}dataCollectionKey;dataCollection;constructor({environment:e,dataCollectionKey:t,dataCollection:n}){super({environment:e,path:`data/${t}/match`}),this.dataCollectionKey=t,this.dataCollection=n}async run(e){const t=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).match(e.input);await this.assert(()=>!!t.record,"Response contains a record");const n=t.record,i=(await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).findById({id:n.id})).record;for(const[s,a]of Object.entries(e.input.query)){const c=i.fields?.[s];await this.assert(()=>Gt(c,a),`Record field ${s} matches input value - expected ${JSON.stringify(a)} got ${JSON.stringify(c)}`)}}async generateConfig(){if(!this.dataCollection.list)throw new Error(`Can't find a record to test match operation for ${this.dataCollectionKey}. List operation is not implemented for this data collection`);const e=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).list({});if(!e?.records?.length)throw new Error("No records found to test match");const t=e.records[0];if(!t?.fields)throw new Error("First record has no fields to match against");const n={},r=t.fields||{},i=Object.entries(r).filter(([s,a])=>s!=="links"&&a!=null&&a!=="").slice(0,1);if(i.length===0)throw new Error("No usable fields found in record for matching");for(const[s,a]of i)n[s]=a;return{input:{query:n}}}async fixTestCase({config:e,error:t}){const n=V(t),r=`I'm trying to match a record in a data collection.
|
|
156
156
|
|
|
157
157
|
I tried to match a record with this query:
|
|
158
158
|
|
|
@@ -172,7 +172,7 @@ Format your response as a JSON object with two fields:
|
|
|
172
172
|
"query": { ... fixed query ... }
|
|
173
173
|
}.
|
|
174
174
|
|
|
175
|
-
Only return the JSON object, no other text or wrapping (like \`\`\`json or \`\`\`).`,i=await this.environment.llm.complete({prompt:r,maxTokens:1e3}),s=JSON.parse(i.trim());return console.warn(
|
|
175
|
+
Only return the JSON object, no other text or wrapping (like \`\`\`json or \`\`\`).`,i=await this.environment.llm.complete({prompt:r,maxTokens:1e3}),s=JSON.parse(i.trim());return console.warn(h.bold.yellow("[auto-fix]"),`${this.path}:`,s.explanation),{input:{query:s.query}}}}class la extends ue{static{l(this,"DataCollectionSearchTester")}dataCollectionKey;dataCollection;constructor({environment:e,dataCollectionKey:t,dataCollection:n}){super({environment:e,path:`data/${t}/search`}),this.dataCollectionKey=t,this.dataCollection=n}async run(e){const t=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).search(e.input);await this.assert(()=>Array.isArray(t.records),"Response has records field as array");const n=t.records.some(r=>r.id===e.expectedRecordId);n||console.debug(h.yellow(`Search query "${e.input.query}" did not return expected record`)),await this.assert(()=>n,"Search returns expected record")}async generateConfig(){if(!this.dataCollection.list)throw new Error(`Can't find a record to test search operation for ${this.dataCollectionKey}. List operation is not implemented for this data collection`);const e=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).list({});if(!e.records.length)throw new Error("No records found to test search");const t=e.records[0],n=await this.getSearchQueryWithLLM(t.fields||{});if(!n)throw new Error("Unable to generate search query. LLM could not identify a suitable field value from the record to use as the search query.");return{input:{query:n},expectedRecordId:t.id}}async getSearchQueryWithLLM(e){const t=`You are given the fields of a record from a data collection. Identify the BEST single field value that a user is MOST likely to type when searching for this record (e.g. name, title, email, external id). Ignore null, empty strings, technical IDs, HTML, and timestamps unless they are obviously human-searchable. Make sure the field value is as unique as possible for this record. RETURN ONLY the field value as a plain string. No additional text, no JSON, no quotes.
|
|
176
176
|
|
|
177
177
|
Record fields:
|
|
178
178
|
${JSON.stringify(e,null,2)}
|
|
@@ -197,7 +197,7 @@ Format your response as a JSON object with two fields:
|
|
|
197
197
|
"input": { ... fixed parameters ... }
|
|
198
198
|
}.
|
|
199
199
|
|
|
200
|
-
Only return the JSON object, no other text or wrapping (like \`\`\`json or \`\`\`).`,i=await this.environment.llm.complete({prompt:r,maxTokens:1e3}),s=JSON.parse(i.trim());return console.warn(
|
|
200
|
+
Only return the JSON object, no other text or wrapping (like \`\`\`json or \`\`\`).`,i=await this.environment.llm.complete({prompt:r,maxTokens:1e3}),s=JSON.parse(i.trim());return console.warn(h.bold.yellow("[auto-fix]"),`${this.path}:`,s.explanation),{input:s.input,expectedRecordId:e.expectedRecordId}}}class ua extends ue{static{l(this,"DataCollectionSpecTester")}dataCollection;constructor({environment:e,dataCollectionKey:t,dataCollection:n}){super({environment:e,path:`data/${t}/spec`}),this.dataCollection=n}async run(){const e=Object.keys(this.dataCollection.fieldsSchema||{}).length;await this.assert(()=>e>0,"Fields schema has field definitions")}}class da extends ue{static{l(this,"DataCollectionUpdateTester")}dataCollectionKey;dataCollection;constructor({environment:e,dataCollectionKey:t,dataCollection:n}){super({environment:e,path:`data/${t}/update`}),this.dataCollectionKey=t,this.dataCollection=n}async run(e){const t=this.environment.state[this.dataCollectionKey]?.createdRecordId||e?.input?.id;if(!t)throw new Error(`No ID found in state or config for ${this.dataCollectionKey} update`);const n=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).update({...e.input,id:t});if(await this.assert(()=>!!n.id,"Returned ID of updated record"),this.environment.state[this.dataCollectionKey]||(this.environment.state[this.dataCollectionKey]={}),this.environment.state[this.dataCollectionKey].createdRecordId=n.id,this.dataCollection.findById){const r=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).findById({id:n.id});await this.assert(()=>!!r.record,"Record is returned from findById");const i=tt(this.dataCollection),s=sn(i),a=Fe(e.input.fields,s,{skipUnknownFields:!0}),c=Fe(r.record.fields,s),u=zt(c,a);await this.assert(()=>!u,"Returned fields match updated fields",{difference:u,sentFields:a,receivedFields:c})}}async generateConfig(){let e=this.environment.state[this.dataCollectionKey]?.createdRecordId;if(!e){if(!this.dataCollection.list)throw new Error(`Can't find a record to test update operation for ${this.dataCollectionKey}. List operation is not implemented for this data collection`);const r=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).list({});if(!r?.records?.length)throw new Error(`No records found to test update for ${this.dataCollectionKey}`);e=r.records[0].id}const t=tt(this.dataCollection);if(!t?.properties)throw new Error("No fields schema found for data collection");const n=await this.generateFieldsWithLLM(t);return{input:{id:e,fields:n}}}async fixTestCase({config:e,error:t}){const n=V(t),r=tt(this.dataCollection),i=await this.getExampleRecordsForSchema(r),s=`I'm trying to update a data record in a data collection with the following fields schema:
|
|
201
201
|
|
|
202
202
|
${JSON.stringify(r,null,2)}
|
|
203
203
|
|
|
@@ -221,7 +221,7 @@ Format your response as a JSON object with two fields:
|
|
|
221
221
|
"fields": { ... fixed fields ... }
|
|
222
222
|
}.
|
|
223
223
|
|
|
224
|
-
Only return the JSON object, no other text or wrapping (like \`\`\`json or \`\`\`).`,a=await this.environment.llm.complete({prompt:s,maxTokens:1e4}),c=JSON.parse(a.trim());return console.warn(
|
|
224
|
+
Only return the JSON object, no other text or wrapping (like \`\`\`json or \`\`\`).`,a=await this.environment.llm.complete({prompt:s,maxTokens:1e4}),c=JSON.parse(a.trim());return console.warn(h.bold.yellow("[auto-fix]"),`${this.path}:`,c.explanation),{input:{id:e.input.id,fields:c.fields}}}async generateFieldsWithLLM(e){const t=await this.getExampleRecordsForSchema(e),n=`Generate a valid JSON object that matches this JSONSchema. Return only the JSON object, no other text.
|
|
225
225
|
|
|
226
226
|
${this.getExampleRecordsPrompt(t)}
|
|
227
227
|
|
|
@@ -237,9 +237,9 @@ ${JSON.stringify(r,null,2)}`).join(`
|
|
|
237
237
|
|
|
238
238
|
`)}.
|
|
239
239
|
|
|
240
|
-
If you don't have an example for a given collection, leave the field empty instead of coming up with a fake record id.`}async findReferenceCollections(e){const t=new Set,n=[];return
|
|
241
|
-
`),"createExperimentalWarning");function ya(o){o.command("test").description("\u26A0\uFE0F EXPERIMENTAL: Test management commands - This feature is experimental and will be changing rapidly. Use at your own risk.").addHelpText("after",He()).action(async()=>{console.warn(He()),b.error("Please specify a subcommand. Use --help for available options."),process.exit(1)}).command("run").description("Run integration tests for various membrane components").argument("<testPath>",'Test path (e.g., "connectors/netsuite", "actions/create-contact", "connectors/hubspot/data/contacts", "connectors/netsuite/data/contacts/create")').option("-p, --path <path>","Additional path filter within the test scope").option("--fix","Enable auto-fix for test issues").addHelpText("after",["",
|
|
242
|
-
`)).action(async(t,n)=>{try{console.warn(He()),t||(b.error("Test path is required"),process.exit(1)),b.header(`Testing: ${t}`);const r=new ga({testPath:t,path:n.path,fix:n.fix});await r.initialize(),await r.run(),b.success("Tests completed")}catch(r){r instanceof Error&&(b.error(r.message),process.exit(1)),b.error("An unknown error occurred"),process.exit(1)}})}l(ya,"setupTestCommand");const wa=l(()=>{try{const o=To(import.meta.url),e=bo(o),t=Ve(e,"..","package.json");return JSON.parse(So(t,"utf-8")).version}catch{return"1.0.0"}},"getPackageVersion"),mo=wa();function Ca(){process.on("SIGINT",()=>process.exit(130));const o=new yo().name("membrane").description("Command-line interface for Membrane Agent").version(mo,"-v, --version","Output the version number").option("--verbose","Enable verbose logging (shows debug messages)");o.configureHelp({sortSubcommands:!0,subcommandTerm:l(t=>
|
|
243
|
-
${
|
|
240
|
+
If you don't have an example for a given collection, leave the field empty instead of coming up with a fake record id.`}async findReferenceCollections(e){const t=new Set,n=[];return an(e,r=>{if(r.referenceCollection){const i=r.referenceCollection.key,s=r.referenceCollection.parameters,a=`${i}:${JSON.stringify(s||{})}`;t.has(a)||(t.add(a),n.push({key:i,parameters:s}))}return r}),n}async fetchExampleRecords(e){return(await this.environment.client.connection(this.environment.connectionId).dataCollection(e.key).list({parameters:e.parameters})).records.map(n=>({id:n.id,fields:n.fields||{}}))}async getExampleRecordsForSchema(e){const t=await this.findReferenceCollections(e),n={};for(const r of t){const i=cn(r);n[i]=await this.fetchExampleRecords(r)}return n}}dr.interpolate=/{{([\s\S]+?)}}/g;function Ht(o,e){if(typeof o=="string"){const t=ur(o),n={state:e,random:{number:l(()=>ke.number.int(),"number"),alphaNumeric:l(i=>ke.string.alphanumeric(i),"alphaNumeric")},faker:{company:{name:l(()=>ke.company.name(),"name"),catchPhrase:l(()=>ke.company.catchPhrase(),"catchPhrase")},internet:{email:l(()=>ke.internet.email(),"email")}},entries:e["journal-entries"],orders:e["purchase-orders"]||e["sales-orders"],bills:e["vendor-bills"]},r=t(n);return o.includes("{{")&&o.includes("}}")&&(console.debug(`[TEMPLATE] Input: ${o}`),console.debug(`[TEMPLATE] Output: ${r}`)),r}return Array.isArray(o)?o.map(t=>Ht(t,e)):typeof o=="object"&&o!==null?Object.fromEntries(Object.entries(o).map(([t,n])=>[t,Ht(n,e)])):o}l(Ht,"processNode");function pa(o,e){return Ht(o,e)}l(pa,"handleTemplate");class ha{static{l(this,"BaseTestSuite")}result;environment;constructor({environment:e}){this.environment=e,this.result={}}async run(){}getResult(){return this.result}async runTest(e){console.debug(`${h.bold.cyan("[start]")} ${h.yellow(e.path)}`);let t=!1,n=!1,r={},i={},s;for(;!t;)try{i=await e.readTestCase(),i||(i=await e.generateConfig(),await this.environment.writeYaml(e.getTestCasePath(),i),console.debug(`${h.bold.yellow("[initialized]")} ${h.yellow(e.path)}`)),s=pa(i,this.environment.state),await e.run(s),console.debug(`${h.bold.green("[success]")} ${h.yellow(e.path)}`),t=!0,r=e.getResult(),et(this.result,e.path,r)}catch(c){if(console.error(`${h.bold.red("[error]")} ${h.yellow(e.path)}: ${c}`),this.environment.options.fix&&!n){n=!0;try{await e.fix(c);continue}catch(u){console.error(`${h.bold.red("[fix fail]")} ${h.yellow(e.path)}: ${u}`)}}et(this.result,e.path,{error:V(c)}),t=!0,r={error:V(c)}}const a={...s,result:r};await this.environment.writeYaml(e.getTestCasePath(),a)}async runTestSuite(e){await e.run(),dt(this.result,e.getResult())}}const Vt={spec:{testerClass:ua},create:{testerClass:ra,operationKey:"create"},"find-by-id":{testerClass:sa,operationKey:"findById"},list:{testerClass:aa,operationKey:"list"},match:{testerClass:ca,operationKey:"match"},search:{testerClass:la,operationKey:"search"},update:{testerClass:da,operationKey:"update"},delete:{testerClass:ia,operationKey:"delete"}};class fa extends ha{static{l(this,"DataCollectionTestSuite")}dataCollectionKey;testMethod;constructor({environment:e,dataCollectionKey:t,testMethod:n}){super({environment:e}),this.dataCollectionKey=t,this.testMethod=n}async run(){const e=await this.fetchDataCollection(),t=this.testMethod?[this.createTester(this.testMethod,e)]:this.createAllAvailableTesters(e);b.info("\u{1F680} Running tests...");for(const n of t)await this.runTest(n);this.displayTestSummary(t.length)}async fetchDataCollection(){return this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).get()}isOperationAvailable(e,t){return t?!!e[t]:!0}createTester(e,t){const n=Vt[e];if(!n)throw new Error(`Unknown test method "${e}". Available: ${this.getAvailableTestMethods(t).join(", ")}`);const r="operationKey"in n?n.operationKey:void 0;if(!this.isOperationAvailable(t,r))throw new Error(`${r} operation not available for data collection "${this.dataCollectionKey}"`);return this.instantiateTester(n,t)}createAllAvailableTesters(e){return Object.entries(Vt).filter(([,t])=>{const n="operationKey"in t?t.operationKey:void 0;return this.isOperationAvailable(e,n)}).map(([,t])=>this.instantiateTester(t,e))}instantiateTester(e,t){const n={environment:this.environment,dataCollectionKey:this.dataCollectionKey,dataCollection:t};return new e.testerClass(n)}getAvailableTestMethods(e){return Object.entries(Vt).filter(([,t])=>{const n="operationKey"in t?t.operationKey:void 0;return this.isOperationAvailable(e,n)}).map(([t])=>t)}displayTestSummary(e){b.info(`\u{1F4CA} ${e} test${e===1?"":"s"} executed`)}}class ma{static{l(this,"BaseRunner")}constructor(e={}){if(this.options=e,this.fsPaths=ft(),e&&typeof e=="object"){const t=e;"client"in t&&t.client&&(this.client=t.client),"workspace"in t&&(this.workspace=t.workspace)}}client;workspace;fsPaths}class ga extends ma{static{l(this,"TestRunner")}constructor(e){super(e)}async initialize(){b.debug("Initializing test runner",{prefix:"TestRunner"})}async run(){try{const{testPath:e,path:t,fix:n}=this.options,r=e.split("/");r.length<2&&(b.error("Invalid test path. Expected format: <type>/<name>[/additional/path][/method]"),process.exit(1));const[i,s,...a]=r;i!=="connectors"&&(b.error(`Test type "${i}" is not yet fully implemented. Currently only "connectors" is fully supported.`),b.error("Supported test types: connectors"),process.exit(1));const c=s,u=i,p=[...a,...t?t.split("/"):[]].join("/"),m=await Yt.create({connectionId:c,testBasePath:u,options:{fix:n}}),y=await m.client.get(`connections/${c}/data`),I=[],S=p?p.split("/"):[];if(S.length===0||S[0]==="data"){S[0]==="data"&&S.shift();let N,M;S.length>=1&&(M=S[0],S.length>=2&&S[1].trim()!==""&&(N=S[1]));for(const K of y){if(M&&M!==K.key)continue;const F=new fa({environment:m,dataCollectionKey:K.key,testMethod:N});I.push(F)}}I.length===0&&(b.error(`No test suites found for path: ${e}${p?"/"+p:""}`),process.exit(1));const R={};for(const N of I){await N.run();const M=N.getResult();b.debug(`Suite ${N.constructor.name} result:`,{prefix:"TestRunner"}),dt(R,M)}console.debug("[TestRunner] All results collected:",Object.keys(R)),m.writeResults(R)}catch(e){throw console.error("Error in TestRunner.run():",e),e}}}const He=l(()=>[h.yellow("\u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510"),h.yellow("\u2502 \u26A0\uFE0F EXPERIMENTAL FEATURE WARNING \u2502"),h.yellow("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524"),h.yellow("\u2502 The test command is experimental and subject to rapid changes. \u2502"),h.yellow("\u2502 Features, APIs, and file structures may change without notice. \u2502"),h.yellow("\u2502 Use in production environments is not recommended. \u2502"),h.yellow("\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518"),""].join(`
|
|
241
|
+
`),"createExperimentalWarning");function ya(o){o.command("test").description("\u26A0\uFE0F EXPERIMENTAL: Test management commands - This feature is experimental and will be changing rapidly. Use at your own risk.").addHelpText("after",He()).action(async()=>{console.warn(He()),b.error("Please specify a subcommand. Use --help for available options."),process.exit(1)}).command("run").description("Run integration tests for various membrane components").argument("<testPath>",'Test path (e.g., "connectors/netsuite", "actions/create-contact", "connectors/hubspot/data/contacts", "connectors/netsuite/data/contacts/create")').option("-p, --path <path>","Additional path filter within the test scope").option("--fix","Enable auto-fix for test issues").addHelpText("after",["",h.bold("Examples:"),` ${h.gray("\u25B8")} ${h.cyan("membrane test run connectors/netsuite")} # Test all data collections for netsuite connector`,` ${h.gray("\u25B8")} ${h.cyan("membrane test run connectors/netsuite/data/contacts")} # Test specific data collection`,` ${h.gray("\u25B8")} ${h.cyan("membrane test run connectors/netsuite/data/contacts/create")} # Test specific method for data collection`,` ${h.gray("\u25B8")} ${h.cyan("membrane test run connectors/netsuite/data/contacts/delete")} # Test delete method for data collection`,` ${h.gray("\u25B8")} ${h.cyan("membrane test run actions/create-contact")} # Test specific action`,` ${h.gray("\u25B8")} ${h.cyan("membrane test run connectors/hubspot/events")} # Test events for hubspot`,` ${h.gray("\u25B8")} ${h.cyan("membrane test run connectors/salesforce --fix")} # Run tests with auto-fix enabled`,"",h.gray("For more information, visit:"),h.blue(" https://docs.getmembrane.com/docs/development-environment"),"",He()].join(`
|
|
242
|
+
`)).action(async(t,n)=>{try{console.warn(He()),t||(b.error("Test path is required"),process.exit(1)),b.header(`Testing: ${t}`);const r=new ga({testPath:t,path:n.path,fix:n.fix});await r.initialize(),await r.run(),b.success("Tests completed")}catch(r){r instanceof Error&&(b.error(r.message),process.exit(1)),b.error("An unknown error occurred"),process.exit(1)}})}l(ya,"setupTestCommand");const wa=l(()=>{try{const o=To(import.meta.url),e=bo(o),t=Ve(e,"..","package.json");return JSON.parse(So(t,"utf-8")).version}catch{return"1.0.0"}},"getPackageVersion"),mo=wa();function Ca(){process.on("SIGINT",()=>process.exit(130));const o=new yo().name("membrane").description("Command-line interface for Membrane Agent").version(mo,"-v, --version","Output the version number").option("--verbose","Enable verbose logging (shows debug messages)");o.configureHelp({sortSubcommands:!0,subcommandTerm:l(t=>h.cyan(t.name()),"subcommandTerm"),commandUsage:l(t=>t.name()==="membrane"?`${h.cyan(t.name())} ${h.gray("[options]")} ${h.cyan("[command]")}`:t.usage(),"commandUsage"),optionTerm:l(t=>{const n=t.flags;return`${h.gray("\u25B8")} ${h.cyan(n)}`},"optionTerm"),subcommandDescription:l(t=>h.gray(t.description()),"subcommandDescription"),optionDescription:l(t=>h.gray(t.description),"optionDescription"),commandDescription:l(t=>h.gray(t.description()),"commandDescription")}),o.addHelpText("beforeAll",`
|
|
243
|
+
${h.bold.cyan("Membrane Agent CLI")} ${h.gray(`v${mo}`)}
|
|
244
244
|
|
|
245
|
-
`);const e=new bi(ze.Cli,process.cwd());Ki(o),zi(o),es(o),Oi(o),Di(o),Ri(o),Or(o),
|
|
245
|
+
`);const e=new bi(ze.Cli,process.cwd());Ki(o),zi(o),es(o),Oi(o),Di(o),Ri(o),Or(o),js(o),Ms(o),Pr(o),Us(o),cs(o),vs(o),as(o),ya(o),ss(o),na(o,e),Wi(o,e),Fr(o,e),Ei(o,e),o.hook("preAction",(t,n)=>{o.opts().verbose&&g.setVerboseMode(!0);const r=n.opts().apiUri||me()||te;r!==te&&console.error(`Using apiUri: ${r}`)}),process.argv.length===2&&(o.outputHelp(),process.exit(0)),o.parse()}l(Ca,"runCLI"),Ca();
|