@membranehq/cli 1.1.19 → 1.1.20
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 +17 -17
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var xc=Object.defineProperty;var c=(s,e)=>xc(s,"name",{value:e,configurable:!0});import{jsx as m,jsxs as _,Fragment as ut}from"react/jsx-runtime";import*as K from"node:path";import{join as Ks,resolve as Pc,dirname as Rc}from"node:path";import k from"chalk";import{useInput as Xe,Box as S,Text as v,Newline as Mc,render as Ut}from"ink";import Lc from"minimist";import{SWRConfig as Dc}from"swr";import Ae,{createContext as Bs,useState as J,useEffect as Fe,useContext as Us,useMemo as jc,useRef as Ws,useId as Fc,useLayoutEffect as _n}from"react";import Ei from"swr/immutable";import _i from"os";import U from"path";import qc from"conf";import{MembraneConfigLoader as Kc,MembraneAxiosInstance as Bc,MembraneClient as Ii,WorkspaceElementType as
|
|
3
|
-
`);return Vc(i,o,"utf-8"),i}catch(t){return console.error("Failed to save logs:",t),null}}}const b=new El,Di=new Yc;class ji{static{c(this,"RequestLogger")}constructor(e=Bc){this.axiosInstance=e}interceptorsConfigured=!1;setup(){if(this.interceptorsConfigured)return;const e=c(t=>(this.logError(t),Promise.reject(t)),"errorHandler");this.axiosInstance.interceptors.request.use(t=>{const n=Di.getStore();t.metadata={startTime:Date.now(),skipErrorLog:n};const{method:r,url:i}=this.getRequestDetails(t);return b.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:o,statusText:a}=t;return b.debug(`[Response]: ${n} ${r} - ${o} ${a} (${i}ms)`),t},e),this.interceptorsConfigured=!0}static withSkipErrorLog(e){return Di.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:o}=e.response;b.error(`[Response]: ${t} ${n} - ${i} ${o} (${r}ms)`),e.response.data&&b.error(`[Response Data]: ${JSON.stringify(e.response.data,null,2)}`)}}}class _l{static{c(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 ji,this.requestLogger.setup()}async withClient(e,t=!0,n=process.cwd()){const r=c(async()=>{try{return await this.withRetry(async()=>{const i=await this.getClient(n);await this.acquireSemaphore();try{return await this.waitIfNeeded(),this.recordRequest(),await this.withTimeout(e(i),this.requestTimeout)}finally{this.releaseSemaphore()}},"API request")}catch(i){if(t)throw i;return}},"executeRequest");return t?r():ji.withSkipErrorLog(r)}async generateAccessToken(e,t){return zs.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=On(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 Ii({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 o=new Date().toISOString(),a=r+2;b.debug(`[${o}] Retrying ${t} (attempt ${a}/${this.maxRetries+1})`);let l=this.retryDelay*Math.pow(2,r);if(this.enableJitter){const u=l*.25*(Math.random()*2-1);l=Math.max(0,l+u)}await new Promise(u=>setTimeout(u,l))}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(o=>t.includes(o))}async withTimeout(e,t){let n;const r=new Promise((i,o)=>{n=setTimeout(()=>o(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}}}const B=new _l;async function Fi(s){const e=await B.withClient(t=>t.get("org-workspace-id"),!0,s);if(!e)throw new Error("Failed to get workspace ID");return e.id}c(Fi,"getWorkspaceId");var q={},$n={},qi;function Ki(){if(qi)return $n;qi=1,Object.defineProperty($n,"__esModule",{value:!0});function s(e){return e===void 0&&(e=""),e?String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/[^A-Za-z0-9]+/g,"$").replace(/([a-z])([A-Z])/g,function(t,n,r){return n+"$"+r}).toLowerCase().replace(/(\$)(\w)/g,function(t,n,r){return r.toUpperCase()}):""}return c(s,"toCamelCase"),$n.default=s,$n}c(Ki,"requireJsCamelcase");var Nn={},Bi;function Ui(){if(Bi)return Nn;Bi=1,Object.defineProperty(Nn,"__esModule",{value:!0});function s(e){return e===void 0&&(e=""),e?String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/([a-z])([A-Z])/g,function(t,n,r){return n+"_"+r.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g,"_").toLowerCase():""}return c(s,"toSnakeCase"),Nn.default=s,Nn}c(Ui,"requireJsSnakecase");var xn={},Wi;function Ji(){if(Wi)return xn;Wi=1,Object.defineProperty(xn,"__esModule",{value:!0});function s(e){return e===void 0&&(e=""),e?String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"$").replace(/[^A-Za-z0-9]+/g,"$").replace(/([a-z])([A-Z])/g,function(t,n,r){return n+"$"+r}).toLowerCase().replace(/(\$)(\w?)/g,function(t,n,r){return r.toUpperCase()}):""}return c(s,"toPascalCase"),xn.default=s,xn}c(Ji,"requireJsPascalcase");var Pn={},Hi;function Il(){if(Hi)return Pn;Hi=1,Object.defineProperty(Pn,"__esModule",{value:!0});function s(e){return e===void 0&&(e=""),e?String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/([a-z])([A-Z])/g,function(t,n,r){return n+"_"+r.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g,".").toLowerCase():""}return c(s,"toDotCase"),Pn.default=s,Pn}c(Il,"requireJsDotcase");var Rn={},Vi;function Al(){if(Vi)return Rn;Vi=1,Object.defineProperty(Rn,"__esModule",{value:!0});function s(e){return e===void 0&&(e=""),e?String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/([a-z])([A-Z])/g,function(t,n,r){return n+"_"+r.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g,"/").toLowerCase():""}return c(s,"toPathCase"),Rn.default=s,Rn}c(Al,"requireJsPathcase");var Mn={},Gi;function Ol(){if(Gi)return Mn;Gi=1,Object.defineProperty(Mn,"__esModule",{value:!0});function s(e){return e===void 0&&(e=""),e?String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/([a-z])([A-Z])/g,function(t,n,r){return n+"_"+r.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g," ").toLowerCase():""}return c(s,"toTextCase"),Mn.default=s,Mn}c(Ol,"requireJsTextcase");var Ln={},zi;function $l(){if(zi)return Ln;zi=1,Object.defineProperty(Ln,"__esModule",{value:!0});function s(e){if(e===void 0&&(e=""),!e)return"";var t=String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/([a-z])([A-Z])/g,function(n,r,i){return r+"_"+i.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g," ").toLowerCase();return t.charAt(0).toUpperCase()+t.slice(1)}return c(s,"toSentenceCase"),Ln.default=s,Ln}c($l,"requireJsSentencecase");var Dn={},Yi;function Nl(){if(Yi)return Dn;Yi=1,Object.defineProperty(Dn,"__esModule",{value:!0});function s(e){return e===void 0&&(e=""),e?String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/([a-z])([A-Z])/g,function(t,n,r){return n+"_"+r.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g," ").toLowerCase().replace(/( ?)(\w+)( ?)/g,function(t,n,r,i){return n+r.charAt(0).toUpperCase()+r.slice(1)+i}):""}return c(s,"toHeaderCase"),Dn.default=s,Dn}c(Nl,"requireJsHeadercase");var jn={},Xi;function Qi(){if(Xi)return jn;Xi=1,Object.defineProperty(jn,"__esModule",{value:!0});function s(e){return e===void 0&&(e=""),e?String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/([a-z])([A-Z])/g,function(t,n,r){return n+"_"+r.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g,"-").toLowerCase():""}return c(s,"toKebabCase"),jn.default=s,jn}c(Qi,"requireJsKebabcase");var ft={},sr={},Zi;function ht(){return Zi||(Zi=1,function(s){Object.defineProperty(s,"__esModule",{value:!0}),s.belongToTypes=s.isValidObject=s.isArrayObject=s.validateOptions=s.DefaultOption=void 0,s.DefaultOption={recursive:!1,recursiveInArray:!1,keepTypesOnRecursion:[]},s.validateOptions=function(e){return e===void 0&&(e=s.DefaultOption),e.recursive==null?e=s.DefaultOption:e.recursiveInArray==null&&(e.recursiveInArray=!1),e},s.isArrayObject=function(e){return e!=null&&Array.isArray(e)},s.isValidObject=function(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)},s.belongToTypes=function(e,t){return(t||[]).some(function(n){return e instanceof n})}}(sr)),sr}c(ht,"requireUtils");var eo;function xl(){if(eo)return ft;eo=1;var s=ft&&ft.__spreadArrays||function(){for(var n=0,r=0,i=arguments.length;r<i;r++)n+=arguments[r].length;for(var o=Array(n),a=0,r=0;r<i;r++)for(var l=arguments[r],u=0,d=l.length;u<d;u++,a++)o[a]=l[u];return o};Object.defineProperty(ft,"__esModule",{value:!0});var e=ht();function t(n,r){if(r===void 0&&(r=e.DefaultOption),!e.isValidObject(n))return null;r=e.validateOptions(r);var i={};return Object.keys(n).forEach(function(o){var a=n[o],l=o.toLowerCase();r.recursive&&(e.isValidObject(a)?e.belongToTypes(a,r.keepTypesOnRecursion)||(a=t(a,r)):r.recursiveInArray&&e.isArrayObject(a)&&(a=s(a).map(function(u){var d=u;if(e.isValidObject(u))e.belongToTypes(d,r.keepTypesOnRecursion)||(d=t(u,r));else if(e.isArrayObject(u)){var f=t({key:u},r);d=f.key}return d}))),i[l]=a}),i}return c(t,"lowerKeys"),ft.default=t,ft}c(xl,"requireLowercaseKeysObject");var pt={},to;function Pl(){if(to)return pt;to=1;var s=pt&&pt.__spreadArrays||function(){for(var n=0,r=0,i=arguments.length;r<i;r++)n+=arguments[r].length;for(var o=Array(n),a=0,r=0;r<i;r++)for(var l=arguments[r],u=0,d=l.length;u<d;u++,a++)o[a]=l[u];return o};Object.defineProperty(pt,"__esModule",{value:!0});var e=ht();function t(n,r){if(r===void 0&&(r=e.DefaultOption),!e.isValidObject(n))return null;r=e.validateOptions(r);var i={};return Object.keys(n).forEach(function(o){var a=n[o],l=o.toUpperCase();r.recursive&&(e.isValidObject(a)?e.belongToTypes(a,r.keepTypesOnRecursion)||(a=t(a,r)):r.recursiveInArray&&e.isArrayObject(a)&&(a=s(a).map(function(u){var d=u;if(e.isValidObject(u))e.belongToTypes(d,r.keepTypesOnRecursion)||(d=t(u,r));else if(e.isArrayObject(u)){var f=t({key:u},r);d=f.key}return d}))),i[l]=a}),i}return c(t,"upperKeys"),pt.default=t,pt}c(Pl,"requireUppercaseKeysObject");var mt={},no;function Rl(){if(no)return mt;no=1;var s=mt&&mt.__spreadArrays||function(){for(var r=0,i=0,o=arguments.length;i<o;i++)r+=arguments[i].length;for(var a=Array(r),l=0,i=0;i<o;i++)for(var u=arguments[i],d=0,f=u.length;d<f;d++,l++)a[l]=u[d];return a};Object.defineProperty(mt,"__esModule",{value:!0});var e=ht(),t=Ki();function n(r,i){if(i===void 0&&(i=e.DefaultOption),!e.isValidObject(r))return null;i=e.validateOptions(i);var o={};return Object.keys(r).forEach(function(a){var l=r[a],u=t.default(a);i.recursive&&(e.isValidObject(l)?e.belongToTypes(l,i.keepTypesOnRecursion)||(l=n(l,i)):i.recursiveInArray&&e.isArrayObject(l)&&(l=s(l).map(function(d){var f=d;if(e.isValidObject(d))e.belongToTypes(f,i.keepTypesOnRecursion)||(f=n(d,i));else if(e.isArrayObject(d)){var h=n({key:d},i);f=h.key}return f}))),o[u]=l}),o}return c(n,"camelKeys"),mt.default=n,mt}c(Rl,"requireCamelcaseKeysObject");var gt={},so;function Ml(){if(so)return gt;so=1;var s=gt&>.__spreadArrays||function(){for(var r=0,i=0,o=arguments.length;i<o;i++)r+=arguments[i].length;for(var a=Array(r),l=0,i=0;i<o;i++)for(var u=arguments[i],d=0,f=u.length;d<f;d++,l++)a[l]=u[d];return a};Object.defineProperty(gt,"__esModule",{value:!0});var e=ht(),t=Ui();function n(r,i){if(i===void 0&&(i=e.DefaultOption),!e.isValidObject(r))return null;i=e.validateOptions(i);var o={};return Object.keys(r).forEach(function(a){var l=r[a],u=t.default(a);i.recursive&&(e.isValidObject(l)?e.belongToTypes(l,i.keepTypesOnRecursion)||(l=n(l,i)):i.recursiveInArray&&e.isArrayObject(l)&&(l=s(l).map(function(d){var f=d;if(e.isValidObject(d))e.belongToTypes(f,i.keepTypesOnRecursion)||(f=n(d,i));else if(e.isArrayObject(d)){var h=n({key:d},i);f=h.key}return f}))),o[u]=l}),o}return c(n,"snakeKeys"),gt.default=n,gt}c(Ml,"requireSnakecaseKeysObject");var yt={},ro;function Ll(){if(ro)return yt;ro=1;var s=yt&&yt.__spreadArrays||function(){for(var r=0,i=0,o=arguments.length;i<o;i++)r+=arguments[i].length;for(var a=Array(r),l=0,i=0;i<o;i++)for(var u=arguments[i],d=0,f=u.length;d<f;d++,l++)a[l]=u[d];return a};Object.defineProperty(yt,"__esModule",{value:!0});var e=ht(),t=Ji();function n(r,i){if(i===void 0&&(i=e.DefaultOption),!e.isValidObject(r))return null;i=e.validateOptions(i);var o={};return Object.keys(r).forEach(function(a){var l=r[a],u=t.default(a);i.recursive&&(e.isValidObject(l)?e.belongToTypes(l,i.keepTypesOnRecursion)||(l=n(l,i)):i.recursiveInArray&&e.isArrayObject(l)&&(l=s(l).map(function(d){var f=d;if(e.isValidObject(d))e.belongToTypes(f,i.keepTypesOnRecursion)||(f=n(d,i));else if(e.isArrayObject(d)){var h=n({key:d},i);f=h.key}return f}))),o[u]=l}),o}return c(n,"pascalKeys"),yt.default=n,yt}c(Ll,"requirePascalcaseKeysObject");var wt={},io;function Dl(){if(io)return wt;io=1;var s=wt&&wt.__spreadArrays||function(){for(var r=0,i=0,o=arguments.length;i<o;i++)r+=arguments[i].length;for(var a=Array(r),l=0,i=0;i<o;i++)for(var u=arguments[i],d=0,f=u.length;d<f;d++,l++)a[l]=u[d];return a};Object.defineProperty(wt,"__esModule",{value:!0});var e=ht(),t=Qi();function n(r,i){if(i===void 0&&(i=e.DefaultOption),!e.isValidObject(r))return null;i=e.validateOptions(i);var o={};return Object.keys(r).forEach(function(a){var l=r[a],u=t.default(a);i.recursive&&(e.isValidObject(l)?e.belongToTypes(l,i.keepTypesOnRecursion)||(l=n(l,i)):i.recursiveInArray&&e.isArrayObject(l)&&(l=s(l).map(function(d){var f=d;if(e.isValidObject(d))e.belongToTypes(f,i.keepTypesOnRecursion)||(f=n(d,i));else if(e.isArrayObject(d)){var h=n({key:d},i);f=h.key}return f}))),o[u]=l}),o}return c(n,"kebabKeys"),wt.default=n,wt}c(Dl,"requireKebabcaseKeysObject");var oo;function jl(){if(oo)return q;oo=1,Object.defineProperty(q,"__esModule",{value:!0}),q.kebabKeys=q.pascalKeys=q.snakeKeys=q.camelKeys=q.upperKeys=q.lowerKeys=q.toLowerCase=q.toUpperCase=q.toKebabCase=q.toHeaderCase=q.toSentenceCase=q.toTextCase=q.toPathCase=q.toDotCase=q.toPascalCase=q.toSnakeCase=q.toCamelCase=void 0;var s=Ki();q.toCamelCase=s.default;var e=Ui();q.toSnakeCase=e.default;var t=Ji();q.toPascalCase=t.default;var n=Il();q.toDotCase=n.default;var r=Al();q.toPathCase=r.default;var i=Ol();q.toTextCase=i.default;var o=$l();q.toSentenceCase=o.default;var a=Nl();q.toHeaderCase=a.default;var l=Qi();q.toKebabCase=l.default;var u=xl();q.lowerKeys=u.default;var d=Pl();q.upperKeys=d.default;var f=Rl();q.camelKeys=f.default;var h=Ml();q.snakeKeys=h.default;var g=Ll();q.pascalKeys=g.default;var y=Dl();q.kebabKeys=y.default;var p=c(function(E){return String(E||"").toLowerCase()},"toLowerCase");q.toLowerCase=p;var w=c(function(E){return String(E||"").toUpperCase()},"toUpperCase");q.toUpperCase=w;var T={toCamelCase:s.default,toSnakeCase:e.default,toPascalCase:t.default,toDotCase:n.default,toPathCase:r.default,toTextCase:i.default,toSentenceCase:o.default,toHeaderCase:a.default,toKebabCase:l.default,toUpperCase:w,toLowerCase:p,lowerKeys:u.default,upperKeys:d.default,camelKeys:f.default,snakeKeys:h.default,pascalKeys:g.default,kebabKeys:y.default};return q.default=T,q}c(jl,"requireLib");var rr,ao;function Fl(){return ao||(ao=1,rr=jl()),rr}c(Fl,"requireJsConvertCase");var ql=Fl();const $e={UPDATE:"update",DELETE:"delete",CREATE:"create"},ae={INCOMING:"incoming",OUTGOING:"outgoing"},ce={[x.Integration]:{element:"integration",elements:"integrations",exportable:!1,exportCleanup:c(s=>({id:s.id,key:s.key,name:s.name,connectorId:s.connectorId,baseUri:s.baseUri,connectorVersion:s.connectorVersion}),"exportCleanup")},[x.Connector]:{element:"connector",elements:"connectors",exportable:!1},[x.Action]:{element:"action",elements:"actions",integrationSpecific:!0,exportCleanup:c(s=>(delete s.integration,s),"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:c(s=>(delete s.dataSourceId,s),"exportCleanup")},[x.Flow]:{element:"flow",elements:"flows",integrationSpecific:!0,parentKey:"universalFlowId"},[x.Package]:{element:"package",elements:"packages",integrationSpecific:!0}};function Kl(s){return delete s.workspaceId,delete s.createdAt,delete s.updatedAt,delete s.revision,Object.keys(s).map(e=>{e.match(/universal.*Revision/g)&&delete s[e]}),s}c(Kl,"baseExportCleanup");const Bl=["id","workspaceId","integrationId","createdAt","updatedAt","revision","archivedAt","baseUri","state","appliedToIntegrations","dependencies"],co=[x.Action,x.FieldMapping,x.Flow,x.DataSource,x.Package];class X{static{c(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||X.extractIntegrationKey(r)}get id(){return X.makeId(this.type,this.key,this.integrationKey)}get dirPath(){const e=qe[this.type].apiPath;if(this.integrationKey){const t=qe[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(dt(process.cwd()),this.path)}get absolutePath(){return K.resolve(K.join(dt(process.cwd()),this.path))}isEqual(e){if(this.id!==e.id)return!1;const t=this.clean(),n=e.clean();return Xc(t,n)}hasParent(){const e=this.getParentKey();return!!e&&!!this.data?.[e]}clean(){const e={...this.data};return Bl.forEach(t=>{delete e[t]}),Object.keys(e).forEach(t=>{t.match(/universal.*Revision/)&&delete e[t]}),e}getParentKey(){let e="parentId";return ce?.[this.type]?.parentKey&&(e=ce?.[this.type]?.parentKey),e}static new(e,t,n,r){return new X(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 X(e,t.key,n,t)}static fromPathAndData(e,t){const n=X.parsePath(e);if(!t)return;const r=t?.key||n?.key;return n?X.new(n.type,r,n.integrationKey,t):void 0}static fromElement(e){return new X(e.type,e.key,e.integrationKey,{...e.data})}static idFromPath(e){const t=X.parsePath(e);if(t)return X.makeId(t.type,t.key,t.integrationKey)}static makeId(e,t,n){return e===x.Integration?`${e}:${t}`:X.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(qe).map(l=>l.apiPath).join("|"),r=new RegExp(`^(?<elementType>${n})/(?<elementKey>[^/]+)/spec\\.ya?ml$`),i=t.match(r);if(i?.groups){const{elementType:l,elementKey:u}=i.groups,d=this.getElementTypeFromPath(l);if(d)return{type:d,key:u}}const o=new RegExp(`^integrations/(?<integrationKey>[^/]+)/(?<elementType>${n})/(?<elementKey>[^/]+)/spec\\.ya?ml$`),a=t.match(o);if(a?.groups){const{integrationKey:l,elementType:u,elementKey:d}=a.groups,f=this.getElementTypeFromPath(u);if(f)return{type:f,key:d,integrationKey:l}}}static extractIntegrationKey(e){return e?.integrationKey||e?.integration?.key||e?.integration_key||void 0}static isElementFile(e){return e.endsWith(".yml")||e.endsWith(".yaml")}static getElementTypeFromPath(e){return Object.values(x).find(t=>qe[t].apiPath===e)}static getRelativePath(e){return K.relative(dt(process.cwd()),e)}static isIntegrationSpecific(e){return co.includes(e)}static canBeIntegrationSpecific(e){return co.includes(e)}}class lo{static{c(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(ce),i=await Promise.all(r.filter(o=>!n.includes(o)).map(async o=>this.getElementsByType(o,t)));for(const o of i)e.push(...o)}catch(t){throw b.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){}}function ir(s,e=!0){if(L.existsSync(s))try{const t=L.readFileSync(s,"utf8");return Wt.load(t)||void 0}catch(t){if(!e)return;if(t instanceof Error){const n=K.relative(process.cwd(),s);throw new Error(`Failed to parse YAML file "${n}": ${t.message}`)}throw t}}c(ir,"readYaml");function Ul(s,e,t){try{const n=Wt.dump(e,t);L.writeFileSync(s,n,"utf8")}catch(n){if(n instanceof Error){const r=K.relative(process.cwd(),s);throw new Error(`Failed to write YAML file "${r}": ${n.message}`)}throw n}}c(Ul,"writeYaml");class Wl extends lo{static{c(this,"LocalWorkspaceElementsRepository")}basePath;constructor(e){super(e),this.basePath=dt(process.cwd())}async getElementsByType(e,t){const n=[],r=K.join(this.basePath,qe[e].apiPath),i=await this.readElementsInDir(r);n.push(...i);for(const o of t){const a=K.join(this.basePath,qe[x.Integration].apiPath,o.key,qe[e].apiPath),l=await this.readElementsInDir(a);n.push(...l)}return n.length>0&&b.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 L.existsSync(n)||L.mkdirSync(n,{recursive:!0}),Ul(r,e.data),b.debug(`[local] Written ${t.relativePath}`),t}async deleteElement(e){const t=K.join(this.basePath,e.path),n=K.join(this.basePath,e.dirPath);L.existsSync(t)&&L.rmSync(t,{force:!0}),this.pruneEmptyDir(n),b.debug(`[local] Deleted ${e.relativePath}`)}async getIntegrations(){const e=K.join(this.basePath,qe[x.Integration].apiPath);return this.readElementsInDir(e)}async readElement(e){const t=ir(e);if(t)return X.fromPathAndData(e,t)}async readElementsInDir(e){const t=[];if(!L.existsSync(e))return t;const n=L.readdirSync(e);if(n.length===0)return t;const r=n.map(async o=>{const a=K.join(e,o,"spec.yaml");return this.readElement(a)});return(await Promise.all(r)).filter(o=>o!=null)}pruneEmptyDir(e){try{if(!e.startsWith(this.basePath)||e===this.basePath||!L.existsSync(e)||L.readdirSync(e).length>0)return;L.rmdirSync(e),this.pruneEmptyDir(K.dirname(e))}catch(t){console.warn(`Failed to prune empty directory ${e}:`,t)}}}class Jl extends lo{static{c(this,"RemoteWorkspaceElementsRepository")}async getElementsByType(e,t){const n=X.canBeIntegrationSpecific(e),r=await this.findAll(e,n?{layer:"universal"}:{});if(!X.canBeIntegrationSpecific(e))return r;for(const i of t){const o=i.key,a=i.data.id,l=await this.findAll(e,a?{integrationId:a}:{integrationKey:o},o);r.push(...l)}return r.length>0&&b.debug(`[remote] Fetched ${r.length} ${e}${r.length!==1?"s":""}`),r}async getElement(e){const t=await B.withClient(n=>n[ce[e.type].element](e.data.id).get());return X.fromData(e.type,t)}async createElement(e,t){const n=e.clean();this.transformElementForCreate(e,n,t);const r=await B.withClient(o=>o[ce[e.type].elements].create(n)),i=X.fromData(e.type,r);return b.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 B.withClient(a=>a[ce[e.type].element](t.data.id).restore());const r=e.clean();this.transformElementForUpdate(e,r,n);const i=await B.withClient(a=>a[ce[e.type].element](t.data.id).put(r)),o=X.fromData(t.type,i);return b.debug(`[remote] Updated ${t.id}`),o}async deleteElement(e){if(!e.data.id)throw new Error("Element must have an id to delete");await B.withClient(t=>t[ce[e.type].element](e.data.id).archive()),b.debug(`[remote] Deleted ${e.id}`)}async getIntegrations(){const e=await B.withClient(n=>n.integrations.findAll());if(!e)return[];const t=e.map(n=>X.fromData(x.Integration,n));return t.length>0&&b.debug(`[remote] Fetched ${t.length} integrations`),t}async getByInternalId(e,t){let n;if(n=await B.withClient(r=>r[ce[t].element](e).get(),!1),!!n)return X.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 l=n.elements.find(u=>u.type===i.type&&u.key===a.key&&u.integrationKey===a.integrationKey);if(!l)throw new Error(`Package element ${i.type} with key ${a.key} not found in target workspace for package ${e.id}`);return{id:l.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(o=>o.type===e.type&&o.key===e.key&&!o.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 B.withClient(i=>i[ce[e].elements].findAll(t));return r?r.filter(i=>i.key).map(i=>(n&&!i.integrationKey&&(i.integrationKey=n),X.fromData(e,i))):[]}}const or=Symbol.for("yaml.alias"),ar=Symbol.for("yaml.document"),Ke=Symbol.for("yaml.map"),uo=Symbol.for("yaml.pair"),Ee=Symbol.for("yaml.scalar"),bt=Symbol.for("yaml.seq"),me=Symbol.for("yaml.node.type"),Be=c(s=>!!s&&typeof s=="object"&&s[me]===or,"isAlias"),Ze=c(s=>!!s&&typeof s=="object"&&s[me]===ar,"isDocument"),St=c(s=>!!s&&typeof s=="object"&&s[me]===Ke,"isMap"),V=c(s=>!!s&&typeof s=="object"&&s[me]===uo,"isPair"),H=c(s=>!!s&&typeof s=="object"&&s[me]===Ee,"isScalar$1"),Ct=c(s=>!!s&&typeof s=="object"&&s[me]===bt,"isSeq");function z(s){if(s&&typeof s=="object")switch(s[me]){case Ke:case bt:return!0}return!1}c(z,"isCollection$1");function Y(s){if(s&&typeof s=="object")switch(s[me]){case or:case Ke:case Ee:case bt:return!0}return!1}c(Y,"isNode");const fo=c(s=>(H(s)||z(s))&&!!s.anchor,"hasAnchor"),le=Symbol("break visit"),ho=Symbol("skip children"),_e=Symbol("remove node");function et(s,e){const t=po(e);Ze(s)?vt(null,s.contents,t,Object.freeze([s]))===_e&&(s.contents=null):vt(null,s,t,Object.freeze([]))}c(et,"visit$1"),et.BREAK=le,et.SKIP=ho,et.REMOVE=_e;function vt(s,e,t,n){const r=mo(s,e,t,n);if(Y(r)||V(r))return go(s,n,r),vt(s,r,t,n);if(typeof r!="symbol"){if(z(e)){n=Object.freeze(n.concat(e));for(let i=0;i<e.items.length;++i){const o=vt(i,e.items[i],t,n);if(typeof o=="number")i=o-1;else{if(o===le)return le;o===_e&&(e.items.splice(i,1),i-=1)}}}else if(V(e)){n=Object.freeze(n.concat(e));const i=vt("key",e.key,t,n);if(i===le)return le;i===_e&&(e.key=null);const o=vt("value",e.value,t,n);if(o===le)return le;o===_e&&(e.value=null)}}return r}c(vt,"visit_");async function Fn(s,e){const t=po(e);Ze(s)?await kt(null,s.contents,t,Object.freeze([s]))===_e&&(s.contents=null):await kt(null,s,t,Object.freeze([]))}c(Fn,"visitAsync"),Fn.BREAK=le,Fn.SKIP=ho,Fn.REMOVE=_e;async function kt(s,e,t,n){const r=await mo(s,e,t,n);if(Y(r)||V(r))return go(s,n,r),kt(s,r,t,n);if(typeof r!="symbol"){if(z(e)){n=Object.freeze(n.concat(e));for(let i=0;i<e.items.length;++i){const o=await kt(i,e.items[i],t,n);if(typeof o=="number")i=o-1;else{if(o===le)return le;o===_e&&(e.items.splice(i,1),i-=1)}}}else if(V(e)){n=Object.freeze(n.concat(e));const i=await kt("key",e.key,t,n);if(i===le)return le;i===_e&&(e.key=null);const o=await kt("value",e.value,t,n);if(o===le)return le;o===_e&&(e.value=null)}}return r}c(kt,"visitAsync_");function po(s){return typeof s=="object"&&(s.Collection||s.Node||s.Value)?Object.assign({Alias:s.Node,Map:s.Node,Scalar:s.Node,Seq:s.Node},s.Value&&{Map:s.Value,Scalar:s.Value,Seq:s.Value},s.Collection&&{Map:s.Collection,Seq:s.Collection},s):s}c(po,"initVisitor");function mo(s,e,t,n){if(typeof t=="function")return t(s,e,n);if(St(e))return t.Map?.(s,e,n);if(Ct(e))return t.Seq?.(s,e,n);if(V(e))return t.Pair?.(s,e,n);if(H(e))return t.Scalar?.(s,e,n);if(Be(e))return t.Alias?.(s,e,n)}c(mo,"callVisitor");function go(s,e,t){const n=e[e.length-1];if(z(n))n.items[s]=t;else if(V(n))s==="key"?n.key=t:n.value=t;else if(Ze(n))n.contents=t;else{const r=Be(n)?"alias":"scalar";throw new Error(`Cannot replace node with ${r} parent`)}}c(go,"replaceNode");const Hl={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},Vl=c(s=>s.replace(/[!,[\]{}]/g,e=>Hl[e]),"escapeTagName");class oe{static{c(this,"Directives")}constructor(e,t){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},oe.defaultYaml,e),this.tags=Object.assign({},oe.defaultTags,t)}clone(){const e=new oe(this.yaml,this.tags);return e.docStart=this.docStart,e}atDocument(){const e=new oe(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:oe.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},oe.defaultTags);break}return e}add(e,t){this.atNextDocument&&(this.yaml={explicit:oe.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},oe.defaultTags),this.atNextDocument=!1);const n=e.trim().split(/[ \t]+/),r=n.shift();switch(r){case"%TAG":{if(n.length!==2&&(t(0,"%TAG directive should contain exactly two parts"),n.length<2))return!1;const[i,o]=n;return this.tags[i]=o,!0}case"%YAML":{if(this.yaml.explicit=!0,n.length!==1)return t(0,"%YAML directive should contain exactly one part"),!1;const[i]=n;if(i==="1.1"||i==="1.2")return this.yaml.version=i,!0;{const o=/^\d+\.\d+$/.test(i);return t(6,`Unsupported YAML version ${i}`,o),!1}}default:return t(0,`Unknown directive ${r}`,!0),!1}}tagName(e,t){if(e==="!")return"!";if(e[0]!=="!")return t(`Not a valid tag: ${e}`),null;if(e[1]==="<"){const o=e.slice(2,-1);return o==="!"||o==="!!"?(t(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==">"&&t("Verbatim tags must end with a >"),o)}const[,n,r]=e.match(/^(.*!)([^!]*)$/s);r||t(`The ${e} tag has no suffix`);const i=this.tags[n];if(i)try{return i+decodeURIComponent(r)}catch(o){return t(String(o)),null}return n==="!"?e:(t(`Could not resolve tag: ${e}`),null)}tagString(e){for(const[t,n]of Object.entries(this.tags))if(e.startsWith(n))return t+Vl(e.substring(n.length));return e[0]==="!"?e:`!<${e}>`}toString(e){const t=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],n=Object.entries(this.tags);let r;if(e&&n.length>0&&Y(e.contents)){const i={};et(e.contents,(o,a)=>{Y(a)&&a.tag&&(i[a.tag]=!0)}),r=Object.keys(i)}else r=[];for(const[i,o]of n)i==="!!"&&o==="tag:yaml.org,2002:"||(!e||r.some(a=>a.startsWith(o)))&&t.push(`%TAG ${i} ${o}`);return t.join(`
|
|
2
|
+
var xc=Object.defineProperty;var c=(s,e)=>xc(s,"name",{value:e,configurable:!0});import{jsx as m,jsxs as _,Fragment as ut}from"react/jsx-runtime";import*as K from"node:path";import{join as Ks,resolve as Pc,dirname as Rc}from"node:path";import k from"chalk";import{useInput as Xe,Box as S,Text as v,Newline as Mc,render as Ut}from"ink";import Lc from"minimist";import{SWRConfig as Dc}from"swr";import Ae,{createContext as Bs,useState as J,useEffect as Fe,useContext as Us,useMemo as jc,useRef as Ws,useId as Fc,useLayoutEffect as _n}from"react";import Ei from"swr/immutable";import _i from"os";import U from"path";import qc from"conf";import{MembraneConfigLoader as Kc,MembraneAxiosInstance as Bc,MembraneClient as Ii,WorkspaceElementType as N,WorkspaceElementSpecs as qe,WorkspaceSyncEventType as Uc,ConnectorFileUpdateType as Js,setValueAtLocator as Hs,extractMembraneErrorData as Te,getDataCollectionCreateFields as Vs,excludeWriteOnlyFieldsFromSchema as Ai,valueToSchema as In,getRequiredFieldsFromSchema as Wc,getValueAtLocator as Jc,walkSchema as Oi,makeDataLocationPath as $i,getDataCollectionUpdateFields as Gs}from"@membranehq/sdk";import zs from"jsonwebtoken";import*as L from"node:fs";import{mkdirSync as Hc,writeFileSync as Vc,readFileSync as Gc}from"node:fs";import{EventEmitter as zc}from"events";import{AsyncLocalStorage as Yc}from"async_hooks";import Xc from"lodash/isEqual.js";import Wt from"js-yaml";import*as Qc from"node:crypto";import{createHash as Zc}from"node:crypto";import el from"chokidar";import{EventSource as tl}from"eventsource";import F from"fs";import nl from"archiver";import sl from"form-data";import rl from"unzipper";import*as il from"node:os";import{exec as ol}from"node:child_process";import{Spinner as al,TextInput as cl,Select as ll}from"@inkjs/ui";import An from"ink-spinner";import Ni from"ink-text-input";import{fileURLToPath as ul}from"node:url";import{Command as dl}from"commander";import Ys from"lodash/camelCase.js";import Xs from"lodash/upperFirst.js";import fl from"code-block-writer";import hl from"lodash/uniqBy.js";import"node:events";import{FastMCP as pl}from"fastmcp";import Qs from"axios";import{z as W}from"zod";import Zs from"lodash/merge.js";import{faker as Jt}from"@faker-js/faker";import ml from"lodash/template.js";import gl from"lodash/templateSettings.js";const yl="membrane",wl="membrane.config.yml",er="https://api.integration.app";function tr(){const s=process.cwd(),e=K.join(s,yl),t=K.join(s,wl),n=e,r=K.join(n,"workspace.yaml");return{membraneDirPath:e,configPath:t,payloadDirPath:n,workspaceDataFilePath:r}}c(tr,"getPaths");function xi(){return tr().membraneDirPath}c(xi,"getBasePath");const bl={pat:{type:"string"},workspace:{type:"object"}},Pi=new qc({schema:bl,configName:"config",cwd:U.join(_i.homedir(),".membrane")}),Sl=c(s=>{Pi.set("pat",s)},"setPat"),Ri=c(()=>Pi.get("pat"),"getPat");class Mi{static{c(this,"AccountApiClient")}constructor(e=er){this.apiBaseUrl=e}async request(e,t={}){const n=t.headers?t.headers instanceof Headers?new Headers(t.headers):new Headers(t.headers):new Headers;if(!n.has("Authorization")){const o=Ri();if(!o)throw new Error("Personal Access Token not found.");n.set("Authorization",`Bearer ${o}`)}t.body&&!n.has("Content-Type")&&n.set("Content-Type","application/json");const r=await fetch(`${this.apiBaseUrl}${e}`,{...t,headers:n});if(!r.ok){const o=await r.text();throw new Error(`API request failed: ${r.status} ${r.statusText} - ${o}`)}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 Cl=c(s=>{const e=new Mi(er);return t=>e.get(t)},"createAccountApiFetcher");class Ft{static{c(this,"ConfigLoader")}static instance=null;sdkLoader;constructor(){this.sdkLoader=new Kc}static getInstance(){return Ft.instance||(Ft.instance=new Ft),Ft.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 Qe=Ft.getInstance();function On(s){return Qe.loadConfig(s)}c(On,"readProjectConfig");const Q={LogAdded:"logAdded",StateChanged:"stateChanged",StatsChanged:"statsChanged",ConflictsChanged:"conflictsChanged",McpStatusChanged:"mcpStatusChanged",McpServersChanged:"mcpServersChanged",ConfigChanged:"configChanged"};class nr extends zc{static{c(this,"TypedEventEmitter")}on(e,t){return super.on(e,t)}emit(e,...t){return super.emit(e,...t)}off(e,t){return super.off(e,t)}once(e,t){return super.once(e,t)}}class vl extends nr{static{c(this,"WorkspaceNotifications")}constructor(e){super(),this.config=e}clientId;heartbeatInterval;isCleaningUp=!1;async connectToRemote(){await this.registerWithRemoteServer(),await this.startHeartbeatLoop()}async setState(e){this.emit(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 B.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 B.withClient(t=>t.post("/local-clients",{hostname:_i.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 B.withClient(e=>e.post(`/local-clients/${this.clientId}/keep-alive`,{}))})}async emitRemote(e){this.clientId&&await this.withErrorHandling(async()=>{await B.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 Oe=new vl({heartbeatIntervalMs:15e3}),kl="membrane",Tl=["**/node_modules/**","**/.git/**","**/.DS_Store","**/Thumbs.db","**/*.tmp","**/*.swp","**/*.swo","**/*.log","**/*.lock","**/.cache/**","**/.next/**","**/.vscode/**","**/.idea/**","**/.logs/**"];function dt(s){return K.join(s,kl)}c(dt,"getMembraneDir");const Li=Ks(dt(process.cwd()),".logs");class El{static{c(this,"WorkspaceLogger")}_logs;workspaceNotifications;verboseMode=!1;constructor(){this._logs=[],this.workspaceNotifications=Oe}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.workspaceNotifications.addLog(n)}info(e){this.log(e,"info")}success(e){this.log(e,"success")}warning(e){this.log(e,"warning")}error(e){this.log(e,"error")}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`;Hc(Li,{recursive:!0});const i=Ks(Li,r),o=this._logs.map(a=>`[${a.timestamp}] ${a.type?.toUpperCase()||"INFO"}: ${a.message}`).join(`
|
|
3
|
+
`);return Vc(i,o,"utf-8"),i}catch(t){return console.error("Failed to save logs:",t),null}}}const b=new El,Di=new Yc;class ji{static{c(this,"RequestLogger")}constructor(e=Bc){this.axiosInstance=e}interceptorsConfigured=!1;setup(){if(this.interceptorsConfigured)return;const e=c(t=>(this.logError(t),Promise.reject(t)),"errorHandler");this.axiosInstance.interceptors.request.use(t=>{const n=Di.getStore();t.metadata={startTime:Date.now(),skipErrorLog:n};const{method:r,url:i}=this.getRequestDetails(t);return b.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:o,statusText:a}=t;return b.debug(`[Response]: ${n} ${r} - ${o} ${a} (${i}ms)`),t},e),this.interceptorsConfigured=!0}static withSkipErrorLog(e){return Di.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:o}=e.response;b.error(`[Response]: ${t} ${n} - ${i} ${o} (${r}ms)`),e.response.data&&b.error(`[Response Data]: ${JSON.stringify(e.response.data,null,2)}`)}}}class _l{static{c(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 ji,this.requestLogger.setup()}async withClient(e,t=!0,n=process.cwd()){const r=c(async()=>{try{return await this.withRetry(async()=>{const i=await this.getClient(n);await this.acquireSemaphore();try{return await this.waitIfNeeded(),this.recordRequest(),await this.withTimeout(e(i),this.requestTimeout)}finally{this.releaseSemaphore()}},"API request")}catch(i){if(t)throw i;return}},"executeRequest");return t?r():ji.withSkipErrorLog(r)}async generateAccessToken(e,t){return zs.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=On(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 Ii({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 o=new Date().toISOString(),a=r+2;b.debug(`[${o}] Retrying ${t} (attempt ${a}/${this.maxRetries+1})`);let l=this.retryDelay*Math.pow(2,r);if(this.enableJitter){const u=l*.25*(Math.random()*2-1);l=Math.max(0,l+u)}await new Promise(u=>setTimeout(u,l))}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(o=>t.includes(o))}async withTimeout(e,t){let n;const r=new Promise((i,o)=>{n=setTimeout(()=>o(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}}}const B=new _l;async function Fi(s){const e=await B.withClient(t=>t.get("org-workspace-id"),!0,s);if(!e)throw new Error("Failed to get workspace ID");return e.id}c(Fi,"getWorkspaceId");var q={},$n={},qi;function Ki(){if(qi)return $n;qi=1,Object.defineProperty($n,"__esModule",{value:!0});function s(e){return e===void 0&&(e=""),e?String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/[^A-Za-z0-9]+/g,"$").replace(/([a-z])([A-Z])/g,function(t,n,r){return n+"$"+r}).toLowerCase().replace(/(\$)(\w)/g,function(t,n,r){return r.toUpperCase()}):""}return c(s,"toCamelCase"),$n.default=s,$n}c(Ki,"requireJsCamelcase");var Nn={},Bi;function Ui(){if(Bi)return Nn;Bi=1,Object.defineProperty(Nn,"__esModule",{value:!0});function s(e){return e===void 0&&(e=""),e?String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/([a-z])([A-Z])/g,function(t,n,r){return n+"_"+r.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g,"_").toLowerCase():""}return c(s,"toSnakeCase"),Nn.default=s,Nn}c(Ui,"requireJsSnakecase");var xn={},Wi;function Ji(){if(Wi)return xn;Wi=1,Object.defineProperty(xn,"__esModule",{value:!0});function s(e){return e===void 0&&(e=""),e?String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"$").replace(/[^A-Za-z0-9]+/g,"$").replace(/([a-z])([A-Z])/g,function(t,n,r){return n+"$"+r}).toLowerCase().replace(/(\$)(\w?)/g,function(t,n,r){return r.toUpperCase()}):""}return c(s,"toPascalCase"),xn.default=s,xn}c(Ji,"requireJsPascalcase");var Pn={},Hi;function Il(){if(Hi)return Pn;Hi=1,Object.defineProperty(Pn,"__esModule",{value:!0});function s(e){return e===void 0&&(e=""),e?String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/([a-z])([A-Z])/g,function(t,n,r){return n+"_"+r.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g,".").toLowerCase():""}return c(s,"toDotCase"),Pn.default=s,Pn}c(Il,"requireJsDotcase");var Rn={},Vi;function Al(){if(Vi)return Rn;Vi=1,Object.defineProperty(Rn,"__esModule",{value:!0});function s(e){return e===void 0&&(e=""),e?String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/([a-z])([A-Z])/g,function(t,n,r){return n+"_"+r.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g,"/").toLowerCase():""}return c(s,"toPathCase"),Rn.default=s,Rn}c(Al,"requireJsPathcase");var Mn={},Gi;function Ol(){if(Gi)return Mn;Gi=1,Object.defineProperty(Mn,"__esModule",{value:!0});function s(e){return e===void 0&&(e=""),e?String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/([a-z])([A-Z])/g,function(t,n,r){return n+"_"+r.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g," ").toLowerCase():""}return c(s,"toTextCase"),Mn.default=s,Mn}c(Ol,"requireJsTextcase");var Ln={},zi;function $l(){if(zi)return Ln;zi=1,Object.defineProperty(Ln,"__esModule",{value:!0});function s(e){if(e===void 0&&(e=""),!e)return"";var t=String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/([a-z])([A-Z])/g,function(n,r,i){return r+"_"+i.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g," ").toLowerCase();return t.charAt(0).toUpperCase()+t.slice(1)}return c(s,"toSentenceCase"),Ln.default=s,Ln}c($l,"requireJsSentencecase");var Dn={},Yi;function Nl(){if(Yi)return Dn;Yi=1,Object.defineProperty(Dn,"__esModule",{value:!0});function s(e){return e===void 0&&(e=""),e?String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/([a-z])([A-Z])/g,function(t,n,r){return n+"_"+r.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g," ").toLowerCase().replace(/( ?)(\w+)( ?)/g,function(t,n,r,i){return n+r.charAt(0).toUpperCase()+r.slice(1)+i}):""}return c(s,"toHeaderCase"),Dn.default=s,Dn}c(Nl,"requireJsHeadercase");var jn={},Xi;function Qi(){if(Xi)return jn;Xi=1,Object.defineProperty(jn,"__esModule",{value:!0});function s(e){return e===void 0&&(e=""),e?String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/([a-z])([A-Z])/g,function(t,n,r){return n+"_"+r.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g,"-").toLowerCase():""}return c(s,"toKebabCase"),jn.default=s,jn}c(Qi,"requireJsKebabcase");var ft={},sr={},Zi;function ht(){return Zi||(Zi=1,function(s){Object.defineProperty(s,"__esModule",{value:!0}),s.belongToTypes=s.isValidObject=s.isArrayObject=s.validateOptions=s.DefaultOption=void 0,s.DefaultOption={recursive:!1,recursiveInArray:!1,keepTypesOnRecursion:[]},s.validateOptions=function(e){return e===void 0&&(e=s.DefaultOption),e.recursive==null?e=s.DefaultOption:e.recursiveInArray==null&&(e.recursiveInArray=!1),e},s.isArrayObject=function(e){return e!=null&&Array.isArray(e)},s.isValidObject=function(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)},s.belongToTypes=function(e,t){return(t||[]).some(function(n){return e instanceof n})}}(sr)),sr}c(ht,"requireUtils");var eo;function xl(){if(eo)return ft;eo=1;var s=ft&&ft.__spreadArrays||function(){for(var n=0,r=0,i=arguments.length;r<i;r++)n+=arguments[r].length;for(var o=Array(n),a=0,r=0;r<i;r++)for(var l=arguments[r],u=0,d=l.length;u<d;u++,a++)o[a]=l[u];return o};Object.defineProperty(ft,"__esModule",{value:!0});var e=ht();function t(n,r){if(r===void 0&&(r=e.DefaultOption),!e.isValidObject(n))return null;r=e.validateOptions(r);var i={};return Object.keys(n).forEach(function(o){var a=n[o],l=o.toLowerCase();r.recursive&&(e.isValidObject(a)?e.belongToTypes(a,r.keepTypesOnRecursion)||(a=t(a,r)):r.recursiveInArray&&e.isArrayObject(a)&&(a=s(a).map(function(u){var d=u;if(e.isValidObject(u))e.belongToTypes(d,r.keepTypesOnRecursion)||(d=t(u,r));else if(e.isArrayObject(u)){var f=t({key:u},r);d=f.key}return d}))),i[l]=a}),i}return c(t,"lowerKeys"),ft.default=t,ft}c(xl,"requireLowercaseKeysObject");var pt={},to;function Pl(){if(to)return pt;to=1;var s=pt&&pt.__spreadArrays||function(){for(var n=0,r=0,i=arguments.length;r<i;r++)n+=arguments[r].length;for(var o=Array(n),a=0,r=0;r<i;r++)for(var l=arguments[r],u=0,d=l.length;u<d;u++,a++)o[a]=l[u];return o};Object.defineProperty(pt,"__esModule",{value:!0});var e=ht();function t(n,r){if(r===void 0&&(r=e.DefaultOption),!e.isValidObject(n))return null;r=e.validateOptions(r);var i={};return Object.keys(n).forEach(function(o){var a=n[o],l=o.toUpperCase();r.recursive&&(e.isValidObject(a)?e.belongToTypes(a,r.keepTypesOnRecursion)||(a=t(a,r)):r.recursiveInArray&&e.isArrayObject(a)&&(a=s(a).map(function(u){var d=u;if(e.isValidObject(u))e.belongToTypes(d,r.keepTypesOnRecursion)||(d=t(u,r));else if(e.isArrayObject(u)){var f=t({key:u},r);d=f.key}return d}))),i[l]=a}),i}return c(t,"upperKeys"),pt.default=t,pt}c(Pl,"requireUppercaseKeysObject");var mt={},no;function Rl(){if(no)return mt;no=1;var s=mt&&mt.__spreadArrays||function(){for(var r=0,i=0,o=arguments.length;i<o;i++)r+=arguments[i].length;for(var a=Array(r),l=0,i=0;i<o;i++)for(var u=arguments[i],d=0,f=u.length;d<f;d++,l++)a[l]=u[d];return a};Object.defineProperty(mt,"__esModule",{value:!0});var e=ht(),t=Ki();function n(r,i){if(i===void 0&&(i=e.DefaultOption),!e.isValidObject(r))return null;i=e.validateOptions(i);var o={};return Object.keys(r).forEach(function(a){var l=r[a],u=t.default(a);i.recursive&&(e.isValidObject(l)?e.belongToTypes(l,i.keepTypesOnRecursion)||(l=n(l,i)):i.recursiveInArray&&e.isArrayObject(l)&&(l=s(l).map(function(d){var f=d;if(e.isValidObject(d))e.belongToTypes(f,i.keepTypesOnRecursion)||(f=n(d,i));else if(e.isArrayObject(d)){var h=n({key:d},i);f=h.key}return f}))),o[u]=l}),o}return c(n,"camelKeys"),mt.default=n,mt}c(Rl,"requireCamelcaseKeysObject");var gt={},so;function Ml(){if(so)return gt;so=1;var s=gt&>.__spreadArrays||function(){for(var r=0,i=0,o=arguments.length;i<o;i++)r+=arguments[i].length;for(var a=Array(r),l=0,i=0;i<o;i++)for(var u=arguments[i],d=0,f=u.length;d<f;d++,l++)a[l]=u[d];return a};Object.defineProperty(gt,"__esModule",{value:!0});var e=ht(),t=Ui();function n(r,i){if(i===void 0&&(i=e.DefaultOption),!e.isValidObject(r))return null;i=e.validateOptions(i);var o={};return Object.keys(r).forEach(function(a){var l=r[a],u=t.default(a);i.recursive&&(e.isValidObject(l)?e.belongToTypes(l,i.keepTypesOnRecursion)||(l=n(l,i)):i.recursiveInArray&&e.isArrayObject(l)&&(l=s(l).map(function(d){var f=d;if(e.isValidObject(d))e.belongToTypes(f,i.keepTypesOnRecursion)||(f=n(d,i));else if(e.isArrayObject(d)){var h=n({key:d},i);f=h.key}return f}))),o[u]=l}),o}return c(n,"snakeKeys"),gt.default=n,gt}c(Ml,"requireSnakecaseKeysObject");var yt={},ro;function Ll(){if(ro)return yt;ro=1;var s=yt&&yt.__spreadArrays||function(){for(var r=0,i=0,o=arguments.length;i<o;i++)r+=arguments[i].length;for(var a=Array(r),l=0,i=0;i<o;i++)for(var u=arguments[i],d=0,f=u.length;d<f;d++,l++)a[l]=u[d];return a};Object.defineProperty(yt,"__esModule",{value:!0});var e=ht(),t=Ji();function n(r,i){if(i===void 0&&(i=e.DefaultOption),!e.isValidObject(r))return null;i=e.validateOptions(i);var o={};return Object.keys(r).forEach(function(a){var l=r[a],u=t.default(a);i.recursive&&(e.isValidObject(l)?e.belongToTypes(l,i.keepTypesOnRecursion)||(l=n(l,i)):i.recursiveInArray&&e.isArrayObject(l)&&(l=s(l).map(function(d){var f=d;if(e.isValidObject(d))e.belongToTypes(f,i.keepTypesOnRecursion)||(f=n(d,i));else if(e.isArrayObject(d)){var h=n({key:d},i);f=h.key}return f}))),o[u]=l}),o}return c(n,"pascalKeys"),yt.default=n,yt}c(Ll,"requirePascalcaseKeysObject");var wt={},io;function Dl(){if(io)return wt;io=1;var s=wt&&wt.__spreadArrays||function(){for(var r=0,i=0,o=arguments.length;i<o;i++)r+=arguments[i].length;for(var a=Array(r),l=0,i=0;i<o;i++)for(var u=arguments[i],d=0,f=u.length;d<f;d++,l++)a[l]=u[d];return a};Object.defineProperty(wt,"__esModule",{value:!0});var e=ht(),t=Qi();function n(r,i){if(i===void 0&&(i=e.DefaultOption),!e.isValidObject(r))return null;i=e.validateOptions(i);var o={};return Object.keys(r).forEach(function(a){var l=r[a],u=t.default(a);i.recursive&&(e.isValidObject(l)?e.belongToTypes(l,i.keepTypesOnRecursion)||(l=n(l,i)):i.recursiveInArray&&e.isArrayObject(l)&&(l=s(l).map(function(d){var f=d;if(e.isValidObject(d))e.belongToTypes(f,i.keepTypesOnRecursion)||(f=n(d,i));else if(e.isArrayObject(d)){var h=n({key:d},i);f=h.key}return f}))),o[u]=l}),o}return c(n,"kebabKeys"),wt.default=n,wt}c(Dl,"requireKebabcaseKeysObject");var oo;function jl(){if(oo)return q;oo=1,Object.defineProperty(q,"__esModule",{value:!0}),q.kebabKeys=q.pascalKeys=q.snakeKeys=q.camelKeys=q.upperKeys=q.lowerKeys=q.toLowerCase=q.toUpperCase=q.toKebabCase=q.toHeaderCase=q.toSentenceCase=q.toTextCase=q.toPathCase=q.toDotCase=q.toPascalCase=q.toSnakeCase=q.toCamelCase=void 0;var s=Ki();q.toCamelCase=s.default;var e=Ui();q.toSnakeCase=e.default;var t=Ji();q.toPascalCase=t.default;var n=Il();q.toDotCase=n.default;var r=Al();q.toPathCase=r.default;var i=Ol();q.toTextCase=i.default;var o=$l();q.toSentenceCase=o.default;var a=Nl();q.toHeaderCase=a.default;var l=Qi();q.toKebabCase=l.default;var u=xl();q.lowerKeys=u.default;var d=Pl();q.upperKeys=d.default;var f=Rl();q.camelKeys=f.default;var h=Ml();q.snakeKeys=h.default;var g=Ll();q.pascalKeys=g.default;var y=Dl();q.kebabKeys=y.default;var p=c(function(E){return String(E||"").toLowerCase()},"toLowerCase");q.toLowerCase=p;var w=c(function(E){return String(E||"").toUpperCase()},"toUpperCase");q.toUpperCase=w;var T={toCamelCase:s.default,toSnakeCase:e.default,toPascalCase:t.default,toDotCase:n.default,toPathCase:r.default,toTextCase:i.default,toSentenceCase:o.default,toHeaderCase:a.default,toKebabCase:l.default,toUpperCase:w,toLowerCase:p,lowerKeys:u.default,upperKeys:d.default,camelKeys:f.default,snakeKeys:h.default,pascalKeys:g.default,kebabKeys:y.default};return q.default=T,q}c(jl,"requireLib");var rr,ao;function Fl(){return ao||(ao=1,rr=jl()),rr}c(Fl,"requireJsConvertCase");var ql=Fl();const $e={UPDATE:"update",DELETE:"delete",CREATE:"create"},ae={INCOMING:"incoming",OUTGOING:"outgoing"},ce={[N.Integration]:{element:"integration",elements:"integrations",exportable:!1,exportCleanup:c(s=>({id:s.id,key:s.key,name:s.name,connectorId:s.connectorId,baseUri:s.baseUri,connectorVersion:s.connectorVersion}),"exportCleanup")},[N.Connector]:{element:"connector",elements:"connectors",exportable:!1},[N.Action]:{element:"action",elements:"actions",integrationSpecific:!0,exportCleanup:c(s=>(delete s.integration,s),"exportCleanup")},[N.AppDataSchema]:{element:"appDataSchema",elements:"appDataSchemas"},[N.AppEventType]:{element:"appEventType",elements:"appEventTypes"},[N.DataLinkTable]:{element:"dataLinkTable",elements:"dataLinkTables"},[N.DataSource]:{element:"dataSource",elements:"dataSources",parentKey:"universalDataSourceId",integrationSpecific:!0},[N.FieldMapping]:{element:"fieldMapping",elements:"fieldMappings",integrationSpecific:!0,parentKey:"universalFieldMappingId",exportCleanup:c(s=>(delete s.dataSourceId,s),"exportCleanup")},[N.Flow]:{element:"flow",elements:"flows",integrationSpecific:!0,parentKey:"universalFlowId"},[N.Package]:{element:"package",elements:"packages",integrationSpecific:!0}};function Kl(s){return delete s.workspaceId,delete s.createdAt,delete s.updatedAt,delete s.revision,Object.keys(s).map(e=>{e.match(/universal.*Revision/g)&&delete s[e]}),s}c(Kl,"baseExportCleanup");const Bl=["id","workspaceId","integrationId","createdAt","updatedAt","revision","archivedAt","baseUri","state","appliedToIntegrations","dependencies"],co=[N.Action,N.FieldMapping,N.Flow,N.DataSource,N.Package];class X{static{c(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||X.extractIntegrationKey(r)}get id(){return X.makeId(this.type,this.key,this.integrationKey)}get dirPath(){const e=qe[this.type].apiPath;if(this.integrationKey){const t=qe[N.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(dt(process.cwd()),this.path)}get absolutePath(){return K.resolve(K.join(dt(process.cwd()),this.path))}isEqual(e){if(this.id!==e.id)return!1;const t=this.clean(),n=e.clean();return Xc(t,n)}hasParent(){const e=this.getParentKey();return!!e&&!!this.data?.[e]}clean(){const e={...this.data};return Bl.forEach(t=>{delete e[t]}),Object.keys(e).forEach(t=>{t.match(/universal.*Revision/)&&delete e[t]}),e}getParentKey(){let e="parentId";return ce?.[this.type]?.parentKey&&(e=ce?.[this.type]?.parentKey),e}static new(e,t,n,r){return new X(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 X(e,t.key,n,t)}static fromPathAndData(e,t){const n=X.parsePath(e);if(!t)return;const r=t?.key||n?.key;return n?X.new(n.type,r,n.integrationKey,t):void 0}static fromElement(e){return new X(e.type,e.key,e.integrationKey,{...e.data})}static idFromPath(e){const t=X.parsePath(e);if(t)return X.makeId(t.type,t.key,t.integrationKey)}static makeId(e,t,n){return e===N.Integration?`${e}:${t}`:X.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(qe).map(l=>l.apiPath).join("|"),r=new RegExp(`^(?<elementType>${n})/(?<elementKey>[^/]+)/spec\\.ya?ml$`),i=t.match(r);if(i?.groups){const{elementType:l,elementKey:u}=i.groups,d=this.getElementTypeFromPath(l);if(d)return{type:d,key:u}}const o=new RegExp(`^integrations/(?<integrationKey>[^/]+)/(?<elementType>${n})/(?<elementKey>[^/]+)/spec\\.ya?ml$`),a=t.match(o);if(a?.groups){const{integrationKey:l,elementType:u,elementKey:d}=a.groups,f=this.getElementTypeFromPath(u);if(f)return{type:f,key:d,integrationKey:l}}}static extractIntegrationKey(e){return e?.integrationKey||e?.integration?.key||e?.integration_key||void 0}static isElementFile(e){return e.endsWith(".yml")||e.endsWith(".yaml")}static getElementTypeFromPath(e){return Object.values(N).find(t=>qe[t].apiPath===e)}static getRelativePath(e){return K.relative(dt(process.cwd()),e)}static isIntegrationSpecific(e){return co.includes(e)}static canBeIntegrationSpecific(e){return co.includes(e)}}class lo{static{c(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=[N.Integration,N.Connector],r=Object.keys(ce),i=await Promise.all(r.filter(o=>!n.includes(o)).map(async o=>this.getElementsByType(o,t)));for(const o of i)e.push(...o)}catch(t){throw b.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){}}function ir(s,e=!0){if(L.existsSync(s))try{const t=L.readFileSync(s,"utf8");return Wt.load(t)||void 0}catch(t){if(!e)return;if(t instanceof Error){const n=K.relative(process.cwd(),s);throw new Error(`Failed to parse YAML file "${n}": ${t.message}`)}throw t}}c(ir,"readYaml");function Ul(s,e,t){try{const n=Wt.dump(e,t);L.writeFileSync(s,n,"utf8")}catch(n){if(n instanceof Error){const r=K.relative(process.cwd(),s);throw new Error(`Failed to write YAML file "${r}": ${n.message}`)}throw n}}c(Ul,"writeYaml");class Wl extends lo{static{c(this,"LocalWorkspaceElementsRepository")}basePath;constructor(e){super(e),this.basePath=dt(process.cwd())}async getElementsByType(e,t){const n=[],r=K.join(this.basePath,qe[e].apiPath),i=await this.readElementsInDir(r);n.push(...i);for(const o of t){const a=K.join(this.basePath,qe[N.Integration].apiPath,o.key,qe[e].apiPath),l=await this.readElementsInDir(a);n.push(...l)}return n.length>0&&b.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 L.existsSync(n)||L.mkdirSync(n,{recursive:!0}),Ul(r,e.data),b.debug(`[local] Written ${t.relativePath}`),t}async deleteElement(e){const t=K.join(this.basePath,e.path),n=K.join(this.basePath,e.dirPath);L.existsSync(t)&&L.rmSync(t,{force:!0}),this.pruneEmptyDir(n),b.debug(`[local] Deleted ${e.relativePath}`)}async getIntegrations(){const e=K.join(this.basePath,qe[N.Integration].apiPath);return this.readElementsInDir(e)}async readElement(e){const t=ir(e);if(t)return X.fromPathAndData(e,t)}async readElementsInDir(e){const t=[];if(!L.existsSync(e))return t;const n=L.readdirSync(e);if(n.length===0)return t;const r=n.map(async o=>{const a=K.join(e,o,"spec.yaml");return this.readElement(a)});return(await Promise.all(r)).filter(o=>o!=null)}pruneEmptyDir(e){try{if(!e.startsWith(this.basePath)||e===this.basePath||!L.existsSync(e)||L.readdirSync(e).length>0)return;L.rmdirSync(e),this.pruneEmptyDir(K.dirname(e))}catch(t){console.warn(`Failed to prune empty directory ${e}:`,t)}}}class Jl extends lo{static{c(this,"RemoteWorkspaceElementsRepository")}async getElementsByType(e,t){const n=X.canBeIntegrationSpecific(e),r=await this.findAll(e,n?{layer:"universal"}:{});if(!X.canBeIntegrationSpecific(e))return r;for(const i of t){const o=i.key,a=i.data.id,l=await this.findAll(e,a?{integrationId:a}:{integrationKey:o},o);r.push(...l)}return r.length>0&&b.debug(`[remote] Fetched ${r.length} ${e}${r.length!==1?"s":""}`),r}async getElement(e){const t=await B.withClient(n=>n[ce[e.type].element](e.data.id).get());return X.fromData(e.type,t)}async createElement(e,t){const n=e.clean();this.transformElementForCreate(e,n,t);const r=await B.withClient(o=>o[ce[e.type].elements].create(n)),i=X.fromData(e.type,r);return b.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 B.withClient(a=>a[ce[e.type].element](t.data.id).restore());const r=e.clean();this.transformElementForUpdate(e,r,n);const i=await B.withClient(a=>a[ce[e.type].element](t.data.id).put(r)),o=X.fromData(t.type,i);return b.debug(`[remote] Updated ${t.id}`),o}async deleteElement(e){if(!e.data.id)throw new Error("Element must have an id to delete");await B.withClient(t=>t[ce[e.type].element](e.data.id).archive()),b.debug(`[remote] Deleted ${e.id}`)}async getIntegrations(){const e=await B.withClient(n=>n.integrations.findAll());if(!e)return[];const t=e.map(n=>X.fromData(N.Integration,n));return t.length>0&&b.debug(`[remote] Fetched ${t.length} integrations`),t}async getByInternalId(e,t){let n;if(n=await B.withClient(r=>r[ce[t].element](e).get(),!1),!!n)return X.fromData(t,n)}transformElementForCreate(e,t,n){if(e.integrationKey){const r=n.elements.find(i=>i.type===N.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===N.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===N.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===N.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!==N.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 l=n.elements.find(u=>u.type===i.type&&u.key===a.key&&u.integrationKey===a.integrationKey);if(!l)throw new Error(`Package element ${i.type} with key ${a.key} not found in target workspace for package ${e.id}`);return{id:l.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(o=>o.type===e.type&&o.key===e.key&&!o.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 B.withClient(i=>i[ce[e].elements].findAll(t));return r?r.filter(i=>i.key).map(i=>(n&&!i.integrationKey&&(i.integrationKey=n),X.fromData(e,i))):[]}}const or=Symbol.for("yaml.alias"),ar=Symbol.for("yaml.document"),Ke=Symbol.for("yaml.map"),uo=Symbol.for("yaml.pair"),Ee=Symbol.for("yaml.scalar"),bt=Symbol.for("yaml.seq"),me=Symbol.for("yaml.node.type"),Be=c(s=>!!s&&typeof s=="object"&&s[me]===or,"isAlias"),Ze=c(s=>!!s&&typeof s=="object"&&s[me]===ar,"isDocument"),St=c(s=>!!s&&typeof s=="object"&&s[me]===Ke,"isMap"),V=c(s=>!!s&&typeof s=="object"&&s[me]===uo,"isPair"),H=c(s=>!!s&&typeof s=="object"&&s[me]===Ee,"isScalar$1"),Ct=c(s=>!!s&&typeof s=="object"&&s[me]===bt,"isSeq");function z(s){if(s&&typeof s=="object")switch(s[me]){case Ke:case bt:return!0}return!1}c(z,"isCollection$1");function Y(s){if(s&&typeof s=="object")switch(s[me]){case or:case Ke:case Ee:case bt:return!0}return!1}c(Y,"isNode");const fo=c(s=>(H(s)||z(s))&&!!s.anchor,"hasAnchor"),le=Symbol("break visit"),ho=Symbol("skip children"),_e=Symbol("remove node");function et(s,e){const t=po(e);Ze(s)?vt(null,s.contents,t,Object.freeze([s]))===_e&&(s.contents=null):vt(null,s,t,Object.freeze([]))}c(et,"visit$1"),et.BREAK=le,et.SKIP=ho,et.REMOVE=_e;function vt(s,e,t,n){const r=mo(s,e,t,n);if(Y(r)||V(r))return go(s,n,r),vt(s,r,t,n);if(typeof r!="symbol"){if(z(e)){n=Object.freeze(n.concat(e));for(let i=0;i<e.items.length;++i){const o=vt(i,e.items[i],t,n);if(typeof o=="number")i=o-1;else{if(o===le)return le;o===_e&&(e.items.splice(i,1),i-=1)}}}else if(V(e)){n=Object.freeze(n.concat(e));const i=vt("key",e.key,t,n);if(i===le)return le;i===_e&&(e.key=null);const o=vt("value",e.value,t,n);if(o===le)return le;o===_e&&(e.value=null)}}return r}c(vt,"visit_");async function Fn(s,e){const t=po(e);Ze(s)?await kt(null,s.contents,t,Object.freeze([s]))===_e&&(s.contents=null):await kt(null,s,t,Object.freeze([]))}c(Fn,"visitAsync"),Fn.BREAK=le,Fn.SKIP=ho,Fn.REMOVE=_e;async function kt(s,e,t,n){const r=await mo(s,e,t,n);if(Y(r)||V(r))return go(s,n,r),kt(s,r,t,n);if(typeof r!="symbol"){if(z(e)){n=Object.freeze(n.concat(e));for(let i=0;i<e.items.length;++i){const o=await kt(i,e.items[i],t,n);if(typeof o=="number")i=o-1;else{if(o===le)return le;o===_e&&(e.items.splice(i,1),i-=1)}}}else if(V(e)){n=Object.freeze(n.concat(e));const i=await kt("key",e.key,t,n);if(i===le)return le;i===_e&&(e.key=null);const o=await kt("value",e.value,t,n);if(o===le)return le;o===_e&&(e.value=null)}}return r}c(kt,"visitAsync_");function po(s){return typeof s=="object"&&(s.Collection||s.Node||s.Value)?Object.assign({Alias:s.Node,Map:s.Node,Scalar:s.Node,Seq:s.Node},s.Value&&{Map:s.Value,Scalar:s.Value,Seq:s.Value},s.Collection&&{Map:s.Collection,Seq:s.Collection},s):s}c(po,"initVisitor");function mo(s,e,t,n){if(typeof t=="function")return t(s,e,n);if(St(e))return t.Map?.(s,e,n);if(Ct(e))return t.Seq?.(s,e,n);if(V(e))return t.Pair?.(s,e,n);if(H(e))return t.Scalar?.(s,e,n);if(Be(e))return t.Alias?.(s,e,n)}c(mo,"callVisitor");function go(s,e,t){const n=e[e.length-1];if(z(n))n.items[s]=t;else if(V(n))s==="key"?n.key=t:n.value=t;else if(Ze(n))n.contents=t;else{const r=Be(n)?"alias":"scalar";throw new Error(`Cannot replace node with ${r} parent`)}}c(go,"replaceNode");const Hl={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},Vl=c(s=>s.replace(/[!,[\]{}]/g,e=>Hl[e]),"escapeTagName");class oe{static{c(this,"Directives")}constructor(e,t){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},oe.defaultYaml,e),this.tags=Object.assign({},oe.defaultTags,t)}clone(){const e=new oe(this.yaml,this.tags);return e.docStart=this.docStart,e}atDocument(){const e=new oe(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:oe.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},oe.defaultTags);break}return e}add(e,t){this.atNextDocument&&(this.yaml={explicit:oe.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},oe.defaultTags),this.atNextDocument=!1);const n=e.trim().split(/[ \t]+/),r=n.shift();switch(r){case"%TAG":{if(n.length!==2&&(t(0,"%TAG directive should contain exactly two parts"),n.length<2))return!1;const[i,o]=n;return this.tags[i]=o,!0}case"%YAML":{if(this.yaml.explicit=!0,n.length!==1)return t(0,"%YAML directive should contain exactly one part"),!1;const[i]=n;if(i==="1.1"||i==="1.2")return this.yaml.version=i,!0;{const o=/^\d+\.\d+$/.test(i);return t(6,`Unsupported YAML version ${i}`,o),!1}}default:return t(0,`Unknown directive ${r}`,!0),!1}}tagName(e,t){if(e==="!")return"!";if(e[0]!=="!")return t(`Not a valid tag: ${e}`),null;if(e[1]==="<"){const o=e.slice(2,-1);return o==="!"||o==="!!"?(t(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==">"&&t("Verbatim tags must end with a >"),o)}const[,n,r]=e.match(/^(.*!)([^!]*)$/s);r||t(`The ${e} tag has no suffix`);const i=this.tags[n];if(i)try{return i+decodeURIComponent(r)}catch(o){return t(String(o)),null}return n==="!"?e:(t(`Could not resolve tag: ${e}`),null)}tagString(e){for(const[t,n]of Object.entries(this.tags))if(e.startsWith(n))return t+Vl(e.substring(n.length));return e[0]==="!"?e:`!<${e}>`}toString(e){const t=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],n=Object.entries(this.tags);let r;if(e&&n.length>0&&Y(e.contents)){const i={};et(e.contents,(o,a)=>{Y(a)&&a.tag&&(i[a.tag]=!0)}),r=Object.keys(i)}else r=[];for(const[i,o]of n)i==="!!"&&o==="tag:yaml.org,2002:"||(!e||r.some(a=>a.startsWith(o)))&&t.push(`%TAG ${i} ${o}`);return t.join(`
|
|
4
4
|
`)}}oe.defaultYaml={explicit:!1,version:"1.2"},oe.defaultTags={"!!":"tag:yaml.org,2002:"};function yo(s){if(/[\x00-\x19\s,[\]{}]/.test(s)){const t=`Anchor must not contain whitespace or control characters: ${JSON.stringify(s)}`;throw new Error(t)}return!0}c(yo,"anchorIsValid");function wo(s){const e=new Set;return et(s,{Value(t,n){n.anchor&&e.add(n.anchor)}}),e}c(wo,"anchorNames");function bo(s,e){for(let t=1;;++t){const n=`${s}${t}`;if(!e.has(n))return n}}c(bo,"findNewAnchor");function Gl(s,e){const t=[],n=new Map;let r=null;return{onAnchor:c(i=>{t.push(i),r??(r=wo(s));const o=bo(e,r);return r.add(o),o},"onAnchor"),setAnchors:c(()=>{for(const i of t){const o=n.get(i);if(typeof o=="object"&&o.anchor&&(H(o.node)||z(o.node)))o.node.anchor=o.anchor;else{const a=new Error("Failed to resolve repeated object (this should not happen)");throw a.source=i,a}}},"setAnchors"),sourceObjects:n}}c(Gl,"createNodeAnchors");function Tt(s,e,t,n){if(n&&typeof n=="object")if(Array.isArray(n))for(let r=0,i=n.length;r<i;++r){const o=n[r],a=Tt(s,n,String(r),o);a===void 0?delete n[r]:a!==o&&(n[r]=a)}else if(n instanceof Map)for(const r of Array.from(n.keys())){const i=n.get(r),o=Tt(s,n,r,i);o===void 0?n.delete(r):o!==i&&n.set(r,o)}else if(n instanceof Set)for(const r of Array.from(n)){const i=Tt(s,n,r,r);i===void 0?n.delete(r):i!==r&&(n.delete(r),n.add(i))}else for(const[r,i]of Object.entries(n)){const o=Tt(s,n,r,i);o===void 0?delete n[r]:o!==i&&(n[r]=o)}return s.call(e,t,n)}c(Tt,"applyReviver");function ge(s,e,t){if(Array.isArray(s))return s.map((n,r)=>ge(n,String(r),t));if(s&&typeof s.toJSON=="function"){if(!t||!fo(s))return s.toJSON(e,t);const n={aliasCount:0,count:1,res:void 0};t.anchors.set(s,n),t.onCreate=i=>{n.res=i,delete t.onCreate};const r=s.toJSON(e,t);return t.onCreate&&t.onCreate(r),r}return typeof s=="bigint"&&!t?.keep?Number(s):s}c(ge,"toJS");class cr{static{c(this,"NodeBase")}constructor(e){Object.defineProperty(this,me,{value:e})}clone(){const e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:t,maxAliasCount:n,onAnchor:r,reviver:i}={}){if(!Ze(e))throw new TypeError("A document argument is required");const o={anchors:new Map,doc:e,keep:!0,mapAsMap:t===!0,mapKeyWarned:!1,maxAliasCount:typeof n=="number"?n:100},a=ge(this,"",o);if(typeof r=="function")for(const{count:l,res:u}of o.anchors.values())r(u,l);return typeof i=="function"?Tt(i,{"":a},"",a):a}}class qn extends cr{static{c(this,"Alias")}constructor(e){super(or),this.source=e,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(e,t){let n;t?.aliasResolveCache?n=t.aliasResolveCache:(n=[],et(e,{Node:c((i,o)=>{(Be(o)||fo(o))&&n.push(o)},"Node")}),t&&(t.aliasResolveCache=n));let r;for(const i of n){if(i===this)break;i.anchor===this.source&&(r=i)}return r}toJSON(e,t){if(!t)return{source:this.source};const{anchors:n,doc:r,maxAliasCount:i}=t,o=this.resolve(r,t);if(!o){const l=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(l)}let a=n.get(o);if(a||(ge(o,null,t),a=n.get(o)),!a||a.res===void 0){const l="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(l)}if(i>=0&&(a.count+=1,a.aliasCount===0&&(a.aliasCount=Kn(r,o,n)),a.count*a.aliasCount>i)){const l="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(l)}return a.res}toString(e,t,n){const r=`*${this.source}`;if(e){if(yo(this.source),e.options.verifyAliasOrder&&!e.anchors.has(this.source)){const i=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(i)}if(e.implicitKey)return`${r} `}return r}}function Kn(s,e,t){if(Be(e)){const n=e.resolve(s),r=t&&n&&t.get(n);return r?r.count*r.aliasCount:0}else if(z(e)){let n=0;for(const r of e.items){const i=Kn(s,r,t);i>n&&(n=i)}return n}else if(V(e)){const n=Kn(s,e.key,t),r=Kn(s,e.value,t);return Math.max(n,r)}return 1}c(Kn,"getAliasCount");const So=c(s=>!s||typeof s!="function"&&typeof s!="object","isScalarValue");class R extends cr{static{c(this,"Scalar")}constructor(e){super(Ee),this.value=e}toJSON(e,t){return t?.keep?this.value:ge(this.value,e,t)}toString(){return String(this.value)}}R.BLOCK_FOLDED="BLOCK_FOLDED",R.BLOCK_LITERAL="BLOCK_LITERAL",R.PLAIN="PLAIN",R.QUOTE_DOUBLE="QUOTE_DOUBLE",R.QUOTE_SINGLE="QUOTE_SINGLE";const zl="tag:yaml.org,2002:";function Yl(s,e,t){if(e){const n=t.filter(i=>i.tag===e),r=n.find(i=>!i.format)??n[0];if(!r)throw new Error(`Tag ${e} not found`);return r}return t.find(n=>n.identify?.(s)&&!n.format)}c(Yl,"findTagObject");function Ht(s,e,t){if(Ze(s)&&(s=s.contents),Y(s))return s;if(V(s)){const f=t.schema[Ke].createNode?.(t.schema,null,t);return f.items.push(s),f}(s instanceof String||s instanceof Number||s instanceof Boolean||typeof BigInt<"u"&&s instanceof BigInt)&&(s=s.valueOf());const{aliasDuplicateObjects:n,onAnchor:r,onTagObj:i,schema:o,sourceObjects:a}=t;let l;if(n&&s&&typeof s=="object"){if(l=a.get(s),l)return l.anchor??(l.anchor=r(s)),new qn(l.anchor);l={anchor:null,node:null},a.set(s,l)}e?.startsWith("!!")&&(e=zl+e.slice(2));let u=Yl(s,e,o.tags);if(!u){if(s&&typeof s.toJSON=="function"&&(s=s.toJSON()),!s||typeof s!="object"){const f=new R(s);return l&&(l.node=f),f}u=s instanceof Map?o[Ke]:Symbol.iterator in Object(s)?o[bt]:o[Ke]}i&&(i(u),delete t.onTagObj);const d=u?.createNode?u.createNode(t.schema,s,t):typeof u?.nodeClass?.from=="function"?u.nodeClass.from(t.schema,s,t):new R(s);return e?d.tag=e:u.default||(d.tag=u.tag),l&&(l.node=d),d}c(Ht,"createNode");function Bn(s,e,t){let n=t;for(let r=e.length-1;r>=0;--r){const i=e[r];if(typeof i=="number"&&Number.isInteger(i)&&i>=0){const o=[];o[i]=n,n=o}else n=new Map([[i,n]])}return Ht(n,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:c(()=>{throw new Error("This should not happen, please report a bug.")},"onAnchor"),schema:s,sourceObjects:new Map})}c(Bn,"collectionFromPath");const Vt=c(s=>s==null||typeof s=="object"&&!!s[Symbol.iterator]().next().done,"isEmptyPath");class Co extends cr{static{c(this,"Collection")}constructor(e,t){super(e),Object.defineProperty(this,"schema",{value:t,configurable:!0,enumerable:!1,writable:!0})}clone(e){const t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return e&&(t.schema=e),t.items=t.items.map(n=>Y(n)||V(n)?n.clone(e):n),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(Vt(e))this.add(t);else{const[n,...r]=e,i=this.get(n,!0);if(z(i))i.addIn(r,t);else if(i===void 0&&this.schema)this.set(n,Bn(this.schema,r,t));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${r}`)}}deleteIn(e){const[t,...n]=e;if(n.length===0)return this.delete(t);const r=this.get(t,!0);if(z(r))return r.deleteIn(n);throw new Error(`Expected YAML collection at ${t}. Remaining path: ${n}`)}getIn(e,t){const[n,...r]=e,i=this.get(n,!0);return r.length===0?!t&&H(i)?i.value:i:z(i)?i.getIn(r,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!V(t))return!1;const n=t.value;return n==null||e&&H(n)&&n.value==null&&!n.commentBefore&&!n.comment&&!n.tag})}hasIn(e){const[t,...n]=e;if(n.length===0)return this.has(t);const r=this.get(t,!0);return z(r)?r.hasIn(n):!1}setIn(e,t){const[n,...r]=e;if(r.length===0)this.set(n,t);else{const i=this.get(n,!0);if(z(i))i.setIn(r,t);else if(i===void 0&&this.schema)this.set(n,Bn(this.schema,r,t));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${r}`)}}}const Xl=c(s=>s.replace(/^(?!$)(?: $)?/gm,"#"),"stringifyComment");function Ne(s,e){return/^\n+$/.test(s)?s.substring(1):e?s.replace(/^(?! *$)/gm,e):s}c(Ne,"indentComment");const tt=c((s,e,t)=>s.endsWith(`
|
|
5
5
|
`)?Ne(t,e):t.includes(`
|
|
6
6
|
`)?`
|
|
@@ -26,7 +26,7 @@ ${t}`)+"'";return e.implicitKey?n:Wn(n,t,vo,Jn(e,!1))}c(ur,"singleQuotedString")
|
|
|
26
26
|
`);y===-1?f="-":t===g||y!==g.length-1?(f="+",i&&i()):f="",g&&(t=t.slice(0,-g.length),g[g.length-1]===`
|
|
27
27
|
`&&(g=g.slice(0,-1)),g=g.replace(dr,`$&${u}`));let p=!1,w,T=-1;for(w=0;w<t.length;++w){const $=t[w];if($===" ")p=!0;else if($===`
|
|
28
28
|
`)T=w;else break}let E=t.substring(0,T<w?T+1:w);E&&(t=t.substring(E.length),E=E.replace(/\n+/g,`$&${u}`));let I=(p?u?"2":"1":"")+f;if(s&&(I+=" "+a(s.replace(/ ?[\r\n]+/g," ")),r&&r()),!d){const $=t.replace(/\n+/g,`
|
|
29
|
-
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${u}`);let
|
|
29
|
+
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${u}`);let x=!1;const D=Jn(n,!0);o!=="folded"&&e!==R.BLOCK_FOLDED&&(D.onOverflow=()=>{x=!0});const A=Wn(`${E}${$}${g}`,u,lr,D);if(!x)return`>${I}
|
|
30
30
|
${u}${A}`}return t=t.replace(/\n+/g,`$&${u}`),`|${I}
|
|
31
31
|
${u}${E}${t}${g}`}c(Vn,"blockString");function Zl(s,e,t,n){const{type:r,value:i}=s,{actualString:o,implicitKey:a,indent:l,indentStep:u,inFlow:d}=e;if(a&&i.includes(`
|
|
32
32
|
`)||d&&/[[\]{},]/.test(i))return Et(i,e);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(i))return a||d||!i.includes(`
|
|
@@ -34,16 +34,16 @@ ${u}${E}${t}${g}`}c(Vn,"blockString");function Zl(s,e,t,n){const{type:r,value:i}
|
|
|
34
34
|
`))return Vn(s,e,t,n);if(Hn(i)){if(l==="")return e.forceBlockIndent=!0,Vn(s,e,t,n);if(a&&l===u)return Et(i,e)}const f=i.replace(/\n+/g,`$&
|
|
35
35
|
${l}`);if(o){const h=c(p=>p.default&&p.tag!=="tag:yaml.org,2002:str"&&p.test?.test(f),"test"),{compat:g,tags:y}=e.doc.schema;if(y.some(h)||g?.some(h))return Et(i,e)}return a?f:Wn(f,l,vo,Jn(e,!1))}c(Zl,"plainString");function zt(s,e,t,n){const{implicitKey:r,inFlow:i}=e,o=typeof s.value=="string"?s:Object.assign({},s,{value:String(s.value)});let{type:a}=s;a!==R.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(a=R.QUOTE_DOUBLE);const l=c(d=>{switch(d){case R.BLOCK_FOLDED:case R.BLOCK_LITERAL:return r||i?Et(o.value,e):Vn(o,e,t,n);case R.QUOTE_DOUBLE:return Gt(o.value,e);case R.QUOTE_SINGLE:return ur(o.value,e);case R.PLAIN:return Zl(o,e,t,n);default:return null}},"_stringify");let u=l(a);if(u===null){const{defaultKeyType:d,defaultStringType:f}=e.options,h=r&&d||f;if(u=l(h),u===null)throw new Error(`Unsupported default string type ${h}`)}return u}c(zt,"stringifyString");function To(s,e){const t=Object.assign({blockQuote:!0,commentString:Xl,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trueStr:"true",verifyAliasOrder:!0},s.schema.toStringOptions,e);let n;switch(t.collectionStyle){case"block":n=!1;break;case"flow":n=!0;break;default:n=null}return{anchors:new Set,doc:s,flowCollectionPadding:t.flowCollectionPadding?" ":"",indent:"",indentStep:typeof t.indent=="number"?" ".repeat(t.indent):" ",inFlow:n,options:t}}c(To,"createStringifyContext");function eu(s,e){if(e.tag){const r=s.filter(i=>i.tag===e.tag);if(r.length>0)return r.find(i=>i.format===e.format)??r[0]}let t,n;if(H(e)){n=e.value;let r=s.filter(i=>i.identify?.(n));if(r.length>1){const i=r.filter(o=>o.test);i.length>0&&(r=i)}t=r.find(i=>i.format===e.format)??r.find(i=>!i.format)}else n=e,t=s.find(r=>r.nodeClass&&n instanceof r.nodeClass);if(!t){const r=n?.constructor?.name??(n===null?"null":typeof n);throw new Error(`Tag not resolved for ${r} value`)}return t}c(eu,"getTagObject");function tu(s,e,{anchors:t,doc:n}){if(!n.directives)return"";const r=[],i=(H(s)||z(s))&&s.anchor;i&&yo(i)&&(t.add(i),r.push(`&${i}`));const o=s.tag??(e.default?null:e.tag);return o&&r.push(n.directives.tagString(o)),r.join(" ")}c(tu,"stringifyProps");function _t(s,e,t,n){if(V(s))return s.toString(e,t,n);if(Be(s)){if(e.doc.directives)return s.toString(e);if(e.resolvedAliases?.has(s))throw new TypeError("Cannot stringify circular structure without alias nodes");e.resolvedAliases?e.resolvedAliases.add(s):e.resolvedAliases=new Set([s]),s=s.resolve(e.doc)}let r;const i=Y(s)?s:e.doc.createNode(s,{onTagObj:c(l=>r=l,"onTagObj")});r??(r=eu(e.doc.schema.tags,i));const o=tu(i,r,e);o.length>0&&(e.indentAtStart=(e.indentAtStart??0)+o.length+1);const a=typeof r.stringify=="function"?r.stringify(i,e,t,n):H(i)?zt(i,e,t,n):i.toString(e,t,n);return o?H(i)||a[0]==="{"||a[0]==="["?`${o} ${a}`:`${o}
|
|
36
36
|
${e.indent}${a}`:a}c(_t,"stringify$2");function nu({key:s,value:e},t,n,r){const{allNullValues:i,doc:o,indent:a,indentStep:l,options:{commentString:u,indentSeq:d,simpleKeys:f}}=t;let h=Y(s)&&s.comment||null;if(f){if(h)throw new Error("With simple keys, key nodes cannot have comments");if(z(s)||!Y(s)&&typeof s=="object"){const D="With simple keys, collection cannot be used as a key value";throw new Error(D)}}let g=!f&&(!s||h&&e==null&&!t.inFlow||z(s)||(H(s)?s.type===R.BLOCK_FOLDED||s.type===R.BLOCK_LITERAL:typeof s=="object"));t=Object.assign({},t,{allNullValues:!1,implicitKey:!g&&(f||!i),indent:a+l});let y=!1,p=!1,w=_t(s,t,()=>y=!0,()=>p=!0);if(!g&&!t.inFlow&&w.length>1024){if(f)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");g=!0}if(t.inFlow){if(i||e==null)return y&&n&&n(),w===""?"?":g?`? ${w}`:w}else if(i&&!f||e==null&&g)return w=`? ${w}`,h&&!y?w+=tt(w,t.indent,u(h)):p&&r&&r(),w;y&&(h=null),g?(h&&(w+=tt(w,t.indent,u(h))),w=`? ${w}
|
|
37
|
-
${a}:`):(w=`${w}:`,h&&(w+=tt(w,t.indent,u(h))));let T,E,O;Y(e)?(T=!!e.spaceBefore,E=e.commentBefore,O=e.comment):(T=!1,E=null,O=null,e&&typeof e=="object"&&(e=o.createNode(e))),t.implicitKey=!1,!g&&!h&&H(e)&&(t.indentAtStart=w.length+1),p=!1,!d&&l.length>=2&&!t.inFlow&&!g&&Ct(e)&&!e.flow&&!e.tag&&!e.anchor&&(t.indent=t.indent.substring(2));let I=!1;const $=_t(e,t,()=>I=!0,()=>p=!0);let
|
|
38
|
-
`:"",E){const D=u(E);
|
|
39
|
-
${Ne(D,t.indent)}`}$===""&&!t.inFlow?
|
|
40
|
-
`&&(
|
|
37
|
+
${a}:`):(w=`${w}:`,h&&(w+=tt(w,t.indent,u(h))));let T,E,O;Y(e)?(T=!!e.spaceBefore,E=e.commentBefore,O=e.comment):(T=!1,E=null,O=null,e&&typeof e=="object"&&(e=o.createNode(e))),t.implicitKey=!1,!g&&!h&&H(e)&&(t.indentAtStart=w.length+1),p=!1,!d&&l.length>=2&&!t.inFlow&&!g&&Ct(e)&&!e.flow&&!e.tag&&!e.anchor&&(t.indent=t.indent.substring(2));let I=!1;const $=_t(e,t,()=>I=!0,()=>p=!0);let x=" ";if(h||T||E){if(x=T?`
|
|
38
|
+
`:"",E){const D=u(E);x+=`
|
|
39
|
+
${Ne(D,t.indent)}`}$===""&&!t.inFlow?x===`
|
|
40
|
+
`&&(x=`
|
|
41
41
|
|
|
42
|
-
`):
|
|
42
|
+
`):x+=`
|
|
43
43
|
${t.indent}`}else if(!g&&z(e)){const D=$[0],A=$.indexOf(`
|
|
44
|
-
`),te=A!==-1,je=t.inFlow??e.flow??e.items.length===0;if(te||!je){let lt=!1;if(te&&(D==="&"||D==="!")){let ne=$.indexOf(" ");D==="&"&&ne!==-1&&ne<A&&$[ne+1]==="!"&&(ne=$.indexOf(" ",ne+1)),(ne===-1||A<ne)&&(lt=!0)}lt||(
|
|
44
|
+
`),te=A!==-1,je=t.inFlow??e.flow??e.items.length===0;if(te||!je){let lt=!1;if(te&&(D==="&"||D==="!")){let ne=$.indexOf(" ");D==="&"&&ne!==-1&&ne<A&&$[ne+1]==="!"&&(ne=$.indexOf(" ",ne+1)),(ne===-1||A<ne)&&(lt=!0)}lt||(x=`
|
|
45
45
|
${t.indent}`)}}else($===""||$[0]===`
|
|
46
|
-
`)&&(
|
|
46
|
+
`)&&(x="");return w+=x+$,t.inFlow?I&&n&&n():O&&!I?w+=tt(w,t.indent,u(O)):p&&r&&r(),w}c(nu,"stringifyPair");function Eo(s,e){(s==="debug"||s==="warn")&&console.warn(e)}c(Eo,"warn");const Gn="<<",xe={identify:c(s=>s===Gn||typeof s=="symbol"&&s.description===Gn,"identify"),default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:c(()=>Object.assign(new R(Symbol(Gn)),{addToJSMap:_o}),"resolve"),stringify:c(()=>Gn,"stringify")},su=c((s,e)=>(xe.identify(e)||H(e)&&(!e.type||e.type===R.PLAIN)&&xe.identify(e.value))&&s?.doc.schema.tags.some(t=>t.tag===xe.tag&&t.default),"isMergeKey");function _o(s,e,t){if(t=s&&Be(t)?t.resolve(s.doc):t,Ct(t))for(const n of t.items)fr(s,e,n);else if(Array.isArray(t))for(const n of t)fr(s,e,n);else fr(s,e,t)}c(_o,"addMergeToJSMap");function fr(s,e,t){const n=s&&Be(t)?t.resolve(s.doc):t;if(!St(n))throw new Error("Merge sources must be maps or map aliases");const r=n.toJSON(null,s,Map);for(const[i,o]of r)e instanceof Map?e.has(i)||e.set(i,o):e instanceof Set?e.add(i):Object.prototype.hasOwnProperty.call(e,i)||Object.defineProperty(e,i,{value:o,writable:!0,enumerable:!0,configurable:!0});return e}c(fr,"mergeValue");function Io(s,e,{key:t,value:n}){if(Y(t)&&t.addToJSMap)t.addToJSMap(s,e,n);else if(su(s,t))_o(s,e,n);else{const r=ge(t,"",s);if(e instanceof Map)e.set(r,ge(n,r,s));else if(e instanceof Set)e.add(r);else{const i=ru(t,r,s),o=ge(n,i,s);i in e?Object.defineProperty(e,i,{value:o,writable:!0,enumerable:!0,configurable:!0}):e[i]=o}}return e}c(Io,"addPairToJSMap");function ru(s,e,t){if(e===null)return"";if(typeof e!="object")return String(e);if(Y(s)&&t?.doc){const n=To(t.doc,{});n.anchors=new Set;for(const i of t.anchors.keys())n.anchors.add(i.anchor);n.inFlow=!0,n.inStringifyKey=!0;const r=s.toString(n);if(!t.mapKeyWarned){let i=JSON.stringify(r);i.length>40&&(i=i.substring(0,36)+'..."'),Eo(t.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${i}. Set mapAsMap: true to use object keys.`),t.mapKeyWarned=!0}return r}return JSON.stringify(e)}c(ru,"stringifyKey");function hr(s,e,t){const n=Ht(s,void 0,t),r=Ht(e,void 0,t);return new se(n,r)}c(hr,"createPair");class se{static{c(this,"Pair")}constructor(e,t=null){Object.defineProperty(this,me,{value:uo}),this.key=e,this.value=t}clone(e){let{key:t,value:n}=this;return Y(t)&&(t=t.clone(e)),Y(n)&&(n=n.clone(e)),new se(t,n)}toJSON(e,t){const n=t?.mapAsMap?new Map:{};return Io(t,n,this)}toString(e,t,n){return e?.doc?nu(this,e,t,n):JSON.stringify(this)}}function Ao(s,e,t){return(e.inFlow??s.flow?ou:iu)(s,e,t)}c(Ao,"stringifyCollection");function iu({comment:s,items:e},t,{blockItemPrefix:n,flowChars:r,itemIndent:i,onChompKeep:o,onComment:a}){const{indent:l,options:{commentString:u}}=t,d=Object.assign({},t,{indent:i,type:null});let f=!1;const h=[];for(let y=0;y<e.length;++y){const p=e[y];let w=null;if(Y(p))!f&&p.spaceBefore&&h.push(""),zn(t,h,p.commentBefore,f),p.comment&&(w=p.comment);else if(V(p)){const E=Y(p.key)?p.key:null;E&&(!f&&E.spaceBefore&&h.push(""),zn(t,h,E.commentBefore,f))}f=!1;let T=_t(p,d,()=>w=null,()=>f=!0);w&&(T+=tt(T,i,u(w))),f&&w&&(f=!1),h.push(n+T)}let g;if(h.length===0)g=r.start+r.end;else{g=h[0];for(let y=1;y<h.length;++y){const p=h[y];g+=p?`
|
|
47
47
|
${l}${p}`:`
|
|
48
48
|
`}}return s?(g+=`
|
|
49
49
|
`+Ne(u(s),l),a&&a()):f&&o&&o(),g}c(iu,"stringifyBlockCollection");function ou({items:s},e,{flowChars:t,itemIndent:n}){const{indent:r,indentStep:i,flowCollectionPadding:o,options:{commentString:a}}=e;n+=i;const l=Object.assign({},e,{indent:n,inFlow:!0,type:null});let u=!1,d=0;const f=[];for(let y=0;y<s.length;++y){const p=s[y];let w=null;if(Y(p))p.spaceBefore&&f.push(""),zn(e,f,p.commentBefore,!1),p.comment&&(w=p.comment);else if(V(p)){const E=Y(p.key)?p.key:null;E&&(E.spaceBefore&&f.push(""),zn(e,f,E.commentBefore,!1),E.comment&&(u=!0));const O=Y(p.value)?p.value:null;O?(O.comment&&(w=O.comment),O.commentBefore&&(u=!0)):p.value==null&&E?.comment&&(w=E.comment)}w&&(u=!0);let T=_t(p,l,()=>w=null);y<s.length-1&&(T+=","),w&&(T+=tt(T,n,a(w))),!u&&(f.length>d||T.includes(`
|
|
@@ -61,12 +61,12 @@ ${i.comment}`:n.comment}n=r}s.items[t]=V(n)?n:new se(n)}}else e("Expected a sequ
|
|
|
61
61
|
|
|
62
62
|
${o}
|
|
63
63
|
${u}
|
|
64
|
-
`}},"prettifyError");function $t(s,{flow:e,indicator:t,next:n,offset:r,onError:i,parentIndent:o,startOnNewline:a}){let l=!1,u=a,d=a,f="",h="",g=!1,y=!1,p=null,w=null,T=null,E=null,O=null,I=null,$=null;for(const A of s)switch(y&&(A.type!=="space"&&A.type!=="newline"&&A.type!=="comma"&&i(A.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),y=!1),p&&(u&&A.type!=="comment"&&A.type!=="newline"&&i(p,"TAB_AS_INDENT","Tabs are not allowed as indentation"),p=null),A.type){case"space":!e&&(t!=="doc-start"||n?.type!=="flow-collection")&&A.source.includes(" ")&&(p=A),d=!0;break;case"comment":{d||i(A,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");const te=A.source.substring(1)||" ";f?f+=h+te:f=te,h="",u=!1;break}case"newline":u?f?f+=A.source:(!I||t!=="seq-item-ind")&&(l=!0):h+=A.source,u=!0,g=!0,(w||T)&&(E=A),d=!0;break;case"anchor":w&&i(A,"MULTIPLE_ANCHORS","A node can have at most one anchor"),A.source.endsWith(":")&&i(A.offset+A.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),w=A,$??($=A.offset),u=!1,d=!1,y=!0;break;case"tag":{T&&i(A,"MULTIPLE_TAGS","A node can have at most one tag"),T=A,$??($=A.offset),u=!1,d=!1,y=!0;break}case t:(w||T)&&i(A,"BAD_PROP_ORDER",`Anchors and tags must be after the ${A.source} indicator`),I&&i(A,"UNEXPECTED_TOKEN",`Unexpected ${A.source} in ${e??"collection"}`),I=A,u=t==="seq-item-ind"||t==="explicit-key-ind",d=!1;break;case"comma":if(e){O&&i(A,"UNEXPECTED_TOKEN",`Unexpected , in ${e}`),O=A,u=!1,d=!1;break}default:i(A,"UNEXPECTED_TOKEN",`Unexpected ${A.type} token`),u=!1,d=!1}const
|
|
64
|
+
`}},"prettifyError");function $t(s,{flow:e,indicator:t,next:n,offset:r,onError:i,parentIndent:o,startOnNewline:a}){let l=!1,u=a,d=a,f="",h="",g=!1,y=!1,p=null,w=null,T=null,E=null,O=null,I=null,$=null;for(const A of s)switch(y&&(A.type!=="space"&&A.type!=="newline"&&A.type!=="comma"&&i(A.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),y=!1),p&&(u&&A.type!=="comment"&&A.type!=="newline"&&i(p,"TAB_AS_INDENT","Tabs are not allowed as indentation"),p=null),A.type){case"space":!e&&(t!=="doc-start"||n?.type!=="flow-collection")&&A.source.includes(" ")&&(p=A),d=!0;break;case"comment":{d||i(A,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");const te=A.source.substring(1)||" ";f?f+=h+te:f=te,h="",u=!1;break}case"newline":u?f?f+=A.source:(!I||t!=="seq-item-ind")&&(l=!0):h+=A.source,u=!0,g=!0,(w||T)&&(E=A),d=!0;break;case"anchor":w&&i(A,"MULTIPLE_ANCHORS","A node can have at most one anchor"),A.source.endsWith(":")&&i(A.offset+A.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),w=A,$??($=A.offset),u=!1,d=!1,y=!0;break;case"tag":{T&&i(A,"MULTIPLE_TAGS","A node can have at most one tag"),T=A,$??($=A.offset),u=!1,d=!1,y=!0;break}case t:(w||T)&&i(A,"BAD_PROP_ORDER",`Anchors and tags must be after the ${A.source} indicator`),I&&i(A,"UNEXPECTED_TOKEN",`Unexpected ${A.source} in ${e??"collection"}`),I=A,u=t==="seq-item-ind"||t==="explicit-key-ind",d=!1;break;case"comma":if(e){O&&i(A,"UNEXPECTED_TOKEN",`Unexpected , in ${e}`),O=A,u=!1,d=!1;break}default:i(A,"UNEXPECTED_TOKEN",`Unexpected ${A.type} token`),u=!1,d=!1}const x=s[s.length-1],D=x?x.offset+x.source.length:r;return y&&n&&n.type!=="space"&&n.type!=="newline"&&n.type!=="comma"&&(n.type!=="scalar"||n.source!=="")&&i(n.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),p&&(u&&p.indent<=o||n?.type==="block-map"||n?.type==="block-seq")&&i(p,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:O,found:I,spaceBefore:l,comment:f,hasNewline:g,anchor:w,tag:T,newlineAfterProp:E,end:D,start:$??D}}c($t,"resolveProps");function Xt(s){if(!s)return null;switch(s.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(s.source.includes(`
|
|
65
65
|
`))return!0;if(s.end){for(const e of s.end)if(e.type==="newline")return!0}return!1;case"flow-collection":for(const e of s.items){for(const t of e.start)if(t.type==="newline")return!0;if(e.sep){for(const t of e.sep)if(t.type==="newline")return!0}if(Xt(e.key)||Xt(e.value))return!0}return!1;default:return!0}}c(Xt,"containsNewline");function Tr(s,e,t){if(e?.type==="flow-collection"){const n=e.end[0];n.indent===s&&(n.source==="]"||n.source==="}")&&Xt(e)&&t(n,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}c(Tr,"flowIndentCheck");function zo(s,e,t){const{uniqueKeys:n}=s.options;if(n===!1)return!1;const r=typeof n=="function"?n:(i,o)=>i===o||H(i)&&H(o)&&i.value===o.value;return e.some(i=>r(i.key,t))}c(zo,"mapIncludes");const Yo="All mapping items must start at the same column";function Cu({composeNode:s,composeEmptyNode:e},t,n,r,i){const o=i?.nodeClass??ue,a=new o(t.schema);t.atRoot&&(t.atRoot=!1);let l=n.offset,u=null;for(const d of n.items){const{start:f,key:h,sep:g,value:y}=d,p=$t(f,{indicator:"explicit-key-ind",next:h??g?.[0],offset:l,onError:r,parentIndent:n.indent,startOnNewline:!0}),w=!p.found;if(w){if(h&&(h.type==="block-seq"?r(l,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in h&&h.indent!==n.indent&&r(l,"BAD_INDENT",Yo)),!p.anchor&&!p.tag&&!g){u=p.end,p.comment&&(a.comment?a.comment+=`
|
|
66
66
|
`+p.comment:a.comment=p.comment);continue}(p.newlineAfterProp||Xt(h))&&r(h??f[f.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else p.found?.indent!==n.indent&&r(l,"BAD_INDENT",Yo);t.atKey=!0;const T=p.end,E=h?s(t,h,p,r):e(t,T,f,null,p,r);t.schema.compat&&Tr(n.indent,h,r),t.atKey=!1,zo(t,a.items,E)&&r(T,"DUPLICATE_KEY","Map keys must be unique");const O=$t(g??[],{indicator:"map-value-ind",next:y,offset:E.range[2],onError:r,parentIndent:n.indent,startOnNewline:!h||h.type==="block-scalar"});if(l=O.end,O.found){w&&(y?.type==="block-map"&&!O.hasNewline&&r(l,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),t.options.strict&&p.start<O.found.offset-1024&&r(E.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));const I=y?s(t,y,O,r):e(t,l,g,null,O,r);t.schema.compat&&Tr(n.indent,y,r),l=I.range[2];const $=new se(E,I);t.options.keepSourceTokens&&($.srcToken=d),a.items.push($)}else{w&&r(E.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),O.comment&&(E.comment?E.comment+=`
|
|
67
|
-
`+O.comment:E.comment=O.comment);const I=new se(E);t.options.keepSourceTokens&&(I.srcToken=d),a.items.push(I)}}return u&&u<l&&r(u,"IMPOSSIBLE","Map comment with trailing content"),a.range=[n.offset,l,u??l],a}c(Cu,"resolveBlockMap");function vu({composeNode:s,composeEmptyNode:e},t,n,r,i){const o=i?.nodeClass??Ue,a=new o(t.schema);t.atRoot&&(t.atRoot=!1),t.atKey&&(t.atKey=!1);let l=n.offset,u=null;for(const{start:d,value:f}of n.items){const h=$t(d,{indicator:"seq-item-ind",next:f,offset:l,onError:r,parentIndent:n.indent,startOnNewline:!0});if(!h.found)if(h.anchor||h.tag||f)f&&f.type==="block-seq"?r(h.end,"BAD_INDENT","All sequence items must start at the same column"):r(l,"MISSING_CHAR","Sequence item without - indicator");else{u=h.end,h.comment&&(a.comment=h.comment);continue}const g=f?s(t,f,h,r):e(t,h.end,d,null,h,r);t.schema.compat&&Tr(n.indent,f,r),l=g.range[2],a.items.push(g)}return a.range=[n.offset,l,u??l],a}c(vu,"resolveBlockSeq");function Qt(s,e,t,n){let r="";if(s){let i=!1,o="";for(const a of s){const{source:l,type:u}=a;switch(u){case"space":i=!0;break;case"comment":{t&&!i&&n(a,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");const d=l.substring(1)||" ";r?r+=o+d:r=d,o="";break}case"newline":r&&(o+=l),i=!0;break;default:n(a,"UNEXPECTED_TOKEN",`Unexpected ${u} at node end`)}e+=l.length}}return{comment:r,offset:e}}c(Qt,"resolveEnd");const Er="Block collections are not allowed within flow collections",_r=c(s=>s&&(s.type==="block-map"||s.type==="block-seq"),"isBlock");function ku({composeNode:s,composeEmptyNode:e},t,n,r,i){const o=n.start.source==="{",a=o?"flow map":"flow sequence",l=i?.nodeClass??(o?ue:Ue),u=new l(t.schema);u.flow=!0;const d=t.atRoot;d&&(t.atRoot=!1),t.atKey&&(t.atKey=!1);let f=n.offset+n.start.source.length;for(let w=0;w<n.items.length;++w){const T=n.items[w],{start:E,key:O,sep:I,value:$}=T,
|
|
68
|
-
`+
|
|
69
|
-
`+D:A.comment=D,
|
|
67
|
+
`+O.comment:E.comment=O.comment);const I=new se(E);t.options.keepSourceTokens&&(I.srcToken=d),a.items.push(I)}}return u&&u<l&&r(u,"IMPOSSIBLE","Map comment with trailing content"),a.range=[n.offset,l,u??l],a}c(Cu,"resolveBlockMap");function vu({composeNode:s,composeEmptyNode:e},t,n,r,i){const o=i?.nodeClass??Ue,a=new o(t.schema);t.atRoot&&(t.atRoot=!1),t.atKey&&(t.atKey=!1);let l=n.offset,u=null;for(const{start:d,value:f}of n.items){const h=$t(d,{indicator:"seq-item-ind",next:f,offset:l,onError:r,parentIndent:n.indent,startOnNewline:!0});if(!h.found)if(h.anchor||h.tag||f)f&&f.type==="block-seq"?r(h.end,"BAD_INDENT","All sequence items must start at the same column"):r(l,"MISSING_CHAR","Sequence item without - indicator");else{u=h.end,h.comment&&(a.comment=h.comment);continue}const g=f?s(t,f,h,r):e(t,h.end,d,null,h,r);t.schema.compat&&Tr(n.indent,f,r),l=g.range[2],a.items.push(g)}return a.range=[n.offset,l,u??l],a}c(vu,"resolveBlockSeq");function Qt(s,e,t,n){let r="";if(s){let i=!1,o="";for(const a of s){const{source:l,type:u}=a;switch(u){case"space":i=!0;break;case"comment":{t&&!i&&n(a,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");const d=l.substring(1)||" ";r?r+=o+d:r=d,o="";break}case"newline":r&&(o+=l),i=!0;break;default:n(a,"UNEXPECTED_TOKEN",`Unexpected ${u} at node end`)}e+=l.length}}return{comment:r,offset:e}}c(Qt,"resolveEnd");const Er="Block collections are not allowed within flow collections",_r=c(s=>s&&(s.type==="block-map"||s.type==="block-seq"),"isBlock");function ku({composeNode:s,composeEmptyNode:e},t,n,r,i){const o=n.start.source==="{",a=o?"flow map":"flow sequence",l=i?.nodeClass??(o?ue:Ue),u=new l(t.schema);u.flow=!0;const d=t.atRoot;d&&(t.atRoot=!1),t.atKey&&(t.atKey=!1);let f=n.offset+n.start.source.length;for(let w=0;w<n.items.length;++w){const T=n.items[w],{start:E,key:O,sep:I,value:$}=T,x=$t(E,{flow:a,indicator:"explicit-key-ind",next:O??I?.[0],offset:f,onError:r,parentIndent:n.indent,startOnNewline:!1});if(!x.found){if(!x.anchor&&!x.tag&&!I&&!$){w===0&&x.comma?r(x.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`):w<n.items.length-1&&r(x.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${a}`),x.comment&&(u.comment?u.comment+=`
|
|
68
|
+
`+x.comment:u.comment=x.comment),f=x.end;continue}!o&&t.options.strict&&Xt(O)&&r(O,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(w===0)x.comma&&r(x.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`);else if(x.comma||r(x.start,"MISSING_CHAR",`Missing , between ${a} items`),x.comment){let D="";e:for(const A of E)switch(A.type){case"comma":case"space":break;case"comment":D=A.source.substring(1);break e;default:break e}if(D){let A=u.items[u.items.length-1];V(A)&&(A=A.value??A.key),A.comment?A.comment+=`
|
|
69
|
+
`+D:A.comment=D,x.comment=x.comment.substring(D.length+1)}}if(!o&&!I&&!x.found){const D=$?s(t,$,x,r):e(t,x.end,I,null,x,r);u.items.push(D),f=D.range[2],_r($)&&r(D.range,"BLOCK_IN_FLOW",Er)}else{t.atKey=!0;const D=x.end,A=O?s(t,O,x,r):e(t,D,E,null,x,r);_r(O)&&r(A.range,"BLOCK_IN_FLOW",Er),t.atKey=!1;const te=$t(I??[],{flow:a,indicator:"map-value-ind",next:$,offset:A.range[2],onError:r,parentIndent:n.indent,startOnNewline:!1});if(te.found){if(!o&&!x.found&&t.options.strict){if(I)for(const ne of I){if(ne===te.found)break;if(ne.type==="newline"){r(ne,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}x.start<te.found.offset-1024&&r(te.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else $&&("source"in $&&$.source&&$.source[0]===":"?r($,"MISSING_CHAR",`Missing space after : in ${a}`):r(te.start,"MISSING_CHAR",`Missing , or : between ${a} items`));const je=$?s(t,$,te,r):te.found?e(t,te.end,I,null,te,r):null;je?_r($)&&r(je.range,"BLOCK_IN_FLOW",Er):te.comment&&(A.comment?A.comment+=`
|
|
70
70
|
`+te.comment:A.comment=te.comment);const lt=new se(A,je);if(t.options.keepSourceTokens&&(lt.srcToken=T),o){const ne=u;zo(t,ne.items,A)&&r(D,"DUPLICATE_KEY","Map keys must be unique"),ne.items.push(lt)}else{const ne=new ue(t.schema);ne.flow=!0,ne.items.push(lt);const Ti=(je??A).range;ne.range=[A.range[0],Ti[1],Ti[2]],u.items.push(ne)}f=je?je.range[2]:te.end}}const h=o?"}":"]",[g,...y]=n.end;let p=f;if(g&&g.source===h)p=g.offset+g.source.length;else{const w=a[0].toUpperCase()+a.substring(1),T=d?`${w} must end with a ${h}`:`${w} in block collection must be sufficiently indented and end with a ${h}`;r(f,d?"MISSING_CHAR":"BAD_INDENT",T),g&&g.source.length!==1&&y.unshift(g)}if(y.length>0){const w=Qt(y,p,t.options.strict,r);w.comment&&(u.comment?u.comment+=`
|
|
71
71
|
`+w.comment:u.comment=w.comment),u.range=[n.offset,p,w.offset]}else u.range=[n.offset,p,p];return u}c(ku,"resolveFlowCollection");function Ir(s,e,t,n,r,i){const o=t.type==="block-map"?Cu(s,e,t,n,i):t.type==="block-seq"?vu(s,e,t,n,i):ku(s,e,t,n,i),a=o.constructor;return r==="!"||r===a.tagName?(o.tag=a.tagName,o):(r&&(o.tag=r),o)}c(Ir,"resolveCollection");function Tu(s,e,t,n,r){const i=n.tag,o=i?e.directives.tagName(i.source,h=>r(i,"TAG_RESOLVE_FAILED",h)):null;if(t.type==="block-seq"){const{anchor:h,newlineAfterProp:g}=n,y=h&&i?h.offset>i.offset?h:i:h??i;y&&(!g||g.offset<y.offset)&&r(y,"MISSING_CHAR","Missing newline after block sequence props")}const a=t.type==="block-map"?"map":t.type==="block-seq"?"seq":t.start.source==="{"?"map":"seq";if(!i||!o||o==="!"||o===ue.tagName&&a==="map"||o===Ue.tagName&&a==="seq")return Ir(s,e,t,r,o);let l=e.schema.tags.find(h=>h.tag===o&&h.collection===a);if(!l){const h=e.schema.knownTags[o];if(h&&h.collection===a)e.schema.tags.push(Object.assign({},h,{default:!1})),l=h;else return h?r(i,"BAD_COLLECTION_TYPE",`${h.tag} used for ${a} collection, but expects ${h.collection??"scalar"}`,!0):r(i,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),Ir(s,e,t,r,o)}const u=Ir(s,e,t,r,o,l),d=l.resolve?.(u,h=>r(i,"TAG_RESOLVE_FAILED",h),e.options)??u,f=Y(d)?d:new R(d);return f.range=u.range,f.tag=o,l?.format&&(f.format=l.format),f}c(Tu,"composeCollection");function Xo(s,e,t){const n=e.offset,r=Eu(e,s.options.strict,t);if(!r)return{value:"",type:null,comment:"",range:[n,n,n]};const i=r.mode===">"?R.BLOCK_FOLDED:R.BLOCK_LITERAL,o=e.source?_u(e.source):[];let a=o.length;for(let p=o.length-1;p>=0;--p){const w=o[p][1];if(w===""||w==="\r")a=p;else break}if(a===0){const p=r.chomp==="+"&&o.length>0?`
|
|
72
72
|
`.repeat(Math.max(1,o.length-1)):"";let w=n+r.length;return e.source&&(w+=e.source.length),{value:p,type:i,comment:r.comment,range:[n,w,w]}}let l=e.indent+r.indent,u=e.offset+r.length,d=0;for(let p=0;p<a;++p){const[w,T]=o[p];if(T===""||T==="\r")r.indent===0&&w.length>l&&(l=w.length);else{w.length<l&&t(u+w.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator"),r.indent===0&&(l=w.length),d=p,l===0&&!s.atRoot&&t(u,"BAD_INDENT","Block scalar values in collections must be indented");break}u+=w.length+T.length+1}for(let p=o.length-1;p>=a;--p)o[p][0].length>l&&(a=p+1);let f="",h="",g=!1;for(let p=0;p<d;++p)f+=o[p][0].slice(l)+`
|
|
@@ -138,13 +138,13 @@ ${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.pus
|
|
|
138
138
|
`)+1;for(;t!==0;)this.onNewLine(this.offset+t),t=this.source.indexOf(`
|
|
139
139
|
`,t)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(e){const t=e.items[e.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,t.value){const n="end"in t.value?t.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type==="comment"?n?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"space":case"comment":if(t.value)e.items.push({start:[this.sourceToken]});else if(t.sep)t.sep.push(this.sourceToken);else{if(this.atIndentedComment(t.start,e.indent)){const r=e.items[e.items.length-2]?.value?.end;if(Array.isArray(r)){Array.prototype.push.apply(r,t.start),r.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return}if(this.indent>=e.indent){const n=!this.onKeyLine&&this.indent===e.indent,r=n&&(t.sep||t.explicitKey)&&this.type!=="seq-item-ind";let i=[];if(r&&t.sep&&!t.value){const o=[];for(let a=0;a<t.sep.length;++a){const l=t.sep[a];switch(l.type){case"newline":o.push(a);break;case"space":break;case"comment":l.indent>e.indent&&(o.length=0);break;default:o.length=0}}o.length>=2&&(i=t.sep.splice(o[1]))}switch(this.type){case"anchor":case"tag":r||t.value?(i.push(this.sourceToken),e.items.push({start:i}),this.onKeyLine=!0):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"explicit-key-ind":!t.sep&&!t.explicitKey?(t.start.push(this.sourceToken),t.explicitKey=!0):r||t.value?(i.push(this.sourceToken),e.items.push({start:i,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(t.explicitKey)if(t.sep)if(t.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(We(t.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,key:null,sep:[this.sourceToken]}]});else if(da(t.key)&&!We(t.sep,"newline")){const o=Nt(t.start),a=t.key,l=t.sep;l.push(this.sourceToken),delete t.key,delete t.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:a,sep:l}]})}else i.length>0?t.sep=t.sep.concat(i,this.sourceToken):t.sep.push(this.sourceToken);else if(We(t.start,"newline"))Object.assign(t,{key:null,sep:[this.sourceToken]});else{const o=Nt(t.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:null,sep:[this.sourceToken]}]})}else t.sep?t.value||r?e.items.push({start:i,key:null,sep:[this.sourceToken]}):We(t.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{const o=this.flowScalar(this.type);r||t.value?(e.items.push({start:i,key:o,sep:[]}),this.onKeyLine=!0):t.sep?this.stack.push(o):(Object.assign(t,{key:o,sep:[]}),this.onKeyLine=!0);return}default:{const o=this.startBlockValue(e);if(o){if(o.type==="block-seq"){if(!t.explicitKey&&t.sep&&!We(t.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else n&&e.items.push({start:i});this.stack.push(o);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(e){const t=e.items[e.items.length-1];switch(this.type){case"newline":if(t.value){const n="end"in t.value?t.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type==="comment"?n?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.start.push(this.sourceToken);return;case"space":case"comment":if(t.value)e.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(t.start,e.indent)){const r=e.items[e.items.length-2]?.value?.end;if(Array.isArray(r)){Array.prototype.push.apply(r,t.start),r.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return;case"anchor":case"tag":if(t.value||this.indent<=e.indent)break;t.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==e.indent)break;t.value||We(t.start,"seq-item-ind")?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return}if(this.indent>e.indent){const n=this.startBlockValue(e);if(n){this.stack.push(n);return}}yield*this.pop(),yield*this.step()}*flowCollection(e){const t=e.items[e.items.length-1];if(this.type==="flow-error-end"){let n;do yield*this.pop(),n=this.peek(1);while(n&&n.type==="flow-collection")}else if(e.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!t||t.sep?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return;case"map-value-ind":!t||t.value?e.items.push({start:[],key:null,sep:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!t||t.value?e.items.push({start:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{const r=this.flowScalar(this.type);!t||t.value?e.items.push({start:[],key:r,sep:[]}):t.sep?this.stack.push(r):Object.assign(t,{key:r,sep:[]});return}case"flow-map-end":case"flow-seq-end":e.end.push(this.sourceToken);return}const n=this.startBlockValue(e);n?this.stack.push(n):(yield*this.pop(),yield*this.step())}else{const n=this.peek(2);if(n.type==="block-map"&&(this.type==="map-value-ind"&&n.indent===e.indent||this.type==="newline"&&!n.items[n.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&n.type!=="flow-collection"){const r=us(n),i=Nt(r);fa(e);const o=e.end.splice(1,e.end.length);o.push(this.sourceToken);const a={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:i,key:e,sep:o}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=a}else yield*this.lineEnd(e)}}flowScalar(e){if(this.onNewLine){let t=this.source.indexOf(`
|
|
140
140
|
`)+1;for(;t!==0;)this.onNewLine(this.offset+t),t=this.source.indexOf(`
|
|
141
|
-
`,t)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;const t=us(e),n=Nt(t);return n.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:n,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;const t=us(e),n=Nt(t);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:n,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,t){return this.type!=="comment"||this.indent<=t?!1:e.every(n=>n.type==="newline"||n.type==="space")}*documentEnd(e){this.type!=="doc-mode"&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(e){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;case"space":case"comment":default:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}}function ha(s){const e=s.prettyErrors!==!1;return{lineCounter:s.lineCounter||e&&new la||null,prettyErrors:e}}c(ha,"parseOptions");function Xu(s,e={}){const{lineCounter:t,prettyErrors:n}=ha(e),r=new Pr(t?.addNewLine),i=new Or(e),o=Array.from(i.compose(r.parse(s)));if(n&&t)for(const a of o)a.errors.forEach(ss(s,t)),a.warnings.forEach(ss(s,t));return o.length>0?o:Object.assign([],{empty:!0},i.streamInfo())}c(Xu,"parseAllDocuments");function pa(s,e={}){const{lineCounter:t,prettyErrors:n}=ha(e),r=new Pr(t?.addNewLine),i=new Or(e);let o=null;for(const a of i.compose(r.parse(s),!0,s.length))if(!o)o=a;else if(o.options.logLevel!=="silent"){o.errors.push(new st(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return n&&t&&(o.errors.forEach(ss(s,t)),o.warnings.forEach(ss(s,t))),o}c(pa,"parseDocument");function Qu(s,e,t){let n;typeof e=="function"?n=e:t===void 0&&e&&typeof e=="object"&&(t=e);const r=pa(s,t);if(!r)return null;if(r.warnings.forEach(i=>Eo(r.options.logLevel,i)),r.errors.length>0){if(r.options.logLevel!=="silent")throw r.errors[0];r.errors=[]}return r.toJS(Object.assign({reviver:n},t))}c(Qu,"parse");function Zu(s,e,t){let n=null;if(typeof e=="function"||Array.isArray(e)?n=e:t===void 0&&e&&(t=e),typeof t=="string"&&(t=t.length),typeof t=="number"){const r=Math.round(t);t=r<1?void 0:r>8?{indent:8}:{indent:r}}if(s===void 0){const{keepUndefined:r}=t??e??{};if(!r)return}return Ze(s)&&!n?s.toString(t):new Bt(s,n,t).toString(t)}c(Zu,"stringify");var ed=Object.freeze({__proto__:null,Alias:qn,CST:Gu,Composer:Or,Document:Bt,Lexer:ca,LineCounter:la,Pair:se,Parser:Pr,Scalar:R,Schema:Ls,YAMLError:kr,YAMLMap:ue,YAMLParseError:st,YAMLSeq:Ue,YAMLWarning:Go,isAlias:Be,isCollection:z,isDocument:Ze,isMap:St,isNode:Y,isPair:V,isScalar:H,isSeq:Ct,parse:Qu,parseAllDocuments:Xu,parseDocument:pa,stringify:Zu,visit:et,visitAsync:Fn});const de={Updated:"updated",Deleted:"deleted",Stopped:"stopped"},td={ignored:Tl,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 nd extends nr{static{c(this,"LocalElementWatcher")}constructor(e){super(),this.options=e,this.membraneDir=dt(this.options.cwd),this.lockTimeoutMs=this.options.lockTimeoutMs??1e3}isWatching=!1;watcher;membraneDir;contentCache={};ignoredPaths=new Set;lockTimeoutMs;async start(){this.isWatching||(L.existsSync(this.membraneDir)||L.mkdirSync(this.membraneDir,{recursive:!0}),this.initializeContentCache(),this.watcher=el.watch(this.membraneDir,td),this.watcher.on("add",e=>this.handleFileSystemEvent(de.Updated,e)).on("change",e=>this.handleFileSystemEvent(de.Updated,e)).on("unlink",e=>this.handleFileSystemEvent(de.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(de.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===de.Deleted){this.removeFromCache(n);const a={filePath:t,relativePath:n,data:void 0};b.info(`[local] ${e}: ${a.relativePath}`),this.emit(e,a);return}const r=this.readFileContent(t);if(!this.hasContentChanged(n,r))return;const o=this.processFileEvent(t,r);this.updateCache(n,r),o&&(b.info(`[local] ${e}: ${o.relativePath}`),this.emit(e,o))}readFileContent(e){return L.readFileSync(e,"utf8")}processFileEvent(e,t){const n=K.relative(this.membraneDir,e);let r;try{r=t?ed.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 Qc.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(){L.existsSync(this.membraneDir)&&this.scanDirectoryForCache(this.membraneDir)}scanDirectoryForCache(e){const t=L.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=L.readFileSync(r,"utf8"),o=K.relative(this.membraneDir,r);this.updateCache(o,i)}catch{}}}}var Rr=(s=>(s.Updated="updated",s.ConnectorFileUpdated="connector-file-updated",s.Connected="connected",s.Disconnected="disconnected",s.Error="error",s))(Rr||{});const sd={debounceMs:2e3,reconnectIntervalMs:5e3,maxReconnectAttempts:1/0,maxBackoffMs:6e4,connectionTimeoutMs:3e5};class rd extends nr{static{c(this,"RemoteElementWatcher")}constructor(e=sd){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{b.debug("[remote-events] Connecting to server"),this.eventSource&&(this.eventSource.close(),this.eventSource=void 0);const e=await B.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)}`;b.debug("[remote-events] Subscribing to workspace events"),this.eventSource=new tl(n),this.setupEventSourceHandlers()}catch(e){b.debug(`[remote-events] Failed to connect: ${e}`),this.emit("error",{error:e}),this.scheduleReconnect()}}setupEventSourceHandlers(){this.eventSource&&(this.eventSource.onopen=()=>{b.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){b.debug(`[remote-events] Failed to parse workspace event: ${t}`)}},this.eventSource.onerror=e=>{b.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!==Uc.ElementUpdate)return;const{elementId:t,elementType:n,data:r={}}=e;if(!(!t||!n)){if(n===x.Connector){const{filePath:i,eventType:o,newPath:a}=r;return b.debug(`[remote-watcher] Received connector event - elementId: ${t}, filePath: ${i}, eventType: ${o}`),this.scheduleConnectorFileUpdate(t,i,o,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}),o=this.debounceTimeouts.get(i);o&&clearTimeout(o);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&&(b.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);b.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&&(b.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 ma{static{c(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())}}async function id(s="full"){const e={};b.info("[connectors] Getting remote workspace data");const t=await B.withClient(n=>n.integrations.findAll());e.integration=t?.map(n=>Mr("integration",n))??[];for(const n of Object.keys(ce)){const r=ce[n];if(r.exportable===!1)continue;const i=[];b.info(`[connectors] Reading ${r.elements} from remote workspace`);const o=await B.withClient(a=>a[r.elements].findAll());if(o&&i.push(...o.map(a=>Mr(n,a))),r.integrationSpecific&&t)for(const a of t){const l=await B.withClient(u=>u[r.elements].findAll({integrationId:a.id}));l&&i.push(...l.map(u=>(u.integrationKey=a.key,Mr(n,u))))}i.length>0&&s=="full"&&(console.table(i.map(a=>({key:a.key,integrationKey:a.integrationKey,universal:!a.integrationKey})).reduce((a,l)=>(a||(a={}),a[l.key]||(a[l.key]={}),l.universal&&(a[l.key].universal=!0),l.integrationKey&&(a[l.key].integration?a[l.key].integration+=` ${l.integrationKey}`:a[l.key].integration=l.integrationKey),a),{})),console.groupEnd()),e[n]=i}return b.success("[connectors] Remote workspace data retrieved successfully"),e}c(id,"getWorkspaceData");function Mr(s,e){return e=Kl(e),ce[s].exportCleanup?ce[s].exportCleanup(e):e}c(Mr,"cleanUpForExport");const xt="connectors",Pe="development",Lr={};async function od(){const s=await id("minified"),t=(await B.withClient(l=>l.get("org-workspace-id"))).id,n={};b.info("[connectors] Loading custom connectors");const r=await B.withClient(l=>l.get(`/connectors?workspaceId=${t}`));b.info("[connectors] Loading public connectors"),s.connector=Array.isArray(r)?r:[];const i=Je(),a=(F.existsSync(i)?F.readdirSync(i):[]).filter(l=>{if(l.startsWith("."))return!1;const u=U.join(i,l);try{return F.statSync(u).isDirectory()}catch{return!1}});for(const l of a){b.info(`[connectors] Loading connector from: ${l}`);const u=F.readdirSync(U.join(i,l)),d=await Dr(l);if(!d)continue;if("baseUri"in d&&delete d.baseUri,d.uuid&&s.connector?.find(h=>h.uuid==d.uuid))n[d.id]=s.connector.find(h=>h.uuid==d.uuid).id,b.info(`[connectors] Matched ${d.name} uuid: ${d.uuid}`);else if(!n[d.id]){let h=!1;try{const g=await jr({connectorId:d.id});g&&g.isPublic&&(h=!0)}catch{}if(!h){b.info(`[connectors] Creating custom connector ${d.name} (${d.key})`);const g=await B.withClient(y=>y.post("connectors",{...d,workspaceId:t}));n[d.id]=g.id}}const f=u.filter(h=>F.statSync(U.join(i,l,h)).isDirectory());for(const h of f)await ld({connector:d,version:h,connectorId:n[d.id]})}return n}c(od,"pushConnectors");async function ga({connectorId:s,connectorVersion:e,allConnectors:t,pulledConnectors:n,pulledConnectorVersions:r}){if(!s||r[s]?.has(e))return;const i=xi(),o=await jr({connectorId:s});if(!o.isPublic||t){if(!o?.key){b.error(`[connectors] Connector ${s} has no key. Skipping..`);return}n.has(s)||(await ud({basePath:i,connector:o}),n.add(s)),r[s]||(r[s]=new Set),r[s].has(e)||(await dd({connector:o,connectorVersion:e,basePath:i}),r[s].add(e))}}c(ga,"pullRemoteConnector");function Je(){const s=tr();return U.join(s.membraneDirPath,xt)}c(Je,"getConnectorsPath");async function Dr(s){const e=U.join(Je(),s,`${s}.yml`);return ir(e,!1)}c(Dr,"readConnector");async function ad(s,e){return b.info(`[connectors] Zipping ${s} into ${e}`),new Promise((t,n)=>{const r=F.createWriteStream(e),i=nl("zip",{zlib:{level:9}});r.on("close",()=>{b.success(`[connectors] Successfully created ${e}`),t()}),r.on("end",()=>{b.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 o=F.readdirSync(s);for(const a of o){const l=U.join(s,a),u=F.statSync(l);u.isFile()?i.file(l,{name:a}):u.isDirectory()&&i.directory(l,a)}i.finalize()})}c(ad,"createZipArchive");async function cd(s,e){return b.info(`[connectors] Unzipping into ${e}`),new Promise((t,n)=>{const r=rl.Parse();r.on("entry",i=>{const o=i.path;if(i.type==="Directory"){const l=U.join(e,o);F.mkdirSync(l,{recursive:!0}),i.autodrain()}else{const l=U.join(e,o),u=U.dirname(l);F.mkdirSync(u,{recursive:!0});const d=F.createWriteStream(l);i.pipe(d),d.on("finish",()=>{})}}),r.on("end",()=>{b.success(`[connectors] Successfully extracted to ${e}`),t()}),r.on("error",i=>{n(i)}),r.write(s),r.end()})}c(cd,"extractZipArchive");async function ld({connector:s,version:e,connectorId:t}){const n=U.join(Je(),Re(s),ya(e)),r=U.join(n,"src"),i=U.join(n,"src.zip"),o=F.existsSync(i);if(F.existsSync(r)&&(b.info(`[connectors] Archiving source code for ${s.name} version ${e}`),await ad(r,i)),!F.existsSync(i)){b.warning(`[connectors] No source code found for ${s.name} version ${e}`);return}try{const a=new sl;if(a.append("file",F.createReadStream(i),"file.zip"),b.info(`[connectors] Pushing connector version ${e} for ${s.name}`),e==Pe)b.info(`[connectors] Uploading connector ${t}`),await B.withClient(l=>l.post(`connectors/${t}/upload`,a,{headers:{...a.getHeaders()}}));else{if(a.append("version",e),a.append("changelog","Imported Version"),(await B.withClient(u=>u.get(`/connectors/${t}/versions`))).find(u=>u.version==e)){b.info(`[connectors] Version ${e} already published`);return}b.info(`[connectors] Publishing version ${e} of connector ${t}`),await B.withClient(u=>u.post(`connectors/${t}/publish-version`,a,{headers:{...a.getHeaders()}}))}b.success(`Successfully pushed connector version ${e} for ${s.name}`)}catch(a){b.error(`Error pushing connector version ${e} for ${s.name}: ${a}`)}finally{!o&&F.existsSync(i)&&(b.info(`[connectors] Cleaning up temporary zip file for ${s.name} version ${e}`),F.unlinkSync(i))}}c(ld,"pushConnectorVersion");async function jr({connectorId:s}){if(s){if(Lr[s])return Lr[s];try{const e=await B.withClient(t=>t.get(`connectors/${s}`));return Lr[s]=e,e}catch(e){return b.error(`[connectors] Failed to get connector ${s}: ${e}`),null}}}c(jr,"getConnector");async function ud({basePath:s,connector:e}){const t=Re(e),n=U.join(s,xt,t);F.mkdirSync(n,{recursive:!0});const r=U.join(n,`${Re(e)}.yml`);F.writeFileSync(r,Wt.dump(e)),b.info(`[connectors] Pulled connector ${e.name}`)}c(ud,"pullConnector");async function dd({connector:s,connectorVersion:e,basePath:t}){const n=Re(s),r=ya(e),i=U.join(t,"connectors",n,r),o=await B.withClient(l=>l.get(`connectors/${s.id}/download`,{version:e},{responseType:"arraybuffer",headers:{Accept:"application/zip"},timeout:1e6}));F.mkdirSync(i,{recursive:!0});const a=U.join(i,"src.zip");if(F.writeFileSync(a,o),!e){const l=U.join(i,"src");F.mkdirSync(l,{recursive:!0}),await cd(o,l)}b.info(`[connectors] Pulled connector version: ${s.name} (${r})`)}c(dd,"pullConnectorVersion");function Re(s){return s.key}c(Re,"getConnectorDirName");function ya(s){return s??Pe}c(ya,"getConnectorVersionDirName");function fd(s){const e=xi(),t=Re(s);return U.join(e,xt,t)}c(fd,"getConnectorDirPath");function hd(s){return s.match(`${xt}/[^/]+/${Pe}/src/.*`)!==null}c(hd,"isConnectorSourceFile");async function pd(s){const e=s.match(`${xt}/([^/]+)/${Pe}/src/(.*)`);if(!e)return;const t=e[1],n=e[2],r=await Dr(t);if(!r){b.warning(`[connectors] Connector ${t} not found. Ignoring file change`);return}const i=r.id,o=F.readFileSync(s,"utf-8");await B.withClient(a=>a.put(`connectors/${i}/files/${n}`,o,{headers:{"Content-Type":"text/plain"}})),b.info(`[connectors] Pushed file ${n} for connector ${r.name}`)}c(pd,"putConnectorFile");async function md(s){const e=s.match(`${xt}/([^/]+)/${Pe}/src/(.*)`);if(!e)return;const t=e[1],n=e[2],r=await Dr(t);if(!r){b.warning(`[connectors] Connector ${t} not found. Ignoring file change`);return}const i=r.id;await B.withClient(o=>o.delete(`connectors/${i}/files/${n}`)),b.info(`[connectors] Deleted file ${n} for connector ${r.name}`)}c(md,"deleteConnectorFile");async function gd(s,e){try{const t=await B.withClient(o=>o.get(`connectors/${s}`));if(!t){b.warning(`[connectors] Connector ${s} not found`);return}const n=await B.withClient(o=>o.get(`connectors/${s}/files/${e}`)),r=Re(t),i=U.join(Je(),r,Pe,"src",e);F.mkdirSync(U.dirname(i),{recursive:!0}),n!=null?(F.writeFileSync(i,n),b.info(`[connectors] Pulled file ${e} for connector ${t.name}`)):F.existsSync(i)&&(F.unlinkSync(i),b.info(`[connectors] Deleted file ${e} for connector ${t.name}`))}catch(t){b.error(`[connectors] Failed to pull connector file ${e} for connector ${s}: ${t}`)}}c(gd,"pullConnectorFile");async function yd(s,e){const t=await B.withClient(i=>i.get(`connectors/${s}`));if(!t){b.warning(`[connectors] Connector ${s} not found`);return}const n=Re(t),r=U.join(Je(),n,Pe,"src",e);F.existsSync(r)&&(F.unlinkSync(r),b.info(`[connectors] Deleted file ${e} for connector ${n}`))}c(yd,"deleteLocalConnectorFile");async function wd(s,e,t){if(t&&e!==t)try{const n=await B.withClient(l=>l.get(`connectors/${s}`));if(!n){b.warning(`[connectors] Connector ${s} not found`);return}const r=Re(n),i=U.join(Je(),r,Pe,"src"),o=U.join(i,e),a=U.join(i,t);F.existsSync(o)&&(F.mkdirSync(U.dirname(a),{recursive:!0}),F.renameSync(o,a),b.info(`[connectors] Renamed directory from ${e} to ${t} for connector ${r}`))}catch(n){b.error(`[connectors] Failed to rename directory ${e} to ${t} for connector ${s}: ${n}`)}}c(wd,"renameLocalConnectorDirectory");async function bd(s,e){try{const t=await B.withClient(i=>i.get(`connectors/${s}`));if(!t){b.warning(`[connectors] Connector ${s} not found`);return}const n=Re(t),r=U.join(Je(),n,Pe,"src",e);if(F.existsSync(r)){const i=U.resolve(Je());if(!U.resolve(r).startsWith(i))return;F.rmSync(r,{recursive:!0,force:!0}),b.info(`[connectors] Deleted directory ${e} for connector ${n}`)}}catch(t){b.error(`[connectors] Failed to delete directory ${e} for connector ${s}: ${t}`)}}c(bd,"deleteLocalConnectorDirectory");const wa=[x.DataSource,x.FieldMapping,x.Action,x.Flow,x.Package,x.AppDataSchema,x.AppEventType];class En{static{c(this,"ElementSyncService")}localWatcher=void 0;remoteWatcher=void 0;notifier;changes=[];localCache;remoteCache;localRepo;remoteRepo;pulledConnectors=new Set;pulledConnectorVersions={};constructor(){this.notifier=Oe,this.localCache=new ma,this.remoteCache=new ma,this.localRepo=new Wl(this.localCache),this.remoteRepo=new Jl(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 b.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 b.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 ga({connectorId:r,connectorVersion:i,allConnectors:e,pulledConnectors:this.pulledConnectors,pulledConnectorVersions:this.pulledConnectorVersions})}}async pushConnectors(){const e=await od();this.remoteRepo.setConnectorsMapping(e)}getHandler(e){return e===ae.INCOMING?this.localRepo:(this.remoteRepo.setSourceCache(this.localCache),this.remoteRepo)}getCache(e){return e===ae.INCOMING?this.localCache:this.remoteCache}async startWatching(){this.localWatcher=new nd({cwd:process.cwd(),lockTimeoutMs:1e3}),this.localWatcher.on(de.Updated,e=>this.handleLocalEvent(e,de.Updated)),this.localWatcher.on(de.Deleted,e=>this.handleLocalEvent(e,de.Deleted)),await this.localWatcher.start(),b.success("[local] Tracking changes.."),this.remoteWatcher=new rd,this.remoteWatcher.on(Rr.Updated,({elementId:e,elementType:t})=>this.handleRemoteElementEvent(e,t)),this.remoteWatcher.on(Rr.ConnectorFileUpdated,({connectorId:e,filePath:t,eventType:n,newPath:r})=>this.handleRemoteConnectorFileEvent(e,t,n,r)),await this.remoteWatcher.start(),b.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 o=n||this.remoteCache.getByInternalId(e);return o?(b.info(`[${this.getDirectionLabel(ae.INCOMING)}] Deleted: ${o.id}`),this.localWatcher?.executeWithPathLock(o.absolutePath,()=>this.deleteElement(o,ae.INCOMING))):void 0}if(b.info(`[${this.getDirectionLabel(ae.INCOMING)}] Updated: ${n.id}`),await this.localWatcher?.executeWithPathLock(n.absolutePath,async()=>this.updateElement(n,ae.INCOMING)),t===x.Integration){const o=n.data.connectorId,a=n.data.connectorVersion,l=await jr({connectorId:o});if(!l?.key)return;const u=fd(l);await this.localWatcher?.executeWithPathLock(u,async()=>ga({connectorId:o,connectorVersion:a,allConnectors:!1,pulledConnectors:this.pulledConnectors,pulledConnectorVersions:this.pulledConnectorVersions}))}}catch(n){b.error(`[sync] Error handling remote event: ${n}`)}}async handleRemoteConnectorFileEvent(e,t,n,r){try{switch(n){case Js.ConnectorFileDeleted:await yd(e,t);break;case Js.ConnectorDirectoryRenamed:await wd(e,t,r);break;case Js.ConnectorDirectoryDeleted:await bd(e,t);break;default:await gd(e,t);break}}catch(i){b.error(`[sync] Error handling remote connector file event: ${i}`)}}async handleLocalEvent(e,t){try{if(hd(e.filePath))switch(t){case de.Updated:await pd(e.filePath);break;case de.Deleted:await md(e.filePath);break}else{let n=X.fromPathAndData(e.filePath,e.data);if(!n){const r=X.idFromPath(e.filePath);if(!r||(n=this.remoteCache.get(r),!n))return}switch(b.info(`[${this.getDirectionLabel(ae.OUTGOING)}] ${ql.toSentenceCase(t)}: ${n.id}`),t){case de.Updated:await this.updateElement(n,ae.OUTGOING);break;case de.Deleted:await this.deleteElement(n,ae.OUTGOING);break}}}catch(n){b.error(`[sync] Error handling local event: ${n}`)}}detectIncomingChanges(){this.clearChanges();const e=En.getChanges(ae.INCOMING,this.remoteCache,this.localCache);return this.updateChanges(e),e}detectOutgoingChanges(){this.clearChanges();const e=En.getChanges(ae.OUTGOING,this.localCache,this.remoteCache);return this.updateChanges(e),e}async resolveChanges(){if(!this.needsSync())return;b.info("[resolver] Resolving changes.."),b.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===ae.INCOMING?this.detectIncomingChanges():this.detectOutgoingChanges(),this.changes=this.changes.filter(r=>r.element.type!==x.Integration)),b.info("[resolver] Resolving universal elements");const t=this.changes.filter(r=>!r.element.hasParent());for(const r of wa){const i=t.filter(o=>o.element.type===r);b.info(`[resolver] Resolving ${r} elements`),await Promise.all(i.map(async o=>this.resolveChange(o)))}b.info("[resolver] Resolving integration level elements");const n=this.changes.filter(r=>r.element.hasParent());for(const r of wa){const i=n.filter(o=>o.element.type===r);b.info(`[resolver] Resolving ${r} elements`),await Promise.all(i.map(async o=>this.resolveChange(o)))}b.success("[resolver] Resolved changes")}async resolveChange(e){switch(e.type){case $e.DELETE:return this.deleteElement(e.element,e.direction);case $e.CREATE:return this.updateElement(e.element,e.direction);case $e.UPDATE:return this.updateElement(e.element,e.direction)}}static getChanges(e,t,n){const r=t.getAllIds(),i=n.getAllIds(),o=new Set([...r,...i]),a=[];for(const l of o){const u=t.get(l),d=n.get(l),f=En.detectChangeForElement(u,d,e);f&&a.push(f)}return a}updateChanges(e){if(this.changes=e,this.needsForcedSync()){const t=e.filter(n=>n.isConflict);b.warning("[resolver] Conflicts detected"),this.notifier.setConflicts(t)}}clearChanges(){this.changes=[]}getDirectionLabel(e){switch(e){case ae.INCOMING:return"local\u2190remote";case ae.OUTGOING:return"local\u2192remote"}}static detectChangeForElement(e,t,n){return e&&!t?{type:$e.CREATE,element:e,direction:n,isConflict:!1}:!e&&t?{type:$e.DELETE,element:t,direction:n,isConflict:!0}:e&&t&&!e.isEqual(t)?{type:$e.UPDATE,element:e,direction:n,isConflict:!1}:null}}const He=K.join(il.tmpdir(),"membrane-mcp-status"),ba=3e4;class Sd{static{c(this,"McpStatusService")}constructor(e=2e3){this.pollIntervalMs=e}isRunning=!1;pollInterval;async start(){this.isRunning||(this.isRunning=!0,this.pollInterval=setInterval(async()=>await this.checkStatus(),this.pollIntervalMs),await this.checkStatus())}async stop(){this.pollInterval&&(clearInterval(this.pollInterval),this.pollInterval=void 0,this.isRunning=!1)}async checkStatus(){try{const e=process.cwd(),t=ds(void 0,e),n=Sa(e);t&&Oe.setMcpStatus(t),await Oe.setMcpServers(n)}catch{b.error("Failed to check MCP status")}}}function ds(s,e){try{const t=e||process.cwd();if(!s){const r=Sa(t);return r.length===0?null:r[0]}const n=Kr(s,t);if(L.existsSync(n)){const r=L.statSync(n),i=new Date;if(i.getTime()-r.mtime.getTime()>ba)return tn(s,t),null;const a=L.readFileSync(n,"utf8"),l=JSON.parse(a);if(l.isRunning){const u=new Date(l.lastActivity).getTime();if(i.getTime()-u>ba)return tn(s,t),null}return l}}catch{s&&e&&tn(s,e)}return null}c(ds,"getMcpStatus");function Sa(s){try{const e=s||process.cwd(),t=qr(e);if(!L.existsSync(He))return[];const n=L.readdirSync(He),r=[];for(const i of n){const o=i.match(new RegExp(`^mcp-${t}-(\\d+)\\.json$`));if(o){const a=parseInt(o[1],10),l=ds(a,e);l&&r.push(l)}}return r.sort((i,o)=>new Date(o.startTime).getTime()-new Date(i.startTime).getTime())}catch{return[]}}c(Sa,"getAllMcpStatusFiles");function Fr(s){try{const t={...ds(s.processId,s.cwd)||{isRunning:!1,startTime:new Date().toISOString(),lastActivity:new Date().toISOString(),toolsCount:0,totalRequests:0,processId:s.processId,cwd:s.cwd,agentName:process.env.AGENT_NAME||"Unnamed Agent"},...s};L.existsSync(He)||L.mkdirSync(He,{recursive:!0});const n=Kr(s.processId,s.cwd);L.writeFileSync(n,JSON.stringify(t,null,2))}catch{}}c(Fr,"updateMcpStatus");function tn(s,e){try{const t=e||process.cwd();if(s){const n=Kr(s,t);L.existsSync(n)&&L.unlinkSync(n)}else{const n=qr(t);if(L.existsSync(He)){const r=L.readdirSync(He);for(const i of r)i.match(new RegExp(`^mcp-${n}-\\d+\\.json$`))&&L.unlinkSync(K.join(He,i))}}}catch{}}c(tn,"clearMcpStatus");function Cd(s,e){const t=ds(s,e);t&&Fr({processId:s,cwd:e,totalRequests:t.totalRequests+1,lastRequestTime:new Date().toISOString(),lastActivity:new Date().toISOString()})}c(Cd,"trackToolExecution");function qr(s){return Zc("md5").update(s).digest("hex").slice(0,8)}c(qr,"getCwdHash");function Kr(s,e){const t=qr(e);return K.join(He,`mcp-${t}-${s}.json`)}c(Kr,"getStatusFilePath");const nn={Agent:"agent",Cli:"cli"},P={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 Ca{static{c(this,"MembraneCLIService")}constructor(e,t,n=()=>process.exit(0)){this.mode=e,this.cwd=t,this.onShutdown=n,this.notifier=Oe,this.mcpStatusService=new Sd,this.syncService=new En,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{if(b.setVerboseMode(!!e.verbose),e.rps!==void 0&&B.init({maxRequestsPerSecond:e.rps}),await this.notifier.setState(P.PULLING),await this.syncService.fetchElements(),this.syncService.detectIncomingChanges(),this.syncService.needsForcedSync()&&!e.force){await this.notifier.setState(P.CONFLICTS),e.watch||(t=!0);return}await this.syncService.pullConnectors(e.allConnectors),await this.syncWorkspaces(e)}catch(n){t=!0,b.error(`Failed to pull workspace: ${n}`),await this.notifier.setState(P.ERROR),b.saveLogsToFile("error")}finally{if(e.saveLogs&&b.saveLogsToFile(),t)process.exit(1);else return e?.onComplete?.()}}async pushWorkspace(e={}){let t=!1;try{if(b.setVerboseMode(!!e.verbose),e.rps!==void 0&&B.init({maxRequestsPerSecond:e.rps}),await this.notifier.setState(P.PUSHING),await this.syncService.fetchElements(),this.syncService.detectOutgoingChanges(),this.syncService.needsForcedSync()&&!e.force){await this.notifier.setState(P.CONFLICTS),e.watch||(t=!0);return}await this.syncService.pushConnectors(),await this.syncWorkspaces(e)}catch(n){t=!0,b.error(`Failed to push workspace: ${n}`),await this.notifier.setState(P.ERROR),b.saveLogsToFile("error")}finally{if(e.saveLogs&&b.saveLogsToFile(),t)process.exit(1);else return e?.onComplete?.()}}async syncWorkspaces(e={}){try{e.verbose!==void 0&&b.setVerboseMode(!!e.verbose),await this.notifier.setState(P.RESOLVING),this.syncService.needsSync()&&await this.syncService.resolveChanges();const t=await this.syncService.getStats();this.notifier.setStats(t),await this.notifier.setState(P.SYNCED),e.watch&&(await this.notifier.setState(P.WATCHING),await this.syncService.startWatching())}catch(t){b.error(`Failed to sync local and remote workspaces: ${t}`),await this.notifier.setState(P.ERROR),b.saveLogsToFile("error")}}async init({force:e=!1}={}){if(!(this.initialized&&!e)){await this.notifier.setState(P.NOT_INITIALIZED);try{await this.loadConfig(),Qe.isCacheDefined()?(await this.initServices(),this.initialized=!0,await this.notifier.setState(P.INITIALIZED)):(this.initialized=!1,await this.notifier.setState(P.SETTING_UP))}catch(t){b.error(`Failed to initialize services: ${t}`),await this.notifier.setState(P.ERROR),b.saveLogsToFile("error"),this.onShutdown()}}}async loadConfig(){this.currentConfig=Qe.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=Qe.updateConfig(t);this.currentConfig=r,await this.init({force:!0})}async shutdown(){!this.initialized||this.isShuttingDown||(this.isShuttingDown=!0,this.mode===nn.Agent&&(await this.notifier.cleanup(),await this.mcpStatusService.stop()),this.initialized=!1,this.onShutdown())}async initServices(){this.mode===nn.Agent&&(await this.notifier.connectToRemote(),await this.mcpStatusService.start()),this.syncService.clear()}async stopServices(){this.mode===nn.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()})}}const va=Bs(null);function vd({children:s,membraneCLIService:e}){const{data:t}=Ei("/account"),[n,r]=J(P.NOT_INITIALIZED),[i,o]=J([]),[a,l]=J({}),[u,d]=J([]),[f,h]=J(null),y=t?.workspaces?.find(p=>p.workspaceKey===f?.workspaceKey)||null;return Fe(()=>{const p=c(({state:I})=>r(I),"handleStateChanged"),w=c(({stats:I})=>l(I),"handleStatsChanged"),T=c(({log:I})=>d($=>[...$,I]),"handleLogAdded"),E=c(({conflicts:I})=>o(I),"handleConflictsUpdated"),O=c(({config:I})=>h(I),"handleConfigChanged");return e.notifier.on(Q.StateChanged,p),e.notifier.on(Q.StatsChanged,w),e.notifier.on(Q.LogAdded,T),e.notifier.on(Q.ConflictsChanged,E),e.notifier.on(Q.ConfigChanged,O),e.init(),()=>{e.notifier.off(Q.StateChanged,p),e.notifier.off(Q.StatsChanged,w),e.notifier.off(Q.LogAdded,T),e.notifier.off(Q.ConflictsChanged,E),e.notifier.off(Q.ConfigChanged,O)}},[]),m(va.Provider,{value:{state:n,stats:a,logs:u,currentWorkspace:y,conflicts:i,config:f,updateConfig:c(p=>e.updateConfig(p),"updateConfig"),resolveConflicts:c(p=>e.syncWorkspaces(p),"resolveConflicts"),pull:c(p=>e.pullWorkspace(p),"pull"),push:c(p=>e.pushWorkspace(p),"push"),exit:c(()=>e.shutdown(),"exit"),fetchElements:c(()=>e.fetchElements(),"fetchElements"),getSyncedElementsByType:c(p=>e.getSyncedElementsByType(p),"getSyncedElementsByType")},children:s})}c(vd,"MembraneCLIServiceProvider");function fe(){const s=Us(va);if(!s)throw new Error("useMembraneCLIService must be used within MembraneCLIServiceProvider");return s}c(fe,"useMembraneCLIService");const ka=Bs(process.cwd());function kd({cwd:s,children:e}){return m(ka.Provider,{value:s,children:e})}c(kd,"CwdProvider");function Td(){return Us(ka)}c(Td,"useCwd");function sn({cwd:s,children:e,membraneCLIService:t}){const n=s||process.cwd();return m(kd,{cwd:n,children:m(Dc,{value:{fetcher:Cl()},children:m(vd,{membraneCLIService:t,children:e})})})}c(sn,"Layout");const Br=[{id:"claude-code",name:"Claude Code",description:"Anthropic Claude Code agent",actionDescription:"Adding membrane MCP to .mcp.json in the current directory",addConfig:c(()=>{const s=K.join(process.cwd(),".mcp.json"),e={mcpServers:{membrane:{command:"membrane",args:["mcp"],env:{AGENT_NAME:"Claude Code"}}}};let t={};if(L.existsSync(s))try{t=JSON.parse(L.readFileSync(s,"utf8"))}catch{t={}}const n={...t,mcpServers:{...t.mcpServers,...e.mcpServers}};return L.writeFileSync(s,JSON.stringify(n,null,2)),`MCP server configuration added to ${s}`},"addConfig")},{id:"cursor",name:"Cursor",description:"Cursor AI editor",actionDescription:"Adding membrane MCP to .cursor/mcp.json in the current directory",addConfig:c(()=>{const s=K.join(process.cwd(),".cursor"),e=K.join(s,"mcp.json");L.existsSync(s)||L.mkdirSync(s);const t={mcpServers:{membrane:{command:"membrane",args:["mcp"],env:{AGENT_NAME:"Cursor"}}}};let n={};if(L.existsSync(e))try{n=JSON.parse(L.readFileSync(e,"utf8"))}catch{n={}}const r={...n,mcpServers:{...n.mcpServers,...t.mcpServers}};return L.writeFileSync(e,JSON.stringify(r,null,2)),`MCP server configuration added to ${e}`},"addConfig")}];function Ed({onExit:s,onComplete:e}){const[t,n]=J(0),[r,i]=J(!1),[o,a]=J(null),[l,u]=J(""),[d,f]=J("");Xe((y,p)=>{if(l||d){(p.escape||y==="q"||p.return)&&e();return}if(r)p.return||y===" "?h(o):p.escape&&(i(!1),a(null));else if(p.escape)s();else if(p.upArrow||y==="k")n(Math.max(0,t-1));else if(p.downArrow||y==="j")n(Math.min(Br.length-1,t+1));else if(p.return||y===" "){const w=Br[t];a(w),i(!0)}});const h=c(y=>{try{const p=y.addConfig();u(p)}catch(p){f(`Failed to write configuration: ${p.message||p}`)}},"addMcpConfiguration"),g=Math.min(80,process.stdout.columns||80);return l?_(S,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:g,children:[m(S,{marginTop:-1,marginBottom:1,children:_(v,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",m(v,{color:"green",children:"Success"})]})}),_(S,{flexDirection:"column",paddingLeft:2,children:[m(v,{color:"green",children:l}),m(S,{marginTop:1,children:m(v,{color:"grey",children:"The agent will now be able to use Membrane's integration capabilities."})})]}),m(S,{marginTop:1,paddingLeft:2,children:m(v,{color:"white",children:"[esc/q/enter: exit]"})})]}):d?_(S,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:g,children:[m(S,{marginTop:-1,marginBottom:1,children:_(v,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",m(v,{color:"red",children:"Error"})]})}),m(S,{flexDirection:"column",paddingLeft:2,children:m(v,{color:"red",children:d})}),m(S,{marginTop:1,children:m(v,{color:"grey",children:"[esc/q/enter: exit]"})})]}):r&&o?_(S,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:g,children:[m(S,{marginTop:-1,marginBottom:1,children:_(v,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",m(v,{color:"cyan",children:"Confirmation"})]})}),_(S,{flexDirection:"column",paddingLeft:2,children:[_(v,{children:["Connect ",m(v,{bold:!0,children:o.name})," to Membrane via MCP?"]}),m(S,{marginTop:1,children:m(v,{color:"grey",children:"This will add an MCP server configuration that allows the agent to use Membrane's integration capabilities."})}),m(S,{marginTop:1,children:m(v,{color:"yellow",bold:!0,children:o.actionDescription})}),m(S,{marginTop:2,marginBottom:1,children:_(v,{children:[m(v,{color:"white",bold:!0,children:"[Enter] Confirm"})," ",m(v,{color:"gray",children:"[Esc] Cancel"})]})})]})]}):_(S,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:g,children:[m(S,{marginTop:-1,marginBottom:1,children:_(v,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",m(v,{color:"cyan",children:"Select Agent"})]})}),_(S,{flexDirection:"column",paddingLeft:2,children:[m(v,{color:"grey",children:"Choose an agent to connect to Membrane via MCP:"}),m(S,{marginTop:1,children:m(v,{color:"grey",children:"This will add an MCP server configuration that allows the agent to use Membrane's integration capabilities."})}),m(S,{marginTop:1,flexDirection:"column",children:Br.map((y,p)=>_(S,{children:[_(v,{color:t===p?"cyan":"white",children:[t===p?"\u25B6 ":" ",y.name]}),_(v,{color:"grey",children:[" \u2014 ",y.description]})]},y.id))})]}),m(S,{marginTop:1,children:m(v,{color:"grey",children:"[\u2191\u2193: select] [enter: choose] [esc: exit]"})})]})}c(Ed,"AddMcpServerScreen");function _d(){const[s,e]=J(null),[t,n]=J([]),[r,i]=J(null);return Fe(()=>{const o=c(({status:l})=>{e(l),i(null)},"handleMcpStatusChanged"),a=c(({servers:l})=>{n(l),i(null)},"handleMcpServersChanged");return Oe.on(Q.McpStatusChanged,o),Oe.on(Q.McpServersChanged,a),()=>{Oe.off(Q.McpStatusChanged,o),Oe.off(Q.McpServersChanged,a)}},[]),{mcpStatus:s,allMcpServers:t,error:r,isRunning:s?.isRunning||!1,toolsCount:s?.toolsCount||0,totalRequests:s?.totalRequests||0,lastActivity:s?.lastActivity,processId:s?.processId,serverCount:t.length}}c(_d,"useMcpStatus");function Id(){const{error:s,serverCount:e,allMcpServers:t}=_d(),n=Math.min(100,process.stdout.columns||100);return _(S,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:n,children:[m(S,{marginTop:-1,marginBottom:0,flexDirection:"column",children:_(v,{bold:!0,children:["\u{1F916} Connected AI Agents:"," ",s?m(v,{color:"red",children:"error reading status"}):e===0?m(v,{color:"yellow",children:"none"}):m(v,{color:"green",children:e})]})}),!s&&e===0&&m(S,{marginTop:1,children:_(v,{color:"grey",children:["Connect your AI agents to Membrane.",m(Mc,{}),"It will give them tools and context to build integrations."]})}),t.length>0&&m(S,{flexDirection:"column",paddingLeft:2,marginTop:1,children:t.map((r,i)=>m(S,{children:_(v,{color:"grey",children:["#",i+1," ",r.agentName,": ",r.totalRequests," calls"]})},r.processId))}),m(S,{marginTop:1,children:m(v,{color:"grey",children:"[a: connect an agent]"})})]})}c(Id,"Agent");const fs=c(s=>{switch(s){case"error":return"red";case"success":return"green";case"warning":return"yellow";default:return}},"getLogColor");function Ta(s,e){return e<3?s.slice(0,Math.max(0,e)):s.length<=e?s:`${s.slice(0,e-3)}...`}c(Ta,"truncateText");function Ur({children:s}){const{state:e,logs:t}=fe();return!e||e===P.NOT_INITIALIZED?_(S,{gap:1,flexDirection:"row",children:[m(al,{type:"dots"}),m(v,{children:"Initializing..."})]}):e===P.SETTING_UP?m(S,{gap:1,flexDirection:"row",children:m(v,{children:"No workspace selected. Please run `membrane init` to select a workspace."})}):e===P.ERROR?m(S,{flexDirection:"column",children:t.slice().map((n,r)=>m(v,{color:fs(n.type),children:n.message},n.timestamp+r))}):s}c(Ur,"EnsureInitialized");function Ea({onExit:s,showEscOption:e=!0}){const[t,n]=J(""),{data:r,error:i,isLoading:o}=Ei("/account"),{updateConfig:a}=fe(),l=r?.workspaces,u=o;if(Xe((p,w)=>{w.escape&&s?.()}),u)return _(S,{children:[m(An,{}),m(v,{children:" Fetching workspaces..."})]});if(i)return _(S,{flexDirection:"column",children:[_(v,{color:"red",children:["Error: ",i.message]}),m(S,{marginTop:1,children:m(v,{color:"grey",children:"Press ESC to go back"})})]});const d=l?.filter(p=>p.name.toLowerCase().includes(t.toLowerCase()))??[],f=d.map(p=>({label:p.name,value:p.id})),h=f.length,g=l?.length??0;async function y(p){const w=d.find(O=>O.id===p);if(!w)return;const{key:T,secret:E}=w;!T||!E||(await a({workspaceKey:T,workspaceSecret:E}),s?.())}return c(y,"handleSelect"),_(S,{flexDirection:"column",borderStyle:"round",borderTop:!0,width:70,paddingX:1,children:[m(S,{marginTop:-1,children:m(v,{bold:!0,children:"\u{1F4C1} Select your workspace"})}),_(S,{marginTop:1,children:[m(v,{children:"Search: "}),m(cl,{placeholder:"Enter a search query...",onChange:n})]}),g>5&&_(v,{children:["Showing ",h," of ",g," workspaces."]}),m(S,{marginTop:1,children:m(ll,{options:f,onChange:c(p=>{p&&y(p)},"onChange")})}),e&&m(S,{marginTop:1,children:m(v,{color:"grey",children:"Press ESC to go back"})})]})}c(Ea,"SelectWorkspace");function Ad({currentPat:s,onSubmit:e}){const[t,n]=J(""),[r,i]=J(!1),[o,a]=J(null);return _(S,{flexDirection:"column",borderStyle:"round",borderTop:!0,width:70,paddingX:1,children:[m(S,{marginTop:-1,marginBottom:1,children:m(v,{bold:!0,children:"\u{1F511} Enter your Personal Access Token"})}),m(v,{children:"Please provide your Personal Access Token. You can find it here:"}),m(S,{marginTop:1,marginBottom:1,children:m(v,{color:"yellow",children:"https://console.integration.app/w/0/manage-account/api-token"})}),s&&m(v,{dimColor:!0,children:"Press Enter to keep your current token or type a new one."}),m(Ni,{mask:"*",placeholder:`${s?"******":"Enter your token here..."}`,value:t,onChange:n,onSubmit:c(async u=>{a(null),i(!0);try{await e(u),n("")}catch{a("Invalid token. Please try again.")}finally{i(!1)}},"handleSubmit")}),r&&m(S,{marginTop:1,children:_(v,{children:[m(An,{type:"dots"})," Validating token..."]})}),o&&m(v,{color:"red",children:o})]})}c(Ad,"PersonalAccessTokenInput");var rn=(s=>(s[s.Authenticate=0]="Authenticate",s[s.ConnectWorkspace=1]="ConnectWorkspace",s))(rn||{});const Od={0:"Authenticate in Membrane",1:"Connect a Membrane Workspace"},Wr=[rn.Authenticate,rn.ConnectWorkspace];function _a({onComplete:s}){const{config:e}=fe(),[t,n]=J(!1),[r,i]=J(0),o=!!(e?.workspaceKey&&e?.workspaceSecret),a=Ri(),l=Wr[r],u=r+1,d=Wr.length,f=Wr.map((y,p)=>{let w="pending";return p<r?w="done":p===r&&(w="current"),{id:y,label:Od[y],status:w}});async function h(y){const p=a&&y===""?a:y,w=new Mi;try{await w.request("/account",{headers:{Authorization:`Bearer ${p}`}}),Sl(p),i(T=>T+1)}catch(T){console.error(T)}}c(h,"handlePatSubmit");function g(){n(!0),s&&s()}return c(g,"handleWorkspaceSelected"),Xe((y,p)=>{o&&p.escape&&s&&s()}),t?m(S,{children:m(v,{children:"\u2705 Setup complete. You are ready to go!"})}):_(S,{flexDirection:"column",alignSelf:"flex-start",gap:1,children:[_(S,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:70,children:[m(S,{marginTop:-1,marginBottom:1,children:_(v,{bold:!0,children:["\u{1F6E0}\uFE0F Setup \u2014"," ",_(v,{color:"cyan",children:["Step ",u," of ",d]}),o&&m(v,{color:"grey",children:" [esc: go back]"})]})}),m(S,{flexDirection:"column",paddingLeft:2,children:f.map(y=>m($d,{status:y.status,label:y.label},y.id))})]}),l===rn.Authenticate&&m(Ad,{currentPat:a,onSubmit:h}),l===rn.ConnectWorkspace&&m(Ea,{onExit:g,showEscOption:!1})]})}c(_a,"Setup");function $d({status:s,label:e}){return _(S,{children:[_(S,{width:2,children:[s==="current"&&m(An,{type:"dots"}),s==="done"&&m(v,{children:"\u2705"})]}),m(v,{dimColor:s!=="current",children:e})]})}c($d,"StepDisplay");function Jr(){const{stats:s}=fe(),e=Object.entries(s).filter(([t,n])=>n>0);return e.length===0?null:_(S,{flexDirection:"column",children:[m(S,{children:m(S,{width:12,children:m(v,{color:"grey",children:"Elements:"})})}),m(S,{flexDirection:"column",marginLeft:1,children:e.map(([t,n])=>_(S,{children:[m(S,{width:20,children:_(v,{children:[t,":"]})}),m(v,{color:"green",children:n})]},t))})]})}c(Jr,"ElementStats");const Hr=5,Nd=6;function xd(){const{logs:s}=fe(),[e,t]=J(0),n=Math.min(100,process.stdout.columns||100),r=Hr,i=Math.max(0,s.length-r-e),o=s.length-e,a=s.slice(i,o),l=n-Nd,u=e<s.length-r,d=e>0;return Xe((f,h)=>{if(s.length!==0)if(h.upArrow){const g=Math.max(0,s.length-r);t(y=>Math.min(g,y+1))}else h.downArrow?t(g=>Math.max(0,g-1)):(f==="G"||f==="g")&&t(0)}),_(S,{flexDirection:"column",paddingTop:1,children:[_(v,{color:"grey",children:["Recent Activity (",i+1,"-",o," of ",s.length,"):",s.length>Hr&&m(v,{color:"grey",children:" [arrows: scroll] [g: end]"})]}),a.map((f,h)=>m(S,{marginLeft:1,children:m(v,{color:fs(f.type),children:Ta(f.message,l)})},f.timestamp+h)),s.length>Hr&&_(S,{marginLeft:1,flexDirection:"row",children:[u&&m(v,{color:"grey",children:"\u2191 "}),d&&m(v,{color:"grey",children:"\u2193 "})]})]})}c(xd,"Logs");const hs=[{value:"sync",label:"Continue (overwrite/delete)",key:""},{value:"exit",label:"Cancel",key:""}];function Pd(){const{state:s,resolveConflicts:e,exit:t}=fe(),[n,r]=J(0),[i,o]=J(!1),[a,l]=J(!1);return Xe((u,d)=>{if(!i){if(d.ctrl&&u.toLowerCase()==="r"){l(!a);return}d.upArrow?r(f=>f>0?f-1:hs.length-1):d.downArrow?r(f=>f<hs.length-1?f+1:0):u.toLowerCase()==="y"?r(0):u.toLowerCase()==="n"?r(1):(d.return||u===" ")&&(o(!0),hs[n].value==="sync"?e({watch:!0}):t())}}),Fe(()=>{s!==P.CONFLICTS&&i&&o(!1)},[s,i]),_(S,{flexDirection:"column",paddingTop:1,children:[m(S,{children:m(S,{flexDirection:"row",gap:2,children:m(v,{bold:!0,color:"white",children:"Conflicts with remote"})})}),m(S,{children:m(v,{color:"grey",children:"The remote workspace has changes that aren't in your local workspace:"})}),m(S,{marginTop:1,marginLeft:2,children:m(Vr,{isExpanded:a})}),_(S,{marginTop:2,flexDirection:"row",gap:1,children:[m(v,{color:"white",bold:!0,children:"What would you like to do?"}),m(v,{color:"grey",children:"[up/down, enter]"})]}),m(S,{children:i?_(S,{flexDirection:"row",gap:1,children:[m(An,{type:"dots"}),m(v,{color:"blue",bold:!0,children:"Syncing with remote..."})]}):m(S,{flexDirection:"column",children:hs.map((u,d)=>m(S,{flexDirection:"column",children:_(S,{flexDirection:"row",gap:1,children:[m(v,{color:n===d?"cyan":"grey",children:n===d?"\u25B6":" "}),m(v,{color:n===d?"cyan":"grey",bold:n===d,children:u.label})]})},u.value))})})]})}c(Pd,"ResolveChangesUI");const Rd={[$e.UPDATE]:{incoming:{label:"Elements updated in remote",description:"(to be overwritten from remote)"},outgoing:{label:"Elements updated locally",description:"(to be pushed to remote)"}},[$e.DELETE]:{incoming:{label:"Elements not existing in remote",description:"(to be deleted locally)"},outgoing:{label:"Elements deleted locally",description:"(to be deleted from remote)"}},[$e.CREATE]:{incoming:{label:"Elements created in remote",description:"(to be created locally)"},outgoing:{label:"Elements created locally",description:"(to be created in remote)"}}};function Vr({isExpanded:s,showControls:e=!0}){const{conflicts:t}=fe(),n=5,r=jc(()=>{const i={};return t.forEach(o=>{const a=`${o.type}-${o.direction}`;i[a]||(i[a]=[]),i[a].push(o)}),i},[t]);return m(S,{flexDirection:"column",children:Object.entries(r).map(([i,o])=>{if(o.length===0)return null;const[a,l]=i.split("-"),u=Rd[a][l];return _(S,{flexDirection:"column",children:[_(S,{flexDirection:"row",gap:1,children:[_(v,{color:"yellow",children:[u.label," (",o.length,")"]}),m(v,{color:"white",children:u.description})]}),(s?o:o.slice(0,n)).map(d=>m(S,{marginLeft:2,children:_(v,{color:"grey",children:["\u2022 ",d.element.id," (",d.element.relativePath,")"]})},d.element.id)),!s&&o.length>n&&m(S,{marginLeft:2,children:_(v,{color:"cyan",children:["... and ",o.length-n," more",e?" (press Ctrl+R to show all)":""]})}),s&&o.length>n&&e&&m(S,{marginLeft:2,children:m(v,{color:"cyan",children:"(press Ctrl+R to collapse)"})})]},i)})})}c(Vr,"Conflicts");function Md(){const{config:s,state:e,logs:t,currentWorkspace:n,pull:r}=fe(),i=n?.name,o=i?Ta(i,30):s?.workspaceKey,a=Math.min(100,process.stdout.columns||100);return Fe(()=>{r({watch:!0})},[]),_(S,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:a,children:[m(S,{marginTop:-1,marginBottom:1,children:_(S,{flexDirection:"row",gap:1,children:[m(v,{bold:!0,children:"\u{1F504} Workspace"}),_(v,{color:Dd(e),children:[" [",Ld(e),"] "]})]})}),_(S,{children:[m(S,{width:12,children:m(v,{color:"grey",children:"Local:"})}),m(v,{color:"grey",children:process.cwd()})]}),_(S,{children:[m(S,{width:12,children:m(v,{color:"grey",children:"Remote:"})}),s?.workspaceKey?_(v,{color:"grey",children:[o," [o: open in console] [w: change]"]}):_(v,{children:[m(v,{color:"yellow",children:"not selected"})," [w: select]"]})]}),e===P.CONFLICTS?m(Pd,{}):_(ut,{children:[m(S,{paddingTop:1,children:m(Jr,{})}),t.length>0&&m(xd,{})]})]})}c(Md,"Workspace");function Ld(s){switch(s){case P.PULLING:return"pulling";case P.PUSHING:return"pushing";case P.CONFLICTS:return"conflicts";case P.SYNCED:return"synced";case P.ERROR:return"error";case P.WATCHING:return"tracking changes";case P.RESOLVING:return"resolving";case P.NOT_SYNCED:return"not synced";case P.INITIALIZED:return"initialized";case P.SETTING_UP:return"setup required";default:return"unknown"}}c(Ld,"getStatusDisplay");function Dd(s){switch(s){case P.PULLING:return"yellow";case P.PUSHING:return"yellow";case P.CONFLICTS:return"red";case P.SYNCED:return"green";case P.ERROR:return"red";case P.WATCHING:return"green";case P.RESOLVING:return"yellow";case P.NOT_SYNCED:return"grey";case P.SETTING_UP:return"yellow";default:return"grey"}}c(Dd,"getStatusColor");const jd="https://console.integration.app/w";function Fd(){const s=Td(),e=Ws(!0),{exit:t,state:n}=fe(),[r,i]=J(null),o=r??(n===P.SETTING_UP?"setup":"main");Xe(l=>{o==="main"&&(l==="w"&&i("workspace-selection"),l==="a"&&i("add-mcp-server"),l==="o"&&n===P.INITIALIZED&&a(),l==="s"&&i("setup"))});async function a(){try{const l=await Fi(s),u=`${jd}/${l}`,d=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";ol(`${d} "${u}"`)}catch(l){console.error("Failed to open workspace:",l),t()}}return c(a,"handleOpenWorkspace"),Fe(()=>(e.current=!0,()=>{e.current=!1}),[]),o==="workspace-selection"?m(Ea,{onExit:c(()=>i(null),"onExit")}):o==="add-mcp-server"?m(Ed,{onExit:c(()=>i(null),"onExit"),onComplete:c(()=>i(null),"onComplete")}):o==="setup"?m(_a,{onComplete:c(()=>i(null),"onComplete")},Date.now()):m(Ur,{children:_(S,{flexDirection:"column",children:[m(S,{flexGrow:1,children:m(Id,{})}),m(Md,{}),m(S,{paddingLeft:2,children:m(v,{color:"grey",children:"[s: (re-)setup]"})})]})})}c(Fd,"Main");const qd=c(()=>[k.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"),k.yellow("\u2502 \u26A0\uFE0F EXPERIMENTAL FEATURE WARNING \u2502"),k.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"),k.yellow("\u2502 Real-time agent mode is experimental and subject to changes. \u2502"),k.yellow("\u2502 Use in production environments is not recommended. \u2502"),k.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(`
|
|
141
|
+
`,t)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;const t=us(e),n=Nt(t);return n.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:n,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;const t=us(e),n=Nt(t);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:n,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,t){return this.type!=="comment"||this.indent<=t?!1:e.every(n=>n.type==="newline"||n.type==="space")}*documentEnd(e){this.type!=="doc-mode"&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(e){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;case"space":case"comment":default:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}}function ha(s){const e=s.prettyErrors!==!1;return{lineCounter:s.lineCounter||e&&new la||null,prettyErrors:e}}c(ha,"parseOptions");function Xu(s,e={}){const{lineCounter:t,prettyErrors:n}=ha(e),r=new Pr(t?.addNewLine),i=new Or(e),o=Array.from(i.compose(r.parse(s)));if(n&&t)for(const a of o)a.errors.forEach(ss(s,t)),a.warnings.forEach(ss(s,t));return o.length>0?o:Object.assign([],{empty:!0},i.streamInfo())}c(Xu,"parseAllDocuments");function pa(s,e={}){const{lineCounter:t,prettyErrors:n}=ha(e),r=new Pr(t?.addNewLine),i=new Or(e);let o=null;for(const a of i.compose(r.parse(s),!0,s.length))if(!o)o=a;else if(o.options.logLevel!=="silent"){o.errors.push(new st(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return n&&t&&(o.errors.forEach(ss(s,t)),o.warnings.forEach(ss(s,t))),o}c(pa,"parseDocument");function Qu(s,e,t){let n;typeof e=="function"?n=e:t===void 0&&e&&typeof e=="object"&&(t=e);const r=pa(s,t);if(!r)return null;if(r.warnings.forEach(i=>Eo(r.options.logLevel,i)),r.errors.length>0){if(r.options.logLevel!=="silent")throw r.errors[0];r.errors=[]}return r.toJS(Object.assign({reviver:n},t))}c(Qu,"parse");function Zu(s,e,t){let n=null;if(typeof e=="function"||Array.isArray(e)?n=e:t===void 0&&e&&(t=e),typeof t=="string"&&(t=t.length),typeof t=="number"){const r=Math.round(t);t=r<1?void 0:r>8?{indent:8}:{indent:r}}if(s===void 0){const{keepUndefined:r}=t??e??{};if(!r)return}return Ze(s)&&!n?s.toString(t):new Bt(s,n,t).toString(t)}c(Zu,"stringify");var ed=Object.freeze({__proto__:null,Alias:qn,CST:Gu,Composer:Or,Document:Bt,Lexer:ca,LineCounter:la,Pair:se,Parser:Pr,Scalar:R,Schema:Ls,YAMLError:kr,YAMLMap:ue,YAMLParseError:st,YAMLSeq:Ue,YAMLWarning:Go,isAlias:Be,isCollection:z,isDocument:Ze,isMap:St,isNode:Y,isPair:V,isScalar:H,isSeq:Ct,parse:Qu,parseAllDocuments:Xu,parseDocument:pa,stringify:Zu,visit:et,visitAsync:Fn});const de={Updated:"updated",Deleted:"deleted",Stopped:"stopped"},td={ignored:Tl,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 nd extends nr{static{c(this,"LocalElementWatcher")}constructor(e){super(),this.options=e,this.membraneDir=dt(this.options.cwd),this.lockTimeoutMs=this.options.lockTimeoutMs??1e3}isWatching=!1;watcher;membraneDir;contentCache={};ignoredPaths=new Set;lockTimeoutMs;async start(){this.isWatching||(L.existsSync(this.membraneDir)||L.mkdirSync(this.membraneDir,{recursive:!0}),this.initializeContentCache(),this.watcher=el.watch(this.membraneDir,td),this.watcher.on("add",e=>this.handleFileSystemEvent(de.Updated,e)).on("change",e=>this.handleFileSystemEvent(de.Updated,e)).on("unlink",e=>this.handleFileSystemEvent(de.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(de.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===de.Deleted){this.removeFromCache(n);const a={filePath:t,relativePath:n,data:void 0};b.info(`[local] ${e}: ${a.relativePath}`),this.emit(e,a);return}const r=this.readFileContent(t);if(!this.hasContentChanged(n,r))return;const o=this.processFileEvent(t,r);this.updateCache(n,r),o&&(b.info(`[local] ${e}: ${o.relativePath}`),this.emit(e,o))}readFileContent(e){return L.readFileSync(e,"utf8")}processFileEvent(e,t){const n=K.relative(this.membraneDir,e);let r;try{r=t?ed.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 Qc.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(){L.existsSync(this.membraneDir)&&this.scanDirectoryForCache(this.membraneDir)}scanDirectoryForCache(e){const t=L.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=L.readFileSync(r,"utf8"),o=K.relative(this.membraneDir,r);this.updateCache(o,i)}catch{}}}}var Rr=(s=>(s.Updated="updated",s.ConnectorFileUpdated="connector-file-updated",s.Connected="connected",s.Disconnected="disconnected",s.Error="error",s))(Rr||{});const sd={debounceMs:2e3,reconnectIntervalMs:5e3,maxReconnectAttempts:1/0,maxBackoffMs:6e4,connectionTimeoutMs:3e5};class rd extends nr{static{c(this,"RemoteElementWatcher")}constructor(e=sd){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{b.debug("[remote-events] Connecting to server"),this.eventSource&&(this.eventSource.close(),this.eventSource=void 0);const e=await B.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)}`;b.debug("[remote-events] Subscribing to workspace events"),this.eventSource=new tl(n),this.setupEventSourceHandlers()}catch(e){b.debug(`[remote-events] Failed to connect: ${e}`),this.emit("error",{error:e}),this.scheduleReconnect()}}setupEventSourceHandlers(){this.eventSource&&(this.eventSource.onopen=()=>{b.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){b.debug(`[remote-events] Failed to parse workspace event: ${t}`)}},this.eventSource.onerror=e=>{b.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!==Uc.ElementUpdate)return;const{elementId:t,elementType:n,data:r={}}=e;if(!(!t||!n)){if(n===N.Connector){const{filePath:i,eventType:o,newPath:a}=r;return b.debug(`[remote-watcher] Received connector event - elementId: ${t}, filePath: ${i}, eventType: ${o}`),this.scheduleConnectorFileUpdate(t,i,o,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}),o=this.debounceTimeouts.get(i);o&&clearTimeout(o);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&&(b.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);b.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&&(b.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 ma{static{c(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())}}async function id(s="full"){const e={};b.info("[connectors] Getting remote workspace data");const t=await B.withClient(n=>n.integrations.findAll());e.integration=t?.map(n=>Mr("integration",n))??[];for(const n of Object.keys(ce)){const r=ce[n];if(r.exportable===!1)continue;const i=[];b.info(`[connectors] Reading ${r.elements} from remote workspace`);const o=await B.withClient(a=>a[r.elements].findAll());if(o&&i.push(...o.map(a=>Mr(n,a))),r.integrationSpecific&&t)for(const a of t){const l=await B.withClient(u=>u[r.elements].findAll({integrationId:a.id}));l&&i.push(...l.map(u=>(u.integrationKey=a.key,Mr(n,u))))}i.length>0&&s=="full"&&(console.table(i.map(a=>({key:a.key,integrationKey:a.integrationKey,universal:!a.integrationKey})).reduce((a,l)=>(a||(a={}),a[l.key]||(a[l.key]={}),l.universal&&(a[l.key].universal=!0),l.integrationKey&&(a[l.key].integration?a[l.key].integration+=` ${l.integrationKey}`:a[l.key].integration=l.integrationKey),a),{})),console.groupEnd()),e[n]=i}return b.success("[connectors] Remote workspace data retrieved successfully"),e}c(id,"getWorkspaceData");function Mr(s,e){return e=Kl(e),ce[s].exportCleanup?ce[s].exportCleanup(e):e}c(Mr,"cleanUpForExport");const xt="connectors",Pe="development",Lr={};async function od(){const s=await id("minified"),t=(await B.withClient(l=>l.get("org-workspace-id"))).id,n={};b.info("[connectors] Loading custom connectors");const r=await B.withClient(l=>l.get(`/connectors?workspaceId=${t}`));b.info("[connectors] Loading public connectors"),s.connector=Array.isArray(r)?r:[];const i=Je(),a=(F.existsSync(i)?F.readdirSync(i):[]).filter(l=>{if(l.startsWith("."))return!1;const u=U.join(i,l);try{return F.statSync(u).isDirectory()}catch{return!1}});for(const l of a){b.info(`[connectors] Loading connector from: ${l}`);const u=F.readdirSync(U.join(i,l)),d=await Dr(l);if(!d)continue;if("baseUri"in d&&delete d.baseUri,d.uuid&&s.connector?.find(h=>h.uuid==d.uuid))n[d.id]=s.connector.find(h=>h.uuid==d.uuid).id,b.info(`[connectors] Matched ${d.name} uuid: ${d.uuid}`);else if(!n[d.id]){let h=!1;try{const g=await jr({connectorId:d.id});g&&g.isPublic&&(h=!0)}catch{}if(!h){b.info(`[connectors] Creating custom connector ${d.name} (${d.key})`);const g=await B.withClient(y=>y.post("connectors",{...d,workspaceId:t}));n[d.id]=g.id}}const f=u.filter(h=>F.statSync(U.join(i,l,h)).isDirectory());for(const h of f)await ld({connector:d,version:h,connectorId:n[d.id]})}return n}c(od,"pushConnectors");async function ga({connectorId:s,connectorVersion:e,allConnectors:t,pulledConnectors:n,pulledConnectorVersions:r}){if(!s||r[s]?.has(e))return;const i=xi(),o=await jr({connectorId:s});if(!o.isPublic||t){if(!o?.key){b.error(`[connectors] Connector ${s} has no key. Skipping..`);return}n.has(s)||(await ud({basePath:i,connector:o}),n.add(s)),r[s]||(r[s]=new Set),r[s].has(e)||(await dd({connector:o,connectorVersion:e,basePath:i}),r[s].add(e))}}c(ga,"pullRemoteConnector");function Je(){const s=tr();return U.join(s.membraneDirPath,xt)}c(Je,"getConnectorsPath");async function Dr(s){const e=U.join(Je(),s,`${s}.yml`);return ir(e,!1)}c(Dr,"readConnector");async function ad(s,e){return b.info(`[connectors] Zipping ${s} into ${e}`),new Promise((t,n)=>{const r=F.createWriteStream(e),i=nl("zip",{zlib:{level:9}});r.on("close",()=>{b.success(`[connectors] Successfully created ${e}`),t()}),r.on("end",()=>{b.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 o=F.readdirSync(s);for(const a of o){const l=U.join(s,a),u=F.statSync(l);u.isFile()?i.file(l,{name:a}):u.isDirectory()&&i.directory(l,a)}i.finalize()})}c(ad,"createZipArchive");async function cd(s,e){return b.info(`[connectors] Unzipping into ${e}`),new Promise((t,n)=>{const r=rl.Parse();r.on("entry",i=>{const o=i.path;if(i.type==="Directory"){const l=U.join(e,o);F.mkdirSync(l,{recursive:!0}),i.autodrain()}else{const l=U.join(e,o),u=U.dirname(l);F.mkdirSync(u,{recursive:!0});const d=F.createWriteStream(l);i.pipe(d),d.on("finish",()=>{})}}),r.on("end",()=>{b.success(`[connectors] Successfully extracted to ${e}`),t()}),r.on("error",i=>{n(i)}),r.write(s),r.end()})}c(cd,"extractZipArchive");async function ld({connector:s,version:e,connectorId:t}){const n=U.join(Je(),Re(s),ya(e)),r=U.join(n,"src"),i=U.join(n,"src.zip"),o=F.existsSync(i);if(F.existsSync(r)&&(b.info(`[connectors] Archiving source code for ${s.name} version ${e}`),await ad(r,i)),!F.existsSync(i)){b.warning(`[connectors] No source code found for ${s.name} version ${e}`);return}try{const a=new sl;if(a.append("file",F.createReadStream(i),"file.zip"),b.info(`[connectors] Pushing connector version ${e} for ${s.name}`),e==Pe)b.info(`[connectors] Uploading connector ${t}`),await B.withClient(l=>l.post(`connectors/${t}/upload`,a,{headers:{...a.getHeaders()}}));else{if(a.append("version",e),a.append("changelog","Imported Version"),(await B.withClient(u=>u.get(`/connectors/${t}/versions`))).find(u=>u.version==e)){b.info(`[connectors] Version ${e} already published`);return}b.info(`[connectors] Publishing version ${e} of connector ${t}`),await B.withClient(u=>u.post(`connectors/${t}/publish-version`,a,{headers:{...a.getHeaders()}}))}b.success(`Successfully pushed connector version ${e} for ${s.name}`)}catch(a){b.error(`Error pushing connector version ${e} for ${s.name}: ${a}`)}finally{!o&&F.existsSync(i)&&(b.info(`[connectors] Cleaning up temporary zip file for ${s.name} version ${e}`),F.unlinkSync(i))}}c(ld,"pushConnectorVersion");async function jr({connectorId:s}){if(s){if(Lr[s])return Lr[s];try{const e=await B.withClient(t=>t.get(`connectors/${s}`));return Lr[s]=e,e}catch(e){return b.error(`[connectors] Failed to get connector ${s}: ${e}`),null}}}c(jr,"getConnector");async function ud({basePath:s,connector:e}){const t=Re(e),n=U.join(s,xt,t);F.mkdirSync(n,{recursive:!0});const r=U.join(n,`${Re(e)}.yml`);F.writeFileSync(r,Wt.dump(e)),b.info(`[connectors] Pulled connector ${e.name}`)}c(ud,"pullConnector");async function dd({connector:s,connectorVersion:e,basePath:t}){const n=Re(s),r=ya(e),i=U.join(t,"connectors",n,r),o=await B.withClient(l=>l.get(`connectors/${s.id}/download`,{version:e},{responseType:"arraybuffer",headers:{Accept:"application/zip"},timeout:1e6}));F.mkdirSync(i,{recursive:!0});const a=U.join(i,"src.zip");if(F.writeFileSync(a,o),!e){const l=U.join(i,"src");F.mkdirSync(l,{recursive:!0}),await cd(o,l)}b.info(`[connectors] Pulled connector version: ${s.name} (${r})`)}c(dd,"pullConnectorVersion");function Re(s){return s.key}c(Re,"getConnectorDirName");function ya(s){return s??Pe}c(ya,"getConnectorVersionDirName");function fd(s){const e=xi(),t=Re(s);return U.join(e,xt,t)}c(fd,"getConnectorDirPath");function hd(s){return s.match(`${xt}/[^/]+/${Pe}/src/.*`)!==null}c(hd,"isConnectorSourceFile");async function pd(s){const e=s.match(`${xt}/([^/]+)/${Pe}/src/(.*)`);if(!e)return;const t=e[1],n=e[2],r=await Dr(t);if(!r){b.warning(`[connectors] Connector ${t} not found. Ignoring file change`);return}const i=r.id,o=F.readFileSync(s,"utf-8");await B.withClient(a=>a.put(`connectors/${i}/files/${n}`,o,{headers:{"Content-Type":"text/plain"}})),b.info(`[connectors] Pushed file ${n} for connector ${r.name}`)}c(pd,"putConnectorFile");async function md(s){const e=s.match(`${xt}/([^/]+)/${Pe}/src/(.*)`);if(!e)return;const t=e[1],n=e[2],r=await Dr(t);if(!r){b.warning(`[connectors] Connector ${t} not found. Ignoring file change`);return}const i=r.id;await B.withClient(o=>o.delete(`connectors/${i}/files/${n}`)),b.info(`[connectors] Deleted file ${n} for connector ${r.name}`)}c(md,"deleteConnectorFile");async function gd(s,e){try{const t=await B.withClient(o=>o.get(`connectors/${s}`));if(!t){b.warning(`[connectors] Connector ${s} not found`);return}const n=await B.withClient(o=>o.get(`connectors/${s}/files/${e}`)),r=Re(t),i=U.join(Je(),r,Pe,"src",e);F.mkdirSync(U.dirname(i),{recursive:!0}),n!=null?(F.writeFileSync(i,n),b.info(`[connectors] Pulled file ${e} for connector ${t.name}`)):F.existsSync(i)&&(F.unlinkSync(i),b.info(`[connectors] Deleted file ${e} for connector ${t.name}`))}catch(t){b.error(`[connectors] Failed to pull connector file ${e} for connector ${s}: ${t}`)}}c(gd,"pullConnectorFile");async function yd(s,e){const t=await B.withClient(i=>i.get(`connectors/${s}`));if(!t){b.warning(`[connectors] Connector ${s} not found`);return}const n=Re(t),r=U.join(Je(),n,Pe,"src",e);F.existsSync(r)&&(F.unlinkSync(r),b.info(`[connectors] Deleted file ${e} for connector ${n}`))}c(yd,"deleteLocalConnectorFile");async function wd(s,e,t){if(t&&e!==t)try{const n=await B.withClient(l=>l.get(`connectors/${s}`));if(!n){b.warning(`[connectors] Connector ${s} not found`);return}const r=Re(n),i=U.join(Je(),r,Pe,"src"),o=U.join(i,e),a=U.join(i,t);F.existsSync(o)&&(F.mkdirSync(U.dirname(a),{recursive:!0}),F.renameSync(o,a),b.info(`[connectors] Renamed directory from ${e} to ${t} for connector ${r}`))}catch(n){b.error(`[connectors] Failed to rename directory ${e} to ${t} for connector ${s}: ${n}`)}}c(wd,"renameLocalConnectorDirectory");async function bd(s,e){try{const t=await B.withClient(i=>i.get(`connectors/${s}`));if(!t){b.warning(`[connectors] Connector ${s} not found`);return}const n=Re(t),r=U.join(Je(),n,Pe,"src",e);if(F.existsSync(r)){const i=U.resolve(Je());if(!U.resolve(r).startsWith(i))return;F.rmSync(r,{recursive:!0,force:!0}),b.info(`[connectors] Deleted directory ${e} for connector ${n}`)}}catch(t){b.error(`[connectors] Failed to delete directory ${e} for connector ${s}: ${t}`)}}c(bd,"deleteLocalConnectorDirectory");const wa=[N.DataSource,N.FieldMapping,N.Action,N.Flow,N.Package,N.AppDataSchema,N.AppEventType,N.DataLinkTable];class En{static{c(this,"ElementSyncService")}localWatcher=void 0;remoteWatcher=void 0;notifier;changes=[];localCache;remoteCache;localRepo;remoteRepo;pulledConnectors=new Set;pulledConnectorVersions={};constructor(){this.notifier=Oe,this.localCache=new ma,this.remoteCache=new ma,this.localRepo=new Wl(this.localCache),this.remoteRepo=new Jl(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 b.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 b.error(`Failed to delete element ${e.id}: ${i}`),i}}async pullConnectors(e=!1){const t=this.remoteCache.getElementsByType(N.Integration).map(n=>n.data);for(const n of t){const r=n.connectorId,i=n.connectorVersion;r&&await ga({connectorId:r,connectorVersion:i,allConnectors:e,pulledConnectors:this.pulledConnectors,pulledConnectorVersions:this.pulledConnectorVersions})}}async pushConnectors(){const e=await od();this.remoteRepo.setConnectorsMapping(e)}getHandler(e){return e===ae.INCOMING?this.localRepo:(this.remoteRepo.setSourceCache(this.localCache),this.remoteRepo)}getCache(e){return e===ae.INCOMING?this.localCache:this.remoteCache}async startWatching(){this.localWatcher=new nd({cwd:process.cwd(),lockTimeoutMs:1e3}),this.localWatcher.on(de.Updated,e=>this.handleLocalEvent(e,de.Updated)),this.localWatcher.on(de.Deleted,e=>this.handleLocalEvent(e,de.Deleted)),await this.localWatcher.start(),b.success("[local] Tracking changes.."),this.remoteWatcher=new rd,this.remoteWatcher.on(Rr.Updated,({elementId:e,elementType:t})=>this.handleRemoteElementEvent(e,t)),this.remoteWatcher.on(Rr.ConnectorFileUpdated,({connectorId:e,filePath:t,eventType:n,newPath:r})=>this.handleRemoteConnectorFileEvent(e,t,n,r)),await this.remoteWatcher.start(),b.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 o=n||this.remoteCache.getByInternalId(e);return o?(b.info(`[${this.getDirectionLabel(ae.INCOMING)}] Deleted: ${o.id}`),this.localWatcher?.executeWithPathLock(o.absolutePath,()=>this.deleteElement(o,ae.INCOMING))):void 0}if(b.info(`[${this.getDirectionLabel(ae.INCOMING)}] Updated: ${n.id}`),await this.localWatcher?.executeWithPathLock(n.absolutePath,async()=>this.updateElement(n,ae.INCOMING)),t===N.Integration){const o=n.data.connectorId,a=n.data.connectorVersion,l=await jr({connectorId:o});if(!l?.key)return;const u=fd(l);await this.localWatcher?.executeWithPathLock(u,async()=>ga({connectorId:o,connectorVersion:a,allConnectors:!1,pulledConnectors:this.pulledConnectors,pulledConnectorVersions:this.pulledConnectorVersions}))}}catch(n){b.error(`[sync] Error handling remote event: ${n}`)}}async handleRemoteConnectorFileEvent(e,t,n,r){try{switch(n){case Js.ConnectorFileDeleted:await yd(e,t);break;case Js.ConnectorDirectoryRenamed:await wd(e,t,r);break;case Js.ConnectorDirectoryDeleted:await bd(e,t);break;default:await gd(e,t);break}}catch(i){b.error(`[sync] Error handling remote connector file event: ${i}`)}}async handleLocalEvent(e,t){try{if(hd(e.filePath))switch(t){case de.Updated:await pd(e.filePath);break;case de.Deleted:await md(e.filePath);break}else{let n=X.fromPathAndData(e.filePath,e.data);if(!n){const r=X.idFromPath(e.filePath);if(!r||(n=this.remoteCache.get(r),!n))return}switch(b.info(`[${this.getDirectionLabel(ae.OUTGOING)}] ${ql.toSentenceCase(t)}: ${n.id}`),t){case de.Updated:await this.updateElement(n,ae.OUTGOING);break;case de.Deleted:await this.deleteElement(n,ae.OUTGOING);break}}}catch(n){b.error(`[sync] Error handling local event: ${n}`)}}detectIncomingChanges(){this.clearChanges();const e=En.getChanges(ae.INCOMING,this.remoteCache,this.localCache);return this.updateChanges(e),e}detectOutgoingChanges(){this.clearChanges();const e=En.getChanges(ae.OUTGOING,this.localCache,this.remoteCache);return this.updateChanges(e),e}async resolveChanges(){if(!this.needsSync())return;b.info("[resolver] Resolving changes.."),b.info("[resolver] Resolving integration elements");const e=this.changes.filter(r=>r.element.type===N.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===ae.INCOMING?this.detectIncomingChanges():this.detectOutgoingChanges(),this.changes=this.changes.filter(r=>r.element.type!==N.Integration)),b.info("[resolver] Resolving universal elements");const t=this.changes.filter(r=>!r.element.hasParent());for(const r of wa){const i=t.filter(o=>o.element.type===r);b.info(`[resolver] Resolving ${r} elements`),await Promise.all(i.map(async o=>this.resolveChange(o)))}b.info("[resolver] Resolving integration level elements");const n=this.changes.filter(r=>r.element.hasParent());for(const r of wa){const i=n.filter(o=>o.element.type===r);b.info(`[resolver] Resolving ${r} elements`),await Promise.all(i.map(async o=>this.resolveChange(o)))}b.success("[resolver] Resolved changes")}async resolveChange(e){switch(e.type){case $e.DELETE:return this.deleteElement(e.element,e.direction);case $e.CREATE:return this.updateElement(e.element,e.direction);case $e.UPDATE:return this.updateElement(e.element,e.direction)}}static getChanges(e,t,n){const r=t.getAllIds(),i=n.getAllIds(),o=new Set([...r,...i]),a=[];for(const l of o){const u=t.get(l),d=n.get(l),f=En.detectChangeForElement(u,d,e);f&&a.push(f)}return a}updateChanges(e){if(this.changes=e,this.needsForcedSync()){const t=e.filter(n=>n.isConflict);b.warning("[resolver] Conflicts detected"),this.notifier.setConflicts(t)}}clearChanges(){this.changes=[]}getDirectionLabel(e){switch(e){case ae.INCOMING:return"local\u2190remote";case ae.OUTGOING:return"local\u2192remote"}}static detectChangeForElement(e,t,n){return e&&!t?{type:$e.CREATE,element:e,direction:n,isConflict:!1}:!e&&t?{type:$e.DELETE,element:t,direction:n,isConflict:!0}:e&&t&&!e.isEqual(t)?{type:$e.UPDATE,element:e,direction:n,isConflict:!1}:null}}const He=K.join(il.tmpdir(),"membrane-mcp-status"),ba=3e4;class Sd{static{c(this,"McpStatusService")}constructor(e=2e3){this.pollIntervalMs=e}isRunning=!1;pollInterval;async start(){this.isRunning||(this.isRunning=!0,this.pollInterval=setInterval(async()=>await this.checkStatus(),this.pollIntervalMs),await this.checkStatus())}async stop(){this.pollInterval&&(clearInterval(this.pollInterval),this.pollInterval=void 0,this.isRunning=!1)}async checkStatus(){try{const e=process.cwd(),t=ds(void 0,e),n=Sa(e);t&&Oe.setMcpStatus(t),await Oe.setMcpServers(n)}catch{b.error("Failed to check MCP status")}}}function ds(s,e){try{const t=e||process.cwd();if(!s){const r=Sa(t);return r.length===0?null:r[0]}const n=Kr(s,t);if(L.existsSync(n)){const r=L.statSync(n),i=new Date;if(i.getTime()-r.mtime.getTime()>ba)return tn(s,t),null;const a=L.readFileSync(n,"utf8"),l=JSON.parse(a);if(l.isRunning){const u=new Date(l.lastActivity).getTime();if(i.getTime()-u>ba)return tn(s,t),null}return l}}catch{s&&e&&tn(s,e)}return null}c(ds,"getMcpStatus");function Sa(s){try{const e=s||process.cwd(),t=qr(e);if(!L.existsSync(He))return[];const n=L.readdirSync(He),r=[];for(const i of n){const o=i.match(new RegExp(`^mcp-${t}-(\\d+)\\.json$`));if(o){const a=parseInt(o[1],10),l=ds(a,e);l&&r.push(l)}}return r.sort((i,o)=>new Date(o.startTime).getTime()-new Date(i.startTime).getTime())}catch{return[]}}c(Sa,"getAllMcpStatusFiles");function Fr(s){try{const t={...ds(s.processId,s.cwd)||{isRunning:!1,startTime:new Date().toISOString(),lastActivity:new Date().toISOString(),toolsCount:0,totalRequests:0,processId:s.processId,cwd:s.cwd,agentName:process.env.AGENT_NAME||"Unnamed Agent"},...s};L.existsSync(He)||L.mkdirSync(He,{recursive:!0});const n=Kr(s.processId,s.cwd);L.writeFileSync(n,JSON.stringify(t,null,2))}catch{}}c(Fr,"updateMcpStatus");function tn(s,e){try{const t=e||process.cwd();if(s){const n=Kr(s,t);L.existsSync(n)&&L.unlinkSync(n)}else{const n=qr(t);if(L.existsSync(He)){const r=L.readdirSync(He);for(const i of r)i.match(new RegExp(`^mcp-${n}-\\d+\\.json$`))&&L.unlinkSync(K.join(He,i))}}}catch{}}c(tn,"clearMcpStatus");function Cd(s,e){const t=ds(s,e);t&&Fr({processId:s,cwd:e,totalRequests:t.totalRequests+1,lastRequestTime:new Date().toISOString(),lastActivity:new Date().toISOString()})}c(Cd,"trackToolExecution");function qr(s){return Zc("md5").update(s).digest("hex").slice(0,8)}c(qr,"getCwdHash");function Kr(s,e){const t=qr(e);return K.join(He,`mcp-${t}-${s}.json`)}c(Kr,"getStatusFilePath");const nn={Agent:"agent",Cli:"cli"},P={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 Ca{static{c(this,"MembraneCLIService")}constructor(e,t,n=()=>process.exit(0)){this.mode=e,this.cwd=t,this.onShutdown=n,this.notifier=Oe,this.mcpStatusService=new Sd,this.syncService=new En,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{if(b.setVerboseMode(!!e.verbose),e.rps!==void 0&&B.init({maxRequestsPerSecond:e.rps}),await this.notifier.setState(P.PULLING),await this.syncService.fetchElements(),this.syncService.detectIncomingChanges(),this.syncService.needsForcedSync()&&!e.force){await this.notifier.setState(P.CONFLICTS),e.watch||(t=!0);return}await this.syncService.pullConnectors(e.allConnectors),await this.syncWorkspaces(e)}catch(n){t=!0,b.error(`Failed to pull workspace: ${n}`),await this.notifier.setState(P.ERROR),b.saveLogsToFile("error")}finally{if(e.saveLogs&&b.saveLogsToFile(),t)process.exit(1);else return e?.onComplete?.()}}async pushWorkspace(e={}){let t=!1;try{if(b.setVerboseMode(!!e.verbose),e.rps!==void 0&&B.init({maxRequestsPerSecond:e.rps}),await this.notifier.setState(P.PUSHING),await this.syncService.fetchElements(),this.syncService.detectOutgoingChanges(),this.syncService.needsForcedSync()&&!e.force){await this.notifier.setState(P.CONFLICTS),e.watch||(t=!0);return}await this.syncService.pushConnectors(),await this.syncWorkspaces(e)}catch(n){t=!0,b.error(`Failed to push workspace: ${n}`),await this.notifier.setState(P.ERROR),b.saveLogsToFile("error")}finally{if(e.saveLogs&&b.saveLogsToFile(),t)process.exit(1);else return e?.onComplete?.()}}async syncWorkspaces(e={}){try{e.verbose!==void 0&&b.setVerboseMode(!!e.verbose),await this.notifier.setState(P.RESOLVING),this.syncService.needsSync()&&await this.syncService.resolveChanges();const t=await this.syncService.getStats();this.notifier.setStats(t),await this.notifier.setState(P.SYNCED),e.watch&&(await this.notifier.setState(P.WATCHING),await this.syncService.startWatching())}catch(t){b.error(`Failed to sync local and remote workspaces: ${t}`),await this.notifier.setState(P.ERROR),b.saveLogsToFile("error")}}async init({force:e=!1}={}){if(!(this.initialized&&!e)){await this.notifier.setState(P.NOT_INITIALIZED);try{await this.loadConfig(),Qe.isCacheDefined()?(await this.initServices(),this.initialized=!0,await this.notifier.setState(P.INITIALIZED)):(this.initialized=!1,await this.notifier.setState(P.SETTING_UP))}catch(t){b.error(`Failed to initialize services: ${t}`),await this.notifier.setState(P.ERROR),b.saveLogsToFile("error"),this.onShutdown()}}}async loadConfig(){this.currentConfig=Qe.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=Qe.updateConfig(t);this.currentConfig=r,await this.init({force:!0})}async shutdown(){!this.initialized||this.isShuttingDown||(this.isShuttingDown=!0,this.mode===nn.Agent&&(await this.notifier.cleanup(),await this.mcpStatusService.stop()),this.initialized=!1,this.onShutdown())}async initServices(){this.mode===nn.Agent&&(await this.notifier.connectToRemote(),await this.mcpStatusService.start()),this.syncService.clear()}async stopServices(){this.mode===nn.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()})}}const va=Bs(null);function vd({children:s,membraneCLIService:e}){const{data:t}=Ei("/account"),[n,r]=J(P.NOT_INITIALIZED),[i,o]=J([]),[a,l]=J({}),[u,d]=J([]),[f,h]=J(null),y=t?.workspaces?.find(p=>p.workspaceKey===f?.workspaceKey)||null;return Fe(()=>{const p=c(({state:I})=>r(I),"handleStateChanged"),w=c(({stats:I})=>l(I),"handleStatsChanged"),T=c(({log:I})=>d($=>[...$,I]),"handleLogAdded"),E=c(({conflicts:I})=>o(I),"handleConflictsUpdated"),O=c(({config:I})=>h(I),"handleConfigChanged");return e.notifier.on(Q.StateChanged,p),e.notifier.on(Q.StatsChanged,w),e.notifier.on(Q.LogAdded,T),e.notifier.on(Q.ConflictsChanged,E),e.notifier.on(Q.ConfigChanged,O),e.init(),()=>{e.notifier.off(Q.StateChanged,p),e.notifier.off(Q.StatsChanged,w),e.notifier.off(Q.LogAdded,T),e.notifier.off(Q.ConflictsChanged,E),e.notifier.off(Q.ConfigChanged,O)}},[]),m(va.Provider,{value:{state:n,stats:a,logs:u,currentWorkspace:y,conflicts:i,config:f,updateConfig:c(p=>e.updateConfig(p),"updateConfig"),resolveConflicts:c(p=>e.syncWorkspaces(p),"resolveConflicts"),pull:c(p=>e.pullWorkspace(p),"pull"),push:c(p=>e.pushWorkspace(p),"push"),exit:c(()=>e.shutdown(),"exit"),fetchElements:c(()=>e.fetchElements(),"fetchElements"),getSyncedElementsByType:c(p=>e.getSyncedElementsByType(p),"getSyncedElementsByType")},children:s})}c(vd,"MembraneCLIServiceProvider");function fe(){const s=Us(va);if(!s)throw new Error("useMembraneCLIService must be used within MembraneCLIServiceProvider");return s}c(fe,"useMembraneCLIService");const ka=Bs(process.cwd());function kd({cwd:s,children:e}){return m(ka.Provider,{value:s,children:e})}c(kd,"CwdProvider");function Td(){return Us(ka)}c(Td,"useCwd");function sn({cwd:s,children:e,membraneCLIService:t}){const n=s||process.cwd();return m(kd,{cwd:n,children:m(Dc,{value:{fetcher:Cl()},children:m(vd,{membraneCLIService:t,children:e})})})}c(sn,"Layout");const Br=[{id:"claude-code",name:"Claude Code",description:"Anthropic Claude Code agent",actionDescription:"Adding membrane MCP to .mcp.json in the current directory",addConfig:c(()=>{const s=K.join(process.cwd(),".mcp.json"),e={mcpServers:{membrane:{command:"membrane",args:["mcp"],env:{AGENT_NAME:"Claude Code"}}}};let t={};if(L.existsSync(s))try{t=JSON.parse(L.readFileSync(s,"utf8"))}catch{t={}}const n={...t,mcpServers:{...t.mcpServers,...e.mcpServers}};return L.writeFileSync(s,JSON.stringify(n,null,2)),`MCP server configuration added to ${s}`},"addConfig")},{id:"cursor",name:"Cursor",description:"Cursor AI editor",actionDescription:"Adding membrane MCP to .cursor/mcp.json in the current directory",addConfig:c(()=>{const s=K.join(process.cwd(),".cursor"),e=K.join(s,"mcp.json");L.existsSync(s)||L.mkdirSync(s);const t={mcpServers:{membrane:{command:"membrane",args:["mcp"],env:{AGENT_NAME:"Cursor"}}}};let n={};if(L.existsSync(e))try{n=JSON.parse(L.readFileSync(e,"utf8"))}catch{n={}}const r={...n,mcpServers:{...n.mcpServers,...t.mcpServers}};return L.writeFileSync(e,JSON.stringify(r,null,2)),`MCP server configuration added to ${e}`},"addConfig")}];function Ed({onExit:s,onComplete:e}){const[t,n]=J(0),[r,i]=J(!1),[o,a]=J(null),[l,u]=J(""),[d,f]=J("");Xe((y,p)=>{if(l||d){(p.escape||y==="q"||p.return)&&e();return}if(r)p.return||y===" "?h(o):p.escape&&(i(!1),a(null));else if(p.escape)s();else if(p.upArrow||y==="k")n(Math.max(0,t-1));else if(p.downArrow||y==="j")n(Math.min(Br.length-1,t+1));else if(p.return||y===" "){const w=Br[t];a(w),i(!0)}});const h=c(y=>{try{const p=y.addConfig();u(p)}catch(p){f(`Failed to write configuration: ${p.message||p}`)}},"addMcpConfiguration"),g=Math.min(80,process.stdout.columns||80);return l?_(S,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:g,children:[m(S,{marginTop:-1,marginBottom:1,children:_(v,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",m(v,{color:"green",children:"Success"})]})}),_(S,{flexDirection:"column",paddingLeft:2,children:[m(v,{color:"green",children:l}),m(S,{marginTop:1,children:m(v,{color:"grey",children:"The agent will now be able to use Membrane's integration capabilities."})})]}),m(S,{marginTop:1,paddingLeft:2,children:m(v,{color:"white",children:"[esc/q/enter: exit]"})})]}):d?_(S,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:g,children:[m(S,{marginTop:-1,marginBottom:1,children:_(v,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",m(v,{color:"red",children:"Error"})]})}),m(S,{flexDirection:"column",paddingLeft:2,children:m(v,{color:"red",children:d})}),m(S,{marginTop:1,children:m(v,{color:"grey",children:"[esc/q/enter: exit]"})})]}):r&&o?_(S,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:g,children:[m(S,{marginTop:-1,marginBottom:1,children:_(v,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",m(v,{color:"cyan",children:"Confirmation"})]})}),_(S,{flexDirection:"column",paddingLeft:2,children:[_(v,{children:["Connect ",m(v,{bold:!0,children:o.name})," to Membrane via MCP?"]}),m(S,{marginTop:1,children:m(v,{color:"grey",children:"This will add an MCP server configuration that allows the agent to use Membrane's integration capabilities."})}),m(S,{marginTop:1,children:m(v,{color:"yellow",bold:!0,children:o.actionDescription})}),m(S,{marginTop:2,marginBottom:1,children:_(v,{children:[m(v,{color:"white",bold:!0,children:"[Enter] Confirm"})," ",m(v,{color:"gray",children:"[Esc] Cancel"})]})})]})]}):_(S,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:g,children:[m(S,{marginTop:-1,marginBottom:1,children:_(v,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",m(v,{color:"cyan",children:"Select Agent"})]})}),_(S,{flexDirection:"column",paddingLeft:2,children:[m(v,{color:"grey",children:"Choose an agent to connect to Membrane via MCP:"}),m(S,{marginTop:1,children:m(v,{color:"grey",children:"This will add an MCP server configuration that allows the agent to use Membrane's integration capabilities."})}),m(S,{marginTop:1,flexDirection:"column",children:Br.map((y,p)=>_(S,{children:[_(v,{color:t===p?"cyan":"white",children:[t===p?"\u25B6 ":" ",y.name]}),_(v,{color:"grey",children:[" \u2014 ",y.description]})]},y.id))})]}),m(S,{marginTop:1,children:m(v,{color:"grey",children:"[\u2191\u2193: select] [enter: choose] [esc: exit]"})})]})}c(Ed,"AddMcpServerScreen");function _d(){const[s,e]=J(null),[t,n]=J([]),[r,i]=J(null);return Fe(()=>{const o=c(({status:l})=>{e(l),i(null)},"handleMcpStatusChanged"),a=c(({servers:l})=>{n(l),i(null)},"handleMcpServersChanged");return Oe.on(Q.McpStatusChanged,o),Oe.on(Q.McpServersChanged,a),()=>{Oe.off(Q.McpStatusChanged,o),Oe.off(Q.McpServersChanged,a)}},[]),{mcpStatus:s,allMcpServers:t,error:r,isRunning:s?.isRunning||!1,toolsCount:s?.toolsCount||0,totalRequests:s?.totalRequests||0,lastActivity:s?.lastActivity,processId:s?.processId,serverCount:t.length}}c(_d,"useMcpStatus");function Id(){const{error:s,serverCount:e,allMcpServers:t}=_d(),n=Math.min(100,process.stdout.columns||100);return _(S,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:n,children:[m(S,{marginTop:-1,marginBottom:0,flexDirection:"column",children:_(v,{bold:!0,children:["\u{1F916} Connected AI Agents:"," ",s?m(v,{color:"red",children:"error reading status"}):e===0?m(v,{color:"yellow",children:"none"}):m(v,{color:"green",children:e})]})}),!s&&e===0&&m(S,{marginTop:1,children:_(v,{color:"grey",children:["Connect your AI agents to Membrane.",m(Mc,{}),"It will give them tools and context to build integrations."]})}),t.length>0&&m(S,{flexDirection:"column",paddingLeft:2,marginTop:1,children:t.map((r,i)=>m(S,{children:_(v,{color:"grey",children:["#",i+1," ",r.agentName,": ",r.totalRequests," calls"]})},r.processId))}),m(S,{marginTop:1,children:m(v,{color:"grey",children:"[a: connect an agent]"})})]})}c(Id,"Agent");const fs=c(s=>{switch(s){case"error":return"red";case"success":return"green";case"warning":return"yellow";default:return}},"getLogColor");function Ta(s,e){return e<3?s.slice(0,Math.max(0,e)):s.length<=e?s:`${s.slice(0,e-3)}...`}c(Ta,"truncateText");function Ur({children:s}){const{state:e,logs:t}=fe();return!e||e===P.NOT_INITIALIZED?_(S,{gap:1,flexDirection:"row",children:[m(al,{type:"dots"}),m(v,{children:"Initializing..."})]}):e===P.SETTING_UP?m(S,{gap:1,flexDirection:"row",children:m(v,{children:"No workspace selected. Please run `membrane init` to select a workspace."})}):e===P.ERROR?m(S,{flexDirection:"column",children:t.slice().map((n,r)=>m(v,{color:fs(n.type),children:n.message},n.timestamp+r))}):s}c(Ur,"EnsureInitialized");function Ea({onExit:s,showEscOption:e=!0}){const[t,n]=J(""),{data:r,error:i,isLoading:o}=Ei("/account"),{updateConfig:a}=fe(),l=r?.workspaces,u=o;if(Xe((p,w)=>{w.escape&&s?.()}),u)return _(S,{children:[m(An,{}),m(v,{children:" Fetching workspaces..."})]});if(i)return _(S,{flexDirection:"column",children:[_(v,{color:"red",children:["Error: ",i.message]}),m(S,{marginTop:1,children:m(v,{color:"grey",children:"Press ESC to go back"})})]});const d=l?.filter(p=>p.name.toLowerCase().includes(t.toLowerCase()))??[],f=d.map(p=>({label:p.name,value:p.id})),h=f.length,g=l?.length??0;async function y(p){const w=d.find(O=>O.id===p);if(!w)return;const{key:T,secret:E}=w;!T||!E||(await a({workspaceKey:T,workspaceSecret:E}),s?.())}return c(y,"handleSelect"),_(S,{flexDirection:"column",borderStyle:"round",borderTop:!0,width:70,paddingX:1,children:[m(S,{marginTop:-1,children:m(v,{bold:!0,children:"\u{1F4C1} Select your workspace"})}),_(S,{marginTop:1,children:[m(v,{children:"Search: "}),m(cl,{placeholder:"Enter a search query...",onChange:n})]}),g>5&&_(v,{children:["Showing ",h," of ",g," workspaces."]}),m(S,{marginTop:1,children:m(ll,{options:f,onChange:c(p=>{p&&y(p)},"onChange")})}),e&&m(S,{marginTop:1,children:m(v,{color:"grey",children:"Press ESC to go back"})})]})}c(Ea,"SelectWorkspace");function Ad({currentPat:s,onSubmit:e}){const[t,n]=J(""),[r,i]=J(!1),[o,a]=J(null);return _(S,{flexDirection:"column",borderStyle:"round",borderTop:!0,width:70,paddingX:1,children:[m(S,{marginTop:-1,marginBottom:1,children:m(v,{bold:!0,children:"\u{1F511} Enter your Personal Access Token"})}),m(v,{children:"Please provide your Personal Access Token. You can find it here:"}),m(S,{marginTop:1,marginBottom:1,children:m(v,{color:"yellow",children:"https://console.integration.app/w/0/manage-account/api-token"})}),s&&m(v,{dimColor:!0,children:"Press Enter to keep your current token or type a new one."}),m(Ni,{mask:"*",placeholder:`${s?"******":"Enter your token here..."}`,value:t,onChange:n,onSubmit:c(async u=>{a(null),i(!0);try{await e(u),n("")}catch{a("Invalid token. Please try again.")}finally{i(!1)}},"handleSubmit")}),r&&m(S,{marginTop:1,children:_(v,{children:[m(An,{type:"dots"})," Validating token..."]})}),o&&m(v,{color:"red",children:o})]})}c(Ad,"PersonalAccessTokenInput");var rn=(s=>(s[s.Authenticate=0]="Authenticate",s[s.ConnectWorkspace=1]="ConnectWorkspace",s))(rn||{});const Od={0:"Authenticate in Membrane",1:"Connect a Membrane Workspace"},Wr=[rn.Authenticate,rn.ConnectWorkspace];function _a({onComplete:s}){const{config:e}=fe(),[t,n]=J(!1),[r,i]=J(0),o=!!(e?.workspaceKey&&e?.workspaceSecret),a=Ri(),l=Wr[r],u=r+1,d=Wr.length,f=Wr.map((y,p)=>{let w="pending";return p<r?w="done":p===r&&(w="current"),{id:y,label:Od[y],status:w}});async function h(y){const p=a&&y===""?a:y,w=new Mi;try{await w.request("/account",{headers:{Authorization:`Bearer ${p}`}}),Sl(p),i(T=>T+1)}catch(T){console.error(T)}}c(h,"handlePatSubmit");function g(){n(!0),s&&s()}return c(g,"handleWorkspaceSelected"),Xe((y,p)=>{o&&p.escape&&s&&s()}),t?m(S,{children:m(v,{children:"\u2705 Setup complete. You are ready to go!"})}):_(S,{flexDirection:"column",alignSelf:"flex-start",gap:1,children:[_(S,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:70,children:[m(S,{marginTop:-1,marginBottom:1,children:_(v,{bold:!0,children:["\u{1F6E0}\uFE0F Setup \u2014"," ",_(v,{color:"cyan",children:["Step ",u," of ",d]}),o&&m(v,{color:"grey",children:" [esc: go back]"})]})}),m(S,{flexDirection:"column",paddingLeft:2,children:f.map(y=>m($d,{status:y.status,label:y.label},y.id))})]}),l===rn.Authenticate&&m(Ad,{currentPat:a,onSubmit:h}),l===rn.ConnectWorkspace&&m(Ea,{onExit:g,showEscOption:!1})]})}c(_a,"Setup");function $d({status:s,label:e}){return _(S,{children:[_(S,{width:2,children:[s==="current"&&m(An,{type:"dots"}),s==="done"&&m(v,{children:"\u2705"})]}),m(v,{dimColor:s!=="current",children:e})]})}c($d,"StepDisplay");function Jr(){const{stats:s}=fe(),e=Object.entries(s).filter(([t,n])=>n>0);return e.length===0?null:_(S,{flexDirection:"column",children:[m(S,{children:m(S,{width:12,children:m(v,{color:"grey",children:"Elements:"})})}),m(S,{flexDirection:"column",marginLeft:1,children:e.map(([t,n])=>_(S,{children:[m(S,{width:20,children:_(v,{children:[t,":"]})}),m(v,{color:"green",children:n})]},t))})]})}c(Jr,"ElementStats");const Hr=5,Nd=6;function xd(){const{logs:s}=fe(),[e,t]=J(0),n=Math.min(100,process.stdout.columns||100),r=Hr,i=Math.max(0,s.length-r-e),o=s.length-e,a=s.slice(i,o),l=n-Nd,u=e<s.length-r,d=e>0;return Xe((f,h)=>{if(s.length!==0)if(h.upArrow){const g=Math.max(0,s.length-r);t(y=>Math.min(g,y+1))}else h.downArrow?t(g=>Math.max(0,g-1)):(f==="G"||f==="g")&&t(0)}),_(S,{flexDirection:"column",paddingTop:1,children:[_(v,{color:"grey",children:["Recent Activity (",i+1,"-",o," of ",s.length,"):",s.length>Hr&&m(v,{color:"grey",children:" [arrows: scroll] [g: end]"})]}),a.map((f,h)=>m(S,{marginLeft:1,children:m(v,{color:fs(f.type),children:Ta(f.message,l)})},f.timestamp+h)),s.length>Hr&&_(S,{marginLeft:1,flexDirection:"row",children:[u&&m(v,{color:"grey",children:"\u2191 "}),d&&m(v,{color:"grey",children:"\u2193 "})]})]})}c(xd,"Logs");const hs=[{value:"sync",label:"Continue (overwrite/delete)",key:""},{value:"exit",label:"Cancel",key:""}];function Pd(){const{state:s,resolveConflicts:e,exit:t}=fe(),[n,r]=J(0),[i,o]=J(!1),[a,l]=J(!1);return Xe((u,d)=>{if(!i){if(d.ctrl&&u.toLowerCase()==="r"){l(!a);return}d.upArrow?r(f=>f>0?f-1:hs.length-1):d.downArrow?r(f=>f<hs.length-1?f+1:0):u.toLowerCase()==="y"?r(0):u.toLowerCase()==="n"?r(1):(d.return||u===" ")&&(o(!0),hs[n].value==="sync"?e({watch:!0}):t())}}),Fe(()=>{s!==P.CONFLICTS&&i&&o(!1)},[s,i]),_(S,{flexDirection:"column",paddingTop:1,children:[m(S,{children:m(S,{flexDirection:"row",gap:2,children:m(v,{bold:!0,color:"white",children:"Conflicts with remote"})})}),m(S,{children:m(v,{color:"grey",children:"The remote workspace has changes that aren't in your local workspace:"})}),m(S,{marginTop:1,marginLeft:2,children:m(Vr,{isExpanded:a})}),_(S,{marginTop:2,flexDirection:"row",gap:1,children:[m(v,{color:"white",bold:!0,children:"What would you like to do?"}),m(v,{color:"grey",children:"[up/down, enter]"})]}),m(S,{children:i?_(S,{flexDirection:"row",gap:1,children:[m(An,{type:"dots"}),m(v,{color:"blue",bold:!0,children:"Syncing with remote..."})]}):m(S,{flexDirection:"column",children:hs.map((u,d)=>m(S,{flexDirection:"column",children:_(S,{flexDirection:"row",gap:1,children:[m(v,{color:n===d?"cyan":"grey",children:n===d?"\u25B6":" "}),m(v,{color:n===d?"cyan":"grey",bold:n===d,children:u.label})]})},u.value))})})]})}c(Pd,"ResolveChangesUI");const Rd={[$e.UPDATE]:{incoming:{label:"Elements updated in remote",description:"(to be overwritten from remote)"},outgoing:{label:"Elements updated locally",description:"(to be pushed to remote)"}},[$e.DELETE]:{incoming:{label:"Elements not existing in remote",description:"(to be deleted locally)"},outgoing:{label:"Elements deleted locally",description:"(to be deleted from remote)"}},[$e.CREATE]:{incoming:{label:"Elements created in remote",description:"(to be created locally)"},outgoing:{label:"Elements created locally",description:"(to be created in remote)"}}};function Vr({isExpanded:s,showControls:e=!0}){const{conflicts:t}=fe(),n=5,r=jc(()=>{const i={};return t.forEach(o=>{const a=`${o.type}-${o.direction}`;i[a]||(i[a]=[]),i[a].push(o)}),i},[t]);return m(S,{flexDirection:"column",children:Object.entries(r).map(([i,o])=>{if(o.length===0)return null;const[a,l]=i.split("-"),u=Rd[a][l];return _(S,{flexDirection:"column",children:[_(S,{flexDirection:"row",gap:1,children:[_(v,{color:"yellow",children:[u.label," (",o.length,")"]}),m(v,{color:"white",children:u.description})]}),(s?o:o.slice(0,n)).map(d=>m(S,{marginLeft:2,children:_(v,{color:"grey",children:["\u2022 ",d.element.id," (",d.element.relativePath,")"]})},d.element.id)),!s&&o.length>n&&m(S,{marginLeft:2,children:_(v,{color:"cyan",children:["... and ",o.length-n," more",e?" (press Ctrl+R to show all)":""]})}),s&&o.length>n&&e&&m(S,{marginLeft:2,children:m(v,{color:"cyan",children:"(press Ctrl+R to collapse)"})})]},i)})})}c(Vr,"Conflicts");function Md(){const{config:s,state:e,logs:t,currentWorkspace:n,pull:r}=fe(),i=n?.name,o=i?Ta(i,30):s?.workspaceKey,a=Math.min(100,process.stdout.columns||100);return Fe(()=>{r({watch:!0})},[]),_(S,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:a,children:[m(S,{marginTop:-1,marginBottom:1,children:_(S,{flexDirection:"row",gap:1,children:[m(v,{bold:!0,children:"\u{1F504} Workspace"}),_(v,{color:Dd(e),children:[" [",Ld(e),"] "]})]})}),_(S,{children:[m(S,{width:12,children:m(v,{color:"grey",children:"Local:"})}),m(v,{color:"grey",children:process.cwd()})]}),_(S,{children:[m(S,{width:12,children:m(v,{color:"grey",children:"Remote:"})}),s?.workspaceKey?_(v,{color:"grey",children:[o," [o: open in console] [w: change]"]}):_(v,{children:[m(v,{color:"yellow",children:"not selected"})," [w: select]"]})]}),e===P.CONFLICTS?m(Pd,{}):_(ut,{children:[m(S,{paddingTop:1,children:m(Jr,{})}),t.length>0&&m(xd,{})]})]})}c(Md,"Workspace");function Ld(s){switch(s){case P.PULLING:return"pulling";case P.PUSHING:return"pushing";case P.CONFLICTS:return"conflicts";case P.SYNCED:return"synced";case P.ERROR:return"error";case P.WATCHING:return"tracking changes";case P.RESOLVING:return"resolving";case P.NOT_SYNCED:return"not synced";case P.INITIALIZED:return"initialized";case P.SETTING_UP:return"setup required";default:return"unknown"}}c(Ld,"getStatusDisplay");function Dd(s){switch(s){case P.PULLING:return"yellow";case P.PUSHING:return"yellow";case P.CONFLICTS:return"red";case P.SYNCED:return"green";case P.ERROR:return"red";case P.WATCHING:return"green";case P.RESOLVING:return"yellow";case P.NOT_SYNCED:return"grey";case P.SETTING_UP:return"yellow";default:return"grey"}}c(Dd,"getStatusColor");const jd="https://console.integration.app/w";function Fd(){const s=Td(),e=Ws(!0),{exit:t,state:n}=fe(),[r,i]=J(null),o=r??(n===P.SETTING_UP?"setup":"main");Xe(l=>{o==="main"&&(l==="w"&&i("workspace-selection"),l==="a"&&i("add-mcp-server"),l==="o"&&n===P.INITIALIZED&&a(),l==="s"&&i("setup"))});async function a(){try{const l=await Fi(s),u=`${jd}/${l}`,d=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";ol(`${d} "${u}"`)}catch(l){console.error("Failed to open workspace:",l),t()}}return c(a,"handleOpenWorkspace"),Fe(()=>(e.current=!0,()=>{e.current=!1}),[]),o==="workspace-selection"?m(Ea,{onExit:c(()=>i(null),"onExit")}):o==="add-mcp-server"?m(Ed,{onExit:c(()=>i(null),"onExit"),onComplete:c(()=>i(null),"onComplete")}):o==="setup"?m(_a,{onComplete:c(()=>i(null),"onComplete")},Date.now()):m(Ur,{children:_(S,{flexDirection:"column",children:[m(S,{flexGrow:1,children:m(Id,{})}),m(Md,{}),m(S,{paddingLeft:2,children:m(v,{color:"grey",children:"[s: (re-)setup]"})})]})})}c(Fd,"Main");const qd=c(()=>[k.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"),k.yellow("\u2502 \u26A0\uFE0F EXPERIMENTAL FEATURE WARNING \u2502"),k.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"),k.yellow("\u2502 Real-time agent mode is experimental and subject to changes. \u2502"),k.yellow("\u2502 Use in production environments is not recommended. \u2502"),k.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(`
|
|
142
142
|
`),"createExperimentalWarning$2"),on=Lc(process.argv.slice(2)),Ia=on.cwd?Pc(on.cwd):process.cwd(),Kd=new Ca(nn.Agent,Ia);if(on.verbose&&b.setVerboseMode(!0),on.rps!==void 0){const s=parseInt(on.rps,10);!isNaN(s)&&s>0&&s<=1e3?B.init({maxRequestsPerSecond:s}):isNaN(s)||(b.error(`Invalid RPS value: ${s}. Must be between 1 and 1000.`),process.exit(1))}const Bd=c(()=>m(sn,{cwd:Ia,membraneCLIService:Kd,children:m(Fd,{})}),"App");function Ud(){console.warn(qd()),Ut(m(Bd,{}))}c(Ud,"runAgent");function it(s){if(s.type){if(Array.isArray(s.type))return{anyOf:s.type.map(t=>it({...s,type:t}))};if(s.type==="array"){const t={type:"array",items:s.items?it(s.items):{type:"object"}};return s.title&&(t.title=s.title),s.description&&(t.description=s.description),s.minItems!==void 0&&(t.minItems=s.minItems),s.maxItems!==void 0&&(t.maxItems=s.maxItems),s.uniqueItems!==void 0&&(t.uniqueItems=s.uniqueItems),t}}const e={};if(s.type&&!Array.isArray(s.type)&&(e.type=s.type),s.title&&(e.title=s.title),s.description&&(e.description=s.description),s.format&&(e.format=s.format),s.enum&&(e.enum=s.enum),s.default!==void 0&&(e.default=s.default),s.minimum!==void 0&&(e.minimum=s.minimum),s.maximum!==void 0&&(e.maximum=s.maximum),s.minLength!==void 0&&(e.minLength=s.minLength),s.maxLength!==void 0&&(e.maxLength=s.maxLength),s.maxItems!==void 0&&(e.maxItems=s.maxItems),s.readOnly!==void 0&&(e.readOnly=s.readOnly),s.writeOnly!==void 0&&(e.writeOnly=s.writeOnly),s.examples&&s.examples.length>0&&(e.example=s.examples[0]),s.properties){e.properties={};for(const[t,n]of Object.entries(s.properties))e.properties[t]=it(n)}return s.anyOf&&(e.anyOf=s.anyOf.map(it)),s.additionalProperties!==void 0&&(typeof s.additionalProperties=="boolean"?e.additionalProperties=s.additionalProperties:e.additionalProperties=it(s.additionalProperties)),s.required&&(e.required=s.required),e}c(it,"convertDataSchemaToOpenAPI");function Wd(s){const{membraneInterfaces:{actions:e}}=s,t=Jd(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)}c(Wd,"generateOpenAPIContent");function Jd(s){const e={};return s.forEach(t=>{const n=Xs(Ys(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=it(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"]},o=t?.customOutputSchema||t?.outputSchema;if(o){const a=it(o);i.properties={...i.properties,data:a}}e[`${n}Response`]=i}),e}c(Jd,"generateOpenAPISchemas");function Hd(s){const{membraneInterfaces:{actions:e}}=s,t=hl(e,"key"),n=new fl({indentNumberOfSpaces:2,newLine:`
|
|
143
143
|
`});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(),Vd(n,t),n.toString()}c(Hd,"generateTypeScriptContent");function Vd(s,e){s.writeLine('declare module "@membranehq/sdk" {'),s.indent(()=>{e.forEach(t=>{const n=zr(t),r=t?.inputSchema;ps(s,{interfaceName:n,properties:r?.properties,required:r?.required||[]});const i=Yr(t),o=t?.customOutputSchema||t?.outputSchema;ps(s,{interfaceName:i,properties:o?.properties,required:o?.required||[],fallbackContent:"result: unknown"}),s.newLine()}),ps(s,{interfaceName:"MembraneClient",methods:e.map(t=>{const n=zr(t),r=Yr(t);return{name:"action",parameters:`selector: "${t.key}"`,returnType:`ActionAccessor<${n}, ${r}>`}})}),s.newLine(),ps(s,{interfaceName:"ConnectionAccessor",methods:e.map(t=>{const n=zr(t),r=Yr(t);return{name:"action",parameters:`selector: "${t.key}"`,returnType:`ConnectionLevelActionAccessor<${n}, ${r}>`}})})}),s.writeLine("}")}c(Vd,"generateModuleAugmentation");function ps(s,e){const{interfaceName:t,properties:n,required:r=[],methods:i,fallbackContent:o}=e;s.writeLine(`interface ${t} {`),s.indent(()=>{n&&Object.keys(n).length>0&&Gd(s,n,r),i&&i.length>0&&(n&&Object.keys(n).length>0&&s.newLine(),i.forEach((a,l)=>{s.writeLine(`${a.name}(${a.parameters}): ${a.returnType};`),l<i.length-1&&s.newLine()})),o&&(!n||Object.keys(n).length===0)&&(!i||i.length===0)&&s.writeLine(o)}),s.writeLine("}")}c(ps,"generateTypeScriptInterface");function Gd(s,e,t){Object.entries(e).forEach(([n,r])=>{const o=t.includes(n)?"":"?",a=Gr(r);s.writeLine(`readonly ${n}${o}: ${a}`)})}c(Gd,"generateTypeScriptProperties");function Gr(s){return s.type==="string"?s.enum?s.enum.map(e=>`'${e}'`).join(" | "):"string":s.type==="number"||s.type==="integer"?"number":s.type==="boolean"?"boolean":s.type==="array"?`${s.items?Gr(s.items):"unknown"}[]`:s.type==="object"?s.properties?`{ ${Object.entries(s.properties).map(([t,n])=>{const i=(s.required||[]).includes(t)?"":"?",o=Gr(n);return`readonly ${t}${i}: ${o}`}).join("; ")} }`:"Record<string, unknown>":"unknown"}c(Gr,"convertJsonSchemaToTypeScript");function zr(s){return`${Xs(Ys(s.key))}Input`}c(zr,"getInputTypeName");function Yr(s){return`${Xs(Ys(s.key))}Output`}c(Yr,"getOutputTypeName");async function Xr(s){const{out:e}=s;await L.promises.mkdir(e,{recursive:!0});const t=zd(s);for(const[n,r]of Object.entries(t)){const i=K.join(e,n);await L.promises.writeFile(i,r,"utf-8")}}c(Xr,"generateCode");function zd(s){switch(s.target){case"openapi":return{"openapi.json":Wd(s)};case"typescript":return{"generated.d.ts":Hd(s)};default:throw new Error(`Unsupported target: ${s.target}`)}}c(zd,"generateContent");const Qr=c(()=>[k.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"),k.yellow("\u2502 \u26A0\uFE0F EXPERIMENTAL FEATURE WARNING \u2502"),k.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"),k.yellow("\u2502 The codegen command is experimental and subject to rapid changes.\u2502"),k.yellow("\u2502 Features, APIs, and file structures may change without notice. \u2502"),k.yellow("\u2502 Use in production environments is not recommended. \u2502"),k.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(`
|
|
144
144
|
`),"createExperimentalWarning$1");function Yd(s,e){s.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",Qr()).addHelpText("after",["",k.bold("Examples:"),` ${k.gray("\u25B8")} ${k.cyan("membrane codegen --actions list-files,get-file-by-id --out src/generated --target openapi --schemasOnly")}`,` ${k.gray("\u25B8")} ${k.cyan("membrane install --actions delete-file --out src/generated --target typescript --schemasOnly")}`,"",Qr()].join(`
|
|
145
|
-
`)).action(async t=>{try{console.warn(Qr()),console.error(k.cyan("\u{1F527} Membrane Codegen")),console.error("Status: Loading membrane interfaces...");const n=await Xd(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 Xr(r),console.error(k.green("\u2705 Code generation completed successfully!")),process.exit(0)}catch(n){console.error(k.red("\u274C Code generation failed:")),console.error(n instanceof Error?n.message:"Unknown error occurred"),process.exit(1)}})}c(Yd,"setupCodegenCommand");async function Xd(s,e){return await s.fetchElements(),{actions:[...s.getSyncedElementsByType(
|
|
145
|
+
`)).action(async t=>{try{console.warn(Qr()),console.error(k.cyan("\u{1F527} Membrane Codegen")),console.error("Status: Loading membrane interfaces...");const n=await Xd(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 Xr(r),console.error(k.green("\u2705 Code generation completed successfully!")),process.exit(0)}catch(n){console.error(k.red("\u274C Code generation failed:")),console.error(n instanceof Error?n.message:"Unknown error occurred"),process.exit(1)}})}c(Yd,"setupCodegenCommand");async function Xd(s,e){return await s.fetchElements(),{actions:[...s.getSyncedElementsByType(N.Action).map(t=>t.data)].filter(t=>e.actions.includes(t.key||""))}}c(Xd,"loadMembraneInterfaces");const Zr=Bs(null),Aa=c(()=>{const s=Us(Zr);if(!s)throw new Error("useTree must be used within TreeView");return s},"useTree"),Qd=c(s=>Ae.Children.count(s)>0,"hasChildren");function Zd(s){const e=Aa(),{label:t,value:n,isInitiallyExpanded:r}=s,i=Fc(),o=Ws(e.registerChildItem(t)).current,a=e.isActiveByRef(o),[l,u]=J(r??!1),d={props:s,ref:o,id:i,active:a,expanded:l,setExpanded:u,label:t,value:n,isInitiallyExpanded:r,isParent:!1},{children:f}=s,h=typeof f=="function"?f(d):f;return{...d,props:{...s,children:h},isParent:Qd(h)}}c(Zd,"useTreeItem");function Pt(s){const e=Aa(),t=Zd(s),{expanded:n,isParent:r,props:{children:i},setExpanded:o}=t,{renderValue:a=tf}=s,l=t.ref;_n(()=>{function h(g){return s.onInput?.(g)?!0:g.active&&g.key.rightArrow&&!n?(o(!0),!0):g.active&&g.key.leftArrow&&n?(o(!1),!0):!1}c(h,"onInput"),l.onInput=h},[l,s.onInput,n,o]),l.firstChild??={parent:l,index:0};let u=l.firstChild;function d(h){const g=u;return g.nextSibling||(g.nextSibling={parent:l,prevSibling:g,index:g.index+1}),u=g.nextSibling,g.label=h,g}c(d,"registerChildItem");function f(){l.lastRenderedChild=u.prevSibling}return c(f,"commitChildren"),_n(()=>{f()}),_(ut,{children:[_(S,{marginLeft:e.depth*2,children:[m(S,{width:2,children:r&&m(v,{children:n?"\u25BC":"\u25B6"})}),ef(t),a(t)]}),n&&m(Zr.Provider,{value:{...e,depth:e.depth+1,registerChildItem:d},children:i})]})}c(Pt,"TreeItem");function ef({active:s,label:e}){return m(S,{width:32,children:m(v,{inverse:s,children:e})})}c(ef,"defaultRenderLabel");function tf(s){return m(v,{})}c(tf,"defaultRenderValue");const ot=c(({label:s,onPress:e,hotkey:t})=>m(Pt,{label:s,onInput:c(({input:n,key:r,active:i})=>i&&r.return||t&&t in r&&r[t]||n===t?(e(),!0):!1,"onInput"),renderValue:c(()=>m(S,{children:m(v,{children:`${t?` (${t})`:""}`})}),"renderValue")}),"ActionTreeItem"),Oa=c(({label:s,value:e,onChange:t,disabled:n=!1,mask:r,...i})=>{const[o,a]=J(e),[l,u]=J(!1);return _n(()=>{l||a(e)},[l,e]),m(Pt,{label:s,value:e,onInput:c(({key:d,active:f})=>n?!1:l?(d.escape&&u(!1),d.return&&(t(o),u(!1)),!0):f&&d.return?(u(!0),a(e),!0):!1,"onInput"),renderValue:c(()=>{const d=o,f=r?r.repeat(d.length):d;return m(S,{children:n||!l?m(v,{dimColor:!0,children:f}):_(ut,{children:[m(S,{width:f.length+1,children:m(Ni,{...i,focus:l,value:d,onChange:a})}),m(v,{dimColor:!0,children:" \u241B cancel"})]})})},"renderValue")})},"TreeTextField"),nf=c(s=>m(Oa,{...s,mask:"*"}),"SecretField"),ye=c(({children:s,showHelp:e=!1})=>{const t=Ws({parent:void 0,label:"<<ROOT>>",index:0}),[n,r]=J(t.current),i={depth:0,isActiveByRef:c(a=>n===a,"isActiveByRef"),registerChildItem:c(()=>t.current,"registerChildItem"),activeItemRef:n};_n(()=>{r(a=>a.parent?a.parent.lastRenderedChild&&a.index>a.parent.lastRenderedChild.index?a.parent.lastRenderedChild:a:t.current.firstChild??t.current)});function*o(a){a&&(yield a,yield*o(a.firstChild),a.nextSibling&&a!==a.parent?.lastRenderedChild&&(yield*o(a.nextSibling)))}return c(o,"walkTree"),Xe((a,l)=>{if(n.onInput?.({input:a,key:l,active:!0}))return;let u,d;for(const f of o(t.current))if(f.label!=null){if(u===n&&(d=f),f&&f.onInput?.({input:a,key:l,active:f===n}))return;u=f}l.upArrow?r(f=>f.prevSibling?.lastRenderedChild??f.prevSibling??f.parent??t.current):l.downArrow?r(f=>d??f):l.pageUp?r(()=>t.current.firstChild??t.current):l.pageDown?r(()=>t.current.lastRenderedChild??t.current):l.tab?console.log({label:n.label,nextSibling:n.nextSibling?.label,prevSibling:n.prevSibling?.label,parent:n.parent?.label,firstChild:n.firstChild?.label,lastRenderedChild:n.lastRenderedChild?.label}):l.leftArrow?r(f=>f.parent??t.current):l.rightArrow&&r(f=>f.lastRenderedChild?f.firstChild:f)}),m(Zr.Provider,{value:i,children:_(S,{flexDirection:"column",children:[m(Pt,{isInitiallyExpanded:!0,label:"rootItem",children:s}),e&&m(S,{marginTop:1,flexDirection:"column",children:m(v,{dimColor:!0,children:"\u2191/\u2193 move \u2022 \u2190 collapse \u2022 \u2192 expand \u2022 Enter/Space select/edit \u2022 Esc exit"})})]})})},"TreeView");ye.Item=Pt,ye.TextField=Oa;function at({label:s,elementType:e,isActionExcluded:t,toggleAction:n,generateCode:r}){const[i,o]=J([]),{fetchElements:a,getSyncedElementsByType:l}=fe();return Fe(()=>{c(async()=>{try{await a();const d=l(e);o(d.map(f=>f.data))}catch(d){console.error(String(d))}},"loadElements")()},[e,a,l,o]),m(Pt,{label:s,children:i.map(u=>m(Pt,{label:u.name,children:e===N.Action&&_(ut,{children:[t&&n&&m(ot,{label:`Toggle ${t(u)?"":"(excluded)"}`,onPress:c(()=>{n(u)},"onPress")}),r&&m(ot,{label:"Generate code",onPress:c(()=>{r?.(u)},"onPress")})]})},u.id))})}c(at,"WorkspaceElementsTreeItem");function sf({onComplete:s}){const{config:e,updateConfig:t,fetchElements:n,getSyncedElementsByType:r}=fe(),[i,o]=J(""),a=e,l=c(h=>{o(h),setTimeout(()=>o(""),2e3)},"setFlash"),u=c(async(h,g)=>{try{await t({[h]:g}),l("\u2705 Configuration updated!")}catch{l("\u274C Error updating configuration")}},"updateField"),d=c(async()=>{try{if(e){const h=Qe.saveToFile(e);l(h?"\u2705 Configuration saved successfully!":"\u274C Failed to save configuration"),await n();const g=r(N.Action);await Xr({out:a?.outputDir??"",target:a?.projectType??"typescript",schemasOnly:!1,membraneInterfaces:{actions:g.filter(y=>!a?.excludedActionKeys?.includes(y.key)).map(y=>y.data)}}),l("\u2705 Code generated successfully!")}}catch{l("\u274C Error saving configuration")}},"handleSaveConfig"),f=c(async()=>{try{const h=Qe.loadConfig();h?(await t(h),l("\u2705 Configuration reloaded successfully!")):l("\u274C No configuration found to reload")}catch{l("\u274C Error reloading configuration")}},"handleReloadConfig");return _(S,{flexDirection:"column",gap:1,children:[m(v,{bold:!0,color:"cyan",children:"\u2699\uFE0F Membrane Configuration Manager"}),m(S,{paddingX:2,children:_(ye,{showHelp:!0,children:[_(ye.Item,{label:"Configuration",isInitiallyExpanded:!0,children:[_(ye.Item,{label:"Project",children:[m(ye.TextField,{label:"Workspace Key",value:a?.workspaceKey??"",onChange:c(h=>u("workspaceKey",h),"onChange"),disabled:!0}),m(nf,{label:"Workspace Secret",value:a?.workspaceSecret??"",onChange:c(h=>u("workspaceSecret",h),"onChange"),disabled:!0}),m(ye.TextField,{label:"API URI",value:a?.apiUri??"",onChange:c(h=>u("apiUri",h),"onChange")}),m(ye.TextField,{label:"Test Customer ID",value:a?.testCustomerId??"",onChange:c(h=>u("testCustomerId",h),"onChange")})]}),_(ye.Item,{label:"Code Generation",isInitiallyExpanded:!0,children:[_(ye.Item,{label:"Project Type",isInitiallyExpanded:!0,value:a?.projectType,renderValue:c(({value:h})=>m(v,{children:h==="typescript"?"TypeScript":h==="openapi"?"OpenAPI":"(Not set)"}),"renderValue"),children:[m(ot,{label:"Update to TypeScript",onPress:c(()=>u("projectType","typescript"),"onPress")}),m(ot,{label:"Update to OpenAPI",onPress:c(()=>u("projectType","openapi"),"onPress")})]}),m(ye.TextField,{label:"Project dir",value:a?.outputDir??"",onChange:c(h=>u("outputDir",h),"onChange")})]}),_(ye.Item,{label:"Workspace Elements",children:[m(at,{label:"Actions",elementType:N.Action,isActionExcluded:c(h=>a?.excludedActionKeys?.includes(h.key)??!1,"isActionExcluded"),toggleAction:c(h=>u("excludedActionKeys",[...a?.excludedActionKeys??[],h.key]),"toggleAction"),generateCode:c(h=>{(async()=>{try{await Xr({out:a?.outputDir??"",target:a?.projectType??"typescript",schemasOnly:!1,membraneInterfaces:{actions:[h]}}),l("\u2705 Code generated successfully!")}catch{l("\u274C Error generating code")}})()},"generateCode")}),m(at,{label:"Flows",elementType:N.Flow}),m(at,{label:"Data Sources",elementType:N.DataSource}),m(at,{label:"Field Mappings",elementType:N.FieldMapping}),m(at,{label:"Packages",elementType:N.Package}),m(at,{label:"App Data Schemas",elementType:N.AppDataSchema}),m(at,{label:"App Event Types",elementType:N.AppEventType})]})]}),m(ot,{label:"Save Configuration",onPress:d,hotkey:"s"}),m(ot,{label:"Reload Configuration",onPress:f,hotkey:"r"}),m(ot,{label:"Exit",onPress:c(()=>s?.(),"onPress"),hotkey:"escape"})]})}),i&&m(S,{paddingX:2,children:m(v,{color:i.includes("\u2705")?"green":"red",children:i})})]})}c(sf,"ConfigManager");function rf(s,e){s.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(`
|
|
146
146
|
`)).action(()=>{Ut(Ae.createElement(sn,{membraneCLIService:e,children:Ae.createElement(sf,{onComplete:c(()=>process.exit(0),"onComplete")})}))})}c(rf,"setupConfigCommand");function of(s,e){s.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(`
|
|
147
|
-
`)).action(t=>{t.key&&t.secret?Qe.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)):Ut(Ae.createElement(sn,{membraneCLIService:e,children:Ae.createElement(_a,{onComplete:c(()=>process.exit(0),"onComplete")})}))})}c(of,"setupInitCommand");async function $a(s,e,t){const n={iss:s,exp:Math.floor(Date.now()/1e3)+600,isAdmin:!0};return t&&(n.id=t),zs.sign(n,e)}c($a,"generateMcpAccessToken");async function af(s,e){return(await Qs.get(`${s}/docs-json`,{headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}})).data}c(af,"fetchOpenApiSchema");function Ve(s,e=!0,t,n=new Set){if(!s)return e?W.string():W.string().optional();if(Object.keys(s).length===0)return e?W.any():W.any().optional();if(s.$ref){const i=s.$ref.replace("#/components/schemas/","");if(n.has(i))return W.any();if(n.add(i),t?.schemas?.[i]){const o=t.schemas[i];return Ve(o,e,t,n)}return W.any()}let r;if(s.type==="object"||s.properties){const i={};if(s.properties)for(const[o,a]of Object.entries(s.properties)){const l=s.required?.includes(o)??!1;i[o]=Ve(a,l,t,n)}if(Object.keys(i).length>0){if(r=W.object(i),s.additionalProperties)if(typeof s.additionalProperties=="object"){const o=Ve(s.additionalProperties,!1,t,n);r=r.catchall(o)}else s.additionalProperties===!0&&(r=r.passthrough())}else if(s.additionalProperties&&typeof s.additionalProperties=="object"){const o=Ve(s.additionalProperties,!1,t,n);r=W.record(W.string(),o)}else r=W.record(W.string(),W.any())}else if(s.type==="array"){const i=s.items?Ve(s.items,!0,t,n):W.any();r=W.array(i)}else if(s.anyOf)r=W.any();else{switch(s.type){case"integer":r=W.coerce.number().int();break;case"number":r=W.coerce.number();break;case"boolean":r=W.coerce.boolean();break;case"string":default:r=W.string();break}s.format==="uuid"?r=W.string().uuid():s.format==="email"?r=W.string().email():s.format==="date"?r=W.string().regex(/^\d{4}-\d{2}-\d{2}$/):s.format==="date-time"&&(r=W.string().datetime()),s.enum&&(r=W.enum(s.enum)),(s.type==="integer"||s.type==="number")&&(s.minimum!==void 0&&(r=r.min(s.minimum)),s.maximum!==void 0&&(r=r.max(s.maximum))),s.type==="string"&&(s.minLength!==void 0&&(r=r.min(s.minLength)),s.maxLength!==void 0&&(r=r.max(s.maxLength)))}return e?r:r.optional()}c(Ve,"convertOpenApiSchemaToZod");function Na(s){const e=s.match(/\{([^}]+)\}/g);return e?e.map(t=>t.slice(1,-1)):[]}c(Na,"extractPathParameters");function cf(s,e,t,n,r,i,o,a){const l=s.operationId||`${t}_${e.replace(/[^a-zA-Z0-9]/g,"_")}`,u=s.description||s.summary||`${t.toUpperCase()} ${e}`,d={},f={},h={};if(s.parameters){for(const y of s.parameters)if(y.in==="path")f[y.name]=Ve(y.schema,!0,o).describe(y.description||`Path parameter: ${y.name}`);else if(y.in==="query"){const p=y.required===!0;h[y.name]=Ve(y.schema,p,o).describe(y.description||`Query parameter: ${y.name}`)}}if(Object.keys(f).length>0&&(d.params=W.object(f).describe("Path parameters")),Object.keys(h).length>0&&(d.query=W.object(h).describe("Query parameters")),s.requestBody&&s.requestBody.content){const y=s.requestBody.required===!0;if(s.requestBody.content["application/json"]){const p=s.requestBody.content["application/json"].schema;p?d.body=Ve(p,y,o).describe("Request body (JSON)"):d.body=W.any().describe("Request body (JSON)")}else s.requestBody.content["application/octet-stream"]||s.requestBody.content["text/plain"]?d.body=y?W.string().describe("Request body (binary/text)"):W.string().optional().describe("Request body (binary/text)"):d.body=W.any().describe("Request body")}const g=Object.keys(d).length>0?W.object(d):W.object({});return{name:l,description:u,parameters:g,async execute(y){try{const p=Na(e);if(p.length>0){if(!y.params)throw new Error(`Missing required path parameters: ${p.join(", ")}`);const
|
|
147
|
+
`)).action(t=>{t.key&&t.secret?Qe.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)):Ut(Ae.createElement(sn,{membraneCLIService:e,children:Ae.createElement(_a,{onComplete:c(()=>process.exit(0),"onComplete")})}))})}c(of,"setupInitCommand");async function $a(s,e,t){const n={iss:s,exp:Math.floor(Date.now()/1e3)+600,isAdmin:!0};return t&&(n.id=t),zs.sign(n,e)}c($a,"generateMcpAccessToken");async function af(s,e){return(await Qs.get(`${s}/docs-json`,{headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}})).data}c(af,"fetchOpenApiSchema");function Ve(s,e=!0,t,n=new Set){if(!s)return e?W.string():W.string().optional();if(Object.keys(s).length===0)return e?W.any():W.any().optional();if(s.$ref){const i=s.$ref.replace("#/components/schemas/","");if(n.has(i))return W.any();if(n.add(i),t?.schemas?.[i]){const o=t.schemas[i];return Ve(o,e,t,n)}return W.any()}let r;if(s.type==="object"||s.properties){const i={};if(s.properties)for(const[o,a]of Object.entries(s.properties)){const l=s.required?.includes(o)??!1;i[o]=Ve(a,l,t,n)}if(Object.keys(i).length>0){if(r=W.object(i),s.additionalProperties)if(typeof s.additionalProperties=="object"){const o=Ve(s.additionalProperties,!1,t,n);r=r.catchall(o)}else s.additionalProperties===!0&&(r=r.passthrough())}else if(s.additionalProperties&&typeof s.additionalProperties=="object"){const o=Ve(s.additionalProperties,!1,t,n);r=W.record(W.string(),o)}else r=W.record(W.string(),W.any())}else if(s.type==="array"){const i=s.items?Ve(s.items,!0,t,n):W.any();r=W.array(i)}else if(s.anyOf)r=W.any();else{switch(s.type){case"integer":r=W.coerce.number().int();break;case"number":r=W.coerce.number();break;case"boolean":r=W.coerce.boolean();break;case"string":default:r=W.string();break}s.format==="uuid"?r=W.string().uuid():s.format==="email"?r=W.string().email():s.format==="date"?r=W.string().regex(/^\d{4}-\d{2}-\d{2}$/):s.format==="date-time"&&(r=W.string().datetime()),s.enum&&(r=W.enum(s.enum)),(s.type==="integer"||s.type==="number")&&(s.minimum!==void 0&&(r=r.min(s.minimum)),s.maximum!==void 0&&(r=r.max(s.maximum))),s.type==="string"&&(s.minLength!==void 0&&(r=r.min(s.minLength)),s.maxLength!==void 0&&(r=r.max(s.maxLength)))}return e?r:r.optional()}c(Ve,"convertOpenApiSchemaToZod");function Na(s){const e=s.match(/\{([^}]+)\}/g);return e?e.map(t=>t.slice(1,-1)):[]}c(Na,"extractPathParameters");function cf(s,e,t,n,r,i,o,a){const l=s.operationId||`${t}_${e.replace(/[^a-zA-Z0-9]/g,"_")}`,u=s.description||s.summary||`${t.toUpperCase()} ${e}`,d={},f={},h={};if(s.parameters){for(const y of s.parameters)if(y.in==="path")f[y.name]=Ve(y.schema,!0,o).describe(y.description||`Path parameter: ${y.name}`);else if(y.in==="query"){const p=y.required===!0;h[y.name]=Ve(y.schema,p,o).describe(y.description||`Query parameter: ${y.name}`)}}if(Object.keys(f).length>0&&(d.params=W.object(f).describe("Path parameters")),Object.keys(h).length>0&&(d.query=W.object(h).describe("Query parameters")),s.requestBody&&s.requestBody.content){const y=s.requestBody.required===!0;if(s.requestBody.content["application/json"]){const p=s.requestBody.content["application/json"].schema;p?d.body=Ve(p,y,o).describe("Request body (JSON)"):d.body=W.any().describe("Request body (JSON)")}else s.requestBody.content["application/octet-stream"]||s.requestBody.content["text/plain"]?d.body=y?W.string().describe("Request body (binary/text)"):W.string().optional().describe("Request body (binary/text)"):d.body=W.any().describe("Request body")}const g=Object.keys(d).length>0?W.object(d):W.object({});return{name:l,description:u,parameters:g,async execute(y){try{const p=Na(e);if(p.length>0){if(!y.params)throw new Error(`Missing required path parameters: ${p.join(", ")}`);const x=p.filter(D=>!(D in y.params));if(x.length>0)throw new Error(`Missing required path parameters: ${x.join(", ")}`)}let w=`${n}${e}`;if(y.params)for(const[x,D]of Object.entries(y.params)){const A=`{${x}}`;w.includes(A)&&(w=w.replace(A,String(D)))}const T=Na(w);if(T.length>0)throw new Error(`Unresolved path parameters: ${T.join(", ")}`);const E=new URLSearchParams;if(y.query)for(const[x,D]of Object.entries(y.query))D!=null&&E.append(x,String(D));E.toString()&&(w+=`?${E.toString()}`);const O=await $a(r,i,a),I={method:t.toUpperCase(),headers:{Authorization:`Bearer ${O}`}};y.body&&t.toLowerCase()!=="get"&&(s.requestBody?.content?.["application/json"]?(I.headers["Content-Type"]="application/json",I.data=y.body):s.requestBody?.content?.["application/octet-stream"]?(I.headers["Content-Type"]="application/octet-stream",I.data=y.body):s.requestBody?.content?.["text/plain"]?(I.headers["Content-Type"]="text/plain",I.data=y.body):(I.headers["Content-Type"]="application/json",I.data=y.body));const $=await Qs.request({url:w,...I});return{content:[{type:"text",text:$.data===""?"":JSON.stringify($.data,null,2)}]}}catch(p){return Qs.isAxiosError(p)?{content:[{type:"text",text:`Error: ${p.response?.data?`HTTP ${p.response.status}: ${p.response.statusText} - ${JSON.stringify(p.response.data)}`:`HTTP ${p.response?.status||"unknown"}: ${p.message}`}`}],isError:!0}:p instanceof Error?{content:[{type:"text",text:`Error: API call failed: ${p.message}`}],isError:!0}:{content:[{type:"text",text:"Error: API call failed with unknown error"}],isError:!0}}}}}c(cf,"createApiTool");function lf(s,e,t,n,r){const i=[];if(!s.paths)return i;const o=s.components||{};for(const[a,l]of Object.entries(s.paths))if(typeof l=="object"&&l!==null){for(const[u,d]of Object.entries(l))if(["get","post","put","delete","patch"].includes(u)&&d&&typeof d=="object"){const f=cf(d,a,u,e,t,n,o,r);i.push(f)}}return i}c(lf,"convertOpenApiToTools");function uf(s){s.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(`
|
|
148
148
|
`)).action(async()=>{try{process.env.FASTMCP_SUPPRESS_WARNINGS="true";const e=On();e||(console.error("No configuration found. Please set MEMBRANE_WORKSPACE_KEY and MEMBRANE_WORKSPACE_SECRET environment variables, or run `membrane init` first."),process.exit(1)),(!e.workspaceKey||!e.workspaceSecret)&&(console.error("Missing workspace credentials. Please provide them in the configuration file, command line, or environment variables."),process.exit(1));const t=e.apiUri||er,n=await $a(e.workspaceKey,e.workspaceSecret,e.testCustomerId),r=await af(t,n),i=lf(r,t,e.workspaceKey,e.workspaceSecret,e.testCustomerId),o=new pl({name:"Membrane API",instructions:`This MCP server lets you interact with Membrane to configure, run, and troubleshoot integrations.
|
|
149
149
|
Use it for anything related to Membrane or integrations.
|
|
150
150
|
`,version:"1.0.0"});for(const u of i){const d=u.execute;u.execute=async f=>(Cd(process.pid,process.cwd()),d(f)),o.addTool(u)}Fr({isRunning:!0,startTime:new Date().toISOString(),toolsCount:i.length,lastActivity:new Date().toISOString(),processId:process.pid,cwd:process.cwd(),agentName:process.env.AGENT_NAME||"Unnamed Agent"});const a=setInterval(()=>{Fr({processId:process.pid,cwd:process.cwd(),lastActivity:new Date().toISOString()})},5e3),l=c(async()=>{clearInterval(a),tn(process.pid,process.cwd());try{await o.stop()}catch{}},"cleanup");await o.start({transportType:"stdio"}),process.on("SIGINT",async()=>{await l(),process.exit(0)}),process.on("SIGTERM",async()=>{await l(),process.exit(0)}),process.on("exit",()=>{tn(process.pid,process.cwd())}),process.on("uncaughtException",async u=>{console.error("Uncaught exception:",u.message),await l(),process.exit(1)}),process.on("unhandledRejection",async u=>{console.error("Unhandled rejection:",u),await l(),process.exit(1)})}catch(e){e instanceof Error&&(console.error(e.message),process.exit(1)),console.error("An unknown error occurred"),process.exit(1)}})}c(uf,"setupMcpCommand");const df={info:"\u{1F4DD}",success:"\u2728",warning:"\u26A0\uFE0F",error:"\u274C",debug:"\u{1F50D}"},ff={info:k.blue,success:k.green,warning:k.yellow,error:k.red,debug:k.gray};class Z{static{c(this,"Logger")}static formatMessage(e,t,n={}){const r=n.timestamp?`${k.gray(new Date().toISOString())} `:"",i=n.prefix?`${k.gray(n.prefix)} `:"",o=n.suffix?` ${k.gray(n.suffix)}`:"",a=df[t],l=ff[t];return`${r}${a} ${i}${l(e)}${o}`}static info(e,t){let n=k.blue;if(t?.color&&(n=k[t.color.toLowerCase()]||k.blue),t?.timestamp){const r=new Date().toLocaleTimeString();console.debug(`${k.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.error(this.formatMessage(e,"error",t))}static debug(e,t){t?.prefix?console.debug(k.gray(`[${t.prefix}] ${e}`),t.error?`
|