@membranehq/cli
Version:
A command-line interface for working with Membrane in your local development environment.
4 lines • 326 kB
JavaScript
#!/usr/bin/env node
var $c=Object.defineProperty;var c=(s,e)=>$c(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 Nc,dirname as xc}from"node:path";import{useInput as Xe,Box as S,Text as v,Newline as Pc,render as Ut}from"ink";import Rc from"minimist";import{SWRConfig as Mc}from"swr";import Ae,{createContext as Bs,useState as J,useEffect as Fe,useContext as Us,useMemo as Lc,useRef as Ws,useId as Dc,useLayoutEffect as _n}from"react";import Ei from"swr/immutable";import _i from"os";import U from"path";import jc from"conf";import{MembraneConfigLoader as Fc,MembraneAxiosInstance as qc,MembraneClient as Ii,WorkspaceElementType as x,WorkspaceElementSpecs as qe,WorkspaceSyncEventType as Kc,ConnectorFileUpdateType as Js,setValueAtLocator as Hs,extractMembraneErrorData as Te,getDataCollectionCreateFields as Vs,excludeWriteOnlyFieldsFromSchema as Ai,valueToSchema as In,getRequiredFieldsFromSchema as Bc,getValueAtLocator as Uc,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 Wc,writeFileSync as Jc,readFileSync as Hc}from"node:fs";import{EventEmitter as Vc}from"events";import Gc from"lodash/isEqual.js";import Wt from"js-yaml";import*as zc from"node:crypto";import{createHash as Yc}from"node:crypto";import Xc from"chokidar";import{EventSource as Qc}from"eventsource";import F from"fs";import Zc from"archiver";import el from"form-data";import tl from"unzipper";import*as nl from"node:os";import{exec as sl}from"node:child_process";import{Spinner as rl,TextInput as il,Select as ol}from"@inkjs/ui";import An from"ink-spinner";import Ni from"ink-text-input";import{fileURLToPath as al}from"node:url";import T from"chalk";import{Command as cl}from"commander";import Ys from"lodash/camelCase.js";import Xs from"lodash/upperFirst.js";import ll from"code-block-writer";import ul from"lodash/uniqBy.js";import"node:events";import{FastMCP as dl}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 fl from"lodash/template.js";import hl from"lodash/templateSettings.js";const pl="membrane",ml="membrane.config.yml",er="https://api.integration.app";function tr(){const s=process.cwd(),e=K.join(s,pl),t=K.join(s,ml),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 gl={pat:{type:"string"},workspace:{type:"object"}},Pi=new jc({schema:gl,configName:"config",cwd:U.join(_i.homedir(),".membrane")}),yl=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 wl=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 Fc}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 Vc{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 bl 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 bl({heartbeatIntervalMs:15e3}),Sl="membrane",Cl=["**/node_modules/**","**/.git/**","**/.DS_Store","**/Thumbs.db","**/*.tmp","**/*.swp","**/*.swo","**/*.log","**/*.lock","**/.cache/**","**/.next/**","**/.vscode/**","**/.idea/**","**/.logs/**"];function dt(s){return K.join(s,Sl)}c(dt,"getMembraneDir");const Li=Ks(dt(process.cwd()),".logs");class vl{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`;Wc(Li,{recursive:!0});const i=Ks(Li,r),o=this._logs.map(a=>`[${a.timestamp}] ${a.type?.toUpperCase()||"INFO"}: ${a.message}`).join(`
`);return Jc(i,o,"utf-8"),i}catch(t){return console.error("Failed to save logs:",t),null}}}const b=new vl;class kl{static{c(this,"RequestLogger")}constructor(e=qc){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=>{t.metadata={startTime:Date.now()};const{method:n,url:r}=this.getRequestDetails(t);return b.debug(`[Request]: ${n} ${r}`),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}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){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 Tl{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 kl,this.requestLogger.setup()}async withClient(e,t=process.cwd()){return this.withRetry(async()=>{const n=await this.getClient(t);await this.acquireSemaphore();try{return await this.waitIfNeeded(),this.recordRequest(),await this.withTimeout(e(n),this.requestTimeout)}finally{this.releaseSemaphore()}},"API request")}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 Tl;async function Di(s){const{id:e}=await B.withClient(t=>t.get("org-workspace-id"),s);return e}c(Di,"getWorkspaceId");var q={},$n={},ji;function Fi(){if(ji)return $n;ji=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(Fi,"requireJsCamelcase");var Nn={},qi;function Ki(){if(qi)return Nn;qi=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(Ki,"requireJsSnakecase");var xn={},Bi;function Ui(){if(Bi)return xn;Bi=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(Ui,"requireJsPascalcase");var Pn={},Wi;function El(){if(Wi)return Pn;Wi=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(El,"requireJsDotcase");var Rn={},Ji;function _l(){if(Ji)return Rn;Ji=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(_l,"requireJsPathcase");var Mn={},Hi;function Il(){if(Hi)return Mn;Hi=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(Il,"requireJsTextcase");var Ln={},Vi;function Al(){if(Vi)return Ln;Vi=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(Al,"requireJsSentencecase");var Dn={},Gi;function Ol(){if(Gi)return Dn;Gi=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(Ol,"requireJsHeadercase");var jn={},zi;function Yi(){if(zi)return jn;zi=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(Yi,"requireJsKebabcase");var ft={},sr={},Xi;function ht(){return Xi||(Xi=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 Qi;function $l(){if(Qi)return ft;Qi=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($l,"requireLowercaseKeysObject");var pt={},Zi;function Nl(){if(Zi)return pt;Zi=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(Nl,"requireUppercaseKeysObject");var mt={},eo;function xl(){if(eo)return mt;eo=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=Fi();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(xl,"requireCamelcaseKeysObject");var gt={},to;function Pl(){if(to)return gt;to=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=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,"snakeKeys"),gt.default=n,gt}c(Pl,"requireSnakecaseKeysObject");var yt={},no;function Rl(){if(no)return yt;no=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=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,"pascalKeys"),yt.default=n,yt}c(Rl,"requirePascalcaseKeysObject");var wt={},so;function Ml(){if(so)return wt;so=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=Yi();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(Ml,"requireKebabcaseKeysObject");var ro;function Ll(){if(ro)return q;ro=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=Fi();q.toCamelCase=s.default;var e=Ki();q.toSnakeCase=e.default;var t=Ui();q.toPascalCase=t.default;var n=El();q.toDotCase=n.default;var r=_l();q.toPathCase=r.default;var i=Il();q.toTextCase=i.default;var o=Al();q.toSentenceCase=o.default;var a=Ol();q.toHeaderCase=a.default;var l=Yi();q.toKebabCase=l.default;var u=$l();q.lowerKeys=u.default;var d=Nl();q.upperKeys=d.default;var f=xl();q.camelKeys=f.default;var h=Pl();q.snakeKeys=h.default;var g=Rl();q.pascalKeys=g.default;var y=Ml();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 k={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=k,q}c(Ll,"requireLib");var rr,io;function Dl(){return io||(io=1,rr=Ll()),rr}c(Dl,"requireJsConvertCase");var jl=Dl();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 Fl(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(Fl,"baseExportCleanup");const ql=["id","workspaceId","integrationId","createdAt","updatedAt","revision","archivedAt","baseUri","state","appliedToIntegrations","dependencies"],oo=[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 Gc(t,n)}hasParent(){const e=this.getParentKey();return!!e&&!!this.data?.[e]}clean(){const e={...this.data};return ql.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 oo.includes(e)}static canBeIntegrationSpecific(e){return oo.includes(e)}}class ao{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)),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){}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 Kl(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(Kl,"writeYaml");class Bl extends ao{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}),Kl(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 Ul extends ao{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(),process.cwd());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),process.cwd()),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(),process.cwd());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),process.cwd()),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(),process.cwd()),b.debug(`[remote] Deleted ${e.id}`)}async getIntegrations(){const t=(await B.withClient(n=>n.integrations.findAll(),process.cwd())).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;try{n=await B.withClient(r=>r[ce[t].element](e).get())}catch{return}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){return(await B.withClient(i=>i[ce[e].elements].findAll(t),process.cwd())).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"),co=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]===co,"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 lo=c(s=>(H(s)||z(s))&&!!s.anchor,"hasAnchor"),le=Symbol("break visit"),uo=Symbol("skip children"),_e=Symbol("remove node");function et(s,e){const t=fo(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=uo,et.REMOVE=_e;function vt(s,e,t,n){const r=ho(s,e,t,n);if(Y(r)||V(r))return po(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=fo(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=uo,Fn.REMOVE=_e;async function kt(s,e,t,n){const r=await ho(s,e,t,n);if(Y(r)||V(r))return po(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 fo(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(fo,"initVisitor");function ho(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(ho,"callVisitor");function po(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(po,"replaceNode");const Wl={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},Jl=c(s=>s.replace(/[!,[\]{}]/g,e=>Wl[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+Jl(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(`
`)}}oe.defaultYaml={explicit:!1,version:"1.2"},oe.defaultTags={"!!":"tag:yaml.org,2002:"};function mo(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(mo,"anchorIsValid");function go(s){const e=new Set;return et(s,{Value(t,n){n.anchor&&e.add(n.anchor)}}),e}c(go,"anchorNames");function yo(s,e){for(let t=1;;++t){const n=`${s}${t}`;if(!e.has(n))return n}}c(yo,"findNewAnchor");function Hl(s,e){const t=[],n=new Map;let r=null;return{onAnchor:c(i=>{t.push(i),r??(r=go(s));const o=yo(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(Hl,"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||!lo(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)||lo(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(mo(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 wo=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 Vl="tag:yaml.org,2002:";function Gl(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(Gl,"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=Vl+e.slice(2));let u=Gl(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 bo 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 zl=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,