@membranehq/cli 0.10.14 → 0.10.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +89 -89
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,75 +1,75 @@
1
1
  #!/usr/bin/env node
2
- var Bi=Object.defineProperty;var c=(s,e)=>Bi(s,"name",{value:e,configurable:!0});import{jsx as m,jsxs as v,Fragment as en}from"react/jsx-runtime";import*as R from"node:path";import{resolve as qi,dirname as Ui,join as Ji}from"node:path";import{useInput as Pe,Box as b,Text as S,Newline as Wi,render as gt}from"ink";import Gi from"minimist";import{SWRConfig as Vi}from"swr";import Re,{createContext as ss,useState as j,useEffect as Ie,useContext as is,useMemo as Hi,useRef as Yi}from"react";import rs from"swr/immutable";import{MembraneConfigLoader as zi,WorkspaceElementType as M,WorkspaceElementSpecs as we,MembraneClient as os,setValueAtLocator as tn,extractMembraneErrorData as le,getDataCollectionCreateFields as nn,excludeWriteOnlyFieldsFromSchema as as,valueToSchema as yt,getRequiredFieldsFromSchema as Qi,getValueAtLocator as Xi,walkSchema as cs,makeDataLocationPath as ls,getDataCollectionUpdateFields as sn}from"@membranehq/sdk";import*as x from"node:fs";import{readFileSync as Zi}from"node:fs";import Te from"js-yaml";import er from"lodash/isEqual.js";import us from"os";import{EventEmitter as tr}from"events";import B from"path";import nr from"conf";import rn from"jsonwebtoken";import*as sr from"node:crypto";import{createHash as ir}from"node:crypto";import rr from"chokidar";import P from"fs";import or from"archiver";import ar from"form-data";import cr from"unzipper";import*as lr from"node:os";import{exec as ur}from"node:child_process";import{Spinner as fr,TextInput as hr,Select as dr}from"@inkjs/ui";import wt from"ink-spinner";import pr from"ink-text-input";import{fileURLToPath as mr}from"node:url";import k from"chalk";import{Command as gr}from"commander";import on from"axios";import{FastMCP as yr}from"fastmcp";import{z}from"zod";import an from"lodash/merge.js";import wr from"@anthropic-ai/sdk";import{faker as Ze}from"@faker-js/faker";import br from"lodash/template.js";import Sr from"lodash/templateSettings.js";class Ye{static{c(this,"ConfigLoader")}static instance=null;sdkLoader;constructor(){this.sdkLoader=new zi}static getInstance(){return Ye.instance||(Ye.instance=new Ye),Ye.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 et=Ye.getInstance(),ne={[M.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")},[M.Connector]:{element:"connector",elements:"connectors",exportable:!1},[M.Action]:{element:"action",elements:"actions",integrationSpecific:!0,exportCleanup:c(s=>(delete s.integration,s),"exportCleanup")},[M.AppDataSchema]:{element:"appDataSchema",elements:"appDataSchemas"},[M.AppEventType]:{element:"appEventType",elements:"appEventTypes"},[M.DataLinkTable]:{element:"dataLinkTable",elements:"dataLinkTables"},[M.DataSource]:{element:"dataSource",elements:"dataSources",parentKey:"universalDataSourceId",integrationSpecific:!0},[M.FieldMapping]:{element:"fieldMapping",elements:"fieldMappings",integrationSpecific:!0,parentKey:"universalFieldMappingId",exportCleanup:c(s=>(delete s.dataSourceId,s),"exportCleanup")},[M.Flow]:{element:"flow",elements:"flows",integrationSpecific:!0,parentKey:"universalFlowId"}};function Cr(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(Cr,"baseExportCleanup");const kr="membrane",Er=["**/node_modules/**","**/.git/**","**/.DS_Store","**/Thumbs.db","**/*.tmp","**/*.swp","**/*.swo","**/*.log","**/*.lock","**/.cache/**","**/.next/**","**/.vscode/**","**/.idea/**"];function bt(s){return R.join(s,kr)}c(bt,"getMembraneDir");const vr=["id","workspaceId","integrationId","createdAt","updatedAt","revision","archivedAt","baseUri","state"],fs=[M.Action,M.FieldMapping,M.Flow,M.DataSource];class G{static{c(this,"Element")}type;key;integrationKey;data;constructor(e,t,n,i){if(!i)throw new Error("Element must always contain data");if(!t)throw new Error("Element must have a key");this.type=e,this.key=t,this.data=i,this.integrationKey=n||G.extractIntegrationKey(i)}get id(){return G.makeId(this.type,this.key,this.integrationKey)}get dirPath(){const e=we[this.type].apiPath;if(this.integrationKey){const t=we[M.Integration].apiPath;return R.join(t,this.integrationKey,e,this.key)}return R.join(e,this.key)}get path(){return R.join(this.dirPath,"spec.yaml")}get relativePath(){return R.relative(bt(process.cwd()),this.path)}isEqual(e){if(this.id!==e.id)return!1;const t=this.clean(),n=e.clean();return er(t,n)}hasParent(){const e=this.getParentKey();return!!e&&!!this.data?.[e]}clean(){const e={...this.data};return vr.forEach(t=>{delete e[t]}),Object.keys(e).forEach(t=>{t.match(/universal.*Revision/)&&delete e[t]}),e}getParentKey(){let e="parentId";return ne?.[this.type]?.parentKey&&(e=ne?.[this.type]?.parentKey),e}static new(e,t,n,i){return new G(e,t,n,i)}static fromData(e,t){if(!t?.key)throw new Error(`Element missing key: ${JSON.stringify(t)}`);const n=this.extractIntegrationKey(t);return new G(e,t.key,n,t)}static fromPathAndData(e,t){const n=G.parsePath(e);if(!t)return;const i=t?.key||n?.key;return n?G.new(n.type,i,n.integrationKey,t):void 0}static fromElement(e){return new G(e.type,e.key,e.integrationKey,{...e.data})}static idFromPath(e){const t=G.parsePath(e);if(t)return G.makeId(t.type,t.key,t.integrationKey)}static makeId(e,t,n){return e===M.Integration?`${e}:${t}`:G.isIntegrationSpecific(e)?`${n||"universal"}:${e}:${t}`:`${e}:${t}`}static parsePath(e){const t=this.getRelativePath(e);if(!this.isElementFile(t))return;const n=Object.values(we).map(l=>l.apiPath).join("|"),i=new RegExp(`^(?<elementType>${n})/(?<elementKey>[^/]+)/spec\\.ya?ml$`),r=t.match(i);if(r?.groups){const{elementType:l,elementKey:u}=r.groups,p=this.getElementTypeFromPath(l);if(p)return{type:p,key:u}}const o=new RegExp(`^integrations/(?<integrationKey>[^/]+)/(?<elementType>${n})/(?<elementKey>[^/]+)/spec\\.ya?ml$`),a=t.match(o);if(a?.groups){const{integrationKey:l,elementType:u,elementKey:p}=a.groups,d=this.getElementTypeFromPath(u);if(d)return{type:d,key:p,integrationKey:l}}}static extractIntegrationKey(e){return e?.integrationKey||e?.integration?.key||e?.integration_key||void 0}static isElementFile(e){return e.endsWith(".yml")||e.endsWith(".yaml")}static getElementTypeFromPath(e){return Object.values(M).find(t=>we[t].apiPath===e)}static getRelativePath(e){return R.relative(bt(process.cwd()),e)}static isIntegrationSpecific(e){return fs.includes(e)}static canBeIntegrationSpecific(e){return fs.includes(e)}}const J={LogAdded:"logAdded",StateChanged:"stateChanged",StatsChanged:"statsChanged",ConflictsChanged:"conflictsChanged",McpStatusChanged:"mcpStatusChanged",McpServersChanged:"mcpServersChanged",ConfigChanged:"configChanged"};class hs extends tr{static{c(this,"TypedEventEmitter")}on(e,t){return super.on(e,t)}emit(e,...t){return super.emit(e,...t)}off(e,t){return super.off(e,t)}once(e,t){return super.once(e,t)}}const Ir="membrane",Tr="membrane.config.yml",cn="https://api.integration.app";function ln(){const s=process.cwd(),e=R.join(s,Ir),t=R.join(s,Tr),n=e,i=R.join(n,"workspace.yaml");return{membraneDirPath:e,configPath:t,payloadDirPath:n,workspaceDataFilePath:i}}c(ln,"getPaths");function Nr(){return ln().membraneDirPath}c(Nr,"getBasePath");const Ar={pat:{type:"string"},workspace:{type:"object"}},ds=new nr({schema:Ar,configName:"config",cwd:B.join(us.homedir(),".membrane")}),Or=c(s=>{ds.set("pat",s)},"setPat"),ps=c(()=>ds.get("pat"),"getPat");class ms{static{c(this,"AccountApiClient")}constructor(e=cn){this.apiBaseUrl=e}async request(e,t={}){const n=t.headers?t.headers instanceof Headers?new Headers(t.headers):new Headers(t.headers):new Headers;if(!n.has("Authorization")){const o=ps();if(!o)throw new Error("Personal Access Token not found.");n.set("Authorization",`Bearer ${o}`)}t.body&&!n.has("Content-Type")&&n.set("Content-Type","application/json");const i=await fetch(`${this.apiBaseUrl}${e}`,{...t,headers:n});if(!i.ok){const o=await i.text();throw new Error(`API request failed: ${i.status} ${i.statusText} - ${o}`)}if(i.status===204)return{};const r=await i.text();return JSON.parse(r)}get(e){return this.request(e,{method:"GET"})}post(e,t){return this.request(e,{method:"POST",body:JSON.stringify(t)})}put(e,t){return this.request(e,{method:"PUT",body:JSON.stringify(t)})}patch(e,t){return this.request(e,{method:"PATCH",body:JSON.stringify(t)})}delete(e){return this.request(e,{method:"DELETE"})}}const $r=c(s=>{const e=new ms(cn);return t=>e.get(t)},"createAccountApiFetcher");function St(s){return et.loadConfig(s)}c(St,"readProjectConfig");class Lr{static{c(this,"MembraneClientManager")}client=null;currentConfig=null;tokenExpiry=0;async generateAccessToken(e,t){return rn.sign({name:"Membrane Agent",isAdmin:!0,exp:Math.floor(Date.now()/1e3)+3600,iss:e},t,{algorithm:"HS512"})}isTokenValid(){return Date.now()<this.tokenExpiry}getCurrentConfig(e){const t=St(e);return!t?.workspaceKey||!t?.workspaceSecret?null:{workspaceKey:t.workspaceKey,workspaceSecret:t.workspaceSecret,apiUri:t.apiUri}}async createClient(e){const t=await this.generateAccessToken(e.workspaceKey,e.workspaceSecret);return this.tokenExpiry=Date.now()+36e5,this.currentConfig=e,new os({token:t,apiUri:e.apiUri})}async getClient(e=process.cwd()){const t=this.getCurrentConfig(e);if(!t)throw new Error("Unable to create MembraneClient: No workspace configuration found.");const n=!this.currentConfig||this.currentConfig.workspaceKey!==t.workspaceKey||this.currentConfig.workspaceSecret!==t.workspaceSecret||this.currentConfig.apiUri!==t.apiUri,i=!this.isTokenValid()||this.tokenExpiry-Date.now()<3e5;return(!this.client||n||i)&&(this.client=await this.createClient(t)),this.client}clearClient(){this.client=null,this.currentConfig=null,this.tokenExpiry=0}getCurrentConfigInfo(){return this.currentConfig}}const ue=new Lr;async function gs(s){const e=await ue.getClient(s);if(!e)throw new Error("No workspace configuration found");return(await e.get("org-workspace-id")).id}c(gs,"getWorkspaceId");class Dr extends hs{static{c(this,"WorkspaceNotifications")}constructor(e){super(),this.config=e}clientId;heartbeatInterval;isCleaningUp=!1;async connectToRemote(){await this.registerWithRemoteServer(),await this.startHeartbeatLoop()}async setState(e){this.emit(J.StateChanged,{state:e}),await this.emitRemote({status:e})}setConflicts(e){this.emit(J.ConflictsChanged,{conflicts:e})}setConfig(e){this.emit(J.ConfigChanged,{config:e})}setStats(e){this.emit(J.StatsChanged,{stats:e})}addLog(e){this.emit(J.LogAdded,{log:e})}setMcpStatus(e){this.emit(J.McpStatusChanged,{status:e})}async setMcpServers(e){this.emit(J.McpServersChanged,{servers:e}),await this.emitRemote({mcpServers:e.map(t=>({name:t.agentName,totalRequests:t.totalRequests}))})}async cleanup(){!this.clientId||this.isCleaningUp||(this.isCleaningUp=!0,this.heartbeatInterval&&(clearInterval(this.heartbeatInterval),this.heartbeatInterval=void 0),await this.withErrorHandling(async()=>{await(await ue.getClient(process.cwd())).delete(`/local-clients/${this.clientId}`)}),this.clientId=void 0)}async registerWithRemoteServer(){if(this.clientId)return;const e=await ue.getClient(process.cwd()),t=await this.withErrorHandling(async()=>await e.post("/local-clients",{hostname:us.hostname(),workingDirectory:process.cwd()}));t?.id?this.clientId=t.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(await ue.getClient(process.cwd())).post(`/local-clients/${this.clientId}/keep-alive`,{})})}async emitRemote(e){this.clientId&&await this.withErrorHandling(async()=>{await(await ue.getClient(process.cwd())).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 de=new Dr({heartbeatIntervalMs:15e3});class xr{static{c(this,"WorkspaceLogger")}_logs;workspaceNotifications;constructor(){this._logs=[],this.workspaceNotifications=de}get logs(){return[...this._logs]}get latestLogs(){return this._logs.slice(this._logs.length-5)}log(e,t="info"){const n={timestamp:new Date().toISOString(),message:e,type:t};this._logs.push(n),this._logs=this._logs.slice(0,1e3),this.workspaceNotifications.addLog(n)}info(e){this.log(e,"info")}success(e){this.log(e,"success")}warning(e){this.log(e,"warning")}error(e){this.log(e,"error")}clear(){this._logs=[]}}const N=new xr;class ys{static{c(this,"BaseWorkspaceElementsRepository")}constructor(e){this.cache=e}connectorsMapping;setConnectorsMapping(e){this.connectorsMapping=e}async getElements(){const e=[];try{const t=await this.getIntegrations();e.push(...t);const n=[M.Integration,M.Connector],i=Object.keys(ne),r=await Promise.all(i.filter(o=>!n.includes(o)).map(async o=>this.getElementsByType(o,t)));for(const o of r)e.push(...o)}catch(t){throw N.error(`Failed to get elements: ${t}`),t}return e}async putElement(e){let t=this.cache.get(e.id);return e.data.id&&t?t=await this.updateElement(e,t,{elements:this.cache.getAll(),connectorsMapping:this.connectorsMapping}):t=await this.createElement(e,{elements:this.cache.getAll(),connectorsMapping:this.connectorsMapping}),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 deleteElement(e,t){}}class Pr extends ys{static{c(this,"LocalWorkspaceElementsRepository")}basePath;constructor(e){super(e),this.basePath=bt(process.cwd())}async getElementsByType(e,t){const n=[],i=R.join(this.basePath,we[e].apiPath),r=await this.readElementsInDir(i);n.push(...r);for(const o of t){const a=R.join(this.basePath,we[M.Integration].apiPath,o.key,we[e].apiPath),l=await this.readElementsInDir(a);n.push(...l)}return n.length>0&&N.success(`[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=R.join(this.basePath,t.dirPath),i=R.join(this.basePath,t.path);return x.existsSync(n)||x.mkdirSync(n,{recursive:!0}),x.writeFileSync(i,Te.dump(e.data)),N.info(`[local] Written ${t.relativePath}`),t}async deleteElement(e){const t=R.join(this.basePath,e.path),n=R.join(this.basePath,e.dirPath);x.existsSync(t)&&x.rmSync(t,{force:!0}),this.pruneEmptyDir(n),N.info(`[local] Deleted ${e.relativePath}`)}async getIntegrations(){const e=R.join(this.basePath,we[M.Integration].apiPath);return this.readElementsInDir(e)}async readElement(e){if(!x.existsSync(e))return;const t=x.readFileSync(e,"utf8"),n=Te.load(t);if(n)return G.fromPathAndData(e,n)}async readElementsInDir(e){const t=[];if(!x.existsSync(e))return t;const n=x.readdirSync(e);if(n.length===0)return t;const i=n.map(async o=>{const a=R.join(e,o,"spec.yaml");return this.readElement(a)});return(await Promise.all(i)).filter(o=>o!=null)}pruneEmptyDir(e){try{if(!e.startsWith(this.basePath)||e===this.basePath||!x.existsSync(e)||x.readdirSync(e).length>0)return;x.rmdirSync(e),this.pruneEmptyDir(R.dirname(e))}catch(t){console.warn(`Failed to prune empty directory ${e}:`,t)}}}class Rr{static{c(this,"RequestThrottler")}requestTimes=[];maxRequestsPerSecond;windowSizeMs;semaphore=0;maxConcurrentRequests;constructor(e=80){this.maxRequestsPerSecond=e,this.windowSizeMs=1e3,this.maxConcurrentRequests=Math.min(e/4,20)}async withThrottle(e){await this.acquireSemaphore();try{return await this.waitIfNeeded(),this.recordRequest(),await e()}finally{this.releaseSemaphore()}}async waitIfNeeded(){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}}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(){for(;this.semaphore>=this.maxConcurrentRequests;)await new Promise(e=>setTimeout(e,10));this.semaphore++}releaseSemaphore(){this.semaphore--}}const pe=new Rr;class Mr extends ys{static{c(this,"RemoteWorkspaceElementsRepository")}client;async getElementsByType(e,t){const n=await this.findAll(e);if(!G.canBeIntegrationSpecific(e))return n;for(const i of t){const r=i.key,o=i.data.id,a=await this.findAll(e,o?{integrationId:o}:{integrationKey:r});n.push(...a)}return n.length>0&&N.success(`[remote] Fetched ${n.length} ${e}${n.length!==1?"s":""}`),n}async getElement(e){const t=await this.getClient(),n=await pe.withThrottle(()=>t[ne[e.type].element](e.data.id).get());return G.fromData(e.type,n)}async createElement(e,t){const n=e.clean(),i=await this.getClient();this.transformElementForCreate(e,n,t);const r=await pe.withThrottle(()=>i[ne[e.type].elements].create(n)),o=G.fromData(e.type,r);return N.info(`[remote] Created ${o.id}`),o}async updateElement(e,t,n){if(!e.data.id)throw new Error("Element must have an id to update");const i=e.clean(),r=await this.getClient();this.transformElementForUpdate(e,i,n);const o=await pe.withThrottle(()=>r[ne[e.type].element](t.data.id).put(i)),a=G.fromData(t.type,o);return N.info(`[remote] Updated ${t.id}`),a}async deleteElement(e){if(!e.data.id)throw new Error("Element must have an id to delete");const t=await this.getClient();await pe.withThrottle(()=>t[ne[e.type].element](e.data.id).archive()),N.info(`[remote] Deleted ${e.id}`)}async getIntegrations(){const e=await this.getClient(),n=(await pe.withThrottle(()=>e.integrations.findAll())).map(i=>G.fromData(M.Integration,i));return n.length>0&&N.success(`[remote] Fetched ${n.length} integrations`),n}transformElementForCreate(e,t,n){if(e.integrationKey){const i=n.elements.find(r=>r.type===M.Integration&&r.key===e.integrationKey);if(i)t.integrationId=i.data.id;else throw new Error(`Dependency integration ${e.integrationKey} not found for ${e.id}`)}if(e.type===M.Integration){const i=n.connectorsMapping?.[t.connectorId];i&&(t.connectorId=i)}this.transformParentDependency(e,t,n)}transformElementForUpdate(e,t,n){if(e.type===M.Integration){const i=n.connectorsMapping?.[t.connectorId];i&&(t.connectorId=i)}if(e.integrationKey){t.integrationKey=e.integrationKey;const i=n.elements.find(r=>r.type===M.Integration&&r.key===e.integrationKey);if(i)t.integrationId=i.data.id;else throw new Error(`Dependency integration ${e.integrationKey} not found for ${e.id}`)}this.transformParentDependency(e,t,n)}transformParentDependency(e,t,n){if(!e.hasParent())return;const i=e.getParentKey();if(!i)return;const r=n.elements.find(o=>o.type===e.type&&o.key===e.key&&!o.hasParent());if(r)t[i]=r.data.id;else throw new Error(`Parent ${e.getParentKey()} not found for ${e.id}`)}async findAll(e,t={}){const n=await this.getClient();return(await pe.withThrottle(()=>n[ne[e].elements].findAll(t))).filter(r=>r.key).map(r=>G.fromData(e,r))}async getClient(){return this.client||(this.client=await ue.getClient(process.cwd())),this.client}}class ws{static{c(this,"ElementsCache")}elements=new Map;typeIndex=new Map;constructor(e){e&&this.addAll(e)}add(e){const t=e.id;this.elements.set(t,e),this.typeIndex.has(e.type)||this.typeIndex.set(e.type,new Set),this.typeIndex.get(e.type).add(t)}remove(e){const t=e.id,n=this.elements.delete(t);if(n){const i=this.typeIndex.get(e.type);i&&(i.delete(t),i.size===0&&this.typeIndex.delete(e.type))}return n}put(e){this.elements.has(e.id)&&this.remove(e),this.add(e)}get(e){return this.elements.get(e)}getElementsByType(e){const t=this.typeIndex.get(e);return t?Array.from(t).map(n=>this.elements.get(n)).filter(n=>n!==void 0):[]}getAll(){return Array.from(this.elements.values())??[]}getTypes(){return Array.from(this.typeIndex.keys())}addAll(e){for(const t of e)t&&this.add(t)}removeAll(e){for(const t of e)this.remove(t)}getElementIdsByType(e){return this.typeIndex.get(e)}clear(){this.elements.clear(),this.typeIndex.clear()}getAllIds(){return new Set(this.elements.keys())}}const un=Symbol.for("yaml.alias"),fn=Symbol.for("yaml.document"),be=Symbol.for("yaml.map"),bs=Symbol.for("yaml.pair"),fe=Symbol.for("yaml.scalar"),Me=Symbol.for("yaml.seq"),se=Symbol.for("yaml.node.type"),Se=c(s=>!!s&&typeof s=="object"&&s[se]===un,"isAlias"),Ne=c(s=>!!s&&typeof s=="object"&&s[se]===fn,"isDocument"),_e=c(s=>!!s&&typeof s=="object"&&s[se]===be,"isMap"),F=c(s=>!!s&&typeof s=="object"&&s[se]===bs,"isPair"),_=c(s=>!!s&&typeof s=="object"&&s[se]===fe,"isScalar$1"),Ke=c(s=>!!s&&typeof s=="object"&&s[se]===Me,"isSeq");function q(s){if(s&&typeof s=="object")switch(s[se]){case be:case Me:return!0}return!1}c(q,"isCollection$1");function U(s){if(s&&typeof s=="object")switch(s[se]){case un:case be:case fe:case Me:return!0}return!1}c(U,"isNode");const Ss=c(s=>(_(s)||q(s))&&!!s.anchor,"hasAnchor"),ee=Symbol("break visit"),Cs=Symbol("skip children"),he=Symbol("remove node");function Ae(s,e){const t=ks(e);Ne(s)?je(null,s.contents,t,Object.freeze([s]))===he&&(s.contents=null):je(null,s,t,Object.freeze([]))}c(Ae,"visit$1"),Ae.BREAK=ee,Ae.SKIP=Cs,Ae.REMOVE=he;function je(s,e,t,n){const i=Es(s,e,t,n);if(U(i)||F(i))return vs(s,n,i),je(s,i,t,n);if(typeof i!="symbol"){if(q(e)){n=Object.freeze(n.concat(e));for(let r=0;r<e.items.length;++r){const o=je(r,e.items[r],t,n);if(typeof o=="number")r=o-1;else{if(o===ee)return ee;o===he&&(e.items.splice(r,1),r-=1)}}}else if(F(e)){n=Object.freeze(n.concat(e));const r=je("key",e.key,t,n);if(r===ee)return ee;r===he&&(e.key=null);const o=je("value",e.value,t,n);if(o===ee)return ee;o===he&&(e.value=null)}}return i}c(je,"visit_");async function Ct(s,e){const t=ks(e);Ne(s)?await Fe(null,s.contents,t,Object.freeze([s]))===he&&(s.contents=null):await Fe(null,s,t,Object.freeze([]))}c(Ct,"visitAsync"),Ct.BREAK=ee,Ct.SKIP=Cs,Ct.REMOVE=he;async function Fe(s,e,t,n){const i=await Es(s,e,t,n);if(U(i)||F(i))return vs(s,n,i),Fe(s,i,t,n);if(typeof i!="symbol"){if(q(e)){n=Object.freeze(n.concat(e));for(let r=0;r<e.items.length;++r){const o=await Fe(r,e.items[r],t,n);if(typeof o=="number")r=o-1;else{if(o===ee)return ee;o===he&&(e.items.splice(r,1),r-=1)}}}else if(F(e)){n=Object.freeze(n.concat(e));const r=await Fe("key",e.key,t,n);if(r===ee)return ee;r===he&&(e.key=null);const o=await Fe("value",e.value,t,n);if(o===ee)return ee;o===he&&(e.value=null)}}return i}c(Fe,"visitAsync_");function ks(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(ks,"initVisitor");function Es(s,e,t,n){if(typeof t=="function")return t(s,e,n);if(_e(e))return t.Map?.(s,e,n);if(Ke(e))return t.Seq?.(s,e,n);if(F(e))return t.Pair?.(s,e,n);if(_(e))return t.Scalar?.(s,e,n);if(Se(e))return t.Alias?.(s,e,n)}c(Es,"callVisitor");function vs(s,e,t){const n=e[e.length-1];if(q(n))n.items[s]=t;else if(F(n))s==="key"?n.key=t:n.value=t;else if(Ne(n))n.contents=t;else{const i=Se(n)?"alias":"scalar";throw new Error(`Cannot replace node with ${i} parent`)}}c(vs,"replaceNode");const _r={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},Kr=c(s=>s.replace(/[!,[\]{}]/g,e=>_r[e]),"escapeTagName");class Z{static{c(this,"Directives")}constructor(e,t){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},Z.defaultYaml,e),this.tags=Object.assign({},Z.defaultTags,t)}clone(){const e=new Z(this.yaml,this.tags);return e.docStart=this.docStart,e}atDocument(){const e=new Z(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:Z.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},Z.defaultTags);break}return e}add(e,t){this.atNextDocument&&(this.yaml={explicit:Z.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},Z.defaultTags),this.atNextDocument=!1);const n=e.trim().split(/[ \t]+/),i=n.shift();switch(i){case"%TAG":{if(n.length!==2&&(t(0,"%TAG directive should contain exactly two parts"),n.length<2))return!1;const[r,o]=n;return this.tags[r]=o,!0}case"%YAML":{if(this.yaml.explicit=!0,n.length!==1)return t(0,"%YAML directive should contain exactly one part"),!1;const[r]=n;if(r==="1.1"||r==="1.2")return this.yaml.version=r,!0;{const o=/^\d+\.\d+$/.test(r);return t(6,`Unsupported YAML version ${r}`,o),!1}}default:return t(0,`Unknown directive ${i}`,!0),!1}}tagName(e,t){if(e==="!")return"!";if(e[0]!=="!")return t(`Not a valid tag: ${e}`),null;if(e[1]==="<"){const o=e.slice(2,-1);return o==="!"||o==="!!"?(t(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==">"&&t("Verbatim tags must end with a >"),o)}const[,n,i]=e.match(/^(.*!)([^!]*)$/s);i||t(`The ${e} tag has no suffix`);const r=this.tags[n];if(r)try{return r+decodeURIComponent(i)}catch(o){return t(String(o)),null}return n==="!"?e:(t(`Could not resolve tag: ${e}`),null)}tagString(e){for(const[t,n]of Object.entries(this.tags))if(e.startsWith(n))return t+Kr(e.substring(n.length));return e[0]==="!"?e:`!<${e}>`}toString(e){const t=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],n=Object.entries(this.tags);let i;if(e&&n.length>0&&U(e.contents)){const r={};Ae(e.contents,(o,a)=>{U(a)&&a.tag&&(r[a.tag]=!0)}),i=Object.keys(r)}else i=[];for(const[r,o]of n)r==="!!"&&o==="tag:yaml.org,2002:"||(!e||i.some(a=>a.startsWith(o)))&&t.push(`%TAG ${r} ${o}`);return t.join(`
3
- `)}}Z.defaultYaml={explicit:!1,version:"1.2"},Z.defaultTags={"!!":"tag:yaml.org,2002:"};function Is(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(Is,"anchorIsValid");function Ts(s){const e=new Set;return Ae(s,{Value(t,n){n.anchor&&e.add(n.anchor)}}),e}c(Ts,"anchorNames");function Ns(s,e){for(let t=1;;++t){const n=`${s}${t}`;if(!e.has(n))return n}}c(Ns,"findNewAnchor");function jr(s,e){const t=[],n=new Map;let i=null;return{onAnchor:c(r=>{t.push(r),i??(i=Ts(s));const o=Ns(e,i);return i.add(o),o},"onAnchor"),setAnchors:c(()=>{for(const r of t){const o=n.get(r);if(typeof o=="object"&&o.anchor&&(_(o.node)||q(o.node)))o.node.anchor=o.anchor;else{const a=new Error("Failed to resolve repeated object (this should not happen)");throw a.source=r,a}}},"setAnchors"),sourceObjects:n}}c(jr,"createNodeAnchors");function Be(s,e,t,n){if(n&&typeof n=="object")if(Array.isArray(n))for(let i=0,r=n.length;i<r;++i){const o=n[i],a=Be(s,n,String(i),o);a===void 0?delete n[i]:a!==o&&(n[i]=a)}else if(n instanceof Map)for(const i of Array.from(n.keys())){const r=n.get(i),o=Be(s,n,i,r);o===void 0?n.delete(i):o!==r&&n.set(i,o)}else if(n instanceof Set)for(const i of Array.from(n)){const r=Be(s,n,i,i);r===void 0?n.delete(i):r!==i&&(n.delete(i),n.add(r))}else for(const[i,r]of Object.entries(n)){const o=Be(s,n,i,r);o===void 0?delete n[i]:o!==r&&(n[i]=o)}return s.call(e,t,n)}c(Be,"applyReviver");function ie(s,e,t){if(Array.isArray(s))return s.map((n,i)=>ie(n,String(i),t));if(s&&typeof s.toJSON=="function"){if(!t||!Ss(s))return s.toJSON(e,t);const n={aliasCount:0,count:1,res:void 0};t.anchors.set(s,n),t.onCreate=r=>{n.res=r,delete t.onCreate};const i=s.toJSON(e,t);return t.onCreate&&t.onCreate(i),i}return typeof s=="bigint"&&!t?.keep?Number(s):s}c(ie,"toJS");class hn{static{c(this,"NodeBase")}constructor(e){Object.defineProperty(this,se,{value:e})}clone(){const e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:t,maxAliasCount:n,onAnchor:i,reviver:r}={}){if(!Ne(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=ie(this,"",o);if(typeof i=="function")for(const{count:l,res:u}of o.anchors.values())i(u,l);return typeof r=="function"?Be(r,{"":a},"",a):a}}class kt extends hn{static{c(this,"Alias")}constructor(e){super(un),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=[],Ae(e,{Node:c((r,o)=>{(Se(o)||Ss(o))&&n.push(o)},"Node")}),t&&(t.aliasResolveCache=n));let i;for(const r of n){if(r===this)break;r.anchor===this.source&&(i=r)}return i}toJSON(e,t){if(!t)return{source:this.source};const{anchors:n,doc:i,maxAliasCount:r}=t,o=this.resolve(i,t);if(!o){const l=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(l)}let a=n.get(o);if(a||(ie(o,null,t),a=n.get(o)),!a||a.res===void 0){const l="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(l)}if(r>=0&&(a.count+=1,a.aliasCount===0&&(a.aliasCount=Et(i,o,n)),a.count*a.aliasCount>r)){const l="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(l)}return a.res}toString(e,t,n){const i=`*${this.source}`;if(e){if(Is(this.source),e.options.verifyAliasOrder&&!e.anchors.has(this.source)){const r=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(r)}if(e.implicitKey)return`${i} `}return i}}function Et(s,e,t){if(Se(e)){const n=e.resolve(s),i=t&&n&&t.get(n);return i?i.count*i.aliasCount:0}else if(q(e)){let n=0;for(const i of e.items){const r=Et(s,i,t);r>n&&(n=r)}return n}else if(F(e)){const n=Et(s,e.key,t),i=Et(s,e.value,t);return Math.max(n,i)}return 1}c(Et,"getAliasCount");const As=c(s=>!s||typeof s!="function"&&typeof s!="object","isScalarValue");class D extends hn{static{c(this,"Scalar")}constructor(e){super(fe),this.value=e}toJSON(e,t){return t?.keep?this.value:ie(this.value,e,t)}toString(){return String(this.value)}}D.BLOCK_FOLDED="BLOCK_FOLDED",D.BLOCK_LITERAL="BLOCK_LITERAL",D.PLAIN="PLAIN",D.QUOTE_DOUBLE="QUOTE_DOUBLE",D.QUOTE_SINGLE="QUOTE_SINGLE";const Fr="tag:yaml.org,2002:";function Br(s,e,t){if(e){const n=t.filter(r=>r.tag===e),i=n.find(r=>!r.format)??n[0];if(!i)throw new Error(`Tag ${e} not found`);return i}return t.find(n=>n.identify?.(s)&&!n.format)}c(Br,"findTagObject");function tt(s,e,t){if(Ne(s)&&(s=s.contents),U(s))return s;if(F(s)){const d=t.schema[be].createNode?.(t.schema,null,t);return d.items.push(s),d}(s instanceof String||s instanceof Number||s instanceof Boolean||typeof BigInt<"u"&&s instanceof BigInt)&&(s=s.valueOf());const{aliasDuplicateObjects:n,onAnchor:i,onTagObj:r,schema:o,sourceObjects:a}=t;let l;if(n&&s&&typeof s=="object"){if(l=a.get(s),l)return l.anchor??(l.anchor=i(s)),new kt(l.anchor);l={anchor:null,node:null},a.set(s,l)}e?.startsWith("!!")&&(e=Fr+e.slice(2));let u=Br(s,e,o.tags);if(!u){if(s&&typeof s.toJSON=="function"&&(s=s.toJSON()),!s||typeof s!="object"){const d=new D(s);return l&&(l.node=d),d}u=s instanceof Map?o[be]:Symbol.iterator in Object(s)?o[Me]:o[be]}r&&(r(u),delete t.onTagObj);const p=u?.createNode?u.createNode(t.schema,s,t):typeof u?.nodeClass?.from=="function"?u.nodeClass.from(t.schema,s,t):new D(s);return e?p.tag=e:u.default||(p.tag=u.tag),l&&(l.node=p),p}c(tt,"createNode");function vt(s,e,t){let n=t;for(let i=e.length-1;i>=0;--i){const r=e[i];if(typeof r=="number"&&Number.isInteger(r)&&r>=0){const o=[];o[r]=n,n=o}else n=new Map([[r,n]])}return tt(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(vt,"collectionFromPath");const nt=c(s=>s==null||typeof s=="object"&&!!s[Symbol.iterator]().next().done,"isEmptyPath");class Os extends hn{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=>U(n)||F(n)?n.clone(e):n),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(nt(e))this.add(t);else{const[n,...i]=e,r=this.get(n,!0);if(q(r))r.addIn(i,t);else if(r===void 0&&this.schema)this.set(n,vt(this.schema,i,t));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${i}`)}}deleteIn(e){const[t,...n]=e;if(n.length===0)return this.delete(t);const i=this.get(t,!0);if(q(i))return i.deleteIn(n);throw new Error(`Expected YAML collection at ${t}. Remaining path: ${n}`)}getIn(e,t){const[n,...i]=e,r=this.get(n,!0);return i.length===0?!t&&_(r)?r.value:r:q(r)?r.getIn(i,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!F(t))return!1;const n=t.value;return n==null||e&&_(n)&&n.value==null&&!n.commentBefore&&!n.comment&&!n.tag})}hasIn(e){const[t,...n]=e;if(n.length===0)return this.has(t);const i=this.get(t,!0);return q(i)?i.hasIn(n):!1}setIn(e,t){const[n,...i]=e;if(i.length===0)this.set(n,t);else{const r=this.get(n,!0);if(q(r))r.setIn(i,t);else if(r===void 0&&this.schema)this.set(n,vt(this.schema,i,t));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${i}`)}}}const qr=c(s=>s.replace(/^(?!$)(?: $)?/gm,"#"),"stringifyComment");function me(s,e){return/^\n+$/.test(s)?s.substring(1):e?s.replace(/^(?! *$)/gm,e):s}c(me,"indentComment");const Oe=c((s,e,t)=>s.endsWith(`
4
- `)?me(t,e):t.includes(`
2
+ var Fi=Object.defineProperty;var c=(s,e)=>Fi(s,"name",{value:e,configurable:!0});import{jsx as m,jsxs as v,Fragment as Zt}from"react/jsx-runtime";import*as R from"node:path";import{resolve as Bi,dirname as qi,join as Ui}from"node:path";import{useInput as Pe,Box as b,Text as S,Newline as Ji,render as mt}from"ink";import Wi from"minimist";import{SWRConfig as Gi}from"swr";import De,{createContext as ns,useState as j,useEffect as ve,useContext as ss,useMemo as Vi,useRef as Hi}from"react";import is from"swr/immutable";import{MembraneConfigLoader as Yi,WorkspaceElementType as M,WorkspaceElementSpecs as ye,MembraneClient as rs,setValueAtLocator as en,extractMembraneErrorData as ue,getDataCollectionCreateFields as tn,excludeWriteOnlyFieldsFromSchema as os,valueToSchema as gt,getRequiredFieldsFromSchema as zi,getValueAtLocator as Qi,walkSchema as as,makeDataLocationPath as cs,getDataCollectionUpdateFields as nn}from"@membranehq/sdk";import*as P from"node:fs";import{readFileSync as Xi}from"node:fs";import Ie from"js-yaml";import Zi from"lodash/isEqual.js";import ls from"os";import{EventEmitter as er}from"events";import q from"path";import tr from"conf";import sn from"jsonwebtoken";import*as nr from"node:crypto";import{createHash as sr}from"node:crypto";import ir from"chokidar";import D from"fs";import rr from"archiver";import or from"form-data";import ar from"unzipper";import*as cr from"node:os";import{exec as lr}from"node:child_process";import{Spinner as ur,TextInput as fr,Select as hr}from"@inkjs/ui";import yt from"ink-spinner";import dr from"ink-text-input";import{fileURLToPath as pr}from"node:url";import k from"chalk";import{Command as mr}from"commander";import rn from"axios";import{FastMCP as gr}from"fastmcp";import{z as Q}from"zod";import on from"lodash/merge.js";import yr from"@anthropic-ai/sdk";import{faker as Xe}from"@faker-js/faker";import wr from"lodash/template.js";import br from"lodash/templateSettings.js";class He{static{c(this,"ConfigLoader")}static instance=null;sdkLoader;constructor(){this.sdkLoader=new Yi}static getInstance(){return He.instance||(He.instance=new He),He.instance}loadConfig(e){e&&e!==this.sdkLoader.getCwd()&&this.sdkLoader.setCwd(e);try{return this.sdkLoader.loadConfig({validate:!0})}catch(t){if(t.message?.includes("Failed to parse"))throw t;return null}}clearCache(){this.sdkLoader.clearCache()}updateConfig(e){return this.sdkLoader.updateConfig(e)}saveToFile(e){return this.sdkLoader.saveToFile(e)}isCacheDefined(){return this.sdkLoader.hasValidConfig()}}const Ze=He.getInstance(),ie={[M.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")},[M.Connector]:{element:"connector",elements:"connectors",exportable:!1},[M.Action]:{element:"action",elements:"actions",integrationSpecific:!0,exportCleanup:c(s=>(delete s.integration,s),"exportCleanup")},[M.AppDataSchema]:{element:"appDataSchema",elements:"appDataSchemas"},[M.AppEventType]:{element:"appEventType",elements:"appEventTypes"},[M.DataLinkTable]:{element:"dataLinkTable",elements:"dataLinkTables"},[M.DataSource]:{element:"dataSource",elements:"dataSources",parentKey:"universalDataSourceId",integrationSpecific:!0},[M.FieldMapping]:{element:"fieldMapping",elements:"fieldMappings",integrationSpecific:!0,parentKey:"universalFieldMappingId",exportCleanup:c(s=>(delete s.dataSourceId,s),"exportCleanup")},[M.Flow]:{element:"flow",elements:"flows",integrationSpecific:!0,parentKey:"universalFlowId"}};function Sr(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(Sr,"baseExportCleanup");const Cr="membrane",kr=["**/node_modules/**","**/.git/**","**/.DS_Store","**/Thumbs.db","**/*.tmp","**/*.swp","**/*.swo","**/*.log","**/*.lock","**/.cache/**","**/.next/**","**/.vscode/**","**/.idea/**"];function wt(s){return R.join(s,Cr)}c(wt,"getMembraneDir");const Er=["id","workspaceId","integrationId","createdAt","updatedAt","revision","archivedAt","baseUri","state"],us=[M.Action,M.FieldMapping,M.Flow,M.DataSource];class V{static{c(this,"Element")}type;key;integrationKey;data;constructor(e,t,n,i){if(!i)throw new Error("Element must always contain data");if(!t)throw new Error("Element must have a key");this.type=e,this.key=t,this.data=i,this.integrationKey=n||V.extractIntegrationKey(i)}get id(){return V.makeId(this.type,this.key,this.integrationKey)}get dirPath(){const e=ye[this.type].apiPath;if(this.integrationKey){const t=ye[M.Integration].apiPath;return R.join(t,this.integrationKey,e,this.key)}return R.join(e,this.key)}get path(){return R.join(this.dirPath,"spec.yaml")}get relativePath(){return R.relative(wt(process.cwd()),this.path)}isEqual(e){if(this.id!==e.id)return!1;const t=this.clean(),n=e.clean();return Zi(t,n)}hasParent(){const e=this.getParentKey();return!!e&&!!this.data?.[e]}clean(){const e={...this.data};return Er.forEach(t=>{delete e[t]}),Object.keys(e).forEach(t=>{t.match(/universal.*Revision/)&&delete e[t]}),e}getParentKey(){let e="parentId";return ie?.[this.type]?.parentKey&&(e=ie?.[this.type]?.parentKey),e}static new(e,t,n,i){return new V(e,t,n,i)}static fromData(e,t){if(!t?.key)throw new Error(`Element missing key: ${JSON.stringify(t)}`);const n=this.extractIntegrationKey(t);return new V(e,t.key,n,t)}static fromPathAndData(e,t){const n=V.parsePath(e);if(!t)return;const i=t?.key||n?.key;return n?V.new(n.type,i,n.integrationKey,t):void 0}static fromElement(e){return new V(e.type,e.key,e.integrationKey,{...e.data})}static idFromPath(e){const t=V.parsePath(e);if(t)return V.makeId(t.type,t.key,t.integrationKey)}static makeId(e,t,n){return e===M.Integration?`${e}:${t}`:V.isIntegrationSpecific(e)?`${n||"universal"}:${e}:${t}`:`${e}:${t}`}static parsePath(e){const t=this.getRelativePath(e);if(!this.isElementFile(t))return;const n=Object.values(ye).map(l=>l.apiPath).join("|"),i=new RegExp(`^(?<elementType>${n})/(?<elementKey>[^/]+)/spec\\.ya?ml$`),r=t.match(i);if(r?.groups){const{elementType:l,elementKey:u}=r.groups,p=this.getElementTypeFromPath(l);if(p)return{type:p,key:u}}const o=new RegExp(`^integrations/(?<integrationKey>[^/]+)/(?<elementType>${n})/(?<elementKey>[^/]+)/spec\\.ya?ml$`),a=t.match(o);if(a?.groups){const{integrationKey:l,elementType:u,elementKey:p}=a.groups,d=this.getElementTypeFromPath(u);if(d)return{type:d,key:p,integrationKey:l}}}static extractIntegrationKey(e){return e?.integrationKey||e?.integration?.key||e?.integration_key||void 0}static isElementFile(e){return e.endsWith(".yml")||e.endsWith(".yaml")}static getElementTypeFromPath(e){return Object.values(M).find(t=>ye[t].apiPath===e)}static getRelativePath(e){return R.relative(wt(process.cwd()),e)}static isIntegrationSpecific(e){return us.includes(e)}static canBeIntegrationSpecific(e){return us.includes(e)}}const W={LogAdded:"logAdded",StateChanged:"stateChanged",StatsChanged:"statsChanged",ConflictsChanged:"conflictsChanged",McpStatusChanged:"mcpStatusChanged",McpServersChanged:"mcpServersChanged",ConfigChanged:"configChanged"};class fs extends er{static{c(this,"TypedEventEmitter")}on(e,t){return super.on(e,t)}emit(e,...t){return super.emit(e,...t)}off(e,t){return super.off(e,t)}once(e,t){return super.once(e,t)}}const vr="membrane",Ir="membrane.config.yml",an="https://api.integration.app";function cn(){const s=process.cwd(),e=R.join(s,vr),t=R.join(s,Ir),n=e,i=R.join(n,"workspace.yaml");return{membraneDirPath:e,configPath:t,payloadDirPath:n,workspaceDataFilePath:i}}c(cn,"getPaths");function Tr(){return cn().membraneDirPath}c(Tr,"getBasePath");const Nr={pat:{type:"string"},workspace:{type:"object"}},hs=new tr({schema:Nr,configName:"config",cwd:q.join(ls.homedir(),".membrane")}),Ar=c(s=>{hs.set("pat",s)},"setPat"),ds=c(()=>hs.get("pat"),"getPat");class ps{static{c(this,"AccountApiClient")}constructor(e=an){this.apiBaseUrl=e}async request(e,t={}){const n=t.headers?t.headers instanceof Headers?new Headers(t.headers):new Headers(t.headers):new Headers;if(!n.has("Authorization")){const o=ds();if(!o)throw new Error("Personal Access Token not found.");n.set("Authorization",`Bearer ${o}`)}t.body&&!n.has("Content-Type")&&n.set("Content-Type","application/json");const i=await fetch(`${this.apiBaseUrl}${e}`,{...t,headers:n});if(!i.ok){const o=await i.text();throw new Error(`API request failed: ${i.status} ${i.statusText} - ${o}`)}if(i.status===204)return{};const r=await i.text();return JSON.parse(r)}get(e){return this.request(e,{method:"GET"})}post(e,t){return this.request(e,{method:"POST",body:JSON.stringify(t)})}put(e,t){return this.request(e,{method:"PUT",body:JSON.stringify(t)})}patch(e,t){return this.request(e,{method:"PATCH",body:JSON.stringify(t)})}delete(e){return this.request(e,{method:"DELETE"})}}const Or=c(s=>{const e=new ps(an);return t=>e.get(t)},"createAccountApiFetcher");function bt(s){return Ze.loadConfig(s)}c(bt,"readProjectConfig");class $r{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();constructor(e={}){this.windowSizeMs=e.windowSizeMs||1e3,this.maxRequestsPerSecond=e.maxRequestsPerSecond||80,this.maxConcurrentRequests=e.maxConcurrentRequests||Math.min(this.maxRequestsPerSecond/4,20),this.maxRetries=e.maxRetries||3,this.retryDelay=e.retryDelay||1e3,this.requestTimeout=e.requestTimeout||12e4,this.enableJitter=e.enableJitter!==!1}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()}})}async generateAccessToken(e,t){return sn.sign({name:"Membrane Agent",isAdmin:!0,exp:Math.floor(Date.now()/1e3)+3600,iss:e},t,{algorithm:"HS512"})}isTokenValid(){return Date.now()<this.tokenExpiry}getCurrentConfig(e){const t=bt(e);return!t?.workspaceKey||!t?.workspaceSecret?null:{workspaceKey:t.workspaceKey,workspaceSecret:t.workspaceSecret,apiUri:t.apiUri}}async createClient(e){const t=await this.generateAccessToken(e.workspaceKey,e.workspaceSecret);return this.tokenExpiry=Date.now()+36e5,this.currentConfig=e,new rs({token:t,apiUri:e.apiUri})}async getClient(e=process.cwd()){const t=this.getCurrentConfig(e);if(!t)throw new Error("Unable to create MembraneClient: No workspace configuration found.");const n=!this.currentConfig||this.currentConfig.workspaceKey!==t.workspaceKey||this.currentConfig.workspaceSecret!==t.workspaceSecret||this.currentConfig.apiUri!==t.apiUri,i=!this.isTokenValid()||this.tokenExpiry-Date.now()<3e5;return(!this.client||n||i)&&(this.client=await this.createClient(t)),this.client}clearClient(){this.client=null,this.currentConfig=null,this.tokenExpiry=0,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){let t;for(let n=0;n<=this.maxRetries;n++)try{return await e()}catch(i){if(t=i,!this.isRetryableError(i)||n===this.maxRetries)throw i;let r=this.retryDelay*Math.pow(2,n);if(this.enableJitter){const o=r*.25*(Math.random()*2-1);r=Math.max(0,r+o)}await new Promise(o=>setTimeout(o,r))}throw t||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 i=new Promise((r,o)=>{n=setTimeout(()=>o(new Error(`Request timeout after ${t}ms`)),t)});try{const r=await Promise.race([e,i]);return n&&clearTimeout(n),r}catch(r){throw n&&clearTimeout(n),r}}}const F=new $r;async function ms(s){const{id:e}=await F.withClient(t=>t.get("org-workspace-id"),s);return e}c(ms,"getWorkspaceId");class Lr extends fs{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(W.StateChanged,{state:e}),await this.emitRemote({status:e})}setConflicts(e){this.emit(W.ConflictsChanged,{conflicts:e})}setConfig(e){this.emit(W.ConfigChanged,{config:e})}setStats(e){this.emit(W.StatsChanged,{stats:e})}addLog(e){this.emit(W.LogAdded,{log:e})}setMcpStatus(e){this.emit(W.McpStatusChanged,{status:e})}async setMcpServers(e){this.emit(W.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 F.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 F.withClient(t=>t.post("/local-clients",{hostname:ls.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 F.withClient(e=>e.post(`/local-clients/${this.clientId}/keep-alive`,{}))})}async emitRemote(e){this.clientId&&await this.withErrorHandling(async()=>{await F.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 de=new Lr({heartbeatIntervalMs:15e3});class xr{static{c(this,"WorkspaceLogger")}_logs;workspaceNotifications;constructor(){this._logs=[],this.workspaceNotifications=de}get logs(){return[...this._logs]}get latestLogs(){return this._logs.slice(this._logs.length-5)}log(e,t="info"){const n={timestamp:new Date().toISOString(),message:e,type:t};this._logs.push(n),this._logs=this._logs.slice(0,1e3),this.workspaceNotifications.addLog(n)}info(e){this.log(e,"info")}success(e){this.log(e,"success")}warning(e){this.log(e,"warning")}error(e){this.log(e,"error")}clear(){this._logs=[]}}const N=new xr;class gs{static{c(this,"BaseWorkspaceElementsRepository")}constructor(e){this.cache=e}connectorsMapping;setConnectorsMapping(e){this.connectorsMapping=e}async getElements(){const e=[];try{const t=await this.getIntegrations();e.push(...t);const n=[M.Integration,M.Connector],i=Object.keys(ie),r=await Promise.all(i.filter(o=>!n.includes(o)).map(async o=>this.getElementsByType(o,t)));for(const o of r)e.push(...o)}catch(t){throw N.error(`Failed to get elements: ${t}`),t}return e}async putElement(e){let t=this.cache.get(e.id);return e.data.id&&t?t=await this.updateElement(e,t,{elements:this.cache.getAll(),connectorsMapping:this.connectorsMapping}):t=await this.createElement(e,{elements:this.cache.getAll(),connectorsMapping:this.connectorsMapping}),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 deleteElement(e,t){}}class Pr extends gs{static{c(this,"LocalWorkspaceElementsRepository")}basePath;constructor(e){super(e),this.basePath=wt(process.cwd())}async getElementsByType(e,t){const n=[],i=R.join(this.basePath,ye[e].apiPath),r=await this.readElementsInDir(i);n.push(...r);for(const o of t){const a=R.join(this.basePath,ye[M.Integration].apiPath,o.key,ye[e].apiPath),l=await this.readElementsInDir(a);n.push(...l)}return n.length>0&&N.success(`[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=R.join(this.basePath,t.dirPath),i=R.join(this.basePath,t.path);return P.existsSync(n)||P.mkdirSync(n,{recursive:!0}),P.writeFileSync(i,Ie.dump(e.data)),N.info(`[local] Written ${t.relativePath}`),t}async deleteElement(e){const t=R.join(this.basePath,e.path),n=R.join(this.basePath,e.dirPath);P.existsSync(t)&&P.rmSync(t,{force:!0}),this.pruneEmptyDir(n),N.info(`[local] Deleted ${e.relativePath}`)}async getIntegrations(){const e=R.join(this.basePath,ye[M.Integration].apiPath);return this.readElementsInDir(e)}async readElement(e){if(!P.existsSync(e))return;const t=P.readFileSync(e,"utf8"),n=Ie.load(t);if(n)return V.fromPathAndData(e,n)}async readElementsInDir(e){const t=[];if(!P.existsSync(e))return t;const n=P.readdirSync(e);if(n.length===0)return t;const i=n.map(async o=>{const a=R.join(e,o,"spec.yaml");return this.readElement(a)});return(await Promise.all(i)).filter(o=>o!=null)}pruneEmptyDir(e){try{if(!e.startsWith(this.basePath)||e===this.basePath||!P.existsSync(e)||P.readdirSync(e).length>0)return;P.rmdirSync(e),this.pruneEmptyDir(R.dirname(e))}catch(t){console.warn(`Failed to prune empty directory ${e}:`,t)}}}class Dr extends gs{static{c(this,"RemoteWorkspaceElementsRepository")}async getElementsByType(e,t){const n=await this.findAll(e);if(!V.canBeIntegrationSpecific(e))return n;for(const i of t){const r=i.key,o=i.data.id,a=await this.findAll(e,o?{integrationId:o}:{integrationKey:r});n.push(...a)}return n.length>0&&N.success(`[remote] Fetched ${n.length} ${e}${n.length!==1?"s":""}`),n}async getElement(e){const t=await F.withClient(n=>n[ie[e.type].element](e.data.id).get(),process.cwd());return V.fromData(e.type,t)}async createElement(e,t){const n=e.clean();this.transformElementForCreate(e,n,t);const i=await F.withClient(o=>o[ie[e.type].elements].create(n),process.cwd()),r=V.fromData(e.type,i);return N.info(`[remote] Created ${r.id}`),r}async updateElement(e,t,n){if(!e.data.id)throw new Error("Element must have an id to update");const i=e.clean();this.transformElementForUpdate(e,i,n);const r=await F.withClient(a=>a[ie[e.type].element](t.data.id).put(i),process.cwd()),o=V.fromData(t.type,r);return N.info(`[remote] Updated ${t.id}`),o}async deleteElement(e){if(!e.data.id)throw new Error("Element must have an id to delete");await F.withClient(t=>t[ie[e.type].element](e.data.id).archive(),process.cwd()),N.info(`[remote] Deleted ${e.id}`)}async getIntegrations(){const t=(await F.withClient(n=>n.integrations.findAll(),process.cwd())).map(n=>V.fromData(M.Integration,n));return t.length>0&&N.success(`[remote] Fetched ${t.length} integrations`),t}transformElementForCreate(e,t,n){if(e.integrationKey){const i=n.elements.find(r=>r.type===M.Integration&&r.key===e.integrationKey);if(i)t.integrationId=i.data.id;else throw new Error(`Dependency integration ${e.integrationKey} not found for ${e.id}`)}if(e.type===M.Integration){const i=n.connectorsMapping?.[t.connectorId];i&&(t.connectorId=i)}this.transformParentDependency(e,t,n)}transformElementForUpdate(e,t,n){if(e.type===M.Integration){const i=n.connectorsMapping?.[t.connectorId];i&&(t.connectorId=i)}if(e.integrationKey){t.integrationKey=e.integrationKey;const i=n.elements.find(r=>r.type===M.Integration&&r.key===e.integrationKey);if(i)t.integrationId=i.data.id;else throw new Error(`Dependency integration ${e.integrationKey} not found for ${e.id}`)}this.transformParentDependency(e,t,n)}transformParentDependency(e,t,n){if(!e.hasParent())return;const i=e.getParentKey();if(!i)return;const r=n.elements.find(o=>o.type===e.type&&o.key===e.key&&!o.hasParent());if(r)t[i]=r.data.id;else throw new Error(`Parent ${e.getParentKey()} not found for ${e.id}`)}async findAll(e,t={}){return(await F.withClient(i=>i[ie[e].elements].findAll(t),process.cwd())).filter(i=>i.key).map(i=>V.fromData(e,i))}}class ys{static{c(this,"ElementsCache")}elements=new Map;typeIndex=new Map;constructor(e){e&&this.addAll(e)}add(e){const t=e.id;this.elements.set(t,e),this.typeIndex.has(e.type)||this.typeIndex.set(e.type,new Set),this.typeIndex.get(e.type).add(t)}remove(e){const t=e.id,n=this.elements.delete(t);if(n){const i=this.typeIndex.get(e.type);i&&(i.delete(t),i.size===0&&this.typeIndex.delete(e.type))}return n}put(e){this.elements.has(e.id)&&this.remove(e),this.add(e)}get(e){return this.elements.get(e)}getElementsByType(e){const t=this.typeIndex.get(e);return t?Array.from(t).map(n=>this.elements.get(n)).filter(n=>n!==void 0):[]}getAll(){return Array.from(this.elements.values())??[]}getTypes(){return Array.from(this.typeIndex.keys())}addAll(e){for(const t of e)t&&this.add(t)}removeAll(e){for(const t of e)this.remove(t)}getElementIdsByType(e){return this.typeIndex.get(e)}clear(){this.elements.clear(),this.typeIndex.clear()}getAllIds(){return new Set(this.elements.keys())}}const ln=Symbol.for("yaml.alias"),un=Symbol.for("yaml.document"),we=Symbol.for("yaml.map"),ws=Symbol.for("yaml.pair"),fe=Symbol.for("yaml.scalar"),Re=Symbol.for("yaml.seq"),re=Symbol.for("yaml.node.type"),be=c(s=>!!s&&typeof s=="object"&&s[re]===ln,"isAlias"),Te=c(s=>!!s&&typeof s=="object"&&s[re]===un,"isDocument"),Me=c(s=>!!s&&typeof s=="object"&&s[re]===we,"isMap"),B=c(s=>!!s&&typeof s=="object"&&s[re]===ws,"isPair"),_=c(s=>!!s&&typeof s=="object"&&s[re]===fe,"isScalar$1"),_e=c(s=>!!s&&typeof s=="object"&&s[re]===Re,"isSeq");function U(s){if(s&&typeof s=="object")switch(s[re]){case we:case Re:return!0}return!1}c(U,"isCollection$1");function J(s){if(s&&typeof s=="object")switch(s[re]){case ln:case we:case fe:case Re:return!0}return!1}c(J,"isNode");const bs=c(s=>(_(s)||U(s))&&!!s.anchor,"hasAnchor"),te=Symbol("break visit"),Ss=Symbol("skip children"),he=Symbol("remove node");function Ne(s,e){const t=Cs(e);Te(s)?Ke(null,s.contents,t,Object.freeze([s]))===he&&(s.contents=null):Ke(null,s,t,Object.freeze([]))}c(Ne,"visit$1"),Ne.BREAK=te,Ne.SKIP=Ss,Ne.REMOVE=he;function Ke(s,e,t,n){const i=ks(s,e,t,n);if(J(i)||B(i))return Es(s,n,i),Ke(s,i,t,n);if(typeof i!="symbol"){if(U(e)){n=Object.freeze(n.concat(e));for(let r=0;r<e.items.length;++r){const o=Ke(r,e.items[r],t,n);if(typeof o=="number")r=o-1;else{if(o===te)return te;o===he&&(e.items.splice(r,1),r-=1)}}}else if(B(e)){n=Object.freeze(n.concat(e));const r=Ke("key",e.key,t,n);if(r===te)return te;r===he&&(e.key=null);const o=Ke("value",e.value,t,n);if(o===te)return te;o===he&&(e.value=null)}}return i}c(Ke,"visit_");async function St(s,e){const t=Cs(e);Te(s)?await je(null,s.contents,t,Object.freeze([s]))===he&&(s.contents=null):await je(null,s,t,Object.freeze([]))}c(St,"visitAsync"),St.BREAK=te,St.SKIP=Ss,St.REMOVE=he;async function je(s,e,t,n){const i=await ks(s,e,t,n);if(J(i)||B(i))return Es(s,n,i),je(s,i,t,n);if(typeof i!="symbol"){if(U(e)){n=Object.freeze(n.concat(e));for(let r=0;r<e.items.length;++r){const o=await je(r,e.items[r],t,n);if(typeof o=="number")r=o-1;else{if(o===te)return te;o===he&&(e.items.splice(r,1),r-=1)}}}else if(B(e)){n=Object.freeze(n.concat(e));const r=await je("key",e.key,t,n);if(r===te)return te;r===he&&(e.key=null);const o=await je("value",e.value,t,n);if(o===te)return te;o===he&&(e.value=null)}}return i}c(je,"visitAsync_");function Cs(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(Cs,"initVisitor");function ks(s,e,t,n){if(typeof t=="function")return t(s,e,n);if(Me(e))return t.Map?.(s,e,n);if(_e(e))return t.Seq?.(s,e,n);if(B(e))return t.Pair?.(s,e,n);if(_(e))return t.Scalar?.(s,e,n);if(be(e))return t.Alias?.(s,e,n)}c(ks,"callVisitor");function Es(s,e,t){const n=e[e.length-1];if(U(n))n.items[s]=t;else if(B(n))s==="key"?n.key=t:n.value=t;else if(Te(n))n.contents=t;else{const i=be(n)?"alias":"scalar";throw new Error(`Cannot replace node with ${i} parent`)}}c(Es,"replaceNode");const Rr={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},Mr=c(s=>s.replace(/[!,[\]{}]/g,e=>Rr[e]),"escapeTagName");class ee{static{c(this,"Directives")}constructor(e,t){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},ee.defaultYaml,e),this.tags=Object.assign({},ee.defaultTags,t)}clone(){const e=new ee(this.yaml,this.tags);return e.docStart=this.docStart,e}atDocument(){const e=new ee(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:ee.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},ee.defaultTags);break}return e}add(e,t){this.atNextDocument&&(this.yaml={explicit:ee.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},ee.defaultTags),this.atNextDocument=!1);const n=e.trim().split(/[ \t]+/),i=n.shift();switch(i){case"%TAG":{if(n.length!==2&&(t(0,"%TAG directive should contain exactly two parts"),n.length<2))return!1;const[r,o]=n;return this.tags[r]=o,!0}case"%YAML":{if(this.yaml.explicit=!0,n.length!==1)return t(0,"%YAML directive should contain exactly one part"),!1;const[r]=n;if(r==="1.1"||r==="1.2")return this.yaml.version=r,!0;{const o=/^\d+\.\d+$/.test(r);return t(6,`Unsupported YAML version ${r}`,o),!1}}default:return t(0,`Unknown directive ${i}`,!0),!1}}tagName(e,t){if(e==="!")return"!";if(e[0]!=="!")return t(`Not a valid tag: ${e}`),null;if(e[1]==="<"){const o=e.slice(2,-1);return o==="!"||o==="!!"?(t(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==">"&&t("Verbatim tags must end with a >"),o)}const[,n,i]=e.match(/^(.*!)([^!]*)$/s);i||t(`The ${e} tag has no suffix`);const r=this.tags[n];if(r)try{return r+decodeURIComponent(i)}catch(o){return t(String(o)),null}return n==="!"?e:(t(`Could not resolve tag: ${e}`),null)}tagString(e){for(const[t,n]of Object.entries(this.tags))if(e.startsWith(n))return t+Mr(e.substring(n.length));return e[0]==="!"?e:`!<${e}>`}toString(e){const t=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],n=Object.entries(this.tags);let i;if(e&&n.length>0&&J(e.contents)){const r={};Ne(e.contents,(o,a)=>{J(a)&&a.tag&&(r[a.tag]=!0)}),i=Object.keys(r)}else i=[];for(const[r,o]of n)r==="!!"&&o==="tag:yaml.org,2002:"||(!e||i.some(a=>a.startsWith(o)))&&t.push(`%TAG ${r} ${o}`);return t.join(`
3
+ `)}}ee.defaultYaml={explicit:!1,version:"1.2"},ee.defaultTags={"!!":"tag:yaml.org,2002:"};function vs(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(vs,"anchorIsValid");function Is(s){const e=new Set;return Ne(s,{Value(t,n){n.anchor&&e.add(n.anchor)}}),e}c(Is,"anchorNames");function Ts(s,e){for(let t=1;;++t){const n=`${s}${t}`;if(!e.has(n))return n}}c(Ts,"findNewAnchor");function _r(s,e){const t=[],n=new Map;let i=null;return{onAnchor:c(r=>{t.push(r),i??(i=Is(s));const o=Ts(e,i);return i.add(o),o},"onAnchor"),setAnchors:c(()=>{for(const r of t){const o=n.get(r);if(typeof o=="object"&&o.anchor&&(_(o.node)||U(o.node)))o.node.anchor=o.anchor;else{const a=new Error("Failed to resolve repeated object (this should not happen)");throw a.source=r,a}}},"setAnchors"),sourceObjects:n}}c(_r,"createNodeAnchors");function Fe(s,e,t,n){if(n&&typeof n=="object")if(Array.isArray(n))for(let i=0,r=n.length;i<r;++i){const o=n[i],a=Fe(s,n,String(i),o);a===void 0?delete n[i]:a!==o&&(n[i]=a)}else if(n instanceof Map)for(const i of Array.from(n.keys())){const r=n.get(i),o=Fe(s,n,i,r);o===void 0?n.delete(i):o!==r&&n.set(i,o)}else if(n instanceof Set)for(const i of Array.from(n)){const r=Fe(s,n,i,i);r===void 0?n.delete(i):r!==i&&(n.delete(i),n.add(r))}else for(const[i,r]of Object.entries(n)){const o=Fe(s,n,i,r);o===void 0?delete n[i]:o!==r&&(n[i]=o)}return s.call(e,t,n)}c(Fe,"applyReviver");function oe(s,e,t){if(Array.isArray(s))return s.map((n,i)=>oe(n,String(i),t));if(s&&typeof s.toJSON=="function"){if(!t||!bs(s))return s.toJSON(e,t);const n={aliasCount:0,count:1,res:void 0};t.anchors.set(s,n),t.onCreate=r=>{n.res=r,delete t.onCreate};const i=s.toJSON(e,t);return t.onCreate&&t.onCreate(i),i}return typeof s=="bigint"&&!t?.keep?Number(s):s}c(oe,"toJS");class fn{static{c(this,"NodeBase")}constructor(e){Object.defineProperty(this,re,{value:e})}clone(){const e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:t,maxAliasCount:n,onAnchor:i,reviver:r}={}){if(!Te(e))throw new TypeError("A document argument is required");const o={anchors:new Map,doc:e,keep:!0,mapAsMap:t===!0,mapKeyWarned:!1,maxAliasCount:typeof n=="number"?n:100},a=oe(this,"",o);if(typeof i=="function")for(const{count:l,res:u}of o.anchors.values())i(u,l);return typeof r=="function"?Fe(r,{"":a},"",a):a}}class Ct extends fn{static{c(this,"Alias")}constructor(e){super(ln),this.source=e,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(e,t){let n;t?.aliasResolveCache?n=t.aliasResolveCache:(n=[],Ne(e,{Node:c((r,o)=>{(be(o)||bs(o))&&n.push(o)},"Node")}),t&&(t.aliasResolveCache=n));let i;for(const r of n){if(r===this)break;r.anchor===this.source&&(i=r)}return i}toJSON(e,t){if(!t)return{source:this.source};const{anchors:n,doc:i,maxAliasCount:r}=t,o=this.resolve(i,t);if(!o){const l=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(l)}let a=n.get(o);if(a||(oe(o,null,t),a=n.get(o)),!a||a.res===void 0){const l="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(l)}if(r>=0&&(a.count+=1,a.aliasCount===0&&(a.aliasCount=kt(i,o,n)),a.count*a.aliasCount>r)){const l="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(l)}return a.res}toString(e,t,n){const i=`*${this.source}`;if(e){if(vs(this.source),e.options.verifyAliasOrder&&!e.anchors.has(this.source)){const r=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(r)}if(e.implicitKey)return`${i} `}return i}}function kt(s,e,t){if(be(e)){const n=e.resolve(s),i=t&&n&&t.get(n);return i?i.count*i.aliasCount:0}else if(U(e)){let n=0;for(const i of e.items){const r=kt(s,i,t);r>n&&(n=r)}return n}else if(B(e)){const n=kt(s,e.key,t),i=kt(s,e.value,t);return Math.max(n,i)}return 1}c(kt,"getAliasCount");const Ns=c(s=>!s||typeof s!="function"&&typeof s!="object","isScalarValue");class x extends fn{static{c(this,"Scalar")}constructor(e){super(fe),this.value=e}toJSON(e,t){return t?.keep?this.value:oe(this.value,e,t)}toString(){return String(this.value)}}x.BLOCK_FOLDED="BLOCK_FOLDED",x.BLOCK_LITERAL="BLOCK_LITERAL",x.PLAIN="PLAIN",x.QUOTE_DOUBLE="QUOTE_DOUBLE",x.QUOTE_SINGLE="QUOTE_SINGLE";const Kr="tag:yaml.org,2002:";function jr(s,e,t){if(e){const n=t.filter(r=>r.tag===e),i=n.find(r=>!r.format)??n[0];if(!i)throw new Error(`Tag ${e} not found`);return i}return t.find(n=>n.identify?.(s)&&!n.format)}c(jr,"findTagObject");function et(s,e,t){if(Te(s)&&(s=s.contents),J(s))return s;if(B(s)){const d=t.schema[we].createNode?.(t.schema,null,t);return d.items.push(s),d}(s instanceof String||s instanceof Number||s instanceof Boolean||typeof BigInt<"u"&&s instanceof BigInt)&&(s=s.valueOf());const{aliasDuplicateObjects:n,onAnchor:i,onTagObj:r,schema:o,sourceObjects:a}=t;let l;if(n&&s&&typeof s=="object"){if(l=a.get(s),l)return l.anchor??(l.anchor=i(s)),new Ct(l.anchor);l={anchor:null,node:null},a.set(s,l)}e?.startsWith("!!")&&(e=Kr+e.slice(2));let u=jr(s,e,o.tags);if(!u){if(s&&typeof s.toJSON=="function"&&(s=s.toJSON()),!s||typeof s!="object"){const d=new x(s);return l&&(l.node=d),d}u=s instanceof Map?o[we]:Symbol.iterator in Object(s)?o[Re]:o[we]}r&&(r(u),delete t.onTagObj);const p=u?.createNode?u.createNode(t.schema,s,t):typeof u?.nodeClass?.from=="function"?u.nodeClass.from(t.schema,s,t):new x(s);return e?p.tag=e:u.default||(p.tag=u.tag),l&&(l.node=p),p}c(et,"createNode");function Et(s,e,t){let n=t;for(let i=e.length-1;i>=0;--i){const r=e[i];if(typeof r=="number"&&Number.isInteger(r)&&r>=0){const o=[];o[r]=n,n=o}else n=new Map([[r,n]])}return et(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(Et,"collectionFromPath");const tt=c(s=>s==null||typeof s=="object"&&!!s[Symbol.iterator]().next().done,"isEmptyPath");class As extends fn{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=>J(n)||B(n)?n.clone(e):n),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(tt(e))this.add(t);else{const[n,...i]=e,r=this.get(n,!0);if(U(r))r.addIn(i,t);else if(r===void 0&&this.schema)this.set(n,Et(this.schema,i,t));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${i}`)}}deleteIn(e){const[t,...n]=e;if(n.length===0)return this.delete(t);const i=this.get(t,!0);if(U(i))return i.deleteIn(n);throw new Error(`Expected YAML collection at ${t}. Remaining path: ${n}`)}getIn(e,t){const[n,...i]=e,r=this.get(n,!0);return i.length===0?!t&&_(r)?r.value:r:U(r)?r.getIn(i,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!B(t))return!1;const n=t.value;return n==null||e&&_(n)&&n.value==null&&!n.commentBefore&&!n.comment&&!n.tag})}hasIn(e){const[t,...n]=e;if(n.length===0)return this.has(t);const i=this.get(t,!0);return U(i)?i.hasIn(n):!1}setIn(e,t){const[n,...i]=e;if(i.length===0)this.set(n,t);else{const r=this.get(n,!0);if(U(r))r.setIn(i,t);else if(r===void 0&&this.schema)this.set(n,Et(this.schema,i,t));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${i}`)}}}const Fr=c(s=>s.replace(/^(?!$)(?: $)?/gm,"#"),"stringifyComment");function pe(s,e){return/^\n+$/.test(s)?s.substring(1):e?s.replace(/^(?! *$)/gm,e):s}c(pe,"indentComment");const Ae=c((s,e,t)=>s.endsWith(`
4
+ `)?pe(t,e):t.includes(`
5
5
  `)?`
6
- `+me(t,e):(s.endsWith(" ")?"":" ")+t,"lineComment"),$s="flow",dn="block",It="quoted";function Tt(s,e,t="flow",{indentAtStart:n,lineWidth:i=80,minContentWidth:r=20,onFold:o,onOverflow:a}={}){if(!i||i<0)return s;i<r&&(r=0);const l=Math.max(1+r,1+i-e.length);if(s.length<=l)return s;const u=[],p={};let d=i-e.length;typeof n=="number"&&(n>i-Math.max(2,r)?u.push(0):d=i-n);let h,g,w=!1,f=-1,y=-1,C=-1;t===dn&&(f=Ls(s,f,e.length),f!==-1&&(d=f+l));for(let A;A=s[f+=1];){if(t===It&&A==="\\"){switch(y=f,s[f+1]){case"x":f+=3;break;case"u":f+=5;break;case"U":f+=9;break;default:f+=1}C=f}if(A===`
7
- `)t===dn&&(f=Ls(s,f,e.length)),d=f+e.length+l,h=void 0;else{if(A===" "&&g&&g!==" "&&g!==`
6
+ `+pe(t,e):(s.endsWith(" ")?"":" ")+t,"lineComment"),Os="flow",hn="block",vt="quoted";function It(s,e,t="flow",{indentAtStart:n,lineWidth:i=80,minContentWidth:r=20,onFold:o,onOverflow:a}={}){if(!i||i<0)return s;i<r&&(r=0);const l=Math.max(1+r,1+i-e.length);if(s.length<=l)return s;const u=[],p={};let d=i-e.length;typeof n=="number"&&(n>i-Math.max(2,r)?u.push(0):d=i-n);let h,g,w=!1,f=-1,y=-1,C=-1;t===hn&&(f=$s(s,f,e.length),f!==-1&&(d=f+l));for(let A;A=s[f+=1];){if(t===vt&&A==="\\"){switch(y=f,s[f+1]){case"x":f+=3;break;case"u":f+=5;break;case"U":f+=9;break;default:f+=1}C=f}if(A===`
7
+ `)t===hn&&(f=$s(s,f,e.length)),d=f+e.length+l,h=void 0;else{if(A===" "&&g&&g!==" "&&g!==`
8
8
  `&&g!==" "){const I=s[f+1];I&&I!==" "&&I!==`
9
- `&&I!==" "&&(h=f)}if(f>=d)if(h)u.push(h),d=h+l,h=void 0;else if(t===It){for(;g===" "||g===" ";)g=A,A=s[f+=1],w=!0;const I=f>C+1?f-2:y-1;if(p[I])return s;u.push(I),p[I]=!0,d=I+l,h=void 0}else w=!0}g=A}if(w&&a&&a(),u.length===0)return s;o&&o();let E=s.slice(0,u[0]);for(let A=0;A<u.length;++A){const I=u[A],O=u[A+1]||s.length;I===0?E=`
10
- ${e}${s.slice(0,O)}`:(t===It&&p[I]&&(E+=`${s[I]}\\`),E+=`
11
- ${e}${s.slice(I+1,O)}`)}return E}c(Tt,"foldFlowLines");function Ls(s,e,t){let n=e,i=e+1,r=s[i];for(;r===" "||r===" ";)if(e<i+t)r=s[++e];else{do r=s[++e];while(r&&r!==`
12
- `);n=e,i=e+1,r=s[i]}return n}c(Ls,"consumeMoreIndentedLines");const Nt=c((s,e)=>({indentAtStart:e?s.indent.length:s.indentAtStart,lineWidth:s.options.lineWidth,minContentWidth:s.options.minContentWidth}),"getFoldOptions"),At=c(s=>/^(%|---|\.\.\.)/m.test(s),"containsDocumentMarker");function Ur(s,e,t){if(!e||e<0)return!1;const n=e-t,i=s.length;if(i<=n)return!1;for(let r=0,o=0;r<i;++r)if(s[r]===`
13
- `){if(r-o>n)return!0;if(o=r+1,i-o<=n)return!1}return!0}c(Ur,"lineLengthOverLimit");function st(s,e){const t=JSON.stringify(s);if(e.options.doubleQuotedAsJSON)return t;const{implicitKey:n}=e,i=e.options.doubleQuotedMinMultiLineLength,r=e.indent||(At(s)?" ":"");let o="",a=0;for(let l=0,u=t[l];u;u=t[++l])if(u===" "&&t[l+1]==="\\"&&t[l+2]==="n"&&(o+=t.slice(a,l)+"\\ ",l+=1,a=l,u="\\"),u==="\\")switch(t[l+1]){case"u":{o+=t.slice(a,l);const p=t.substr(l+2,4);switch(p){case"0000":o+="\\0";break;case"0007":o+="\\a";break;case"000b":o+="\\v";break;case"001b":o+="\\e";break;case"0085":o+="\\N";break;case"00a0":o+="\\_";break;case"2028":o+="\\L";break;case"2029":o+="\\P";break;default:p.substr(0,2)==="00"?o+="\\x"+p.substr(2):o+=t.substr(l,6)}l+=5,a=l+1}break;case"n":if(n||t[l+2]==='"'||t.length<i)l+=1;else{for(o+=t.slice(a,l)+`
9
+ `&&I!==" "&&(h=f)}if(f>=d)if(h)u.push(h),d=h+l,h=void 0;else if(t===vt){for(;g===" "||g===" ";)g=A,A=s[f+=1],w=!0;const I=f>C+1?f-2:y-1;if(p[I])return s;u.push(I),p[I]=!0,d=I+l,h=void 0}else w=!0}g=A}if(w&&a&&a(),u.length===0)return s;o&&o();let E=s.slice(0,u[0]);for(let A=0;A<u.length;++A){const I=u[A],O=u[A+1]||s.length;I===0?E=`
10
+ ${e}${s.slice(0,O)}`:(t===vt&&p[I]&&(E+=`${s[I]}\\`),E+=`
11
+ ${e}${s.slice(I+1,O)}`)}return E}c(It,"foldFlowLines");function $s(s,e,t){let n=e,i=e+1,r=s[i];for(;r===" "||r===" ";)if(e<i+t)r=s[++e];else{do r=s[++e];while(r&&r!==`
12
+ `);n=e,i=e+1,r=s[i]}return n}c($s,"consumeMoreIndentedLines");const Tt=c((s,e)=>({indentAtStart:e?s.indent.length:s.indentAtStart,lineWidth:s.options.lineWidth,minContentWidth:s.options.minContentWidth}),"getFoldOptions"),Nt=c(s=>/^(%|---|\.\.\.)/m.test(s),"containsDocumentMarker");function Br(s,e,t){if(!e||e<0)return!1;const n=e-t,i=s.length;if(i<=n)return!1;for(let r=0,o=0;r<i;++r)if(s[r]===`
13
+ `){if(r-o>n)return!0;if(o=r+1,i-o<=n)return!1}return!0}c(Br,"lineLengthOverLimit");function nt(s,e){const t=JSON.stringify(s);if(e.options.doubleQuotedAsJSON)return t;const{implicitKey:n}=e,i=e.options.doubleQuotedMinMultiLineLength,r=e.indent||(Nt(s)?" ":"");let o="",a=0;for(let l=0,u=t[l];u;u=t[++l])if(u===" "&&t[l+1]==="\\"&&t[l+2]==="n"&&(o+=t.slice(a,l)+"\\ ",l+=1,a=l,u="\\"),u==="\\")switch(t[l+1]){case"u":{o+=t.slice(a,l);const p=t.substr(l+2,4);switch(p){case"0000":o+="\\0";break;case"0007":o+="\\a";break;case"000b":o+="\\v";break;case"001b":o+="\\e";break;case"0085":o+="\\N";break;case"00a0":o+="\\_";break;case"2028":o+="\\L";break;case"2029":o+="\\P";break;default:p.substr(0,2)==="00"?o+="\\x"+p.substr(2):o+=t.substr(l,6)}l+=5,a=l+1}break;case"n":if(n||t[l+2]==='"'||t.length<i)l+=1;else{for(o+=t.slice(a,l)+`
14
14
 
15
15
  `;t[l+2]==="\\"&&t[l+3]==="n"&&t[l+4]!=='"';)o+=`
16
- `,l+=2;o+=r,t[l+2]===" "&&(o+="\\"),l+=1,a=l+1}break;default:l+=1}return o=a?o+t.slice(a):t,n?o:Tt(o,r,It,Nt(e,!1))}c(st,"doubleQuotedString");function pn(s,e){if(e.options.singleQuote===!1||e.implicitKey&&s.includes(`
17
- `)||/[ \t]\n|\n[ \t]/.test(s))return st(s,e);const t=e.indent||(At(s)?" ":""),n="'"+s.replace(/'/g,"''").replace(/\n+/g,`$&
18
- ${t}`)+"'";return e.implicitKey?n:Tt(n,t,$s,Nt(e,!1))}c(pn,"singleQuotedString");function qe(s,e){const{singleQuote:t}=e.options;let n;if(t===!1)n=st;else{const i=s.includes('"'),r=s.includes("'");i&&!r?n=pn:r&&!i?n=st:n=t?pn:st}return n(s,e)}c(qe,"quotedString");let mn;try{mn=new RegExp(`(^|(?<!
16
+ `,l+=2;o+=r,t[l+2]===" "&&(o+="\\"),l+=1,a=l+1}break;default:l+=1}return o=a?o+t.slice(a):t,n?o:It(o,r,vt,Tt(e,!1))}c(nt,"doubleQuotedString");function dn(s,e){if(e.options.singleQuote===!1||e.implicitKey&&s.includes(`
17
+ `)||/[ \t]\n|\n[ \t]/.test(s))return nt(s,e);const t=e.indent||(Nt(s)?" ":""),n="'"+s.replace(/'/g,"''").replace(/\n+/g,`$&
18
+ ${t}`)+"'";return e.implicitKey?n:It(n,t,Os,Tt(e,!1))}c(dn,"singleQuotedString");function Be(s,e){const{singleQuote:t}=e.options;let n;if(t===!1)n=nt;else{const i=s.includes('"'),r=s.includes("'");i&&!r?n=dn:r&&!i?n=nt:n=t?dn:nt}return n(s,e)}c(Be,"quotedString");let pn;try{pn=new RegExp(`(^|(?<!
19
19
  ))
20
20
  +(?!
21
- |$)`,"g")}catch{mn=/\n+(?!\n|$)/g}function Ot({comment:s,type:e,value:t},n,i,r){const{blockQuote:o,commentString:a,lineWidth:l}=n.options;if(!o||/\n[\t ]+$/.test(t)||/^\s*$/.test(t))return qe(t,n);const u=n.indent||(n.forceBlockIndent||At(t)?" ":""),p=o==="literal"?!0:o==="folded"||e===D.BLOCK_FOLDED?!1:e===D.BLOCK_LITERAL?!0:!Ur(t,l,u.length);if(!t)return p?`|
21
+ |$)`,"g")}catch{pn=/\n+(?!\n|$)/g}function At({comment:s,type:e,value:t},n,i,r){const{blockQuote:o,commentString:a,lineWidth:l}=n.options;if(!o||/\n[\t ]+$/.test(t)||/^\s*$/.test(t))return Be(t,n);const u=n.indent||(n.forceBlockIndent||Nt(t)?" ":""),p=o==="literal"?!0:o==="folded"||e===x.BLOCK_FOLDED?!1:e===x.BLOCK_LITERAL?!0:!Br(t,l,u.length);if(!t)return p?`|
22
22
  `:`>
23
23
  `;let d,h;for(h=t.length;h>0;--h){const O=t[h-1];if(O!==`
24
24
  `&&O!==" "&&O!==" ")break}let g=t.substring(h);const w=g.indexOf(`
25
25
  `);w===-1?d="-":t===g||w!==g.length-1?(d="+",r&&r()):d="",g&&(t=t.slice(0,-g.length),g[g.length-1]===`
26
- `&&(g=g.slice(0,-1)),g=g.replace(mn,`$&${u}`));let f=!1,y,C=-1;for(y=0;y<t.length;++y){const O=t[y];if(O===" ")f=!0;else if(O===`
26
+ `&&(g=g.slice(0,-1)),g=g.replace(pn,`$&${u}`));let f=!1,y,C=-1;for(y=0;y<t.length;++y){const O=t[y];if(O===" ")f=!0;else if(O===`
27
27
  `)C=y;else break}let E=t.substring(0,C<y?C+1:y);E&&(t=t.substring(E.length),E=E.replace(/\n+/g,`$&${u}`));let I=(f?u?"2":"1":"")+d;if(s&&(I+=" "+a(s.replace(/ ?[\r\n]+/g," ")),i&&i()),!p){const O=t.replace(/\n+/g,`
28
- $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${u}`);let $=!1;const K=Nt(n,!0);o!=="folded"&&e!==D.BLOCK_FOLDED&&(K.onOverflow=()=>{$=!0});const T=Tt(`${E}${O}${g}`,u,dn,K);if(!$)return`>${I}
28
+ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${u}`);let $=!1;const K=Tt(n,!0);o!=="folded"&&e!==x.BLOCK_FOLDED&&(K.onOverflow=()=>{$=!0});const T=It(`${E}${O}${g}`,u,hn,K);if(!$)return`>${I}
29
29
  ${u}${T}`}return t=t.replace(/\n+/g,`$&${u}`),`|${I}
30
- ${u}${E}${t}${g}`}c(Ot,"blockString");function Jr(s,e,t,n){const{type:i,value:r}=s,{actualString:o,implicitKey:a,indent:l,indentStep:u,inFlow:p}=e;if(a&&r.includes(`
31
- `)||p&&/[[\]{},]/.test(r))return qe(r,e);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(r))return a||p||!r.includes(`
32
- `)?qe(r,e):Ot(s,e,t,n);if(!a&&!p&&i!==D.PLAIN&&r.includes(`
33
- `))return Ot(s,e,t,n);if(At(r)){if(l==="")return e.forceBlockIndent=!0,Ot(s,e,t,n);if(a&&l===u)return qe(r,e)}const d=r.replace(/\n+/g,`$&
34
- ${l}`);if(o){const h=c(f=>f.default&&f.tag!=="tag:yaml.org,2002:str"&&f.test?.test(d),"test"),{compat:g,tags:w}=e.doc.schema;if(w.some(h)||g?.some(h))return qe(r,e)}return a?d:Tt(d,l,$s,Nt(e,!1))}c(Jr,"plainString");function it(s,e,t,n){const{implicitKey:i,inFlow:r}=e,o=typeof s.value=="string"?s:Object.assign({},s,{value:String(s.value)});let{type:a}=s;a!==D.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(a=D.QUOTE_DOUBLE);const l=c(p=>{switch(p){case D.BLOCK_FOLDED:case D.BLOCK_LITERAL:return i||r?qe(o.value,e):Ot(o,e,t,n);case D.QUOTE_DOUBLE:return st(o.value,e);case D.QUOTE_SINGLE:return pn(o.value,e);case D.PLAIN:return Jr(o,e,t,n);default:return null}},"_stringify");let u=l(a);if(u===null){const{defaultKeyType:p,defaultStringType:d}=e.options,h=i&&p||d;if(u=l(h),u===null)throw new Error(`Unsupported default string type ${h}`)}return u}c(it,"stringifyString");function Ds(s,e){const t=Object.assign({blockQuote:!0,commentString:qr,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(Ds,"createStringifyContext");function Wr(s,e){if(e.tag){const i=s.filter(r=>r.tag===e.tag);if(i.length>0)return i.find(r=>r.format===e.format)??i[0]}let t,n;if(_(e)){n=e.value;let i=s.filter(r=>r.identify?.(n));if(i.length>1){const r=i.filter(o=>o.test);r.length>0&&(i=r)}t=i.find(r=>r.format===e.format)??i.find(r=>!r.format)}else n=e,t=s.find(i=>i.nodeClass&&n instanceof i.nodeClass);if(!t){const i=n?.constructor?.name??(n===null?"null":typeof n);throw new Error(`Tag not resolved for ${i} value`)}return t}c(Wr,"getTagObject");function Gr(s,e,{anchors:t,doc:n}){if(!n.directives)return"";const i=[],r=(_(s)||q(s))&&s.anchor;r&&Is(r)&&(t.add(r),i.push(`&${r}`));const o=s.tag??(e.default?null:e.tag);return o&&i.push(n.directives.tagString(o)),i.join(" ")}c(Gr,"stringifyProps");function Ue(s,e,t,n){if(F(s))return s.toString(e,t,n);if(Se(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 i;const r=U(s)?s:e.doc.createNode(s,{onTagObj:c(l=>i=l,"onTagObj")});i??(i=Wr(e.doc.schema.tags,r));const o=Gr(r,i,e);o.length>0&&(e.indentAtStart=(e.indentAtStart??0)+o.length+1);const a=typeof i.stringify=="function"?i.stringify(r,e,t,n):_(r)?it(r,e,t,n):r.toString(e,t,n);return o?_(r)||a[0]==="{"||a[0]==="["?`${o} ${a}`:`${o}
35
- ${e.indent}${a}`:a}c(Ue,"stringify$2");function Vr({key:s,value:e},t,n,i){const{allNullValues:r,doc:o,indent:a,indentStep:l,options:{commentString:u,indentSeq:p,simpleKeys:d}}=t;let h=U(s)&&s.comment||null;if(d){if(h)throw new Error("With simple keys, key nodes cannot have comments");if(q(s)||!U(s)&&typeof s=="object"){const K="With simple keys, collection cannot be used as a key value";throw new Error(K)}}let g=!d&&(!s||h&&e==null&&!t.inFlow||q(s)||(_(s)?s.type===D.BLOCK_FOLDED||s.type===D.BLOCK_LITERAL:typeof s=="object"));t=Object.assign({},t,{allNullValues:!1,implicitKey:!g&&(d||!r),indent:a+l});let w=!1,f=!1,y=Ue(s,t,()=>w=!0,()=>f=!0);if(!g&&!t.inFlow&&y.length>1024){if(d)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");g=!0}if(t.inFlow){if(r||e==null)return w&&n&&n(),y===""?"?":g?`? ${y}`:y}else if(r&&!d||e==null&&g)return y=`? ${y}`,h&&!w?y+=Oe(y,t.indent,u(h)):f&&i&&i(),y;w&&(h=null),g?(h&&(y+=Oe(y,t.indent,u(h))),y=`? ${y}
36
- ${a}:`):(y=`${y}:`,h&&(y+=Oe(y,t.indent,u(h))));let C,E,A;U(e)?(C=!!e.spaceBefore,E=e.commentBefore,A=e.comment):(C=!1,E=null,A=null,e&&typeof e=="object"&&(e=o.createNode(e))),t.implicitKey=!1,!g&&!h&&_(e)&&(t.indentAtStart=y.length+1),f=!1,!p&&l.length>=2&&!t.inFlow&&!g&&Ke(e)&&!e.flow&&!e.tag&&!e.anchor&&(t.indent=t.indent.substring(2));let I=!1;const O=Ue(e,t,()=>I=!0,()=>f=!0);let $=" ";if(h||C||E){if($=C?`
30
+ ${u}${E}${t}${g}`}c(At,"blockString");function qr(s,e,t,n){const{type:i,value:r}=s,{actualString:o,implicitKey:a,indent:l,indentStep:u,inFlow:p}=e;if(a&&r.includes(`
31
+ `)||p&&/[[\]{},]/.test(r))return Be(r,e);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(r))return a||p||!r.includes(`
32
+ `)?Be(r,e):At(s,e,t,n);if(!a&&!p&&i!==x.PLAIN&&r.includes(`
33
+ `))return At(s,e,t,n);if(Nt(r)){if(l==="")return e.forceBlockIndent=!0,At(s,e,t,n);if(a&&l===u)return Be(r,e)}const d=r.replace(/\n+/g,`$&
34
+ ${l}`);if(o){const h=c(f=>f.default&&f.tag!=="tag:yaml.org,2002:str"&&f.test?.test(d),"test"),{compat:g,tags:w}=e.doc.schema;if(w.some(h)||g?.some(h))return Be(r,e)}return a?d:It(d,l,Os,Tt(e,!1))}c(qr,"plainString");function st(s,e,t,n){const{implicitKey:i,inFlow:r}=e,o=typeof s.value=="string"?s:Object.assign({},s,{value:String(s.value)});let{type:a}=s;a!==x.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(a=x.QUOTE_DOUBLE);const l=c(p=>{switch(p){case x.BLOCK_FOLDED:case x.BLOCK_LITERAL:return i||r?Be(o.value,e):At(o,e,t,n);case x.QUOTE_DOUBLE:return nt(o.value,e);case x.QUOTE_SINGLE:return dn(o.value,e);case x.PLAIN:return qr(o,e,t,n);default:return null}},"_stringify");let u=l(a);if(u===null){const{defaultKeyType:p,defaultStringType:d}=e.options,h=i&&p||d;if(u=l(h),u===null)throw new Error(`Unsupported default string type ${h}`)}return u}c(st,"stringifyString");function Ls(s,e){const t=Object.assign({blockQuote:!0,commentString:Fr,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(Ls,"createStringifyContext");function Ur(s,e){if(e.tag){const i=s.filter(r=>r.tag===e.tag);if(i.length>0)return i.find(r=>r.format===e.format)??i[0]}let t,n;if(_(e)){n=e.value;let i=s.filter(r=>r.identify?.(n));if(i.length>1){const r=i.filter(o=>o.test);r.length>0&&(i=r)}t=i.find(r=>r.format===e.format)??i.find(r=>!r.format)}else n=e,t=s.find(i=>i.nodeClass&&n instanceof i.nodeClass);if(!t){const i=n?.constructor?.name??(n===null?"null":typeof n);throw new Error(`Tag not resolved for ${i} value`)}return t}c(Ur,"getTagObject");function Jr(s,e,{anchors:t,doc:n}){if(!n.directives)return"";const i=[],r=(_(s)||U(s))&&s.anchor;r&&vs(r)&&(t.add(r),i.push(`&${r}`));const o=s.tag??(e.default?null:e.tag);return o&&i.push(n.directives.tagString(o)),i.join(" ")}c(Jr,"stringifyProps");function qe(s,e,t,n){if(B(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 i;const r=J(s)?s:e.doc.createNode(s,{onTagObj:c(l=>i=l,"onTagObj")});i??(i=Ur(e.doc.schema.tags,r));const o=Jr(r,i,e);o.length>0&&(e.indentAtStart=(e.indentAtStart??0)+o.length+1);const a=typeof i.stringify=="function"?i.stringify(r,e,t,n):_(r)?st(r,e,t,n):r.toString(e,t,n);return o?_(r)||a[0]==="{"||a[0]==="["?`${o} ${a}`:`${o}
35
+ ${e.indent}${a}`:a}c(qe,"stringify$2");function Wr({key:s,value:e},t,n,i){const{allNullValues:r,doc:o,indent:a,indentStep:l,options:{commentString:u,indentSeq:p,simpleKeys:d}}=t;let h=J(s)&&s.comment||null;if(d){if(h)throw new Error("With simple keys, key nodes cannot have comments");if(U(s)||!J(s)&&typeof s=="object"){const K="With simple keys, collection cannot be used as a key value";throw new Error(K)}}let g=!d&&(!s||h&&e==null&&!t.inFlow||U(s)||(_(s)?s.type===x.BLOCK_FOLDED||s.type===x.BLOCK_LITERAL:typeof s=="object"));t=Object.assign({},t,{allNullValues:!1,implicitKey:!g&&(d||!r),indent:a+l});let w=!1,f=!1,y=qe(s,t,()=>w=!0,()=>f=!0);if(!g&&!t.inFlow&&y.length>1024){if(d)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");g=!0}if(t.inFlow){if(r||e==null)return w&&n&&n(),y===""?"?":g?`? ${y}`:y}else if(r&&!d||e==null&&g)return y=`? ${y}`,h&&!w?y+=Ae(y,t.indent,u(h)):f&&i&&i(),y;w&&(h=null),g?(h&&(y+=Ae(y,t.indent,u(h))),y=`? ${y}
36
+ ${a}:`):(y=`${y}:`,h&&(y+=Ae(y,t.indent,u(h))));let C,E,A;J(e)?(C=!!e.spaceBefore,E=e.commentBefore,A=e.comment):(C=!1,E=null,A=null,e&&typeof e=="object"&&(e=o.createNode(e))),t.implicitKey=!1,!g&&!h&&_(e)&&(t.indentAtStart=y.length+1),f=!1,!p&&l.length>=2&&!t.inFlow&&!g&&_e(e)&&!e.flow&&!e.tag&&!e.anchor&&(t.indent=t.indent.substring(2));let I=!1;const O=qe(e,t,()=>I=!0,()=>f=!0);let $=" ";if(h||C||E){if($=C?`
37
37
  `:"",E){const K=u(E);$+=`
38
- ${me(K,t.indent)}`}O===""&&!t.inFlow?$===`
38
+ ${pe(K,t.indent)}`}O===""&&!t.inFlow?$===`
39
39
  `&&($=`
40
40
 
41
41
  `):$+=`
42
- ${t.indent}`}else if(!g&&q(e)){const K=O[0],T=O.indexOf(`
43
- `),V=T!==-1,ye=t.inFlow??e.flow??e.items.length===0;if(V||!ye){let xe=!1;if(V&&(K==="&"||K==="!")){let H=O.indexOf(" ");K==="&"&&H!==-1&&H<T&&O[H+1]==="!"&&(H=O.indexOf(" ",H+1)),(H===-1||T<H)&&(xe=!0)}xe||($=`
42
+ ${t.indent}`}else if(!g&&U(e)){const K=O[0],T=O.indexOf(`
43
+ `),H=T!==-1,ge=t.inFlow??e.flow??e.items.length===0;if(H||!ge){let xe=!1;if(H&&(K==="&"||K==="!")){let Y=O.indexOf(" ");K==="&"&&Y!==-1&&Y<T&&O[Y+1]==="!"&&(Y=O.indexOf(" ",Y+1)),(Y===-1||T<Y)&&(xe=!0)}xe||($=`
44
44
  ${t.indent}`)}}else(O===""||O[0]===`
45
- `)&&($="");return y+=$+O,t.inFlow?I&&n&&n():A&&!I?y+=Oe(y,t.indent,u(A)):f&&i&&i(),y}c(Vr,"stringifyPair");function xs(s,e){(s==="debug"||s==="warn")&&console.warn(e)}c(xs,"warn");const $t="<<",ge={identify:c(s=>s===$t||typeof s=="symbol"&&s.description===$t,"identify"),default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:c(()=>Object.assign(new D(Symbol($t)),{addToJSMap:Ps}),"resolve"),stringify:c(()=>$t,"stringify")},Hr=c((s,e)=>(ge.identify(e)||_(e)&&(!e.type||e.type===D.PLAIN)&&ge.identify(e.value))&&s?.doc.schema.tags.some(t=>t.tag===ge.tag&&t.default),"isMergeKey");function Ps(s,e,t){if(t=s&&Se(t)?t.resolve(s.doc):t,Ke(t))for(const n of t.items)gn(s,e,n);else if(Array.isArray(t))for(const n of t)gn(s,e,n);else gn(s,e,t)}c(Ps,"addMergeToJSMap");function gn(s,e,t){const n=s&&Se(t)?t.resolve(s.doc):t;if(!_e(n))throw new Error("Merge sources must be maps or map aliases");const i=n.toJSON(null,s,Map);for(const[r,o]of i)e instanceof Map?e.has(r)||e.set(r,o):e instanceof Set?e.add(r):Object.prototype.hasOwnProperty.call(e,r)||Object.defineProperty(e,r,{value:o,writable:!0,enumerable:!0,configurable:!0});return e}c(gn,"mergeValue");function Rs(s,e,{key:t,value:n}){if(U(t)&&t.addToJSMap)t.addToJSMap(s,e,n);else if(Hr(s,t))Ps(s,e,n);else{const i=ie(t,"",s);if(e instanceof Map)e.set(i,ie(n,i,s));else if(e instanceof Set)e.add(i);else{const r=Yr(t,i,s),o=ie(n,r,s);r in e?Object.defineProperty(e,r,{value:o,writable:!0,enumerable:!0,configurable:!0}):e[r]=o}}return e}c(Rs,"addPairToJSMap");function Yr(s,e,t){if(e===null)return"";if(typeof e!="object")return String(e);if(U(s)&&t?.doc){const n=Ds(t.doc,{});n.anchors=new Set;for(const r of t.anchors.keys())n.anchors.add(r.anchor);n.inFlow=!0,n.inStringifyKey=!0;const i=s.toString(n);if(!t.mapKeyWarned){let r=JSON.stringify(i);r.length>40&&(r=r.substring(0,36)+'..."'),xs(t.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${r}. Set mapAsMap: true to use object keys.`),t.mapKeyWarned=!0}return i}return JSON.stringify(e)}c(Yr,"stringifyKey");function yn(s,e,t){const n=tt(s,void 0,t),i=tt(e,void 0,t);return new Q(n,i)}c(yn,"createPair");class Q{static{c(this,"Pair")}constructor(e,t=null){Object.defineProperty(this,se,{value:bs}),this.key=e,this.value=t}clone(e){let{key:t,value:n}=this;return U(t)&&(t=t.clone(e)),U(n)&&(n=n.clone(e)),new Q(t,n)}toJSON(e,t){const n=t?.mapAsMap?new Map:{};return Rs(t,n,this)}toString(e,t,n){return e?.doc?Vr(this,e,t,n):JSON.stringify(this)}}function Ms(s,e,t){return(e.inFlow??s.flow?Qr:zr)(s,e,t)}c(Ms,"stringifyCollection");function zr({comment:s,items:e},t,{blockItemPrefix:n,flowChars:i,itemIndent:r,onChompKeep:o,onComment:a}){const{indent:l,options:{commentString:u}}=t,p=Object.assign({},t,{indent:r,type:null});let d=!1;const h=[];for(let w=0;w<e.length;++w){const f=e[w];let y=null;if(U(f))!d&&f.spaceBefore&&h.push(""),Lt(t,h,f.commentBefore,d),f.comment&&(y=f.comment);else if(F(f)){const E=U(f.key)?f.key:null;E&&(!d&&E.spaceBefore&&h.push(""),Lt(t,h,E.commentBefore,d))}d=!1;let C=Ue(f,p,()=>y=null,()=>d=!0);y&&(C+=Oe(C,r,u(y))),d&&y&&(d=!1),h.push(n+C)}let g;if(h.length===0)g=i.start+i.end;else{g=h[0];for(let w=1;w<h.length;++w){const f=h[w];g+=f?`
45
+ `)&&($="");return y+=$+O,t.inFlow?I&&n&&n():A&&!I?y+=Ae(y,t.indent,u(A)):f&&i&&i(),y}c(Wr,"stringifyPair");function xs(s,e){(s==="debug"||s==="warn")&&console.warn(e)}c(xs,"warn");const Ot="<<",me={identify:c(s=>s===Ot||typeof s=="symbol"&&s.description===Ot,"identify"),default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:c(()=>Object.assign(new x(Symbol(Ot)),{addToJSMap:Ps}),"resolve"),stringify:c(()=>Ot,"stringify")},Gr=c((s,e)=>(me.identify(e)||_(e)&&(!e.type||e.type===x.PLAIN)&&me.identify(e.value))&&s?.doc.schema.tags.some(t=>t.tag===me.tag&&t.default),"isMergeKey");function Ps(s,e,t){if(t=s&&be(t)?t.resolve(s.doc):t,_e(t))for(const n of t.items)mn(s,e,n);else if(Array.isArray(t))for(const n of t)mn(s,e,n);else mn(s,e,t)}c(Ps,"addMergeToJSMap");function mn(s,e,t){const n=s&&be(t)?t.resolve(s.doc):t;if(!Me(n))throw new Error("Merge sources must be maps or map aliases");const i=n.toJSON(null,s,Map);for(const[r,o]of i)e instanceof Map?e.has(r)||e.set(r,o):e instanceof Set?e.add(r):Object.prototype.hasOwnProperty.call(e,r)||Object.defineProperty(e,r,{value:o,writable:!0,enumerable:!0,configurable:!0});return e}c(mn,"mergeValue");function Ds(s,e,{key:t,value:n}){if(J(t)&&t.addToJSMap)t.addToJSMap(s,e,n);else if(Gr(s,t))Ps(s,e,n);else{const i=oe(t,"",s);if(e instanceof Map)e.set(i,oe(n,i,s));else if(e instanceof Set)e.add(i);else{const r=Vr(t,i,s),o=oe(n,r,s);r in e?Object.defineProperty(e,r,{value:o,writable:!0,enumerable:!0,configurable:!0}):e[r]=o}}return e}c(Ds,"addPairToJSMap");function Vr(s,e,t){if(e===null)return"";if(typeof e!="object")return String(e);if(J(s)&&t?.doc){const n=Ls(t.doc,{});n.anchors=new Set;for(const r of t.anchors.keys())n.anchors.add(r.anchor);n.inFlow=!0,n.inStringifyKey=!0;const i=s.toString(n);if(!t.mapKeyWarned){let r=JSON.stringify(i);r.length>40&&(r=r.substring(0,36)+'..."'),xs(t.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${r}. Set mapAsMap: true to use object keys.`),t.mapKeyWarned=!0}return i}return JSON.stringify(e)}c(Vr,"stringifyKey");function gn(s,e,t){const n=et(s,void 0,t),i=et(e,void 0,t);return new X(n,i)}c(gn,"createPair");class X{static{c(this,"Pair")}constructor(e,t=null){Object.defineProperty(this,re,{value:ws}),this.key=e,this.value=t}clone(e){let{key:t,value:n}=this;return J(t)&&(t=t.clone(e)),J(n)&&(n=n.clone(e)),new X(t,n)}toJSON(e,t){const n=t?.mapAsMap?new Map:{};return Ds(t,n,this)}toString(e,t,n){return e?.doc?Wr(this,e,t,n):JSON.stringify(this)}}function Rs(s,e,t){return(e.inFlow??s.flow?Yr:Hr)(s,e,t)}c(Rs,"stringifyCollection");function Hr({comment:s,items:e},t,{blockItemPrefix:n,flowChars:i,itemIndent:r,onChompKeep:o,onComment:a}){const{indent:l,options:{commentString:u}}=t,p=Object.assign({},t,{indent:r,type:null});let d=!1;const h=[];for(let w=0;w<e.length;++w){const f=e[w];let y=null;if(J(f))!d&&f.spaceBefore&&h.push(""),$t(t,h,f.commentBefore,d),f.comment&&(y=f.comment);else if(B(f)){const E=J(f.key)?f.key:null;E&&(!d&&E.spaceBefore&&h.push(""),$t(t,h,E.commentBefore,d))}d=!1;let C=qe(f,p,()=>y=null,()=>d=!0);y&&(C+=Ae(C,r,u(y))),d&&y&&(d=!1),h.push(n+C)}let g;if(h.length===0)g=i.start+i.end;else{g=h[0];for(let w=1;w<h.length;++w){const f=h[w];g+=f?`
46
46
  ${l}${f}`:`
47
47
  `}}return s?(g+=`
48
- `+me(u(s),l),a&&a()):d&&o&&o(),g}c(zr,"stringifyBlockCollection");function Qr({items:s},e,{flowChars:t,itemIndent:n}){const{indent:i,indentStep:r,flowCollectionPadding:o,options:{commentString:a}}=e;n+=r;const l=Object.assign({},e,{indent:n,inFlow:!0,type:null});let u=!1,p=0;const d=[];for(let w=0;w<s.length;++w){const f=s[w];let y=null;if(U(f))f.spaceBefore&&d.push(""),Lt(e,d,f.commentBefore,!1),f.comment&&(y=f.comment);else if(F(f)){const E=U(f.key)?f.key:null;E&&(E.spaceBefore&&d.push(""),Lt(e,d,E.commentBefore,!1),E.comment&&(u=!0));const A=U(f.value)?f.value:null;A?(A.comment&&(y=A.comment),A.commentBefore&&(u=!0)):f.value==null&&E?.comment&&(y=E.comment)}y&&(u=!0);let C=Ue(f,l,()=>y=null);w<s.length-1&&(C+=","),y&&(C+=Oe(C,n,a(y))),!u&&(d.length>p||C.includes(`
48
+ `+pe(u(s),l),a&&a()):d&&o&&o(),g}c(Hr,"stringifyBlockCollection");function Yr({items:s},e,{flowChars:t,itemIndent:n}){const{indent:i,indentStep:r,flowCollectionPadding:o,options:{commentString:a}}=e;n+=r;const l=Object.assign({},e,{indent:n,inFlow:!0,type:null});let u=!1,p=0;const d=[];for(let w=0;w<s.length;++w){const f=s[w];let y=null;if(J(f))f.spaceBefore&&d.push(""),$t(e,d,f.commentBefore,!1),f.comment&&(y=f.comment);else if(B(f)){const E=J(f.key)?f.key:null;E&&(E.spaceBefore&&d.push(""),$t(e,d,E.commentBefore,!1),E.comment&&(u=!0));const A=J(f.value)?f.value:null;A?(A.comment&&(y=A.comment),A.commentBefore&&(u=!0)):f.value==null&&E?.comment&&(y=E.comment)}y&&(u=!0);let C=qe(f,l,()=>y=null);w<s.length-1&&(C+=","),y&&(C+=Ae(C,n,a(y))),!u&&(d.length>p||C.includes(`
49
49
  `))&&(u=!0),d.push(C),p=d.length}const{start:h,end:g}=t;if(d.length===0)return h+g;if(!u){const w=d.reduce((f,y)=>f+y.length+2,2);u=e.options.lineWidth>0&&w>e.options.lineWidth}if(u){let w=h;for(const f of d)w+=f?`
50
50
  ${r}${i}${f}`:`
51
51
  `;return`${w}
52
- ${i}${g}`}else return`${h}${o}${d.join(" ")}${o}${g}`}c(Qr,"stringifyFlowCollection");function Lt({indent:s,options:{commentString:e}},t,n,i){if(n&&i&&(n=n.replace(/^\n+/,"")),n){const r=me(e(n),s);t.push(r.trimStart())}}c(Lt,"addCommentBefore");function $e(s,e){const t=_(e)?e.value:e;for(const n of s)if(F(n)&&(n.key===e||n.key===t||_(n.key)&&n.key.value===t))return n}c($e,"findPair");class te extends Os{static{c(this,"YAMLMap")}static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(be,e),this.items=[]}static from(e,t,n){const{keepUndefined:i,replacer:r}=n,o=new this(e),a=c((l,u)=>{if(typeof r=="function")u=r.call(t,l,u);else if(Array.isArray(r)&&!r.includes(l))return;(u!==void 0||i)&&o.items.push(yn(l,u,n))},"add");if(t instanceof Map)for(const[l,u]of t)a(l,u);else if(t&&typeof t=="object")for(const l of Object.keys(t))a(l,t[l]);return typeof e.sortMapEntries=="function"&&o.items.sort(e.sortMapEntries),o}add(e,t){let n;F(e)?n=e:!e||typeof e!="object"||!("key"in e)?n=new Q(e,e?.value):n=new Q(e.key,e.value);const i=$e(this.items,n.key),r=this.schema?.sortMapEntries;if(i){if(!t)throw new Error(`Key ${n.key} already set`);_(i.value)&&As(n.value)?i.value.value=n.value:i.value=n.value}else if(r){const o=this.items.findIndex(a=>r(n,a)<0);o===-1?this.items.push(n):this.items.splice(o,0,n)}else this.items.push(n)}delete(e){const t=$e(this.items,e);return t?this.items.splice(this.items.indexOf(t),1).length>0:!1}get(e,t){const i=$e(this.items,e)?.value;return(!t&&_(i)?i.value:i)??void 0}has(e){return!!$e(this.items,e)}set(e,t){this.add(new Q(e,t),!0)}toJSON(e,t,n){const i=n?new n:t?.mapAsMap?new Map:{};t?.onCreate&&t.onCreate(i);for(const r of this.items)Rs(t,i,r);return i}toString(e,t,n){if(!e)return JSON.stringify(this);for(const i of this.items)if(!F(i))throw new Error(`Map items must all be pairs; found ${JSON.stringify(i)} instead`);return!e.allNullValues&&this.hasAllNullValues(!1)&&(e=Object.assign({},e,{allNullValues:!0})),Ms(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:n,onComment:t})}}const Je={collection:"map",default:!0,nodeClass:te,tag:"tag:yaml.org,2002:map",resolve(s,e){return _e(s)||e("Expected a mapping for this tag"),s},createNode:c((s,e,t)=>te.from(s,e,t),"createNode")};class Ce extends Os{static{c(this,"YAMLSeq")}static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(Me,e),this.items=[]}add(e){this.items.push(e)}delete(e){const t=Dt(e);return typeof t!="number"?!1:this.items.splice(t,1).length>0}get(e,t){const n=Dt(e);if(typeof n!="number")return;const i=this.items[n];return!t&&_(i)?i.value:i}has(e){const t=Dt(e);return typeof t=="number"&&t<this.items.length}set(e,t){const n=Dt(e);if(typeof n!="number")throw new Error(`Expected a valid index, not ${e}.`);const i=this.items[n];_(i)&&As(t)?i.value=t:this.items[n]=t}toJSON(e,t){const n=[];t?.onCreate&&t.onCreate(n);let i=0;for(const r of this.items)n.push(ie(r,String(i++),t));return n}toString(e,t,n){return e?Ms(this,e,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(e.indent||"")+" ",onChompKeep:n,onComment:t}):JSON.stringify(this)}static from(e,t,n){const{replacer:i}=n,r=new this(e);if(t&&Symbol.iterator in Object(t)){let o=0;for(let a of t){if(typeof i=="function"){const l=t instanceof Set?a:String(o++);a=i.call(t,l,a)}r.items.push(tt(a,void 0,n))}}return r}}function Dt(s){let e=_(s)?s.value:s;return e&&typeof e=="string"&&(e=Number(e)),typeof e=="number"&&Number.isInteger(e)&&e>=0?e:null}c(Dt,"asItemIndex");const We={collection:"seq",default:!0,nodeClass:Ce,tag:"tag:yaml.org,2002:seq",resolve(s,e){return Ke(s)||e("Expected a sequence for this tag"),s},createNode:c((s,e,t)=>Ce.from(s,e,t),"createNode")},xt={identify:c(s=>typeof s=="string","identify"),default:!0,tag:"tag:yaml.org,2002:str",resolve:c(s=>s,"resolve"),stringify(s,e,t,n){return e=Object.assign({actualString:!0},e),it(s,e,t,n)}},Pt={identify:c(s=>s==null,"identify"),createNode:c(()=>new D(null),"createNode"),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:c(()=>new D(null),"resolve"),stringify:c(({source:s},e)=>typeof s=="string"&&Pt.test.test(s)?s:e.options.nullStr,"stringify")},wn={identify:c(s=>typeof s=="boolean","identify"),default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:c(s=>new D(s[0]==="t"||s[0]==="T"),"resolve"),stringify({source:s,value:e},t){if(s&&wn.test.test(s)){const n=s[0]==="t"||s[0]==="T";if(e===n)return s}return e?t.options.trueStr:t.options.falseStr}};function oe({format:s,minFractionDigits:e,tag:t,value:n}){if(typeof n=="bigint")return String(n);const i=typeof n=="number"?n:Number(n);if(!isFinite(i))return isNaN(i)?".nan":i<0?"-.inf":".inf";let r=JSON.stringify(n);if(!s&&e&&(!t||t==="tag:yaml.org,2002:float")&&/^\d/.test(r)){let o=r.indexOf(".");o<0&&(o=r.length,r+=".");let a=e-(r.length-o-1);for(;a-- >0;)r+="0"}return r}c(oe,"stringifyNumber");const _s={identify:c(s=>typeof s=="number","identify"),default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:c(s=>s.slice(-3).toLowerCase()==="nan"?NaN:s[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,"resolve"),stringify:oe},Ks={identify:c(s=>typeof s=="number","identify"),default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:c(s=>parseFloat(s),"resolve"),stringify(s){const e=Number(s.value);return isFinite(e)?e.toExponential():oe(s)}},js={identify:c(s=>typeof s=="number","identify"),default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(s){const e=new D(parseFloat(s)),t=s.indexOf(".");return t!==-1&&s[s.length-1]==="0"&&(e.minFractionDigits=s.length-t-1),e},stringify:oe},Rt=c(s=>typeof s=="bigint"||Number.isInteger(s),"intIdentify$2"),bn=c((s,e,t,{intAsBigInt:n})=>n?BigInt(s):parseInt(s.substring(e),t),"intResolve$1");function Fs(s,e,t){const{value:n}=s;return Rt(n)&&n>=0?t+n.toString(e):oe(s)}c(Fs,"intStringify$1");const Bs={identify:c(s=>Rt(s)&&s>=0,"identify"),default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:c((s,e,t)=>bn(s,2,8,t),"resolve"),stringify:c(s=>Fs(s,8,"0o"),"stringify")},qs={identify:Rt,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:c((s,e,t)=>bn(s,0,10,t),"resolve"),stringify:oe},Us={identify:c(s=>Rt(s)&&s>=0,"identify"),default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:c((s,e,t)=>bn(s,2,16,t),"resolve"),stringify:c(s=>Fs(s,16,"0x"),"stringify")},Xr=[Je,We,xt,Pt,wn,Bs,qs,Us,_s,Ks,js];function Js(s){return typeof s=="bigint"||Number.isInteger(s)}c(Js,"intIdentify$1");const Mt=c(({value:s})=>JSON.stringify(s),"stringifyJSON"),Zr=[{identify:c(s=>typeof s=="string","identify"),default:!0,tag:"tag:yaml.org,2002:str",resolve:c(s=>s,"resolve"),stringify:Mt},{identify:c(s=>s==null,"identify"),createNode:c(()=>new D(null),"createNode"),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:c(()=>null,"resolve"),stringify:Mt},{identify:c(s=>typeof s=="boolean","identify"),default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:c(s=>s==="true","resolve"),stringify:Mt},{identify:Js,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:c((s,e,{intAsBigInt:t})=>t?BigInt(s):parseInt(s,10),"resolve"),stringify:c(({value:s})=>Js(s)?s.toString():JSON.stringify(s),"stringify")},{identify:c(s=>typeof s=="number","identify"),default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:c(s=>parseFloat(s),"resolve"),stringify:Mt}],eo={default:!0,tag:"",test:/^/,resolve(s,e){return e(`Unresolved plain scalar ${JSON.stringify(s)}`),s}},to=[Je,We].concat(Zr,eo),Sn={identify:c(s=>s instanceof Uint8Array,"identify"),default:!1,tag:"tag:yaml.org,2002:binary",resolve(s,e){if(typeof atob=="function"){const t=atob(s.replace(/[\n\r]/g,"")),n=new Uint8Array(t.length);for(let i=0;i<t.length;++i)n[i]=t.charCodeAt(i);return n}else return e("This environment does not support reading binary tags; either Buffer or atob is required"),s},stringify({comment:s,type:e,value:t},n,i,r){if(!t)return"";const o=t;let a;if(typeof btoa=="function"){let l="";for(let u=0;u<o.length;++u)l+=String.fromCharCode(o[u]);a=btoa(l)}else throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required");if(e??(e=D.BLOCK_LITERAL),e!==D.QUOTE_DOUBLE){const l=Math.max(n.options.lineWidth-n.indent.length,n.options.minContentWidth),u=Math.ceil(a.length/l),p=new Array(u);for(let d=0,h=0;d<u;++d,h+=l)p[d]=a.substr(h,l);a=p.join(e===D.BLOCK_LITERAL?`
53
- `:" ")}return it({comment:s,type:e,value:a},n,i,r)}};function Ws(s,e){if(Ke(s))for(let t=0;t<s.items.length;++t){let n=s.items[t];if(!F(n)){if(_e(n)){n.items.length>1&&e("Each pair must have its own sequence indicator");const i=n.items[0]||new Q(new D(null));if(n.commentBefore&&(i.key.commentBefore=i.key.commentBefore?`${n.commentBefore}
52
+ ${i}${g}`}else return`${h}${o}${d.join(" ")}${o}${g}`}c(Yr,"stringifyFlowCollection");function $t({indent:s,options:{commentString:e}},t,n,i){if(n&&i&&(n=n.replace(/^\n+/,"")),n){const r=pe(e(n),s);t.push(r.trimStart())}}c($t,"addCommentBefore");function Oe(s,e){const t=_(e)?e.value:e;for(const n of s)if(B(n)&&(n.key===e||n.key===t||_(n.key)&&n.key.value===t))return n}c(Oe,"findPair");class ne extends As{static{c(this,"YAMLMap")}static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(we,e),this.items=[]}static from(e,t,n){const{keepUndefined:i,replacer:r}=n,o=new this(e),a=c((l,u)=>{if(typeof r=="function")u=r.call(t,l,u);else if(Array.isArray(r)&&!r.includes(l))return;(u!==void 0||i)&&o.items.push(gn(l,u,n))},"add");if(t instanceof Map)for(const[l,u]of t)a(l,u);else if(t&&typeof t=="object")for(const l of Object.keys(t))a(l,t[l]);return typeof e.sortMapEntries=="function"&&o.items.sort(e.sortMapEntries),o}add(e,t){let n;B(e)?n=e:!e||typeof e!="object"||!("key"in e)?n=new X(e,e?.value):n=new X(e.key,e.value);const i=Oe(this.items,n.key),r=this.schema?.sortMapEntries;if(i){if(!t)throw new Error(`Key ${n.key} already set`);_(i.value)&&Ns(n.value)?i.value.value=n.value:i.value=n.value}else if(r){const o=this.items.findIndex(a=>r(n,a)<0);o===-1?this.items.push(n):this.items.splice(o,0,n)}else this.items.push(n)}delete(e){const t=Oe(this.items,e);return t?this.items.splice(this.items.indexOf(t),1).length>0:!1}get(e,t){const i=Oe(this.items,e)?.value;return(!t&&_(i)?i.value:i)??void 0}has(e){return!!Oe(this.items,e)}set(e,t){this.add(new X(e,t),!0)}toJSON(e,t,n){const i=n?new n:t?.mapAsMap?new Map:{};t?.onCreate&&t.onCreate(i);for(const r of this.items)Ds(t,i,r);return i}toString(e,t,n){if(!e)return JSON.stringify(this);for(const i of this.items)if(!B(i))throw new Error(`Map items must all be pairs; found ${JSON.stringify(i)} instead`);return!e.allNullValues&&this.hasAllNullValues(!1)&&(e=Object.assign({},e,{allNullValues:!0})),Rs(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:n,onComment:t})}}const Ue={collection:"map",default:!0,nodeClass:ne,tag:"tag:yaml.org,2002:map",resolve(s,e){return Me(s)||e("Expected a mapping for this tag"),s},createNode:c((s,e,t)=>ne.from(s,e,t),"createNode")};class Se extends As{static{c(this,"YAMLSeq")}static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(Re,e),this.items=[]}add(e){this.items.push(e)}delete(e){const t=Lt(e);return typeof t!="number"?!1:this.items.splice(t,1).length>0}get(e,t){const n=Lt(e);if(typeof n!="number")return;const i=this.items[n];return!t&&_(i)?i.value:i}has(e){const t=Lt(e);return typeof t=="number"&&t<this.items.length}set(e,t){const n=Lt(e);if(typeof n!="number")throw new Error(`Expected a valid index, not ${e}.`);const i=this.items[n];_(i)&&Ns(t)?i.value=t:this.items[n]=t}toJSON(e,t){const n=[];t?.onCreate&&t.onCreate(n);let i=0;for(const r of this.items)n.push(oe(r,String(i++),t));return n}toString(e,t,n){return e?Rs(this,e,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(e.indent||"")+" ",onChompKeep:n,onComment:t}):JSON.stringify(this)}static from(e,t,n){const{replacer:i}=n,r=new this(e);if(t&&Symbol.iterator in Object(t)){let o=0;for(let a of t){if(typeof i=="function"){const l=t instanceof Set?a:String(o++);a=i.call(t,l,a)}r.items.push(et(a,void 0,n))}}return r}}function Lt(s){let e=_(s)?s.value:s;return e&&typeof e=="string"&&(e=Number(e)),typeof e=="number"&&Number.isInteger(e)&&e>=0?e:null}c(Lt,"asItemIndex");const Je={collection:"seq",default:!0,nodeClass:Se,tag:"tag:yaml.org,2002:seq",resolve(s,e){return _e(s)||e("Expected a sequence for this tag"),s},createNode:c((s,e,t)=>Se.from(s,e,t),"createNode")},xt={identify:c(s=>typeof s=="string","identify"),default:!0,tag:"tag:yaml.org,2002:str",resolve:c(s=>s,"resolve"),stringify(s,e,t,n){return e=Object.assign({actualString:!0},e),st(s,e,t,n)}},Pt={identify:c(s=>s==null,"identify"),createNode:c(()=>new x(null),"createNode"),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:c(()=>new x(null),"resolve"),stringify:c(({source:s},e)=>typeof s=="string"&&Pt.test.test(s)?s:e.options.nullStr,"stringify")},yn={identify:c(s=>typeof s=="boolean","identify"),default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:c(s=>new x(s[0]==="t"||s[0]==="T"),"resolve"),stringify({source:s,value:e},t){if(s&&yn.test.test(s)){const n=s[0]==="t"||s[0]==="T";if(e===n)return s}return e?t.options.trueStr:t.options.falseStr}};function ae({format:s,minFractionDigits:e,tag:t,value:n}){if(typeof n=="bigint")return String(n);const i=typeof n=="number"?n:Number(n);if(!isFinite(i))return isNaN(i)?".nan":i<0?"-.inf":".inf";let r=JSON.stringify(n);if(!s&&e&&(!t||t==="tag:yaml.org,2002:float")&&/^\d/.test(r)){let o=r.indexOf(".");o<0&&(o=r.length,r+=".");let a=e-(r.length-o-1);for(;a-- >0;)r+="0"}return r}c(ae,"stringifyNumber");const Ms={identify:c(s=>typeof s=="number","identify"),default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:c(s=>s.slice(-3).toLowerCase()==="nan"?NaN:s[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,"resolve"),stringify:ae},_s={identify:c(s=>typeof s=="number","identify"),default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:c(s=>parseFloat(s),"resolve"),stringify(s){const e=Number(s.value);return isFinite(e)?e.toExponential():ae(s)}},Ks={identify:c(s=>typeof s=="number","identify"),default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(s){const e=new x(parseFloat(s)),t=s.indexOf(".");return t!==-1&&s[s.length-1]==="0"&&(e.minFractionDigits=s.length-t-1),e},stringify:ae},Dt=c(s=>typeof s=="bigint"||Number.isInteger(s),"intIdentify$2"),wn=c((s,e,t,{intAsBigInt:n})=>n?BigInt(s):parseInt(s.substring(e),t),"intResolve$1");function js(s,e,t){const{value:n}=s;return Dt(n)&&n>=0?t+n.toString(e):ae(s)}c(js,"intStringify$1");const Fs={identify:c(s=>Dt(s)&&s>=0,"identify"),default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:c((s,e,t)=>wn(s,2,8,t),"resolve"),stringify:c(s=>js(s,8,"0o"),"stringify")},Bs={identify:Dt,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:c((s,e,t)=>wn(s,0,10,t),"resolve"),stringify:ae},qs={identify:c(s=>Dt(s)&&s>=0,"identify"),default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:c((s,e,t)=>wn(s,2,16,t),"resolve"),stringify:c(s=>js(s,16,"0x"),"stringify")},zr=[Ue,Je,xt,Pt,yn,Fs,Bs,qs,Ms,_s,Ks];function Us(s){return typeof s=="bigint"||Number.isInteger(s)}c(Us,"intIdentify$1");const Rt=c(({value:s})=>JSON.stringify(s),"stringifyJSON"),Qr=[{identify:c(s=>typeof s=="string","identify"),default:!0,tag:"tag:yaml.org,2002:str",resolve:c(s=>s,"resolve"),stringify:Rt},{identify:c(s=>s==null,"identify"),createNode:c(()=>new x(null),"createNode"),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:c(()=>null,"resolve"),stringify:Rt},{identify:c(s=>typeof s=="boolean","identify"),default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:c(s=>s==="true","resolve"),stringify:Rt},{identify:Us,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:c((s,e,{intAsBigInt:t})=>t?BigInt(s):parseInt(s,10),"resolve"),stringify:c(({value:s})=>Us(s)?s.toString():JSON.stringify(s),"stringify")},{identify:c(s=>typeof s=="number","identify"),default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:c(s=>parseFloat(s),"resolve"),stringify:Rt}],Xr={default:!0,tag:"",test:/^/,resolve(s,e){return e(`Unresolved plain scalar ${JSON.stringify(s)}`),s}},Zr=[Ue,Je].concat(Qr,Xr),bn={identify:c(s=>s instanceof Uint8Array,"identify"),default:!1,tag:"tag:yaml.org,2002:binary",resolve(s,e){if(typeof atob=="function"){const t=atob(s.replace(/[\n\r]/g,"")),n=new Uint8Array(t.length);for(let i=0;i<t.length;++i)n[i]=t.charCodeAt(i);return n}else return e("This environment does not support reading binary tags; either Buffer or atob is required"),s},stringify({comment:s,type:e,value:t},n,i,r){if(!t)return"";const o=t;let a;if(typeof btoa=="function"){let l="";for(let u=0;u<o.length;++u)l+=String.fromCharCode(o[u]);a=btoa(l)}else throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required");if(e??(e=x.BLOCK_LITERAL),e!==x.QUOTE_DOUBLE){const l=Math.max(n.options.lineWidth-n.indent.length,n.options.minContentWidth),u=Math.ceil(a.length/l),p=new Array(u);for(let d=0,h=0;d<u;++d,h+=l)p[d]=a.substr(h,l);a=p.join(e===x.BLOCK_LITERAL?`
53
+ `:" ")}return st({comment:s,type:e,value:a},n,i,r)}};function Js(s,e){if(_e(s))for(let t=0;t<s.items.length;++t){let n=s.items[t];if(!B(n)){if(Me(n)){n.items.length>1&&e("Each pair must have its own sequence indicator");const i=n.items[0]||new X(new x(null));if(n.commentBefore&&(i.key.commentBefore=i.key.commentBefore?`${n.commentBefore}
54
54
  ${i.key.commentBefore}`:n.commentBefore),n.comment){const r=i.value??i.key;r.comment=r.comment?`${n.comment}
55
- ${r.comment}`:n.comment}n=i}s.items[t]=F(n)?n:new Q(n)}}else e("Expected a sequence for this tag");return s}c(Ws,"resolvePairs");function Gs(s,e,t){const{replacer:n}=t,i=new Ce(s);i.tag="tag:yaml.org,2002:pairs";let r=0;if(e&&Symbol.iterator in Object(e))for(let o of e){typeof n=="function"&&(o=n.call(e,String(r++),o));let a,l;if(Array.isArray(o))if(o.length===2)a=o[0],l=o[1];else throw new TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){const u=Object.keys(o);if(u.length===1)a=u[0],l=o[a];else throw new TypeError(`Expected tuple with one key, not ${u.length} keys`)}else a=o;i.items.push(yn(a,l,t))}return i}c(Gs,"createPairs");const Cn={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:Ws,createNode:Gs};class ze extends Ce{static{c(this,"YAMLOMap")}constructor(){super(),this.add=te.prototype.add.bind(this),this.delete=te.prototype.delete.bind(this),this.get=te.prototype.get.bind(this),this.has=te.prototype.has.bind(this),this.set=te.prototype.set.bind(this),this.tag=ze.tag}toJSON(e,t){if(!t)return super.toJSON(e);const n=new Map;t?.onCreate&&t.onCreate(n);for(const i of this.items){let r,o;if(F(i)?(r=ie(i.key,"",t),o=ie(i.value,r,t)):r=ie(i,"",t),n.has(r))throw new Error("Ordered maps must not include duplicate keys");n.set(r,o)}return n}static from(e,t,n){const i=Gs(e,t,n),r=new this;return r.items=i.items,r}}ze.tag="tag:yaml.org,2002:omap";const kn={collection:"seq",identify:c(s=>s instanceof Map,"identify"),nodeClass:ze,default:!1,tag:"tag:yaml.org,2002:omap",resolve(s,e){const t=Ws(s,e),n=[];for(const{key:i}of t.items)_(i)&&(n.includes(i.value)?e(`Ordered maps must not include duplicate keys: ${i.value}`):n.push(i.value));return Object.assign(new ze,t)},createNode:c((s,e,t)=>ze.from(s,e,t),"createNode")};function Vs({value:s,source:e},t){return e&&(s?Hs:Ys).test.test(e)?e:s?t.options.trueStr:t.options.falseStr}c(Vs,"boolStringify");const Hs={identify:c(s=>s===!0,"identify"),default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:c(()=>new D(!0),"resolve"),stringify:Vs},Ys={identify:c(s=>s===!1,"identify"),default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:c(()=>new D(!1),"resolve"),stringify:Vs},no={identify:c(s=>typeof s=="number","identify"),default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:c(s=>s.slice(-3).toLowerCase()==="nan"?NaN:s[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,"resolve"),stringify:oe},so={identify:c(s=>typeof s=="number","identify"),default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:c(s=>parseFloat(s.replace(/_/g,"")),"resolve"),stringify(s){const e=Number(s.value);return isFinite(e)?e.toExponential():oe(s)}},io={identify:c(s=>typeof s=="number","identify"),default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(s){const e=new D(parseFloat(s.replace(/_/g,""))),t=s.indexOf(".");if(t!==-1){const n=s.substring(t+1).replace(/_/g,"");n[n.length-1]==="0"&&(e.minFractionDigits=n.length)}return e},stringify:oe},rt=c(s=>typeof s=="bigint"||Number.isInteger(s),"intIdentify");function _t(s,e,t,{intAsBigInt:n}){const i=s[0];if((i==="-"||i==="+")&&(e+=1),s=s.substring(e).replace(/_/g,""),n){switch(t){case 2:s=`0b${s}`;break;case 8:s=`0o${s}`;break;case 16:s=`0x${s}`;break}const o=BigInt(s);return i==="-"?BigInt(-1)*o:o}const r=parseInt(s,t);return i==="-"?-1*r:r}c(_t,"intResolve");function En(s,e,t){const{value:n}=s;if(rt(n)){const i=n.toString(e);return n<0?"-"+t+i.substr(1):t+i}return oe(s)}c(En,"intStringify");const ro={identify:rt,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:c((s,e,t)=>_t(s,2,2,t),"resolve"),stringify:c(s=>En(s,2,"0b"),"stringify")},oo={identify:rt,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:c((s,e,t)=>_t(s,1,8,t),"resolve"),stringify:c(s=>En(s,8,"0"),"stringify")},ao={identify:rt,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:c((s,e,t)=>_t(s,0,10,t),"resolve"),stringify:oe},co={identify:rt,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:c((s,e,t)=>_t(s,2,16,t),"resolve"),stringify:c(s=>En(s,16,"0x"),"stringify")};class Qe extends te{static{c(this,"YAMLSet")}constructor(e){super(e),this.tag=Qe.tag}add(e){let t;F(e)?t=e:e&&typeof e=="object"&&"key"in e&&"value"in e&&e.value===null?t=new Q(e.key,null):t=new Q(e,null),$e(this.items,t.key)||this.items.push(t)}get(e,t){const n=$e(this.items,e);return!t&&F(n)?_(n.key)?n.key.value:n.key:n}set(e,t){if(typeof t!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof t}`);const n=$e(this.items,e);n&&!t?this.items.splice(this.items.indexOf(n),1):!n&&t&&this.items.push(new Q(e))}toJSON(e,t){return super.toJSON(e,t,Set)}toString(e,t,n){if(!e)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},e,{allNullValues:!0}),t,n);throw new Error("Set items must all have null values")}static from(e,t,n){const{replacer:i}=n,r=new this(e);if(t&&Symbol.iterator in Object(t))for(let o of t)typeof i=="function"&&(o=i.call(t,o,o)),r.items.push(yn(o,null,n));return r}}Qe.tag="tag:yaml.org,2002:set";const vn={collection:"map",identify:c(s=>s instanceof Set,"identify"),nodeClass:Qe,default:!1,tag:"tag:yaml.org,2002:set",createNode:c((s,e,t)=>Qe.from(s,e,t),"createNode"),resolve(s,e){if(_e(s)){if(s.hasAllNullValues(!0))return Object.assign(new Qe,s);e("Set items must all have null values")}else e("Expected a mapping for this tag");return s}};function In(s,e){const t=s[0],n=t==="-"||t==="+"?s.substring(1):s,i=c(o=>e?BigInt(o):Number(o),"num"),r=n.replace(/_/g,"").split(":").reduce((o,a)=>o*i(60)+i(a),i(0));return t==="-"?i(-1)*r:r}c(In,"parseSexagesimal");function zs(s){let{value:e}=s,t=c(o=>o,"num");if(typeof e=="bigint")t=c(o=>BigInt(o),"num");else if(isNaN(e)||!isFinite(e))return oe(s);let n="";e<0&&(n="-",e*=t(-1));const i=t(60),r=[e%i];return e<60?r.unshift(0):(e=(e-r[0])/i,r.unshift(e%i),e>=60&&(e=(e-r[0])/i,r.unshift(e))),n+r.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}c(zs,"stringifySexagesimal");const Qs={identify:c(s=>typeof s=="bigint"||Number.isInteger(s),"identify"),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:c((s,e,{intAsBigInt:t})=>In(s,t),"resolve"),stringify:zs},Xs={identify:c(s=>typeof s=="number","identify"),default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:c(s=>In(s,!1),"resolve"),stringify:zs},Kt={identify:c(s=>s instanceof Date,"identify"),default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),resolve(s){const e=s.match(Kt.test);if(!e)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");const[,t,n,i,r,o,a]=e.map(Number),l=e[7]?Number((e[7]+"00").substr(1,3)):0;let u=Date.UTC(t,n-1,i,r||0,o||0,a||0,l);const p=e[8];if(p&&p!=="Z"){let d=In(p,!1);Math.abs(d)<30&&(d*=60),u-=6e4*d}return new Date(u)},stringify:c(({value:s})=>s?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??"","stringify")},Zs=[Je,We,xt,Pt,Hs,Ys,ro,oo,ao,co,no,so,io,Sn,ge,kn,Cn,vn,Qs,Xs,Kt],ei=new Map([["core",Xr],["failsafe",[Je,We,xt]],["json",to],["yaml11",Zs],["yaml-1.1",Zs]]),ti={binary:Sn,bool:wn,float:js,floatExp:Ks,floatNaN:_s,floatTime:Xs,int:qs,intHex:Us,intOct:Bs,intTime:Qs,map:Je,merge:ge,null:Pt,omap:kn,pairs:Cn,seq:We,set:vn,timestamp:Kt},lo={"tag:yaml.org,2002:binary":Sn,"tag:yaml.org,2002:merge":ge,"tag:yaml.org,2002:omap":kn,"tag:yaml.org,2002:pairs":Cn,"tag:yaml.org,2002:set":vn,"tag:yaml.org,2002:timestamp":Kt};function Tn(s,e,t){const n=ei.get(e);if(n&&!s)return t&&!n.includes(ge)?n.concat(ge):n.slice();let i=n;if(!i)if(Array.isArray(s))i=[];else{const r=Array.from(ei.keys()).filter(o=>o!=="yaml11").map(o=>JSON.stringify(o)).join(", ");throw new Error(`Unknown schema "${e}"; use one of ${r} or define customTags array`)}if(Array.isArray(s))for(const r of s)i=i.concat(r);else typeof s=="function"&&(i=s(i.slice()));return t&&(i=i.concat(ge)),i.reduce((r,o)=>{const a=typeof o=="string"?ti[o]:o;if(!a){const l=JSON.stringify(o),u=Object.keys(ti).map(p=>JSON.stringify(p)).join(", ");throw new Error(`Unknown custom tag ${l}; use one of ${u}`)}return r.includes(a)||r.push(a),r},[])}c(Tn,"getTags");const uo=c((s,e)=>s.key<e.key?-1:s.key>e.key?1:0,"sortMapEntriesByKey");class Zt{static{c(this,"Schema")}constructor({compat:e,customTags:t,merge:n,resolveKnownTags:i,schema:r,sortMapEntries:o,toStringDefaults:a}){this.compat=Array.isArray(e)?Tn(e,"compat"):e?Tn(null,e):null,this.name=typeof r=="string"&&r||"core",this.knownTags=i?lo:{},this.tags=Tn(t,this.name,n),this.toStringOptions=a??null,Object.defineProperty(this,be,{value:Je}),Object.defineProperty(this,fe,{value:xt}),Object.defineProperty(this,Me,{value:We}),this.sortMapEntries=typeof o=="function"?o:o===!0?uo:null}clone(){const e=Object.create(Zt.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}}function fo(s,e){const t=[];let n=e.directives===!0;if(e.directives!==!1&&s.directives){const l=s.directives.toString(s);l?(t.push(l),n=!0):s.directives.docStart&&(n=!0)}n&&t.push("---");const i=Ds(s,e),{commentString:r}=i.options;if(s.commentBefore){t.length!==1&&t.unshift("");const l=r(s.commentBefore);t.unshift(me(l,""))}let o=!1,a=null;if(s.contents){if(U(s.contents)){if(s.contents.spaceBefore&&n&&t.push(""),s.contents.commentBefore){const p=r(s.contents.commentBefore);t.push(me(p,""))}i.forceBlockIndent=!!s.comment,a=s.contents.comment}const l=a?void 0:()=>o=!0;let u=Ue(s.contents,i,()=>a=null,l);a&&(u+=Oe(u,"",r(a))),(u[0]==="|"||u[0]===">")&&t[t.length-1]==="---"?t[t.length-1]=`--- ${u}`:t.push(u)}else t.push(Ue(s.contents,i));if(s.directives?.docEnd)if(s.comment){const l=r(s.comment);l.includes(`
56
- `)?(t.push("..."),t.push(me(l,""))):t.push(`... ${l}`)}else t.push("...");else{let l=s.comment;l&&o&&(l=l.replace(/^\n+/,"")),l&&((!o||a)&&t[t.length-1]!==""&&t.push(""),t.push(me(r(l),"")))}return t.join(`
55
+ ${r.comment}`:n.comment}n=i}s.items[t]=B(n)?n:new X(n)}}else e("Expected a sequence for this tag");return s}c(Js,"resolvePairs");function Ws(s,e,t){const{replacer:n}=t,i=new Se(s);i.tag="tag:yaml.org,2002:pairs";let r=0;if(e&&Symbol.iterator in Object(e))for(let o of e){typeof n=="function"&&(o=n.call(e,String(r++),o));let a,l;if(Array.isArray(o))if(o.length===2)a=o[0],l=o[1];else throw new TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){const u=Object.keys(o);if(u.length===1)a=u[0],l=o[a];else throw new TypeError(`Expected tuple with one key, not ${u.length} keys`)}else a=o;i.items.push(gn(a,l,t))}return i}c(Ws,"createPairs");const Sn={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:Js,createNode:Ws};class Ye extends Se{static{c(this,"YAMLOMap")}constructor(){super(),this.add=ne.prototype.add.bind(this),this.delete=ne.prototype.delete.bind(this),this.get=ne.prototype.get.bind(this),this.has=ne.prototype.has.bind(this),this.set=ne.prototype.set.bind(this),this.tag=Ye.tag}toJSON(e,t){if(!t)return super.toJSON(e);const n=new Map;t?.onCreate&&t.onCreate(n);for(const i of this.items){let r,o;if(B(i)?(r=oe(i.key,"",t),o=oe(i.value,r,t)):r=oe(i,"",t),n.has(r))throw new Error("Ordered maps must not include duplicate keys");n.set(r,o)}return n}static from(e,t,n){const i=Ws(e,t,n),r=new this;return r.items=i.items,r}}Ye.tag="tag:yaml.org,2002:omap";const Cn={collection:"seq",identify:c(s=>s instanceof Map,"identify"),nodeClass:Ye,default:!1,tag:"tag:yaml.org,2002:omap",resolve(s,e){const t=Js(s,e),n=[];for(const{key:i}of t.items)_(i)&&(n.includes(i.value)?e(`Ordered maps must not include duplicate keys: ${i.value}`):n.push(i.value));return Object.assign(new Ye,t)},createNode:c((s,e,t)=>Ye.from(s,e,t),"createNode")};function Gs({value:s,source:e},t){return e&&(s?Vs:Hs).test.test(e)?e:s?t.options.trueStr:t.options.falseStr}c(Gs,"boolStringify");const Vs={identify:c(s=>s===!0,"identify"),default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:c(()=>new x(!0),"resolve"),stringify:Gs},Hs={identify:c(s=>s===!1,"identify"),default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:c(()=>new x(!1),"resolve"),stringify:Gs},eo={identify:c(s=>typeof s=="number","identify"),default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:c(s=>s.slice(-3).toLowerCase()==="nan"?NaN:s[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,"resolve"),stringify:ae},to={identify:c(s=>typeof s=="number","identify"),default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:c(s=>parseFloat(s.replace(/_/g,"")),"resolve"),stringify(s){const e=Number(s.value);return isFinite(e)?e.toExponential():ae(s)}},no={identify:c(s=>typeof s=="number","identify"),default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(s){const e=new x(parseFloat(s.replace(/_/g,""))),t=s.indexOf(".");if(t!==-1){const n=s.substring(t+1).replace(/_/g,"");n[n.length-1]==="0"&&(e.minFractionDigits=n.length)}return e},stringify:ae},it=c(s=>typeof s=="bigint"||Number.isInteger(s),"intIdentify");function Mt(s,e,t,{intAsBigInt:n}){const i=s[0];if((i==="-"||i==="+")&&(e+=1),s=s.substring(e).replace(/_/g,""),n){switch(t){case 2:s=`0b${s}`;break;case 8:s=`0o${s}`;break;case 16:s=`0x${s}`;break}const o=BigInt(s);return i==="-"?BigInt(-1)*o:o}const r=parseInt(s,t);return i==="-"?-1*r:r}c(Mt,"intResolve");function kn(s,e,t){const{value:n}=s;if(it(n)){const i=n.toString(e);return n<0?"-"+t+i.substr(1):t+i}return ae(s)}c(kn,"intStringify");const so={identify:it,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:c((s,e,t)=>Mt(s,2,2,t),"resolve"),stringify:c(s=>kn(s,2,"0b"),"stringify")},io={identify:it,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:c((s,e,t)=>Mt(s,1,8,t),"resolve"),stringify:c(s=>kn(s,8,"0"),"stringify")},ro={identify:it,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:c((s,e,t)=>Mt(s,0,10,t),"resolve"),stringify:ae},oo={identify:it,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:c((s,e,t)=>Mt(s,2,16,t),"resolve"),stringify:c(s=>kn(s,16,"0x"),"stringify")};class ze extends ne{static{c(this,"YAMLSet")}constructor(e){super(e),this.tag=ze.tag}add(e){let t;B(e)?t=e:e&&typeof e=="object"&&"key"in e&&"value"in e&&e.value===null?t=new X(e.key,null):t=new X(e,null),Oe(this.items,t.key)||this.items.push(t)}get(e,t){const n=Oe(this.items,e);return!t&&B(n)?_(n.key)?n.key.value:n.key:n}set(e,t){if(typeof t!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof t}`);const n=Oe(this.items,e);n&&!t?this.items.splice(this.items.indexOf(n),1):!n&&t&&this.items.push(new X(e))}toJSON(e,t){return super.toJSON(e,t,Set)}toString(e,t,n){if(!e)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},e,{allNullValues:!0}),t,n);throw new Error("Set items must all have null values")}static from(e,t,n){const{replacer:i}=n,r=new this(e);if(t&&Symbol.iterator in Object(t))for(let o of t)typeof i=="function"&&(o=i.call(t,o,o)),r.items.push(gn(o,null,n));return r}}ze.tag="tag:yaml.org,2002:set";const En={collection:"map",identify:c(s=>s instanceof Set,"identify"),nodeClass:ze,default:!1,tag:"tag:yaml.org,2002:set",createNode:c((s,e,t)=>ze.from(s,e,t),"createNode"),resolve(s,e){if(Me(s)){if(s.hasAllNullValues(!0))return Object.assign(new ze,s);e("Set items must all have null values")}else e("Expected a mapping for this tag");return s}};function vn(s,e){const t=s[0],n=t==="-"||t==="+"?s.substring(1):s,i=c(o=>e?BigInt(o):Number(o),"num"),r=n.replace(/_/g,"").split(":").reduce((o,a)=>o*i(60)+i(a),i(0));return t==="-"?i(-1)*r:r}c(vn,"parseSexagesimal");function Ys(s){let{value:e}=s,t=c(o=>o,"num");if(typeof e=="bigint")t=c(o=>BigInt(o),"num");else if(isNaN(e)||!isFinite(e))return ae(s);let n="";e<0&&(n="-",e*=t(-1));const i=t(60),r=[e%i];return e<60?r.unshift(0):(e=(e-r[0])/i,r.unshift(e%i),e>=60&&(e=(e-r[0])/i,r.unshift(e))),n+r.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}c(Ys,"stringifySexagesimal");const zs={identify:c(s=>typeof s=="bigint"||Number.isInteger(s),"identify"),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:c((s,e,{intAsBigInt:t})=>vn(s,t),"resolve"),stringify:Ys},Qs={identify:c(s=>typeof s=="number","identify"),default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:c(s=>vn(s,!1),"resolve"),stringify:Ys},_t={identify:c(s=>s instanceof Date,"identify"),default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),resolve(s){const e=s.match(_t.test);if(!e)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");const[,t,n,i,r,o,a]=e.map(Number),l=e[7]?Number((e[7]+"00").substr(1,3)):0;let u=Date.UTC(t,n-1,i,r||0,o||0,a||0,l);const p=e[8];if(p&&p!=="Z"){let d=vn(p,!1);Math.abs(d)<30&&(d*=60),u-=6e4*d}return new Date(u)},stringify:c(({value:s})=>s?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??"","stringify")},Xs=[Ue,Je,xt,Pt,Vs,Hs,so,io,ro,oo,eo,to,no,bn,me,Cn,Sn,En,zs,Qs,_t],Zs=new Map([["core",zr],["failsafe",[Ue,Je,xt]],["json",Zr],["yaml11",Xs],["yaml-1.1",Xs]]),ei={binary:bn,bool:yn,float:Ks,floatExp:_s,floatNaN:Ms,floatTime:Qs,int:Bs,intHex:qs,intOct:Fs,intTime:zs,map:Ue,merge:me,null:Pt,omap:Cn,pairs:Sn,seq:Je,set:En,timestamp:_t},ao={"tag:yaml.org,2002:binary":bn,"tag:yaml.org,2002:merge":me,"tag:yaml.org,2002:omap":Cn,"tag:yaml.org,2002:pairs":Sn,"tag:yaml.org,2002:set":En,"tag:yaml.org,2002:timestamp":_t};function In(s,e,t){const n=Zs.get(e);if(n&&!s)return t&&!n.includes(me)?n.concat(me):n.slice();let i=n;if(!i)if(Array.isArray(s))i=[];else{const r=Array.from(Zs.keys()).filter(o=>o!=="yaml11").map(o=>JSON.stringify(o)).join(", ");throw new Error(`Unknown schema "${e}"; use one of ${r} or define customTags array`)}if(Array.isArray(s))for(const r of s)i=i.concat(r);else typeof s=="function"&&(i=s(i.slice()));return t&&(i=i.concat(me)),i.reduce((r,o)=>{const a=typeof o=="string"?ei[o]:o;if(!a){const l=JSON.stringify(o),u=Object.keys(ei).map(p=>JSON.stringify(p)).join(", ");throw new Error(`Unknown custom tag ${l}; use one of ${u}`)}return r.includes(a)||r.push(a),r},[])}c(In,"getTags");const co=c((s,e)=>s.key<e.key?-1:s.key>e.key?1:0,"sortMapEntriesByKey");class Xt{static{c(this,"Schema")}constructor({compat:e,customTags:t,merge:n,resolveKnownTags:i,schema:r,sortMapEntries:o,toStringDefaults:a}){this.compat=Array.isArray(e)?In(e,"compat"):e?In(null,e):null,this.name=typeof r=="string"&&r||"core",this.knownTags=i?ao:{},this.tags=In(t,this.name,n),this.toStringOptions=a??null,Object.defineProperty(this,we,{value:Ue}),Object.defineProperty(this,fe,{value:xt}),Object.defineProperty(this,Re,{value:Je}),this.sortMapEntries=typeof o=="function"?o:o===!0?co:null}clone(){const e=Object.create(Xt.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}}function lo(s,e){const t=[];let n=e.directives===!0;if(e.directives!==!1&&s.directives){const l=s.directives.toString(s);l?(t.push(l),n=!0):s.directives.docStart&&(n=!0)}n&&t.push("---");const i=Ls(s,e),{commentString:r}=i.options;if(s.commentBefore){t.length!==1&&t.unshift("");const l=r(s.commentBefore);t.unshift(pe(l,""))}let o=!1,a=null;if(s.contents){if(J(s.contents)){if(s.contents.spaceBefore&&n&&t.push(""),s.contents.commentBefore){const p=r(s.contents.commentBefore);t.push(pe(p,""))}i.forceBlockIndent=!!s.comment,a=s.contents.comment}const l=a?void 0:()=>o=!0;let u=qe(s.contents,i,()=>a=null,l);a&&(u+=Ae(u,"",r(a))),(u[0]==="|"||u[0]===">")&&t[t.length-1]==="---"?t[t.length-1]=`--- ${u}`:t.push(u)}else t.push(qe(s.contents,i));if(s.directives?.docEnd)if(s.comment){const l=r(s.comment);l.includes(`
56
+ `)?(t.push("..."),t.push(pe(l,""))):t.push(`... ${l}`)}else t.push("...");else{let l=s.comment;l&&o&&(l=l.replace(/^\n+/,"")),l&&((!o||a)&&t[t.length-1]!==""&&t.push(""),t.push(pe(r(l),"")))}return t.join(`
57
57
  `)+`
58
- `}c(fo,"stringifyDocument");class Xe{static{c(this,"Document")}constructor(e,t,n){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,se,{value:fn});let i=null;typeof t=="function"||Array.isArray(t)?i=t:n===void 0&&t&&(n=t,t=void 0);const r=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},n);this.options=r;let{version:o}=r;n?._directives?(this.directives=n._directives.atDocument(),this.directives.yaml.explicit&&(o=this.directives.yaml.version)):this.directives=new Z({version:o}),this.setSchema(o,n),this.contents=e===void 0?null:this.createNode(e,i,n)}clone(){const e=Object.create(Xe.prototype,{[se]:{value:fn}});return e.commentBefore=this.commentBefore,e.comment=this.comment,e.errors=this.errors.slice(),e.warnings=this.warnings.slice(),e.options=Object.assign({},this.options),this.directives&&(e.directives=this.directives.clone()),e.schema=this.schema.clone(),e.contents=U(this.contents)?this.contents.clone(e.schema):this.contents,this.range&&(e.range=this.range.slice()),e}add(e){Ge(this.contents)&&this.contents.add(e)}addIn(e,t){Ge(this.contents)&&this.contents.addIn(e,t)}createAlias(e,t){if(!e.anchor){const n=Ts(this);e.anchor=!t||n.has(t)?Ns(t||"a",n):t}return new kt(e.anchor)}createNode(e,t,n){let i;if(typeof t=="function")e=t.call({"":e},"",e),i=t;else if(Array.isArray(t)){const y=c(E=>typeof E=="number"||E instanceof String||E instanceof Number,"keyToStr"),C=t.filter(y).map(String);C.length>0&&(t=t.concat(C)),i=t}else n===void 0&&t&&(n=t,t=void 0);const{aliasDuplicateObjects:r,anchorPrefix:o,flow:a,keepUndefined:l,onTagObj:u,tag:p}=n??{},{onAnchor:d,setAnchors:h,sourceObjects:g}=jr(this,o||"a"),w={aliasDuplicateObjects:r??!0,keepUndefined:l??!1,onAnchor:d,onTagObj:u,replacer:i,schema:this.schema,sourceObjects:g},f=tt(e,p,w);return a&&q(f)&&(f.flow=!0),h(),f}createPair(e,t,n={}){const i=this.createNode(e,null,n),r=this.createNode(t,null,n);return new Q(i,r)}delete(e){return Ge(this.contents)?this.contents.delete(e):!1}deleteIn(e){return nt(e)?this.contents==null?!1:(this.contents=null,!0):Ge(this.contents)?this.contents.deleteIn(e):!1}get(e,t){return q(this.contents)?this.contents.get(e,t):void 0}getIn(e,t){return nt(e)?!t&&_(this.contents)?this.contents.value:this.contents:q(this.contents)?this.contents.getIn(e,t):void 0}has(e){return q(this.contents)?this.contents.has(e):!1}hasIn(e){return nt(e)?this.contents!==void 0:q(this.contents)?this.contents.hasIn(e):!1}set(e,t){this.contents==null?this.contents=vt(this.schema,[e],t):Ge(this.contents)&&this.contents.set(e,t)}setIn(e,t){nt(e)?this.contents=t:this.contents==null?this.contents=vt(this.schema,Array.from(e),t):Ge(this.contents)&&this.contents.setIn(e,t)}setSchema(e,t={}){typeof e=="number"&&(e=String(e));let n;switch(e){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new Z({version:"1.1"}),n={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=e:this.directives=new Z({version:e}),n={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,n=null;break;default:{const i=JSON.stringify(e);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${i}`)}}if(t.schema instanceof Object)this.schema=t.schema;else if(n)this.schema=new Zt(Object.assign(n,t));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:e,jsonArg:t,mapAsMap:n,maxAliasCount:i,onAnchor:r,reviver:o}={}){const a={anchors:new Map,doc:this,keep:!e,mapAsMap:n===!0,mapKeyWarned:!1,maxAliasCount:typeof i=="number"?i:100},l=ie(this.contents,t??"",a);if(typeof r=="function")for(const{count:u,res:p}of a.anchors.values())r(p,u);return typeof o=="function"?Be(o,{"":l},"",l):l}toJSON(e,t){return this.toJS({json:!0,jsonArg:e,mapAsMap:!1,onAnchor:t})}toString(e={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in e&&(!Number.isInteger(e.indent)||Number(e.indent)<=0)){const t=JSON.stringify(e.indent);throw new Error(`"indent" option must be a positive integer, not ${t}`)}return fo(this,e)}}function Ge(s){if(q(s))return!0;throw new Error("Expected a YAML collection as document contents")}c(Ge,"assertCollection");class Nn extends Error{static{c(this,"YAMLError")}constructor(e,t,n,i){super(),this.name=e,this.code=n,this.message=i,this.pos=t}}class Le extends Nn{static{c(this,"YAMLParseError")}constructor(e,t,n){super("YAMLParseError",e,t,n)}}class ni extends Nn{static{c(this,"YAMLWarning")}constructor(e,t,n){super("YAMLWarning",e,t,n)}}const jt=c((s,e)=>t=>{if(t.pos[0]===-1)return;t.linePos=t.pos.map(a=>e.linePos(a));const{line:n,col:i}=t.linePos[0];t.message+=` at line ${n}, column ${i}`;let r=i-1,o=s.substring(e.lineStarts[n-1],e.lineStarts[n]).replace(/[\n\r]+$/,"");if(r>=60&&o.length>80){const a=Math.min(r-39,o.length-79);o="\u2026"+o.substring(a),r-=a-1}if(o.length>80&&(o=o.substring(0,79)+"\u2026"),n>1&&/^ *$/.test(o.substring(0,r))){let a=s.substring(e.lineStarts[n-2],e.lineStarts[n-1]);a.length>80&&(a=a.substring(0,79)+`\u2026
58
+ `}c(lo,"stringifyDocument");class Qe{static{c(this,"Document")}constructor(e,t,n){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,re,{value:un});let i=null;typeof t=="function"||Array.isArray(t)?i=t:n===void 0&&t&&(n=t,t=void 0);const r=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},n);this.options=r;let{version:o}=r;n?._directives?(this.directives=n._directives.atDocument(),this.directives.yaml.explicit&&(o=this.directives.yaml.version)):this.directives=new ee({version:o}),this.setSchema(o,n),this.contents=e===void 0?null:this.createNode(e,i,n)}clone(){const e=Object.create(Qe.prototype,{[re]:{value:un}});return e.commentBefore=this.commentBefore,e.comment=this.comment,e.errors=this.errors.slice(),e.warnings=this.warnings.slice(),e.options=Object.assign({},this.options),this.directives&&(e.directives=this.directives.clone()),e.schema=this.schema.clone(),e.contents=J(this.contents)?this.contents.clone(e.schema):this.contents,this.range&&(e.range=this.range.slice()),e}add(e){We(this.contents)&&this.contents.add(e)}addIn(e,t){We(this.contents)&&this.contents.addIn(e,t)}createAlias(e,t){if(!e.anchor){const n=Is(this);e.anchor=!t||n.has(t)?Ts(t||"a",n):t}return new Ct(e.anchor)}createNode(e,t,n){let i;if(typeof t=="function")e=t.call({"":e},"",e),i=t;else if(Array.isArray(t)){const y=c(E=>typeof E=="number"||E instanceof String||E instanceof Number,"keyToStr"),C=t.filter(y).map(String);C.length>0&&(t=t.concat(C)),i=t}else n===void 0&&t&&(n=t,t=void 0);const{aliasDuplicateObjects:r,anchorPrefix:o,flow:a,keepUndefined:l,onTagObj:u,tag:p}=n??{},{onAnchor:d,setAnchors:h,sourceObjects:g}=_r(this,o||"a"),w={aliasDuplicateObjects:r??!0,keepUndefined:l??!1,onAnchor:d,onTagObj:u,replacer:i,schema:this.schema,sourceObjects:g},f=et(e,p,w);return a&&U(f)&&(f.flow=!0),h(),f}createPair(e,t,n={}){const i=this.createNode(e,null,n),r=this.createNode(t,null,n);return new X(i,r)}delete(e){return We(this.contents)?this.contents.delete(e):!1}deleteIn(e){return tt(e)?this.contents==null?!1:(this.contents=null,!0):We(this.contents)?this.contents.deleteIn(e):!1}get(e,t){return U(this.contents)?this.contents.get(e,t):void 0}getIn(e,t){return tt(e)?!t&&_(this.contents)?this.contents.value:this.contents:U(this.contents)?this.contents.getIn(e,t):void 0}has(e){return U(this.contents)?this.contents.has(e):!1}hasIn(e){return tt(e)?this.contents!==void 0:U(this.contents)?this.contents.hasIn(e):!1}set(e,t){this.contents==null?this.contents=Et(this.schema,[e],t):We(this.contents)&&this.contents.set(e,t)}setIn(e,t){tt(e)?this.contents=t:this.contents==null?this.contents=Et(this.schema,Array.from(e),t):We(this.contents)&&this.contents.setIn(e,t)}setSchema(e,t={}){typeof e=="number"&&(e=String(e));let n;switch(e){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new ee({version:"1.1"}),n={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=e:this.directives=new ee({version:e}),n={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,n=null;break;default:{const i=JSON.stringify(e);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${i}`)}}if(t.schema instanceof Object)this.schema=t.schema;else if(n)this.schema=new Xt(Object.assign(n,t));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:e,jsonArg:t,mapAsMap:n,maxAliasCount:i,onAnchor:r,reviver:o}={}){const a={anchors:new Map,doc:this,keep:!e,mapAsMap:n===!0,mapKeyWarned:!1,maxAliasCount:typeof i=="number"?i:100},l=oe(this.contents,t??"",a);if(typeof r=="function")for(const{count:u,res:p}of a.anchors.values())r(p,u);return typeof o=="function"?Fe(o,{"":l},"",l):l}toJSON(e,t){return this.toJS({json:!0,jsonArg:e,mapAsMap:!1,onAnchor:t})}toString(e={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in e&&(!Number.isInteger(e.indent)||Number(e.indent)<=0)){const t=JSON.stringify(e.indent);throw new Error(`"indent" option must be a positive integer, not ${t}`)}return lo(this,e)}}function We(s){if(U(s))return!0;throw new Error("Expected a YAML collection as document contents")}c(We,"assertCollection");class Tn extends Error{static{c(this,"YAMLError")}constructor(e,t,n,i){super(),this.name=e,this.code=n,this.message=i,this.pos=t}}class $e extends Tn{static{c(this,"YAMLParseError")}constructor(e,t,n){super("YAMLParseError",e,t,n)}}class ti extends Tn{static{c(this,"YAMLWarning")}constructor(e,t,n){super("YAMLWarning",e,t,n)}}const Kt=c((s,e)=>t=>{if(t.pos[0]===-1)return;t.linePos=t.pos.map(a=>e.linePos(a));const{line:n,col:i}=t.linePos[0];t.message+=` at line ${n}, column ${i}`;let r=i-1,o=s.substring(e.lineStarts[n-1],e.lineStarts[n]).replace(/[\n\r]+$/,"");if(r>=60&&o.length>80){const a=Math.min(r-39,o.length-79);o="\u2026"+o.substring(a),r-=a-1}if(o.length>80&&(o=o.substring(0,79)+"\u2026"),n>1&&/^ *$/.test(o.substring(0,r))){let a=s.substring(e.lineStarts[n-2],e.lineStarts[n-1]);a.length>80&&(a=a.substring(0,79)+`\u2026
59
59
  `),o=a+o}if(/[^ ]/.test(o)){let a=1;const l=t.linePos[1];l&&l.line===n&&l.col>i&&(a=Math.max(1,Math.min(l.col-i,80-r)));const u=" ".repeat(r)+"^".repeat(a);t.message+=`:
60
60
 
61
61
  ${o}
62
62
  ${u}
63
- `}},"prettifyError");function Ve(s,{flow:e,indicator:t,next:n,offset:i,onError:r,parentIndent:o,startOnNewline:a}){let l=!1,u=a,p=a,d="",h="",g=!1,w=!1,f=null,y=null,C=null,E=null,A=null,I=null,O=null;for(const T of s)switch(w&&(T.type!=="space"&&T.type!=="newline"&&T.type!=="comma"&&r(T.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),w=!1),f&&(u&&T.type!=="comment"&&T.type!=="newline"&&r(f,"TAB_AS_INDENT","Tabs are not allowed as indentation"),f=null),T.type){case"space":!e&&(t!=="doc-start"||n?.type!=="flow-collection")&&T.source.includes(" ")&&(f=T),p=!0;break;case"comment":{p||r(T,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");const V=T.source.substring(1)||" ";d?d+=h+V:d=V,h="",u=!1;break}case"newline":u?d?d+=T.source:(!I||t!=="seq-item-ind")&&(l=!0):h+=T.source,u=!0,g=!0,(y||C)&&(E=T),p=!0;break;case"anchor":y&&r(T,"MULTIPLE_ANCHORS","A node can have at most one anchor"),T.source.endsWith(":")&&r(T.offset+T.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),y=T,O??(O=T.offset),u=!1,p=!1,w=!0;break;case"tag":{C&&r(T,"MULTIPLE_TAGS","A node can have at most one tag"),C=T,O??(O=T.offset),u=!1,p=!1,w=!0;break}case t:(y||C)&&r(T,"BAD_PROP_ORDER",`Anchors and tags must be after the ${T.source} indicator`),I&&r(T,"UNEXPECTED_TOKEN",`Unexpected ${T.source} in ${e??"collection"}`),I=T,u=t==="seq-item-ind"||t==="explicit-key-ind",p=!1;break;case"comma":if(e){A&&r(T,"UNEXPECTED_TOKEN",`Unexpected , in ${e}`),A=T,u=!1,p=!1;break}default:r(T,"UNEXPECTED_TOKEN",`Unexpected ${T.type} token`),u=!1,p=!1}const $=s[s.length-1],K=$?$.offset+$.source.length:i;return w&&n&&n.type!=="space"&&n.type!=="newline"&&n.type!=="comma"&&(n.type!=="scalar"||n.source!=="")&&r(n.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),f&&(u&&f.indent<=o||n?.type==="block-map"||n?.type==="block-seq")&&r(f,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:A,found:I,spaceBefore:l,comment:d,hasNewline:g,anchor:y,tag:C,newlineAfterProp:E,end:K,start:O??K}}c(Ve,"resolveProps");function ot(s){if(!s)return null;switch(s.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(s.source.includes(`
64
- `))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(ot(e.key)||ot(e.value))return!0}return!1;default:return!0}}c(ot,"containsNewline");function An(s,e,t){if(e?.type==="flow-collection"){const n=e.end[0];n.indent===s&&(n.source==="]"||n.source==="}")&&ot(e)&&t(n,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}c(An,"flowIndentCheck");function si(s,e,t){const{uniqueKeys:n}=s.options;if(n===!1)return!1;const i=typeof n=="function"?n:(r,o)=>r===o||_(r)&&_(o)&&r.value===o.value;return e.some(r=>i(r.key,t))}c(si,"mapIncludes");const ii="All mapping items must start at the same column";function ho({composeNode:s,composeEmptyNode:e},t,n,i,r){const o=r?.nodeClass??te,a=new o(t.schema);t.atRoot&&(t.atRoot=!1);let l=n.offset,u=null;for(const p of n.items){const{start:d,key:h,sep:g,value:w}=p,f=Ve(d,{indicator:"explicit-key-ind",next:h??g?.[0],offset:l,onError:i,parentIndent:n.indent,startOnNewline:!0}),y=!f.found;if(y){if(h&&(h.type==="block-seq"?i(l,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in h&&h.indent!==n.indent&&i(l,"BAD_INDENT",ii)),!f.anchor&&!f.tag&&!g){u=f.end,f.comment&&(a.comment?a.comment+=`
65
- `+f.comment:a.comment=f.comment);continue}(f.newlineAfterProp||ot(h))&&i(h??d[d.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else f.found?.indent!==n.indent&&i(l,"BAD_INDENT",ii);t.atKey=!0;const C=f.end,E=h?s(t,h,f,i):e(t,C,d,null,f,i);t.schema.compat&&An(n.indent,h,i),t.atKey=!1,si(t,a.items,E)&&i(C,"DUPLICATE_KEY","Map keys must be unique");const A=Ve(g??[],{indicator:"map-value-ind",next:w,offset:E.range[2],onError:i,parentIndent:n.indent,startOnNewline:!h||h.type==="block-scalar"});if(l=A.end,A.found){y&&(w?.type==="block-map"&&!A.hasNewline&&i(l,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),t.options.strict&&f.start<A.found.offset-1024&&i(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=w?s(t,w,A,i):e(t,l,g,null,A,i);t.schema.compat&&An(n.indent,w,i),l=I.range[2];const O=new Q(E,I);t.options.keepSourceTokens&&(O.srcToken=p),a.items.push(O)}else{y&&i(E.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),A.comment&&(E.comment?E.comment+=`
66
- `+A.comment:E.comment=A.comment);const I=new Q(E);t.options.keepSourceTokens&&(I.srcToken=p),a.items.push(I)}}return u&&u<l&&i(u,"IMPOSSIBLE","Map comment with trailing content"),a.range=[n.offset,l,u??l],a}c(ho,"resolveBlockMap");function po({composeNode:s,composeEmptyNode:e},t,n,i,r){const o=r?.nodeClass??Ce,a=new o(t.schema);t.atRoot&&(t.atRoot=!1),t.atKey&&(t.atKey=!1);let l=n.offset,u=null;for(const{start:p,value:d}of n.items){const h=Ve(p,{indicator:"seq-item-ind",next:d,offset:l,onError:i,parentIndent:n.indent,startOnNewline:!0});if(!h.found)if(h.anchor||h.tag||d)d&&d.type==="block-seq"?i(h.end,"BAD_INDENT","All sequence items must start at the same column"):i(l,"MISSING_CHAR","Sequence item without - indicator");else{u=h.end,h.comment&&(a.comment=h.comment);continue}const g=d?s(t,d,h,i):e(t,h.end,p,null,h,i);t.schema.compat&&An(n.indent,d,i),l=g.range[2],a.items.push(g)}return a.range=[n.offset,l,u??l],a}c(po,"resolveBlockSeq");function at(s,e,t,n){let i="";if(s){let r=!1,o="";for(const a of s){const{source:l,type:u}=a;switch(u){case"space":r=!0;break;case"comment":{t&&!r&&n(a,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");const p=l.substring(1)||" ";i?i+=o+p:i=p,o="";break}case"newline":i&&(o+=l),r=!0;break;default:n(a,"UNEXPECTED_TOKEN",`Unexpected ${u} at node end`)}e+=l.length}}return{comment:i,offset:e}}c(at,"resolveEnd");const On="Block collections are not allowed within flow collections",$n=c(s=>s&&(s.type==="block-map"||s.type==="block-seq"),"isBlock");function mo({composeNode:s,composeEmptyNode:e},t,n,i,r){const o=n.start.source==="{",a=o?"flow map":"flow sequence",l=r?.nodeClass??(o?te:Ce),u=new l(t.schema);u.flow=!0;const p=t.atRoot;p&&(t.atRoot=!1),t.atKey&&(t.atKey=!1);let d=n.offset+n.start.source.length;for(let y=0;y<n.items.length;++y){const C=n.items[y],{start:E,key:A,sep:I,value:O}=C,$=Ve(E,{flow:a,indicator:"explicit-key-ind",next:A??I?.[0],offset:d,onError:i,parentIndent:n.indent,startOnNewline:!1});if(!$.found){if(!$.anchor&&!$.tag&&!I&&!O){y===0&&$.comma?i($.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`):y<n.items.length-1&&i($.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${a}`),$.comment&&(u.comment?u.comment+=`
67
- `+$.comment:u.comment=$.comment),d=$.end;continue}!o&&t.options.strict&&ot(A)&&i(A,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(y===0)$.comma&&i($.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`);else if($.comma||i($.start,"MISSING_CHAR",`Missing , between ${a} items`),$.comment){let K="";e:for(const T of E)switch(T.type){case"comma":case"space":break;case"comment":K=T.source.substring(1);break e;default:break e}if(K){let T=u.items[u.items.length-1];F(T)&&(T=T.value??T.key),T.comment?T.comment+=`
68
- `+K:T.comment=K,$.comment=$.comment.substring(K.length+1)}}if(!o&&!I&&!$.found){const K=O?s(t,O,$,i):e(t,$.end,I,null,$,i);u.items.push(K),d=K.range[2],$n(O)&&i(K.range,"BLOCK_IN_FLOW",On)}else{t.atKey=!0;const K=$.end,T=A?s(t,A,$,i):e(t,K,E,null,$,i);$n(A)&&i(T.range,"BLOCK_IN_FLOW",On),t.atKey=!1;const V=Ve(I??[],{flow:a,indicator:"map-value-ind",next:O,offset:T.range[2],onError:i,parentIndent:n.indent,startOnNewline:!1});if(V.found){if(!o&&!$.found&&t.options.strict){if(I)for(const H of I){if(H===V.found)break;if(H.type==="newline"){i(H,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}$.start<V.found.offset-1024&&i(V.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else O&&("source"in O&&O.source&&O.source[0]===":"?i(O,"MISSING_CHAR",`Missing space after : in ${a}`):i(V.start,"MISSING_CHAR",`Missing , or : between ${a} items`));const ye=O?s(t,O,V,i):V.found?e(t,V.end,I,null,V,i):null;ye?$n(O)&&i(ye.range,"BLOCK_IN_FLOW",On):V.comment&&(T.comment?T.comment+=`
69
- `+V.comment:T.comment=V.comment);const xe=new Q(T,ye);if(t.options.keepSourceTokens&&(xe.srcToken=C),o){const H=u;si(t,H.items,T)&&i(K,"DUPLICATE_KEY","Map keys must be unique"),H.items.push(xe)}else{const H=new te(t.schema);H.flow=!0,H.items.push(xe);const ns=(ye??T).range;H.range=[T.range[0],ns[1],ns[2]],u.items.push(H)}d=ye?ye.range[2]:V.end}}const h=o?"}":"]",[g,...w]=n.end;let f=d;if(g&&g.source===h)f=g.offset+g.source.length;else{const y=a[0].toUpperCase()+a.substring(1),C=p?`${y} must end with a ${h}`:`${y} in block collection must be sufficiently indented and end with a ${h}`;i(d,p?"MISSING_CHAR":"BAD_INDENT",C),g&&g.source.length!==1&&w.unshift(g)}if(w.length>0){const y=at(w,f,t.options.strict,i);y.comment&&(u.comment?u.comment+=`
70
- `+y.comment:u.comment=y.comment),u.range=[n.offset,f,y.offset]}else u.range=[n.offset,f,f];return u}c(mo,"resolveFlowCollection");function Ln(s,e,t,n,i,r){const o=t.type==="block-map"?ho(s,e,t,n,r):t.type==="block-seq"?po(s,e,t,n,r):mo(s,e,t,n,r),a=o.constructor;return i==="!"||i===a.tagName?(o.tag=a.tagName,o):(i&&(o.tag=i),o)}c(Ln,"resolveCollection");function go(s,e,t,n,i){const r=n.tag,o=r?e.directives.tagName(r.source,h=>i(r,"TAG_RESOLVE_FAILED",h)):null;if(t.type==="block-seq"){const{anchor:h,newlineAfterProp:g}=n,w=h&&r?h.offset>r.offset?h:r:h??r;w&&(!g||g.offset<w.offset)&&i(w,"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(!r||!o||o==="!"||o===te.tagName&&a==="map"||o===Ce.tagName&&a==="seq")return Ln(s,e,t,i,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?i(r,"BAD_COLLECTION_TYPE",`${h.tag} used for ${a} collection, but expects ${h.collection??"scalar"}`,!0):i(r,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),Ln(s,e,t,i,o)}const u=Ln(s,e,t,i,o,l),p=l.resolve?.(u,h=>i(r,"TAG_RESOLVE_FAILED",h),e.options)??u,d=U(p)?p:new D(p);return d.range=u.range,d.tag=o,l?.format&&(d.format=l.format),d}c(go,"composeCollection");function ri(s,e,t){const n=e.offset,i=yo(e,s.options.strict,t);if(!i)return{value:"",type:null,comment:"",range:[n,n,n]};const r=i.mode===">"?D.BLOCK_FOLDED:D.BLOCK_LITERAL,o=e.source?wo(e.source):[];let a=o.length;for(let f=o.length-1;f>=0;--f){const y=o[f][1];if(y===""||y==="\r")a=f;else break}if(a===0){const f=i.chomp==="+"&&o.length>0?`
63
+ `}},"prettifyError");function Ge(s,{flow:e,indicator:t,next:n,offset:i,onError:r,parentIndent:o,startOnNewline:a}){let l=!1,u=a,p=a,d="",h="",g=!1,w=!1,f=null,y=null,C=null,E=null,A=null,I=null,O=null;for(const T of s)switch(w&&(T.type!=="space"&&T.type!=="newline"&&T.type!=="comma"&&r(T.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),w=!1),f&&(u&&T.type!=="comment"&&T.type!=="newline"&&r(f,"TAB_AS_INDENT","Tabs are not allowed as indentation"),f=null),T.type){case"space":!e&&(t!=="doc-start"||n?.type!=="flow-collection")&&T.source.includes(" ")&&(f=T),p=!0;break;case"comment":{p||r(T,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");const H=T.source.substring(1)||" ";d?d+=h+H:d=H,h="",u=!1;break}case"newline":u?d?d+=T.source:(!I||t!=="seq-item-ind")&&(l=!0):h+=T.source,u=!0,g=!0,(y||C)&&(E=T),p=!0;break;case"anchor":y&&r(T,"MULTIPLE_ANCHORS","A node can have at most one anchor"),T.source.endsWith(":")&&r(T.offset+T.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),y=T,O??(O=T.offset),u=!1,p=!1,w=!0;break;case"tag":{C&&r(T,"MULTIPLE_TAGS","A node can have at most one tag"),C=T,O??(O=T.offset),u=!1,p=!1,w=!0;break}case t:(y||C)&&r(T,"BAD_PROP_ORDER",`Anchors and tags must be after the ${T.source} indicator`),I&&r(T,"UNEXPECTED_TOKEN",`Unexpected ${T.source} in ${e??"collection"}`),I=T,u=t==="seq-item-ind"||t==="explicit-key-ind",p=!1;break;case"comma":if(e){A&&r(T,"UNEXPECTED_TOKEN",`Unexpected , in ${e}`),A=T,u=!1,p=!1;break}default:r(T,"UNEXPECTED_TOKEN",`Unexpected ${T.type} token`),u=!1,p=!1}const $=s[s.length-1],K=$?$.offset+$.source.length:i;return w&&n&&n.type!=="space"&&n.type!=="newline"&&n.type!=="comma"&&(n.type!=="scalar"||n.source!=="")&&r(n.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),f&&(u&&f.indent<=o||n?.type==="block-map"||n?.type==="block-seq")&&r(f,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:A,found:I,spaceBefore:l,comment:d,hasNewline:g,anchor:y,tag:C,newlineAfterProp:E,end:K,start:O??K}}c(Ge,"resolveProps");function rt(s){if(!s)return null;switch(s.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(s.source.includes(`
64
+ `))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(rt(e.key)||rt(e.value))return!0}return!1;default:return!0}}c(rt,"containsNewline");function Nn(s,e,t){if(e?.type==="flow-collection"){const n=e.end[0];n.indent===s&&(n.source==="]"||n.source==="}")&&rt(e)&&t(n,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}c(Nn,"flowIndentCheck");function ni(s,e,t){const{uniqueKeys:n}=s.options;if(n===!1)return!1;const i=typeof n=="function"?n:(r,o)=>r===o||_(r)&&_(o)&&r.value===o.value;return e.some(r=>i(r.key,t))}c(ni,"mapIncludes");const si="All mapping items must start at the same column";function uo({composeNode:s,composeEmptyNode:e},t,n,i,r){const o=r?.nodeClass??ne,a=new o(t.schema);t.atRoot&&(t.atRoot=!1);let l=n.offset,u=null;for(const p of n.items){const{start:d,key:h,sep:g,value:w}=p,f=Ge(d,{indicator:"explicit-key-ind",next:h??g?.[0],offset:l,onError:i,parentIndent:n.indent,startOnNewline:!0}),y=!f.found;if(y){if(h&&(h.type==="block-seq"?i(l,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in h&&h.indent!==n.indent&&i(l,"BAD_INDENT",si)),!f.anchor&&!f.tag&&!g){u=f.end,f.comment&&(a.comment?a.comment+=`
65
+ `+f.comment:a.comment=f.comment);continue}(f.newlineAfterProp||rt(h))&&i(h??d[d.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else f.found?.indent!==n.indent&&i(l,"BAD_INDENT",si);t.atKey=!0;const C=f.end,E=h?s(t,h,f,i):e(t,C,d,null,f,i);t.schema.compat&&Nn(n.indent,h,i),t.atKey=!1,ni(t,a.items,E)&&i(C,"DUPLICATE_KEY","Map keys must be unique");const A=Ge(g??[],{indicator:"map-value-ind",next:w,offset:E.range[2],onError:i,parentIndent:n.indent,startOnNewline:!h||h.type==="block-scalar"});if(l=A.end,A.found){y&&(w?.type==="block-map"&&!A.hasNewline&&i(l,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),t.options.strict&&f.start<A.found.offset-1024&&i(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=w?s(t,w,A,i):e(t,l,g,null,A,i);t.schema.compat&&Nn(n.indent,w,i),l=I.range[2];const O=new X(E,I);t.options.keepSourceTokens&&(O.srcToken=p),a.items.push(O)}else{y&&i(E.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),A.comment&&(E.comment?E.comment+=`
66
+ `+A.comment:E.comment=A.comment);const I=new X(E);t.options.keepSourceTokens&&(I.srcToken=p),a.items.push(I)}}return u&&u<l&&i(u,"IMPOSSIBLE","Map comment with trailing content"),a.range=[n.offset,l,u??l],a}c(uo,"resolveBlockMap");function fo({composeNode:s,composeEmptyNode:e},t,n,i,r){const o=r?.nodeClass??Se,a=new o(t.schema);t.atRoot&&(t.atRoot=!1),t.atKey&&(t.atKey=!1);let l=n.offset,u=null;for(const{start:p,value:d}of n.items){const h=Ge(p,{indicator:"seq-item-ind",next:d,offset:l,onError:i,parentIndent:n.indent,startOnNewline:!0});if(!h.found)if(h.anchor||h.tag||d)d&&d.type==="block-seq"?i(h.end,"BAD_INDENT","All sequence items must start at the same column"):i(l,"MISSING_CHAR","Sequence item without - indicator");else{u=h.end,h.comment&&(a.comment=h.comment);continue}const g=d?s(t,d,h,i):e(t,h.end,p,null,h,i);t.schema.compat&&Nn(n.indent,d,i),l=g.range[2],a.items.push(g)}return a.range=[n.offset,l,u??l],a}c(fo,"resolveBlockSeq");function ot(s,e,t,n){let i="";if(s){let r=!1,o="";for(const a of s){const{source:l,type:u}=a;switch(u){case"space":r=!0;break;case"comment":{t&&!r&&n(a,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");const p=l.substring(1)||" ";i?i+=o+p:i=p,o="";break}case"newline":i&&(o+=l),r=!0;break;default:n(a,"UNEXPECTED_TOKEN",`Unexpected ${u} at node end`)}e+=l.length}}return{comment:i,offset:e}}c(ot,"resolveEnd");const An="Block collections are not allowed within flow collections",On=c(s=>s&&(s.type==="block-map"||s.type==="block-seq"),"isBlock");function ho({composeNode:s,composeEmptyNode:e},t,n,i,r){const o=n.start.source==="{",a=o?"flow map":"flow sequence",l=r?.nodeClass??(o?ne:Se),u=new l(t.schema);u.flow=!0;const p=t.atRoot;p&&(t.atRoot=!1),t.atKey&&(t.atKey=!1);let d=n.offset+n.start.source.length;for(let y=0;y<n.items.length;++y){const C=n.items[y],{start:E,key:A,sep:I,value:O}=C,$=Ge(E,{flow:a,indicator:"explicit-key-ind",next:A??I?.[0],offset:d,onError:i,parentIndent:n.indent,startOnNewline:!1});if(!$.found){if(!$.anchor&&!$.tag&&!I&&!O){y===0&&$.comma?i($.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`):y<n.items.length-1&&i($.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${a}`),$.comment&&(u.comment?u.comment+=`
67
+ `+$.comment:u.comment=$.comment),d=$.end;continue}!o&&t.options.strict&&rt(A)&&i(A,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(y===0)$.comma&&i($.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`);else if($.comma||i($.start,"MISSING_CHAR",`Missing , between ${a} items`),$.comment){let K="";e:for(const T of E)switch(T.type){case"comma":case"space":break;case"comment":K=T.source.substring(1);break e;default:break e}if(K){let T=u.items[u.items.length-1];B(T)&&(T=T.value??T.key),T.comment?T.comment+=`
68
+ `+K:T.comment=K,$.comment=$.comment.substring(K.length+1)}}if(!o&&!I&&!$.found){const K=O?s(t,O,$,i):e(t,$.end,I,null,$,i);u.items.push(K),d=K.range[2],On(O)&&i(K.range,"BLOCK_IN_FLOW",An)}else{t.atKey=!0;const K=$.end,T=A?s(t,A,$,i):e(t,K,E,null,$,i);On(A)&&i(T.range,"BLOCK_IN_FLOW",An),t.atKey=!1;const H=Ge(I??[],{flow:a,indicator:"map-value-ind",next:O,offset:T.range[2],onError:i,parentIndent:n.indent,startOnNewline:!1});if(H.found){if(!o&&!$.found&&t.options.strict){if(I)for(const Y of I){if(Y===H.found)break;if(Y.type==="newline"){i(Y,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}$.start<H.found.offset-1024&&i(H.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else O&&("source"in O&&O.source&&O.source[0]===":"?i(O,"MISSING_CHAR",`Missing space after : in ${a}`):i(H.start,"MISSING_CHAR",`Missing , or : between ${a} items`));const ge=O?s(t,O,H,i):H.found?e(t,H.end,I,null,H,i):null;ge?On(O)&&i(ge.range,"BLOCK_IN_FLOW",An):H.comment&&(T.comment?T.comment+=`
69
+ `+H.comment:T.comment=H.comment);const xe=new X(T,ge);if(t.options.keepSourceTokens&&(xe.srcToken=C),o){const Y=u;ni(t,Y.items,T)&&i(K,"DUPLICATE_KEY","Map keys must be unique"),Y.items.push(xe)}else{const Y=new ne(t.schema);Y.flow=!0,Y.items.push(xe);const ts=(ge??T).range;Y.range=[T.range[0],ts[1],ts[2]],u.items.push(Y)}d=ge?ge.range[2]:H.end}}const h=o?"}":"]",[g,...w]=n.end;let f=d;if(g&&g.source===h)f=g.offset+g.source.length;else{const y=a[0].toUpperCase()+a.substring(1),C=p?`${y} must end with a ${h}`:`${y} in block collection must be sufficiently indented and end with a ${h}`;i(d,p?"MISSING_CHAR":"BAD_INDENT",C),g&&g.source.length!==1&&w.unshift(g)}if(w.length>0){const y=ot(w,f,t.options.strict,i);y.comment&&(u.comment?u.comment+=`
70
+ `+y.comment:u.comment=y.comment),u.range=[n.offset,f,y.offset]}else u.range=[n.offset,f,f];return u}c(ho,"resolveFlowCollection");function $n(s,e,t,n,i,r){const o=t.type==="block-map"?uo(s,e,t,n,r):t.type==="block-seq"?fo(s,e,t,n,r):ho(s,e,t,n,r),a=o.constructor;return i==="!"||i===a.tagName?(o.tag=a.tagName,o):(i&&(o.tag=i),o)}c($n,"resolveCollection");function po(s,e,t,n,i){const r=n.tag,o=r?e.directives.tagName(r.source,h=>i(r,"TAG_RESOLVE_FAILED",h)):null;if(t.type==="block-seq"){const{anchor:h,newlineAfterProp:g}=n,w=h&&r?h.offset>r.offset?h:r:h??r;w&&(!g||g.offset<w.offset)&&i(w,"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(!r||!o||o==="!"||o===ne.tagName&&a==="map"||o===Se.tagName&&a==="seq")return $n(s,e,t,i,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?i(r,"BAD_COLLECTION_TYPE",`${h.tag} used for ${a} collection, but expects ${h.collection??"scalar"}`,!0):i(r,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),$n(s,e,t,i,o)}const u=$n(s,e,t,i,o,l),p=l.resolve?.(u,h=>i(r,"TAG_RESOLVE_FAILED",h),e.options)??u,d=J(p)?p:new x(p);return d.range=u.range,d.tag=o,l?.format&&(d.format=l.format),d}c(po,"composeCollection");function ii(s,e,t){const n=e.offset,i=mo(e,s.options.strict,t);if(!i)return{value:"",type:null,comment:"",range:[n,n,n]};const r=i.mode===">"?x.BLOCK_FOLDED:x.BLOCK_LITERAL,o=e.source?go(e.source):[];let a=o.length;for(let f=o.length-1;f>=0;--f){const y=o[f][1];if(y===""||y==="\r")a=f;else break}if(a===0){const f=i.chomp==="+"&&o.length>0?`
71
71
  `.repeat(Math.max(1,o.length-1)):"";let y=n+i.length;return e.source&&(y+=e.source.length),{value:f,type:r,comment:i.comment,range:[n,y,y]}}let l=e.indent+i.indent,u=e.offset+i.length,p=0;for(let f=0;f<a;++f){const[y,C]=o[f];if(C===""||C==="\r")i.indent===0&&y.length>l&&(l=y.length);else{y.length<l&&t(u+y.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator"),i.indent===0&&(l=y.length),p=f,l===0&&!s.atRoot&&t(u,"BAD_INDENT","Block scalar values in collections must be indented");break}u+=y.length+C.length+1}for(let f=o.length-1;f>=a;--f)o[f][0].length>l&&(a=f+1);let d="",h="",g=!1;for(let f=0;f<p;++f)d+=o[f][0].slice(l)+`
72
- `;for(let f=p;f<a;++f){let[y,C]=o[f];u+=y.length+C.length+1;const E=C[C.length-1]==="\r";if(E&&(C=C.slice(0,-1)),C&&y.length<l){const I=`Block scalar lines must not be less indented than their ${i.indent?"explicit indentation indicator":"first line"}`;t(u-C.length-(E?2:1),"BAD_INDENT",I),y=""}r===D.BLOCK_LITERAL?(d+=h+y.slice(l)+C,h=`
72
+ `;for(let f=p;f<a;++f){let[y,C]=o[f];u+=y.length+C.length+1;const E=C[C.length-1]==="\r";if(E&&(C=C.slice(0,-1)),C&&y.length<l){const I=`Block scalar lines must not be less indented than their ${i.indent?"explicit indentation indicator":"first line"}`;t(u-C.length-(E?2:1),"BAD_INDENT",I),y=""}r===x.BLOCK_LITERAL?(d+=h+y.slice(l)+C,h=`
73
73
  `):y.length>l||C[0]===" "?(h===" "?h=`
74
74
  `:!g&&h===`
75
75
  `&&(h=`
@@ -82,71 +82,71 @@ ${u}
82
82
  `+o[f][0].slice(l);d[d.length-1]!==`
83
83
  `&&(d+=`
84
84
  `);break;default:d+=`
85
- `}const w=n+i.length+e.source.length;return{value:d,type:r,comment:i.comment,range:[n,w,w]}}c(ri,"resolveBlockScalar");function yo({offset:s,props:e},t,n){if(e[0].type!=="block-scalar-header")return n(e[0],"IMPOSSIBLE","Block scalar header not found"),null;const{source:i}=e[0],r=i[0];let o=0,a="",l=-1;for(let h=1;h<i.length;++h){const g=i[h];if(!a&&(g==="-"||g==="+"))a=g;else{const w=Number(g);!o&&w?o=w:l===-1&&(l=s+h)}}l!==-1&&n(l,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${i}`);let u=!1,p="",d=i.length;for(let h=1;h<e.length;++h){const g=e[h];switch(g.type){case"space":u=!0;case"newline":d+=g.source.length;break;case"comment":t&&!u&&n(g,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),d+=g.source.length,p=g.source.substring(1);break;case"error":n(g,"UNEXPECTED_TOKEN",g.message),d+=g.source.length;break;default:{const w=`Unexpected token in block scalar header: ${g.type}`;n(g,"UNEXPECTED_TOKEN",w);const f=g.source;f&&typeof f=="string"&&(d+=f.length)}}}return{mode:r,indent:o,chomp:a,comment:p,length:d}}c(yo,"parseBlockScalarHeader");function wo(s){const e=s.split(/\n( *)/),t=e[0],n=t.match(/^( *)/),r=[n?.[1]?[n[1],t.slice(n[1].length)]:["",t]];for(let o=1;o<e.length;o+=2)r.push([e[o],e[o+1]]);return r}c(wo,"splitLines");function oi(s,e,t){const{offset:n,type:i,source:r,end:o}=s;let a,l;const u=c((h,g,w)=>t(n+h,g,w),"_onError");switch(i){case"scalar":a=D.PLAIN,l=bo(r,u);break;case"single-quoted-scalar":a=D.QUOTE_SINGLE,l=So(r,u);break;case"double-quoted-scalar":a=D.QUOTE_DOUBLE,l=Co(r,u);break;default:return t(s,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${i}`),{value:"",type:null,comment:"",range:[n,n+r.length,n+r.length]}}const p=n+r.length,d=at(o,p,e,t);return{value:l,type:a,comment:d.comment,range:[n,p,d.offset]}}c(oi,"resolveFlowScalar");function bo(s,e){let t="";switch(s[0]){case" ":t="a tab character";break;case",":t="flow indicator character ,";break;case"%":t="directive indicator character %";break;case"|":case">":{t=`block scalar indicator ${s[0]}`;break}case"@":case"`":{t=`reserved character ${s[0]}`;break}}return t&&e(0,"BAD_SCALAR_START",`Plain value cannot start with ${t}`),ai(s)}c(bo,"plainValue");function So(s,e){return(s[s.length-1]!=="'"||s.length===1)&&e(s.length,"MISSING_CHAR","Missing closing 'quote"),ai(s.slice(1,-1)).replace(/''/g,"'")}c(So,"singleQuotedValue");function ai(s){let e,t;try{e=new RegExp(`(.*?)(?<![ ])[ ]*\r?
85
+ `}const w=n+i.length+e.source.length;return{value:d,type:r,comment:i.comment,range:[n,w,w]}}c(ii,"resolveBlockScalar");function mo({offset:s,props:e},t,n){if(e[0].type!=="block-scalar-header")return n(e[0],"IMPOSSIBLE","Block scalar header not found"),null;const{source:i}=e[0],r=i[0];let o=0,a="",l=-1;for(let h=1;h<i.length;++h){const g=i[h];if(!a&&(g==="-"||g==="+"))a=g;else{const w=Number(g);!o&&w?o=w:l===-1&&(l=s+h)}}l!==-1&&n(l,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${i}`);let u=!1,p="",d=i.length;for(let h=1;h<e.length;++h){const g=e[h];switch(g.type){case"space":u=!0;case"newline":d+=g.source.length;break;case"comment":t&&!u&&n(g,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),d+=g.source.length,p=g.source.substring(1);break;case"error":n(g,"UNEXPECTED_TOKEN",g.message),d+=g.source.length;break;default:{const w=`Unexpected token in block scalar header: ${g.type}`;n(g,"UNEXPECTED_TOKEN",w);const f=g.source;f&&typeof f=="string"&&(d+=f.length)}}}return{mode:r,indent:o,chomp:a,comment:p,length:d}}c(mo,"parseBlockScalarHeader");function go(s){const e=s.split(/\n( *)/),t=e[0],n=t.match(/^( *)/),r=[n?.[1]?[n[1],t.slice(n[1].length)]:["",t]];for(let o=1;o<e.length;o+=2)r.push([e[o],e[o+1]]);return r}c(go,"splitLines");function ri(s,e,t){const{offset:n,type:i,source:r,end:o}=s;let a,l;const u=c((h,g,w)=>t(n+h,g,w),"_onError");switch(i){case"scalar":a=x.PLAIN,l=yo(r,u);break;case"single-quoted-scalar":a=x.QUOTE_SINGLE,l=wo(r,u);break;case"double-quoted-scalar":a=x.QUOTE_DOUBLE,l=bo(r,u);break;default:return t(s,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${i}`),{value:"",type:null,comment:"",range:[n,n+r.length,n+r.length]}}const p=n+r.length,d=ot(o,p,e,t);return{value:l,type:a,comment:d.comment,range:[n,p,d.offset]}}c(ri,"resolveFlowScalar");function yo(s,e){let t="";switch(s[0]){case" ":t="a tab character";break;case",":t="flow indicator character ,";break;case"%":t="directive indicator character %";break;case"|":case">":{t=`block scalar indicator ${s[0]}`;break}case"@":case"`":{t=`reserved character ${s[0]}`;break}}return t&&e(0,"BAD_SCALAR_START",`Plain value cannot start with ${t}`),oi(s)}c(yo,"plainValue");function wo(s,e){return(s[s.length-1]!=="'"||s.length===1)&&e(s.length,"MISSING_CHAR","Missing closing 'quote"),oi(s.slice(1,-1)).replace(/''/g,"'")}c(wo,"singleQuotedValue");function oi(s){let e,t;try{e=new RegExp(`(.*?)(?<![ ])[ ]*\r?
86
86
  `,"sy"),t=new RegExp(`[ ]*(.*?)(?:(?<![ ])[ ]*)?\r?
87
87
  `,"sy")}catch{e=/(.*?)[ \t]*\r?\n/sy,t=/[ \t]*(.*?)[ \t]*\r?\n/sy}let n=e.exec(s);if(!n)return s;let i=n[1],r=" ",o=e.lastIndex;for(t.lastIndex=o;n=t.exec(s);)n[1]===""?r===`
88
88
  `?i+=r:r=`
89
- `:(i+=r+n[1],r=" "),o=t.lastIndex;const a=/[ \t]*(.*)/sy;return a.lastIndex=o,n=a.exec(s),i+r+(n?.[1]??"")}c(ai,"foldLines");function Co(s,e){let t="";for(let n=1;n<s.length-1;++n){const i=s[n];if(!(i==="\r"&&s[n+1]===`
89
+ `:(i+=r+n[1],r=" "),o=t.lastIndex;const a=/[ \t]*(.*)/sy;return a.lastIndex=o,n=a.exec(s),i+r+(n?.[1]??"")}c(oi,"foldLines");function bo(s,e){let t="";for(let n=1;n<s.length-1;++n){const i=s[n];if(!(i==="\r"&&s[n+1]===`
90
90
  `))if(i===`
91
- `){const{fold:r,offset:o}=ko(s,n);t+=r,n=o}else if(i==="\\"){let r=s[++n];const o=Eo[r];if(o)t+=o;else if(r===`
91
+ `){const{fold:r,offset:o}=So(s,n);t+=r,n=o}else if(i==="\\"){let r=s[++n];const o=Co[r];if(o)t+=o;else if(r===`
92
92
  `)for(r=s[n+1];r===" "||r===" ";)r=s[++n+1];else if(r==="\r"&&s[n+1]===`
93
- `)for(r=s[++n+1];r===" "||r===" ";)r=s[++n+1];else if(r==="x"||r==="u"||r==="U"){const a={x:2,u:4,U:8}[r];t+=vo(s,n+1,a,e),n+=a}else{const a=s.substr(n-1,2);e(n-1,"BAD_DQ_ESCAPE",`Invalid escape sequence ${a}`),t+=a}}else if(i===" "||i===" "){const r=n;let o=s[n+1];for(;o===" "||o===" ";)o=s[++n+1];o!==`
93
+ `)for(r=s[++n+1];r===" "||r===" ";)r=s[++n+1];else if(r==="x"||r==="u"||r==="U"){const a={x:2,u:4,U:8}[r];t+=ko(s,n+1,a,e),n+=a}else{const a=s.substr(n-1,2);e(n-1,"BAD_DQ_ESCAPE",`Invalid escape sequence ${a}`),t+=a}}else if(i===" "||i===" "){const r=n;let o=s[n+1];for(;o===" "||o===" ";)o=s[++n+1];o!==`
94
94
  `&&!(o==="\r"&&s[n+2]===`
95
- `)&&(t+=n>r?s.slice(r,n+1):i)}else t+=i}return(s[s.length-1]!=='"'||s.length===1)&&e(s.length,"MISSING_CHAR",'Missing closing "quote'),t}c(Co,"doubleQuotedValue");function ko(s,e){let t="",n=s[e+1];for(;(n===" "||n===" "||n===`
95
+ `)&&(t+=n>r?s.slice(r,n+1):i)}else t+=i}return(s[s.length-1]!=='"'||s.length===1)&&e(s.length,"MISSING_CHAR",'Missing closing "quote'),t}c(bo,"doubleQuotedValue");function So(s,e){let t="",n=s[e+1];for(;(n===" "||n===" "||n===`
96
96
  `||n==="\r")&&!(n==="\r"&&s[e+2]!==`
97
97
  `);)n===`
98
98
  `&&(t+=`
99
- `),e+=1,n=s[e+1];return t||(t=" "),{fold:t,offset:e}}c(ko,"foldNewline");const Eo={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
100
- `,r:"\r",t:" ",v:"\v",N:"\x85",_:"\xA0",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function vo(s,e,t,n){const i=s.substr(e,t),o=i.length===t&&/^[0-9a-fA-F]+$/.test(i)?parseInt(i,16):NaN;if(isNaN(o)){const a=s.substr(e-2,t+2);return n(e-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${a}`),a}return String.fromCodePoint(o)}c(vo,"parseCharCode");function ci(s,e,t,n){const{value:i,type:r,comment:o,range:a}=e.type==="block-scalar"?ri(s,e,n):oi(e,s.options.strict,n),l=t?s.directives.tagName(t.source,d=>n(t,"TAG_RESOLVE_FAILED",d)):null;let u;s.options.stringKeys&&s.atKey?u=s.schema[fe]:l?u=Io(s.schema,i,l,t,n):e.type==="scalar"?u=To(s,i,e,n):u=s.schema[fe];let p;try{const d=u.resolve(i,h=>n(t??e,"TAG_RESOLVE_FAILED",h),s.options);p=_(d)?d:new D(d)}catch(d){const h=d instanceof Error?d.message:String(d);n(t??e,"TAG_RESOLVE_FAILED",h),p=new D(i)}return p.range=a,p.source=i,r&&(p.type=r),l&&(p.tag=l),u.format&&(p.format=u.format),o&&(p.comment=o),p}c(ci,"composeScalar");function Io(s,e,t,n,i){if(t==="!")return s[fe];const r=[];for(const a of s.tags)if(!a.collection&&a.tag===t)if(a.default&&a.test)r.push(a);else return a;for(const a of r)if(a.test?.test(e))return a;const o=s.knownTags[t];return o&&!o.collection?(s.tags.push(Object.assign({},o,{default:!1,test:void 0})),o):(i(n,"TAG_RESOLVE_FAILED",`Unresolved tag: ${t}`,t!=="tag:yaml.org,2002:str"),s[fe])}c(Io,"findScalarTagByName");function To({atKey:s,directives:e,schema:t},n,i,r){const o=t.tags.find(a=>(a.default===!0||s&&a.default==="key")&&a.test?.test(n))||t[fe];if(t.compat){const a=t.compat.find(l=>l.default&&l.test?.test(n))??t[fe];if(o.tag!==a.tag){const l=e.tagString(o.tag),u=e.tagString(a.tag),p=`Value may be parsed as either ${l} or ${u}`;r(i,"TAG_RESOLVE_FAILED",p,!0)}}return o}c(To,"findScalarTagByTest");function No(s,e,t){if(e){t??(t=e.length);for(let n=t-1;n>=0;--n){let i=e[n];switch(i.type){case"space":case"comment":case"newline":s-=i.source.length;continue}for(i=e[++n];i?.type==="space";)s+=i.source.length,i=e[++n];break}}return s}c(No,"emptyScalarPosition");const Ao={composeNode:li,composeEmptyNode:Dn};function li(s,e,t,n){const i=s.atKey,{spaceBefore:r,comment:o,anchor:a,tag:l}=t;let u,p=!0;switch(e.type){case"alias":u=Oo(s,e,n),(a||l)&&n(e,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":u=ci(s,e,l,n),a&&(u.anchor=a.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":u=go(Ao,s,e,t,n),a&&(u.anchor=a.source.substring(1));break;default:{const d=e.type==="error"?e.message:`Unsupported token (type: ${e.type})`;n(e,"UNEXPECTED_TOKEN",d),u=Dn(s,e.offset,void 0,null,t,n),p=!1}}return a&&u.anchor===""&&n(a,"BAD_ALIAS","Anchor cannot be an empty string"),i&&s.options.stringKeys&&(!_(u)||typeof u.value!="string"||u.tag&&u.tag!=="tag:yaml.org,2002:str")&&n(l??e,"NON_STRING_KEY","With stringKeys, all keys must be strings"),r&&(u.spaceBefore=!0),o&&(e.type==="scalar"&&e.source===""?u.comment=o:u.commentBefore=o),s.options.keepSourceTokens&&p&&(u.srcToken=e),u}c(li,"composeNode");function Dn(s,e,t,n,{spaceBefore:i,comment:r,anchor:o,tag:a,end:l},u){const p={type:"scalar",offset:No(e,t,n),indent:-1,source:""},d=ci(s,p,a,u);return o&&(d.anchor=o.source.substring(1),d.anchor===""&&u(o,"BAD_ALIAS","Anchor cannot be an empty string")),i&&(d.spaceBefore=!0),r&&(d.comment=r,d.range[2]=l),d}c(Dn,"composeEmptyNode");function Oo({options:s},{offset:e,source:t,end:n},i){const r=new kt(t.substring(1));r.source===""&&i(e,"BAD_ALIAS","Alias cannot be an empty string"),r.source.endsWith(":")&&i(e+t.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);const o=e+t.length,a=at(n,o,s.strict,i);return r.range=[e,o,a.offset],a.comment&&(r.comment=a.comment),r}c(Oo,"composeAlias");function $o(s,e,{offset:t,start:n,value:i,end:r},o){const a=Object.assign({_directives:e},s),l=new Xe(void 0,a),u={atKey:!1,atRoot:!0,directives:l.directives,options:l.options,schema:l.schema},p=Ve(n,{indicator:"doc-start",next:i??r?.[0],offset:t,onError:o,parentIndent:0,startOnNewline:!0});p.found&&(l.directives.docStart=!0,i&&(i.type==="block-map"||i.type==="block-seq")&&!p.hasNewline&&o(p.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),l.contents=i?li(u,i,p,o):Dn(u,p.end,n,null,p,o);const d=l.contents.range[2],h=at(r,d,!1,o);return h.comment&&(l.comment=h.comment),l.range=[t,d,h.offset],l}c($o,"composeDoc");function ct(s){if(typeof s=="number")return[s,s+1];if(Array.isArray(s))return s.length===2?s:[s[0],s[1]];const{offset:e,source:t}=s;return[e,e+(typeof t=="string"?t.length:1)]}c(ct,"getErrorPos");function ui(s){let e="",t=!1,n=!1;for(let i=0;i<s.length;++i){const r=s[i];switch(r[0]){case"#":e+=(e===""?"":n?`
99
+ `),e+=1,n=s[e+1];return t||(t=" "),{fold:t,offset:e}}c(So,"foldNewline");const Co={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
100
+ `,r:"\r",t:" ",v:"\v",N:"\x85",_:"\xA0",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function ko(s,e,t,n){const i=s.substr(e,t),o=i.length===t&&/^[0-9a-fA-F]+$/.test(i)?parseInt(i,16):NaN;if(isNaN(o)){const a=s.substr(e-2,t+2);return n(e-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${a}`),a}return String.fromCodePoint(o)}c(ko,"parseCharCode");function ai(s,e,t,n){const{value:i,type:r,comment:o,range:a}=e.type==="block-scalar"?ii(s,e,n):ri(e,s.options.strict,n),l=t?s.directives.tagName(t.source,d=>n(t,"TAG_RESOLVE_FAILED",d)):null;let u;s.options.stringKeys&&s.atKey?u=s.schema[fe]:l?u=Eo(s.schema,i,l,t,n):e.type==="scalar"?u=vo(s,i,e,n):u=s.schema[fe];let p;try{const d=u.resolve(i,h=>n(t??e,"TAG_RESOLVE_FAILED",h),s.options);p=_(d)?d:new x(d)}catch(d){const h=d instanceof Error?d.message:String(d);n(t??e,"TAG_RESOLVE_FAILED",h),p=new x(i)}return p.range=a,p.source=i,r&&(p.type=r),l&&(p.tag=l),u.format&&(p.format=u.format),o&&(p.comment=o),p}c(ai,"composeScalar");function Eo(s,e,t,n,i){if(t==="!")return s[fe];const r=[];for(const a of s.tags)if(!a.collection&&a.tag===t)if(a.default&&a.test)r.push(a);else return a;for(const a of r)if(a.test?.test(e))return a;const o=s.knownTags[t];return o&&!o.collection?(s.tags.push(Object.assign({},o,{default:!1,test:void 0})),o):(i(n,"TAG_RESOLVE_FAILED",`Unresolved tag: ${t}`,t!=="tag:yaml.org,2002:str"),s[fe])}c(Eo,"findScalarTagByName");function vo({atKey:s,directives:e,schema:t},n,i,r){const o=t.tags.find(a=>(a.default===!0||s&&a.default==="key")&&a.test?.test(n))||t[fe];if(t.compat){const a=t.compat.find(l=>l.default&&l.test?.test(n))??t[fe];if(o.tag!==a.tag){const l=e.tagString(o.tag),u=e.tagString(a.tag),p=`Value may be parsed as either ${l} or ${u}`;r(i,"TAG_RESOLVE_FAILED",p,!0)}}return o}c(vo,"findScalarTagByTest");function Io(s,e,t){if(e){t??(t=e.length);for(let n=t-1;n>=0;--n){let i=e[n];switch(i.type){case"space":case"comment":case"newline":s-=i.source.length;continue}for(i=e[++n];i?.type==="space";)s+=i.source.length,i=e[++n];break}}return s}c(Io,"emptyScalarPosition");const To={composeNode:ci,composeEmptyNode:Ln};function ci(s,e,t,n){const i=s.atKey,{spaceBefore:r,comment:o,anchor:a,tag:l}=t;let u,p=!0;switch(e.type){case"alias":u=No(s,e,n),(a||l)&&n(e,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":u=ai(s,e,l,n),a&&(u.anchor=a.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":u=po(To,s,e,t,n),a&&(u.anchor=a.source.substring(1));break;default:{const d=e.type==="error"?e.message:`Unsupported token (type: ${e.type})`;n(e,"UNEXPECTED_TOKEN",d),u=Ln(s,e.offset,void 0,null,t,n),p=!1}}return a&&u.anchor===""&&n(a,"BAD_ALIAS","Anchor cannot be an empty string"),i&&s.options.stringKeys&&(!_(u)||typeof u.value!="string"||u.tag&&u.tag!=="tag:yaml.org,2002:str")&&n(l??e,"NON_STRING_KEY","With stringKeys, all keys must be strings"),r&&(u.spaceBefore=!0),o&&(e.type==="scalar"&&e.source===""?u.comment=o:u.commentBefore=o),s.options.keepSourceTokens&&p&&(u.srcToken=e),u}c(ci,"composeNode");function Ln(s,e,t,n,{spaceBefore:i,comment:r,anchor:o,tag:a,end:l},u){const p={type:"scalar",offset:Io(e,t,n),indent:-1,source:""},d=ai(s,p,a,u);return o&&(d.anchor=o.source.substring(1),d.anchor===""&&u(o,"BAD_ALIAS","Anchor cannot be an empty string")),i&&(d.spaceBefore=!0),r&&(d.comment=r,d.range[2]=l),d}c(Ln,"composeEmptyNode");function No({options:s},{offset:e,source:t,end:n},i){const r=new Ct(t.substring(1));r.source===""&&i(e,"BAD_ALIAS","Alias cannot be an empty string"),r.source.endsWith(":")&&i(e+t.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);const o=e+t.length,a=ot(n,o,s.strict,i);return r.range=[e,o,a.offset],a.comment&&(r.comment=a.comment),r}c(No,"composeAlias");function Ao(s,e,{offset:t,start:n,value:i,end:r},o){const a=Object.assign({_directives:e},s),l=new Qe(void 0,a),u={atKey:!1,atRoot:!0,directives:l.directives,options:l.options,schema:l.schema},p=Ge(n,{indicator:"doc-start",next:i??r?.[0],offset:t,onError:o,parentIndent:0,startOnNewline:!0});p.found&&(l.directives.docStart=!0,i&&(i.type==="block-map"||i.type==="block-seq")&&!p.hasNewline&&o(p.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),l.contents=i?ci(u,i,p,o):Ln(u,p.end,n,null,p,o);const d=l.contents.range[2],h=ot(r,d,!1,o);return h.comment&&(l.comment=h.comment),l.range=[t,d,h.offset],l}c(Ao,"composeDoc");function at(s){if(typeof s=="number")return[s,s+1];if(Array.isArray(s))return s.length===2?s:[s[0],s[1]];const{offset:e,source:t}=s;return[e,e+(typeof t=="string"?t.length:1)]}c(at,"getErrorPos");function li(s){let e="",t=!1,n=!1;for(let i=0;i<s.length;++i){const r=s[i];switch(r[0]){case"#":e+=(e===""?"":n?`
101
101
 
102
102
  `:`
103
- `)+(r.substring(1)||" "),t=!0,n=!1;break;case"%":s[i+1]?.[0]!=="#"&&(i+=1),t=!1;break;default:t||(n=!0),t=!1}}return{comment:e,afterEmptyLine:n}}c(ui,"parsePrelude");class xn{static{c(this,"Composer")}constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(t,n,i,r)=>{const o=ct(t);r?this.warnings.push(new ni(o,n,i)):this.errors.push(new Le(o,n,i))},this.directives=new Z({version:e.version||"1.2"}),this.options=e}decorate(e,t){const{comment:n,afterEmptyLine:i}=ui(this.prelude);if(n){const r=e.contents;if(t)e.comment=e.comment?`${e.comment}
104
- ${n}`:n;else if(i||e.directives.docStart||!r)e.commentBefore=n;else if(q(r)&&!r.flow&&r.items.length>0){let o=r.items[0];F(o)&&(o=o.key);const a=o.commentBefore;o.commentBefore=a?`${n}
103
+ `)+(r.substring(1)||" "),t=!0,n=!1;break;case"%":s[i+1]?.[0]!=="#"&&(i+=1),t=!1;break;default:t||(n=!0),t=!1}}return{comment:e,afterEmptyLine:n}}c(li,"parsePrelude");class xn{static{c(this,"Composer")}constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(t,n,i,r)=>{const o=at(t);r?this.warnings.push(new ti(o,n,i)):this.errors.push(new $e(o,n,i))},this.directives=new ee({version:e.version||"1.2"}),this.options=e}decorate(e,t){const{comment:n,afterEmptyLine:i}=li(this.prelude);if(n){const r=e.contents;if(t)e.comment=e.comment?`${e.comment}
104
+ ${n}`:n;else if(i||e.directives.docStart||!r)e.commentBefore=n;else if(U(r)&&!r.flow&&r.items.length>0){let o=r.items[0];B(o)&&(o=o.key);const a=o.commentBefore;o.commentBefore=a?`${n}
105
105
  ${a}`:n}else{const o=r.commentBefore;r.commentBefore=o?`${n}
106
- ${o}`:n}}t?(Array.prototype.push.apply(e.errors,this.errors),Array.prototype.push.apply(e.warnings,this.warnings)):(e.errors=this.errors,e.warnings=this.warnings),this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:ui(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(e,t=!1,n=-1){for(const i of e)yield*this.next(i);yield*this.end(t,n)}*next(e){switch(e.type){case"directive":this.directives.add(e.source,(t,n,i)=>{const r=ct(e);r[0]+=t,this.onError(r,"BAD_DIRECTIVE",n,i)}),this.prelude.push(e.source),this.atDirectives=!0;break;case"document":{const t=$o(this.options,this.directives,e,this.onError);this.atDirectives&&!t.directives.docStart&&this.onError(e,"MISSING_CHAR","Missing directives-end/doc-start indicator line"),this.decorate(t,!1),this.doc&&(yield this.doc),this.doc=t,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(e.source);break;case"error":{const t=e.source?`${e.message}: ${JSON.stringify(e.source)}`:e.message,n=new Le(ct(e),"UNEXPECTED_TOKEN",t);this.atDirectives||!this.doc?this.errors.push(n):this.doc.errors.push(n);break}case"doc-end":{if(!this.doc){const n="Unexpected doc-end without preceding document";this.errors.push(new Le(ct(e),"UNEXPECTED_TOKEN",n));break}this.doc.directives.docEnd=!0;const t=at(e.end,e.offset+e.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),t.comment){const n=this.doc.comment;this.doc.comment=n?`${n}
107
- ${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.push(new Le(ct(e),"UNEXPECTED_TOKEN",`Unsupported token ${e.type}`))}}*end(e=!1,t=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(e){const n=Object.assign({_directives:this.directives},this.options),i=new Xe(void 0,n);this.atDirectives&&this.onError(t,"MISSING_CHAR","Missing directives-end indicator line"),i.range=[0,t,t],this.decorate(i,!1),yield i}}}function Lo(s,e=!0,t){if(s){const n=c((i,r,o)=>{const a=typeof i=="number"?i:Array.isArray(i)?i[0]:i.offset;if(t)t(a,r,o);else throw new Le([a,a+1],r,o)},"_onError");switch(s.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return oi(s,e,n);case"block-scalar":return ri({options:{strict:e}},s,n)}}return null}c(Lo,"resolveAsScalar");function Do(s,e){const{implicitKey:t=!1,indent:n,inFlow:i=!1,offset:r=-1,type:o="PLAIN"}=e,a=it({type:o,value:s},{implicitKey:t,indent:n>0?" ".repeat(n):"",inFlow:i,options:{blockQuote:!0,lineWidth:-1}}),l=e.end??[{type:"newline",offset:-1,indent:n,source:`
106
+ ${o}`:n}}t?(Array.prototype.push.apply(e.errors,this.errors),Array.prototype.push.apply(e.warnings,this.warnings)):(e.errors=this.errors,e.warnings=this.warnings),this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:li(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(e,t=!1,n=-1){for(const i of e)yield*this.next(i);yield*this.end(t,n)}*next(e){switch(e.type){case"directive":this.directives.add(e.source,(t,n,i)=>{const r=at(e);r[0]+=t,this.onError(r,"BAD_DIRECTIVE",n,i)}),this.prelude.push(e.source),this.atDirectives=!0;break;case"document":{const t=Ao(this.options,this.directives,e,this.onError);this.atDirectives&&!t.directives.docStart&&this.onError(e,"MISSING_CHAR","Missing directives-end/doc-start indicator line"),this.decorate(t,!1),this.doc&&(yield this.doc),this.doc=t,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(e.source);break;case"error":{const t=e.source?`${e.message}: ${JSON.stringify(e.source)}`:e.message,n=new $e(at(e),"UNEXPECTED_TOKEN",t);this.atDirectives||!this.doc?this.errors.push(n):this.doc.errors.push(n);break}case"doc-end":{if(!this.doc){const n="Unexpected doc-end without preceding document";this.errors.push(new $e(at(e),"UNEXPECTED_TOKEN",n));break}this.doc.directives.docEnd=!0;const t=ot(e.end,e.offset+e.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),t.comment){const n=this.doc.comment;this.doc.comment=n?`${n}
107
+ ${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.push(new $e(at(e),"UNEXPECTED_TOKEN",`Unsupported token ${e.type}`))}}*end(e=!1,t=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(e){const n=Object.assign({_directives:this.directives},this.options),i=new Qe(void 0,n);this.atDirectives&&this.onError(t,"MISSING_CHAR","Missing directives-end indicator line"),i.range=[0,t,t],this.decorate(i,!1),yield i}}}function Oo(s,e=!0,t){if(s){const n=c((i,r,o)=>{const a=typeof i=="number"?i:Array.isArray(i)?i[0]:i.offset;if(t)t(a,r,o);else throw new $e([a,a+1],r,o)},"_onError");switch(s.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return ri(s,e,n);case"block-scalar":return ii({options:{strict:e}},s,n)}}return null}c(Oo,"resolveAsScalar");function $o(s,e){const{implicitKey:t=!1,indent:n,inFlow:i=!1,offset:r=-1,type:o="PLAIN"}=e,a=st({type:o,value:s},{implicitKey:t,indent:n>0?" ".repeat(n):"",inFlow:i,options:{blockQuote:!0,lineWidth:-1}}),l=e.end??[{type:"newline",offset:-1,indent:n,source:`
108
108
  `}];switch(a[0]){case"|":case">":{const u=a.indexOf(`
109
109
  `),p=a.substring(0,u),d=a.substring(u+1)+`
110
- `,h=[{type:"block-scalar-header",offset:r,indent:n,source:p}];return fi(h,l)||h.push({type:"newline",offset:-1,indent:n,source:`
111
- `}),{type:"block-scalar",offset:r,indent:n,props:h,source:d}}case'"':return{type:"double-quoted-scalar",offset:r,indent:n,source:a,end:l};case"'":return{type:"single-quoted-scalar",offset:r,indent:n,source:a,end:l};default:return{type:"scalar",offset:r,indent:n,source:a,end:l}}}c(Do,"createScalarToken");function xo(s,e,t={}){let{afterKey:n=!1,implicitKey:i=!1,inFlow:r=!1,type:o}=t,a="indent"in s?s.indent:null;if(n&&typeof a=="number"&&(a+=2),!o)switch(s.type){case"single-quoted-scalar":o="QUOTE_SINGLE";break;case"double-quoted-scalar":o="QUOTE_DOUBLE";break;case"block-scalar":{const u=s.props[0];if(u.type!=="block-scalar-header")throw new Error("Invalid block scalar header");o=u.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:o="PLAIN"}const l=it({type:o,value:e},{implicitKey:i||a===null,indent:a!==null&&a>0?" ".repeat(a):"",inFlow:r,options:{blockQuote:!0,lineWidth:-1}});switch(l[0]){case"|":case">":Po(s,l);break;case'"':Pn(s,l,"double-quoted-scalar");break;case"'":Pn(s,l,"single-quoted-scalar");break;default:Pn(s,l,"scalar")}}c(xo,"setScalarValue");function Po(s,e){const t=e.indexOf(`
110
+ `,h=[{type:"block-scalar-header",offset:r,indent:n,source:p}];return ui(h,l)||h.push({type:"newline",offset:-1,indent:n,source:`
111
+ `}),{type:"block-scalar",offset:r,indent:n,props:h,source:d}}case'"':return{type:"double-quoted-scalar",offset:r,indent:n,source:a,end:l};case"'":return{type:"single-quoted-scalar",offset:r,indent:n,source:a,end:l};default:return{type:"scalar",offset:r,indent:n,source:a,end:l}}}c($o,"createScalarToken");function Lo(s,e,t={}){let{afterKey:n=!1,implicitKey:i=!1,inFlow:r=!1,type:o}=t,a="indent"in s?s.indent:null;if(n&&typeof a=="number"&&(a+=2),!o)switch(s.type){case"single-quoted-scalar":o="QUOTE_SINGLE";break;case"double-quoted-scalar":o="QUOTE_DOUBLE";break;case"block-scalar":{const u=s.props[0];if(u.type!=="block-scalar-header")throw new Error("Invalid block scalar header");o=u.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:o="PLAIN"}const l=st({type:o,value:e},{implicitKey:i||a===null,indent:a!==null&&a>0?" ".repeat(a):"",inFlow:r,options:{blockQuote:!0,lineWidth:-1}});switch(l[0]){case"|":case">":xo(s,l);break;case'"':Pn(s,l,"double-quoted-scalar");break;case"'":Pn(s,l,"single-quoted-scalar");break;default:Pn(s,l,"scalar")}}c(Lo,"setScalarValue");function xo(s,e){const t=e.indexOf(`
112
112
  `),n=e.substring(0,t),i=e.substring(t+1)+`
113
- `;if(s.type==="block-scalar"){const r=s.props[0];if(r.type!=="block-scalar-header")throw new Error("Invalid block scalar header");r.source=n,s.source=i}else{const{offset:r}=s,o="indent"in s?s.indent:-1,a=[{type:"block-scalar-header",offset:r,indent:o,source:n}];fi(a,"end"in s?s.end:void 0)||a.push({type:"newline",offset:-1,indent:o,source:`
114
- `});for(const l of Object.keys(s))l!=="type"&&l!=="offset"&&delete s[l];Object.assign(s,{type:"block-scalar",indent:o,props:a,source:i})}}c(Po,"setBlockScalarValue");function fi(s,e){if(e)for(const t of e)switch(t.type){case"space":case"comment":s.push(t);break;case"newline":return s.push(t),!0}return!1}c(fi,"addEndtoBlockProps");function Pn(s,e,t){switch(s.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":s.type=t,s.source=e;break;case"block-scalar":{const n=s.props.slice(1);let i=e.length;s.props[0].type==="block-scalar-header"&&(i-=s.props[0].source.length);for(const r of n)r.offset+=i;delete s.props,Object.assign(s,{type:t,source:e,end:n});break}case"block-map":case"block-seq":{const i={type:"newline",offset:s.offset+e.length,indent:s.indent,source:`
115
- `};delete s.items,Object.assign(s,{type:t,source:e,end:[i]});break}default:{const n="indent"in s?s.indent:-1,i="end"in s&&Array.isArray(s.end)?s.end.filter(r=>r.type==="space"||r.type==="comment"||r.type==="newline"):[];for(const r of Object.keys(s))r!=="type"&&r!=="offset"&&delete s[r];Object.assign(s,{type:t,indent:n,source:e,end:i})}}}c(Pn,"setFlowScalarValue");const Ro=c(s=>"type"in s?Ft(s):Bt(s),"stringify$1");function Ft(s){switch(s.type){case"block-scalar":{let e="";for(const t of s.props)e+=Ft(t);return e+s.source}case"block-map":case"block-seq":{let e="";for(const t of s.items)e+=Bt(t);return e}case"flow-collection":{let e=s.start.source;for(const t of s.items)e+=Bt(t);for(const t of s.end)e+=t.source;return e}case"document":{let e=Bt(s);if(s.end)for(const t of s.end)e+=t.source;return e}default:{let e=s.source;if("end"in s&&s.end)for(const t of s.end)e+=t.source;return e}}}c(Ft,"stringifyToken");function Bt({start:s,key:e,sep:t,value:n}){let i="";for(const r of s)i+=r.source;if(e&&(i+=Ft(e)),t)for(const r of t)i+=r.source;return n&&(i+=Ft(n)),i}c(Bt,"stringifyItem");const Rn=Symbol("break visit"),Mo=Symbol("skip children"),hi=Symbol("remove item");function De(s,e){"type"in s&&s.type==="document"&&(s={start:s.start,value:s.value}),di(Object.freeze([]),s,e)}c(De,"visit"),De.BREAK=Rn,De.SKIP=Mo,De.REMOVE=hi,De.itemAtPath=(s,e)=>{let t=s;for(const[n,i]of e){const r=t?.[n];if(r&&"items"in r)t=r.items[i];else return}return t},De.parentCollection=(s,e)=>{const t=De.itemAtPath(s,e.slice(0,-1)),n=e[e.length-1][0],i=t?.[n];if(i&&"items"in i)return i;throw new Error("Parent collection not found")};function di(s,e,t){let n=t(e,s);if(typeof n=="symbol")return n;for(const i of["key","value"]){const r=e[i];if(r&&"items"in r){for(let o=0;o<r.items.length;++o){const a=di(Object.freeze(s.concat([[i,o]])),r.items[o],t);if(typeof a=="number")o=a-1;else{if(a===Rn)return Rn;a===hi&&(r.items.splice(o,1),o-=1)}}typeof n=="function"&&i==="key"&&(n=n(e,s))}}return typeof n=="function"?n(e,s):n}c(di,"_visit");const qt="\uFEFF",Ut="",Jt="",lt="",_o=c(s=>!!s&&"items"in s,"isCollection"),Ko=c(s=>!!s&&(s.type==="scalar"||s.type==="single-quoted-scalar"||s.type==="double-quoted-scalar"||s.type==="block-scalar"),"isScalar");function jo(s){switch(s){case qt:return"<BOM>";case Ut:return"<DOC>";case Jt:return"<FLOW_END>";case lt:return"<SCALAR>";default:return JSON.stringify(s)}}c(jo,"prettyToken");function pi(s){switch(s){case qt:return"byte-order-mark";case Ut:return"doc-mode";case Jt:return"flow-error-end";case lt:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case`
113
+ `;if(s.type==="block-scalar"){const r=s.props[0];if(r.type!=="block-scalar-header")throw new Error("Invalid block scalar header");r.source=n,s.source=i}else{const{offset:r}=s,o="indent"in s?s.indent:-1,a=[{type:"block-scalar-header",offset:r,indent:o,source:n}];ui(a,"end"in s?s.end:void 0)||a.push({type:"newline",offset:-1,indent:o,source:`
114
+ `});for(const l of Object.keys(s))l!=="type"&&l!=="offset"&&delete s[l];Object.assign(s,{type:"block-scalar",indent:o,props:a,source:i})}}c(xo,"setBlockScalarValue");function ui(s,e){if(e)for(const t of e)switch(t.type){case"space":case"comment":s.push(t);break;case"newline":return s.push(t),!0}return!1}c(ui,"addEndtoBlockProps");function Pn(s,e,t){switch(s.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":s.type=t,s.source=e;break;case"block-scalar":{const n=s.props.slice(1);let i=e.length;s.props[0].type==="block-scalar-header"&&(i-=s.props[0].source.length);for(const r of n)r.offset+=i;delete s.props,Object.assign(s,{type:t,source:e,end:n});break}case"block-map":case"block-seq":{const i={type:"newline",offset:s.offset+e.length,indent:s.indent,source:`
115
+ `};delete s.items,Object.assign(s,{type:t,source:e,end:[i]});break}default:{const n="indent"in s?s.indent:-1,i="end"in s&&Array.isArray(s.end)?s.end.filter(r=>r.type==="space"||r.type==="comment"||r.type==="newline"):[];for(const r of Object.keys(s))r!=="type"&&r!=="offset"&&delete s[r];Object.assign(s,{type:t,indent:n,source:e,end:i})}}}c(Pn,"setFlowScalarValue");const Po=c(s=>"type"in s?jt(s):Ft(s),"stringify$1");function jt(s){switch(s.type){case"block-scalar":{let e="";for(const t of s.props)e+=jt(t);return e+s.source}case"block-map":case"block-seq":{let e="";for(const t of s.items)e+=Ft(t);return e}case"flow-collection":{let e=s.start.source;for(const t of s.items)e+=Ft(t);for(const t of s.end)e+=t.source;return e}case"document":{let e=Ft(s);if(s.end)for(const t of s.end)e+=t.source;return e}default:{let e=s.source;if("end"in s&&s.end)for(const t of s.end)e+=t.source;return e}}}c(jt,"stringifyToken");function Ft({start:s,key:e,sep:t,value:n}){let i="";for(const r of s)i+=r.source;if(e&&(i+=jt(e)),t)for(const r of t)i+=r.source;return n&&(i+=jt(n)),i}c(Ft,"stringifyItem");const Dn=Symbol("break visit"),Do=Symbol("skip children"),fi=Symbol("remove item");function Le(s,e){"type"in s&&s.type==="document"&&(s={start:s.start,value:s.value}),hi(Object.freeze([]),s,e)}c(Le,"visit"),Le.BREAK=Dn,Le.SKIP=Do,Le.REMOVE=fi,Le.itemAtPath=(s,e)=>{let t=s;for(const[n,i]of e){const r=t?.[n];if(r&&"items"in r)t=r.items[i];else return}return t},Le.parentCollection=(s,e)=>{const t=Le.itemAtPath(s,e.slice(0,-1)),n=e[e.length-1][0],i=t?.[n];if(i&&"items"in i)return i;throw new Error("Parent collection not found")};function hi(s,e,t){let n=t(e,s);if(typeof n=="symbol")return n;for(const i of["key","value"]){const r=e[i];if(r&&"items"in r){for(let o=0;o<r.items.length;++o){const a=hi(Object.freeze(s.concat([[i,o]])),r.items[o],t);if(typeof a=="number")o=a-1;else{if(a===Dn)return Dn;a===fi&&(r.items.splice(o,1),o-=1)}}typeof n=="function"&&i==="key"&&(n=n(e,s))}}return typeof n=="function"?n(e,s):n}c(hi,"_visit");const Bt="\uFEFF",qt="",Ut="",ct="",Ro=c(s=>!!s&&"items"in s,"isCollection"),Mo=c(s=>!!s&&(s.type==="scalar"||s.type==="single-quoted-scalar"||s.type==="double-quoted-scalar"||s.type==="block-scalar"),"isScalar");function _o(s){switch(s){case Bt:return"<BOM>";case qt:return"<DOC>";case Ut:return"<FLOW_END>";case ct:return"<SCALAR>";default:return JSON.stringify(s)}}c(_o,"prettyToken");function di(s){switch(s){case Bt:return"byte-order-mark";case qt:return"doc-mode";case Ut:return"flow-error-end";case ct:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case`
116
116
  `:case`\r
117
- `:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(s[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}c(pi,"tokenType");var Fo=Object.freeze({__proto__:null,BOM:qt,DOCUMENT:Ut,FLOW_END:Jt,SCALAR:lt,createScalarToken:Do,isCollection:_o,isScalar:Ko,prettyToken:jo,resolveAsScalar:Lo,setScalarValue:xo,stringify:Ro,tokenType:pi,visit:De});function ae(s){switch(s){case void 0:case" ":case`
118
- `:case"\r":case" ":return!0;default:return!1}}c(ae,"isEmpty");const mi=new Set("0123456789ABCDEFabcdef"),Bo=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),Wt=new Set(",[]{}"),qo=new Set(` ,[]{}
119
- \r `),Mn=c(s=>!s||qo.has(s),"isNotAnchorChar");class gi{static{c(this,"Lexer")}constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(e,t=!1){if(e){if(typeof e!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+e:e,this.lineEndPos=null}this.atEnd=!t;let n=this.next??"stream";for(;n&&(t||this.hasChars(1));)n=yield*this.parseNext(n)}atLineEnd(){let e=this.pos,t=this.buffer[e];for(;t===" "||t===" ";)t=this.buffer[++e];return!t||t==="#"||t===`
117
+ `:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(s[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}c(di,"tokenType");var Ko=Object.freeze({__proto__:null,BOM:Bt,DOCUMENT:qt,FLOW_END:Ut,SCALAR:ct,createScalarToken:$o,isCollection:Ro,isScalar:Mo,prettyToken:_o,resolveAsScalar:Oo,setScalarValue:Lo,stringify:Po,tokenType:di,visit:Le});function ce(s){switch(s){case void 0:case" ":case`
118
+ `:case"\r":case" ":return!0;default:return!1}}c(ce,"isEmpty");const pi=new Set("0123456789ABCDEFabcdef"),jo=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),Jt=new Set(",[]{}"),Fo=new Set(` ,[]{}
119
+ \r `),Rn=c(s=>!s||Fo.has(s),"isNotAnchorChar");class mi{static{c(this,"Lexer")}constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(e,t=!1){if(e){if(typeof e!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+e:e,this.lineEndPos=null}this.atEnd=!t;let n=this.next??"stream";for(;n&&(t||this.hasChars(1));)n=yield*this.parseNext(n)}atLineEnd(){let e=this.pos,t=this.buffer[e];for(;t===" "||t===" ";)t=this.buffer[++e];return!t||t==="#"||t===`
120
120
  `?!0:t==="\r"?this.buffer[e+1]===`
121
121
  `:!1}charAt(e){return this.buffer[this.pos+e]}continueScalar(e){let t=this.buffer[e];if(this.indentNext>0){let n=0;for(;t===" ";)t=this.buffer[++n+e];if(t==="\r"){const i=this.buffer[n+e+1];if(i===`
122
122
  `||!i&&!this.atEnd)return e+n+1}return t===`
123
- `||n>=this.indentNext||!t&&!this.atEnd?e+n:-1}if(t==="-"||t==="."){const n=this.buffer.substr(e,3);if((n==="---"||n==="...")&&ae(this.buffer[e+3]))return-1}return e}getLine(){let e=this.lineEndPos;return(typeof e!="number"||e!==-1&&e<this.pos)&&(e=this.buffer.indexOf(`
124
- `,this.pos),this.lineEndPos=e),e===-1?this.atEnd?this.buffer.substring(this.pos):null:(this.buffer[e-1]==="\r"&&(e-=1),this.buffer.substring(this.pos,e))}hasChars(e){return this.pos+e<=this.buffer.length}setNext(e){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=e,null}peek(e){return this.buffer.substr(this.pos,e)}*parseNext(e){switch(e){case"stream":return yield*this.parseStream();case"line-start":return yield*this.parseLineStart();case"block-start":return yield*this.parseBlockStart();case"doc":return yield*this.parseDocument();case"flow":return yield*this.parseFlowCollection();case"quoted-scalar":return yield*this.parseQuotedScalar();case"block-scalar":return yield*this.parseBlockScalar();case"plain-scalar":return yield*this.parsePlainScalar()}}*parseStream(){let e=this.getLine();if(e===null)return this.setNext("stream");if(e[0]===qt&&(yield*this.pushCount(1),e=e.substring(1)),e[0]==="%"){let t=e.length,n=e.indexOf("#");for(;n!==-1;){const r=e[n-1];if(r===" "||r===" "){t=n-1;break}else n=e.indexOf("#",n+1)}for(;;){const r=e[t-1];if(r===" "||r===" ")t-=1;else break}const i=(yield*this.pushCount(t))+(yield*this.pushSpaces(!0));return yield*this.pushCount(e.length-i),this.pushNewline(),"stream"}if(this.atLineEnd()){const t=yield*this.pushSpaces(!0);return yield*this.pushCount(e.length-t),yield*this.pushNewline(),"stream"}return yield Ut,yield*this.parseLineStart()}*parseLineStart(){const e=this.charAt(0);if(!e&&!this.atEnd)return this.setNext("line-start");if(e==="-"||e==="."){if(!this.atEnd&&!this.hasChars(4))return this.setNext("line-start");const t=this.peek(3);if((t==="---"||t==="...")&&ae(this.charAt(3)))return yield*this.pushCount(3),this.indentValue=0,this.indentNext=0,t==="---"?"doc":"stream"}return this.indentValue=yield*this.pushSpaces(!1),this.indentNext>this.indentValue&&!ae(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){const[e,t]=this.peek(2);if(!t&&!this.atEnd)return this.setNext("block-start");if((e==="-"||e==="?"||e===":")&&ae(t)){const n=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=n,yield*this.parseBlockStart()}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);const e=this.getLine();if(e===null)return this.setNext("doc");let t=yield*this.pushIndicators();switch(e[t]){case"#":yield*this.pushCount(e.length-t);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,"flow";case"}":case"]":return yield*this.pushCount(1),"doc";case"*":return yield*this.pushUntil(Mn),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return t+=yield*this.parseBlockScalarHeader(),t+=yield*this.pushSpaces(!0),yield*this.pushCount(e.length-t),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let e,t,n=-1;do e=yield*this.pushNewline(),e>0?(t=yield*this.pushSpaces(!1),this.indentValue=n=t):t=0,t+=yield*this.pushSpaces(!0);while(e+t>0);const i=this.getLine();if(i===null)return this.setNext("flow");if((n!==-1&&n<this.indentNext&&i[0]!=="#"||n===0&&(i.startsWith("---")||i.startsWith("..."))&&ae(i[3]))&&!(n===this.indentNext-1&&this.flowLevel===1&&(i[0]==="]"||i[0]==="}")))return this.flowLevel=0,yield Jt,yield*this.parseLineStart();let r=0;for(;i[r]===",";)r+=yield*this.pushCount(1),r+=yield*this.pushSpaces(!0),this.flowKey=!1;switch(r+=yield*this.pushIndicators(),i[r]){case void 0:return"flow";case"#":return yield*this.pushCount(i.length-r),"flow";case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel+=1,"flow";case"}":case"]":return yield*this.pushCount(1),this.flowKey=!0,this.flowLevel-=1,this.flowLevel?"flow":"doc";case"*":return yield*this.pushUntil(Mn),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{const o=this.charAt(1);if(this.flowKey||ae(o)||o===",")return this.flowKey=!1,yield*this.pushCount(1),yield*this.pushSpaces(!0),"flow"}default:return this.flowKey=!1,yield*this.parsePlainScalar()}}*parseQuotedScalar(){const e=this.charAt(0);let t=this.buffer.indexOf(e,this.pos+1);if(e==="'")for(;t!==-1&&this.buffer[t+1]==="'";)t=this.buffer.indexOf("'",t+2);else for(;t!==-1;){let r=0;for(;this.buffer[t-1-r]==="\\";)r+=1;if(r%2===0)break;t=this.buffer.indexOf('"',t+1)}const n=this.buffer.substring(0,t);let i=n.indexOf(`
123
+ `||n>=this.indentNext||!t&&!this.atEnd?e+n:-1}if(t==="-"||t==="."){const n=this.buffer.substr(e,3);if((n==="---"||n==="...")&&ce(this.buffer[e+3]))return-1}return e}getLine(){let e=this.lineEndPos;return(typeof e!="number"||e!==-1&&e<this.pos)&&(e=this.buffer.indexOf(`
124
+ `,this.pos),this.lineEndPos=e),e===-1?this.atEnd?this.buffer.substring(this.pos):null:(this.buffer[e-1]==="\r"&&(e-=1),this.buffer.substring(this.pos,e))}hasChars(e){return this.pos+e<=this.buffer.length}setNext(e){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=e,null}peek(e){return this.buffer.substr(this.pos,e)}*parseNext(e){switch(e){case"stream":return yield*this.parseStream();case"line-start":return yield*this.parseLineStart();case"block-start":return yield*this.parseBlockStart();case"doc":return yield*this.parseDocument();case"flow":return yield*this.parseFlowCollection();case"quoted-scalar":return yield*this.parseQuotedScalar();case"block-scalar":return yield*this.parseBlockScalar();case"plain-scalar":return yield*this.parsePlainScalar()}}*parseStream(){let e=this.getLine();if(e===null)return this.setNext("stream");if(e[0]===Bt&&(yield*this.pushCount(1),e=e.substring(1)),e[0]==="%"){let t=e.length,n=e.indexOf("#");for(;n!==-1;){const r=e[n-1];if(r===" "||r===" "){t=n-1;break}else n=e.indexOf("#",n+1)}for(;;){const r=e[t-1];if(r===" "||r===" ")t-=1;else break}const i=(yield*this.pushCount(t))+(yield*this.pushSpaces(!0));return yield*this.pushCount(e.length-i),this.pushNewline(),"stream"}if(this.atLineEnd()){const t=yield*this.pushSpaces(!0);return yield*this.pushCount(e.length-t),yield*this.pushNewline(),"stream"}return yield qt,yield*this.parseLineStart()}*parseLineStart(){const e=this.charAt(0);if(!e&&!this.atEnd)return this.setNext("line-start");if(e==="-"||e==="."){if(!this.atEnd&&!this.hasChars(4))return this.setNext("line-start");const t=this.peek(3);if((t==="---"||t==="...")&&ce(this.charAt(3)))return yield*this.pushCount(3),this.indentValue=0,this.indentNext=0,t==="---"?"doc":"stream"}return this.indentValue=yield*this.pushSpaces(!1),this.indentNext>this.indentValue&&!ce(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){const[e,t]=this.peek(2);if(!t&&!this.atEnd)return this.setNext("block-start");if((e==="-"||e==="?"||e===":")&&ce(t)){const n=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=n,yield*this.parseBlockStart()}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);const e=this.getLine();if(e===null)return this.setNext("doc");let t=yield*this.pushIndicators();switch(e[t]){case"#":yield*this.pushCount(e.length-t);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,"flow";case"}":case"]":return yield*this.pushCount(1),"doc";case"*":return yield*this.pushUntil(Rn),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return t+=yield*this.parseBlockScalarHeader(),t+=yield*this.pushSpaces(!0),yield*this.pushCount(e.length-t),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let e,t,n=-1;do e=yield*this.pushNewline(),e>0?(t=yield*this.pushSpaces(!1),this.indentValue=n=t):t=0,t+=yield*this.pushSpaces(!0);while(e+t>0);const i=this.getLine();if(i===null)return this.setNext("flow");if((n!==-1&&n<this.indentNext&&i[0]!=="#"||n===0&&(i.startsWith("---")||i.startsWith("..."))&&ce(i[3]))&&!(n===this.indentNext-1&&this.flowLevel===1&&(i[0]==="]"||i[0]==="}")))return this.flowLevel=0,yield Ut,yield*this.parseLineStart();let r=0;for(;i[r]===",";)r+=yield*this.pushCount(1),r+=yield*this.pushSpaces(!0),this.flowKey=!1;switch(r+=yield*this.pushIndicators(),i[r]){case void 0:return"flow";case"#":return yield*this.pushCount(i.length-r),"flow";case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel+=1,"flow";case"}":case"]":return yield*this.pushCount(1),this.flowKey=!0,this.flowLevel-=1,this.flowLevel?"flow":"doc";case"*":return yield*this.pushUntil(Rn),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{const o=this.charAt(1);if(this.flowKey||ce(o)||o===",")return this.flowKey=!1,yield*this.pushCount(1),yield*this.pushSpaces(!0),"flow"}default:return this.flowKey=!1,yield*this.parsePlainScalar()}}*parseQuotedScalar(){const e=this.charAt(0);let t=this.buffer.indexOf(e,this.pos+1);if(e==="'")for(;t!==-1&&this.buffer[t+1]==="'";)t=this.buffer.indexOf("'",t+2);else for(;t!==-1;){let r=0;for(;this.buffer[t-1-r]==="\\";)r+=1;if(r%2===0)break;t=this.buffer.indexOf('"',t+1)}const n=this.buffer.substring(0,t);let i=n.indexOf(`
125
125
  `,this.pos);if(i!==-1){for(;i!==-1;){const r=this.continueScalar(i+1);if(r===-1)break;i=n.indexOf(`
126
- `,r)}i!==-1&&(t=i-(n[i-1]==="\r"?2:1))}if(t===-1){if(!this.atEnd)return this.setNext("quoted-scalar");t=this.buffer.length}return yield*this.pushToIndex(t+1,!1),this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let e=this.pos;for(;;){const t=this.buffer[++e];if(t==="+")this.blockScalarKeep=!0;else if(t>"0"&&t<="9")this.blockScalarIndent=Number(t)-1;else if(t!=="-")break}return yield*this.pushUntil(t=>ae(t)||t==="#")}*parseBlockScalar(){let e=this.pos-1,t=0,n;e:for(let r=this.pos;n=this.buffer[r];++r)switch(n){case" ":t+=1;break;case`
126
+ `,r)}i!==-1&&(t=i-(n[i-1]==="\r"?2:1))}if(t===-1){if(!this.atEnd)return this.setNext("quoted-scalar");t=this.buffer.length}return yield*this.pushToIndex(t+1,!1),this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let e=this.pos;for(;;){const t=this.buffer[++e];if(t==="+")this.blockScalarKeep=!0;else if(t>"0"&&t<="9")this.blockScalarIndent=Number(t)-1;else if(t!=="-")break}return yield*this.pushUntil(t=>ce(t)||t==="#")}*parseBlockScalar(){let e=this.pos-1,t=0,n;e:for(let r=this.pos;n=this.buffer[r];++r)switch(n){case" ":t+=1;break;case`
127
127
  `:e=r,t=0;break;case"\r":{const o=this.buffer[r+1];if(!o&&!this.atEnd)return this.setNext("block-scalar");if(o===`
128
128
  `)break}default:break e}if(!n&&!this.atEnd)return this.setNext("block-scalar");if(t>=this.indentNext){this.blockScalarIndent===-1?this.indentNext=t:this.indentNext=this.blockScalarIndent+(this.indentNext===0?1:this.indentNext);do{const r=this.continueScalar(e+1);if(r===-1)break;e=this.buffer.indexOf(`
129
129
  `,r)}while(e!==-1);if(e===-1){if(!this.atEnd)return this.setNext("block-scalar");e=this.buffer.length}}let i=e+1;for(n=this.buffer[i];n===" ";)n=this.buffer[++i];if(n===" "){for(;n===" "||n===" "||n==="\r"||n===`
130
130
  `;)n=this.buffer[++i];e=i-1}else if(!this.blockScalarKeep)do{let r=e-1,o=this.buffer[r];o==="\r"&&(o=this.buffer[--r]);const a=r;for(;o===" ";)o=this.buffer[--r];if(o===`
131
- `&&r>=this.pos&&r+1+t>a)e=r;else break}while(!0);return yield lt,yield*this.pushToIndex(e+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){const e=this.flowLevel>0;let t=this.pos-1,n=this.pos-1,i;for(;i=this.buffer[++n];)if(i===":"){const r=this.buffer[n+1];if(ae(r)||e&&Wt.has(r))break;t=n}else if(ae(i)){let r=this.buffer[n+1];if(i==="\r"&&(r===`
131
+ `&&r>=this.pos&&r+1+t>a)e=r;else break}while(!0);return yield ct,yield*this.pushToIndex(e+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){const e=this.flowLevel>0;let t=this.pos-1,n=this.pos-1,i;for(;i=this.buffer[++n];)if(i===":"){const r=this.buffer[n+1];if(ce(r)||e&&Jt.has(r))break;t=n}else if(ce(i)){let r=this.buffer[n+1];if(i==="\r"&&(r===`
132
132
  `?(n+=1,i=`
133
- `,r=this.buffer[n+1]):t=n),r==="#"||e&&Wt.has(r))break;if(i===`
134
- `){const o=this.continueScalar(n+1);if(o===-1)break;n=Math.max(n,o-2)}}else{if(e&&Wt.has(i))break;t=n}return!i&&!this.atEnd?this.setNext("plain-scalar"):(yield lt,yield*this.pushToIndex(t+1,!0),e?"flow":"doc")}*pushCount(e){return e>0?(yield this.buffer.substr(this.pos,e),this.pos+=e,e):0}*pushToIndex(e,t){const n=this.buffer.slice(this.pos,e);return n?(yield n,this.pos+=n.length,n.length):(t&&(yield""),0)}*pushIndicators(){switch(this.charAt(0)){case"!":return(yield*this.pushTag())+(yield*this.pushSpaces(!0))+(yield*this.pushIndicators());case"&":return(yield*this.pushUntil(Mn))+(yield*this.pushSpaces(!0))+(yield*this.pushIndicators());case"-":case"?":case":":{const e=this.flowLevel>0,t=this.charAt(1);if(ae(t)||e&&Wt.has(t))return e?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,(yield*this.pushCount(1))+(yield*this.pushSpaces(!0))+(yield*this.pushIndicators())}}return 0}*pushTag(){if(this.charAt(1)==="<"){let e=this.pos+2,t=this.buffer[e];for(;!ae(t)&&t!==">";)t=this.buffer[++e];return yield*this.pushToIndex(t===">"?e+1:e,!1)}else{let e=this.pos+1,t=this.buffer[e];for(;t;)if(Bo.has(t))t=this.buffer[++e];else if(t==="%"&&mi.has(this.buffer[e+1])&&mi.has(this.buffer[e+2]))t=this.buffer[e+=3];else break;return yield*this.pushToIndex(e,!1)}}*pushNewline(){const e=this.buffer[this.pos];return e===`
133
+ `,r=this.buffer[n+1]):t=n),r==="#"||e&&Jt.has(r))break;if(i===`
134
+ `){const o=this.continueScalar(n+1);if(o===-1)break;n=Math.max(n,o-2)}}else{if(e&&Jt.has(i))break;t=n}return!i&&!this.atEnd?this.setNext("plain-scalar"):(yield ct,yield*this.pushToIndex(t+1,!0),e?"flow":"doc")}*pushCount(e){return e>0?(yield this.buffer.substr(this.pos,e),this.pos+=e,e):0}*pushToIndex(e,t){const n=this.buffer.slice(this.pos,e);return n?(yield n,this.pos+=n.length,n.length):(t&&(yield""),0)}*pushIndicators(){switch(this.charAt(0)){case"!":return(yield*this.pushTag())+(yield*this.pushSpaces(!0))+(yield*this.pushIndicators());case"&":return(yield*this.pushUntil(Rn))+(yield*this.pushSpaces(!0))+(yield*this.pushIndicators());case"-":case"?":case":":{const e=this.flowLevel>0,t=this.charAt(1);if(ce(t)||e&&Jt.has(t))return e?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,(yield*this.pushCount(1))+(yield*this.pushSpaces(!0))+(yield*this.pushIndicators())}}return 0}*pushTag(){if(this.charAt(1)==="<"){let e=this.pos+2,t=this.buffer[e];for(;!ce(t)&&t!==">";)t=this.buffer[++e];return yield*this.pushToIndex(t===">"?e+1:e,!1)}else{let e=this.pos+1,t=this.buffer[e];for(;t;)if(jo.has(t))t=this.buffer[++e];else if(t==="%"&&pi.has(this.buffer[e+1])&&pi.has(this.buffer[e+2]))t=this.buffer[e+=3];else break;return yield*this.pushToIndex(e,!1)}}*pushNewline(){const e=this.buffer[this.pos];return e===`
135
135
  `?yield*this.pushCount(1):e==="\r"&&this.charAt(1)===`
136
- `?yield*this.pushCount(2):0}*pushSpaces(e){let t=this.pos-1,n;do n=this.buffer[++t];while(n===" "||e&&n===" ");const i=t-this.pos;return i>0&&(yield this.buffer.substr(this.pos,i),this.pos=t),i}*pushUntil(e){let t=this.pos,n=this.buffer[t];for(;!e(n);)n=this.buffer[++t];return yield*this.pushToIndex(t,!1)}}class yi{static{c(this,"LineCounter")}constructor(){this.lineStarts=[],this.addNewLine=e=>this.lineStarts.push(e),this.linePos=e=>{let t=0,n=this.lineStarts.length;for(;t<n;){const r=t+n>>1;this.lineStarts[r]<e?t=r+1:n=r}if(this.lineStarts[t]===e)return{line:t+1,col:1};if(t===0)return{line:0,col:e};const i=this.lineStarts[t-1];return{line:t,col:e-i+1}}}}function ke(s,e){for(let t=0;t<s.length;++t)if(s[t].type===e)return!0;return!1}c(ke,"includesToken");function wi(s){for(let e=0;e<s.length;++e)switch(s[e].type){case"space":case"comment":case"newline":break;default:return e}return-1}c(wi,"findNonEmptyIndex");function bi(s){switch(s?.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"flow-collection":return!0;default:return!1}}c(bi,"isFlowToken");function Gt(s){switch(s.type){case"document":return s.start;case"block-map":{const e=s.items[s.items.length-1];return e.sep??e.start}case"block-seq":return s.items[s.items.length-1].start;default:return[]}}c(Gt,"getPrevProps");function He(s){if(s.length===0)return[];let e=s.length;e:for(;--e>=0;)switch(s[e].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break e}for(;s[++e]?.type==="space";);return s.splice(e,s.length)}c(He,"getFirstKeyStartProps");function Si(s){if(s.start.type==="flow-seq-start")for(const e of s.items)e.sep&&!e.value&&!ke(e.start,"explicit-key-ind")&&!ke(e.sep,"map-value-ind")&&(e.key&&(e.value=e.key),delete e.key,bi(e.value)?e.value.end?Array.prototype.push.apply(e.value.end,e.sep):e.value.end=e.sep:Array.prototype.push.apply(e.start,e.sep),delete e.sep)}c(Si,"fixFlowSeqItems");class _n{static{c(this,"Parser")}constructor(e){this.atNewLine=!0,this.atScalar=!1,this.indent=0,this.offset=0,this.onKeyLine=!1,this.stack=[],this.source="",this.type="",this.lexer=new gi,this.onNewLine=e}*parse(e,t=!1){this.onNewLine&&this.offset===0&&this.onNewLine(0);for(const n of this.lexer.lex(e,t))yield*this.next(n);t||(yield*this.end())}*next(e){if(this.source=e,this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=e.length;return}const t=pi(e);if(t)if(t==="scalar")this.atNewLine=!1,this.atScalar=!0,this.type="scalar";else{switch(this.type=t,yield*this.step(),t){case"newline":this.atNewLine=!0,this.indent=0,this.onNewLine&&this.onNewLine(this.offset+e.length);break;case"space":this.atNewLine&&e[0]===" "&&(this.indent+=e.length);break;case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":this.atNewLine&&(this.indent+=e.length);break;case"doc-mode":case"flow-error-end":return;default:this.atNewLine=!1}this.offset+=e.length}else{const n=`Not a YAML token: ${e}`;yield*this.pop({type:"error",offset:this.offset,message:n,source:e}),this.offset+=e.length}}*end(){for(;this.stack.length>0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){const e=this.peek(1);if(this.type==="doc-end"&&(!e||e.type!=="doc-end")){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!e)return yield*this.stream();switch(e.type){case"document":return yield*this.document(e);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(e);case"block-scalar":return yield*this.blockScalar(e);case"block-map":return yield*this.blockMap(e);case"block-seq":return yield*this.blockSequence(e);case"flow-collection":return yield*this.flowCollection(e);case"doc-end":return yield*this.documentEnd(e)}yield*this.pop()}peek(e){return this.stack[this.stack.length-e]}*pop(e){const t=e??this.stack.pop();if(!t)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield t;else{const n=this.peek(1);switch(t.type==="block-scalar"?t.indent="indent"in n?n.indent:0:t.type==="flow-collection"&&n.type==="document"&&(t.indent=0),t.type==="flow-collection"&&Si(t),n.type){case"document":n.value=t;break;case"block-scalar":n.props.push(t);break;case"block-map":{const i=n.items[n.items.length-1];if(i.value){n.items.push({start:[],key:t,sep:[]}),this.onKeyLine=!0;return}else if(i.sep)i.value=t;else{Object.assign(i,{key:t,sep:[]}),this.onKeyLine=!i.explicitKey;return}break}case"block-seq":{const i=n.items[n.items.length-1];i.value?n.items.push({start:[],value:t}):i.value=t;break}case"flow-collection":{const i=n.items[n.items.length-1];!i||i.value?n.items.push({start:[],key:t,sep:[]}):i.sep?i.value=t:Object.assign(i,{key:t,sep:[]});return}default:yield*this.pop(),yield*this.pop(t)}if((n.type==="document"||n.type==="block-map"||n.type==="block-seq")&&(t.type==="block-map"||t.type==="block-seq")){const i=t.items[t.items.length-1];i&&!i.sep&&!i.value&&i.start.length>0&&wi(i.start)===-1&&(t.indent===0||i.start.every(r=>r.type!=="comment"||r.indent<t.indent))&&(n.type==="document"?n.end=i.start:n.items.push({start:i.start}),t.items.splice(-1,1))}}}*stream(){switch(this.type){case"directive-line":yield{type:"directive",offset:this.offset,source:this.source};return;case"byte-order-mark":case"space":case"comment":case"newline":yield this.sourceToken;return;case"doc-mode":case"doc-start":{const e={type:"document",offset:this.offset,start:[]};this.type==="doc-start"&&e.start.push(this.sourceToken),this.stack.push(e);return}}yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document(e){if(e.value)return yield*this.lineEnd(e);switch(this.type){case"doc-start":{wi(e.start)!==-1?(yield*this.pop(),yield*this.step()):e.start.push(this.sourceToken);return}case"anchor":case"tag":case"space":case"comment":case"newline":e.start.push(this.sourceToken);return}const t=this.startBlockValue(e);t?this.stack.push(t):yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML document`,source:this.source}}*scalar(e){if(this.type==="map-value-ind"){const t=Gt(this.peek(2)),n=He(t);let i;e.end?(i=e.end,i.push(this.sourceToken),delete e.end):i=[this.sourceToken];const r={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:n,key:e,sep:i}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=r}else yield*this.lineEnd(e)}*blockScalar(e){switch(this.type){case"space":case"comment":case"newline":e.props.push(this.sourceToken);return;case"scalar":if(e.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let t=this.source.indexOf(`
136
+ `?yield*this.pushCount(2):0}*pushSpaces(e){let t=this.pos-1,n;do n=this.buffer[++t];while(n===" "||e&&n===" ");const i=t-this.pos;return i>0&&(yield this.buffer.substr(this.pos,i),this.pos=t),i}*pushUntil(e){let t=this.pos,n=this.buffer[t];for(;!e(n);)n=this.buffer[++t];return yield*this.pushToIndex(t,!1)}}class gi{static{c(this,"LineCounter")}constructor(){this.lineStarts=[],this.addNewLine=e=>this.lineStarts.push(e),this.linePos=e=>{let t=0,n=this.lineStarts.length;for(;t<n;){const r=t+n>>1;this.lineStarts[r]<e?t=r+1:n=r}if(this.lineStarts[t]===e)return{line:t+1,col:1};if(t===0)return{line:0,col:e};const i=this.lineStarts[t-1];return{line:t,col:e-i+1}}}}function Ce(s,e){for(let t=0;t<s.length;++t)if(s[t].type===e)return!0;return!1}c(Ce,"includesToken");function yi(s){for(let e=0;e<s.length;++e)switch(s[e].type){case"space":case"comment":case"newline":break;default:return e}return-1}c(yi,"findNonEmptyIndex");function wi(s){switch(s?.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"flow-collection":return!0;default:return!1}}c(wi,"isFlowToken");function Wt(s){switch(s.type){case"document":return s.start;case"block-map":{const e=s.items[s.items.length-1];return e.sep??e.start}case"block-seq":return s.items[s.items.length-1].start;default:return[]}}c(Wt,"getPrevProps");function Ve(s){if(s.length===0)return[];let e=s.length;e:for(;--e>=0;)switch(s[e].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break e}for(;s[++e]?.type==="space";);return s.splice(e,s.length)}c(Ve,"getFirstKeyStartProps");function bi(s){if(s.start.type==="flow-seq-start")for(const e of s.items)e.sep&&!e.value&&!Ce(e.start,"explicit-key-ind")&&!Ce(e.sep,"map-value-ind")&&(e.key&&(e.value=e.key),delete e.key,wi(e.value)?e.value.end?Array.prototype.push.apply(e.value.end,e.sep):e.value.end=e.sep:Array.prototype.push.apply(e.start,e.sep),delete e.sep)}c(bi,"fixFlowSeqItems");class Mn{static{c(this,"Parser")}constructor(e){this.atNewLine=!0,this.atScalar=!1,this.indent=0,this.offset=0,this.onKeyLine=!1,this.stack=[],this.source="",this.type="",this.lexer=new mi,this.onNewLine=e}*parse(e,t=!1){this.onNewLine&&this.offset===0&&this.onNewLine(0);for(const n of this.lexer.lex(e,t))yield*this.next(n);t||(yield*this.end())}*next(e){if(this.source=e,this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=e.length;return}const t=di(e);if(t)if(t==="scalar")this.atNewLine=!1,this.atScalar=!0,this.type="scalar";else{switch(this.type=t,yield*this.step(),t){case"newline":this.atNewLine=!0,this.indent=0,this.onNewLine&&this.onNewLine(this.offset+e.length);break;case"space":this.atNewLine&&e[0]===" "&&(this.indent+=e.length);break;case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":this.atNewLine&&(this.indent+=e.length);break;case"doc-mode":case"flow-error-end":return;default:this.atNewLine=!1}this.offset+=e.length}else{const n=`Not a YAML token: ${e}`;yield*this.pop({type:"error",offset:this.offset,message:n,source:e}),this.offset+=e.length}}*end(){for(;this.stack.length>0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){const e=this.peek(1);if(this.type==="doc-end"&&(!e||e.type!=="doc-end")){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!e)return yield*this.stream();switch(e.type){case"document":return yield*this.document(e);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(e);case"block-scalar":return yield*this.blockScalar(e);case"block-map":return yield*this.blockMap(e);case"block-seq":return yield*this.blockSequence(e);case"flow-collection":return yield*this.flowCollection(e);case"doc-end":return yield*this.documentEnd(e)}yield*this.pop()}peek(e){return this.stack[this.stack.length-e]}*pop(e){const t=e??this.stack.pop();if(!t)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield t;else{const n=this.peek(1);switch(t.type==="block-scalar"?t.indent="indent"in n?n.indent:0:t.type==="flow-collection"&&n.type==="document"&&(t.indent=0),t.type==="flow-collection"&&bi(t),n.type){case"document":n.value=t;break;case"block-scalar":n.props.push(t);break;case"block-map":{const i=n.items[n.items.length-1];if(i.value){n.items.push({start:[],key:t,sep:[]}),this.onKeyLine=!0;return}else if(i.sep)i.value=t;else{Object.assign(i,{key:t,sep:[]}),this.onKeyLine=!i.explicitKey;return}break}case"block-seq":{const i=n.items[n.items.length-1];i.value?n.items.push({start:[],value:t}):i.value=t;break}case"flow-collection":{const i=n.items[n.items.length-1];!i||i.value?n.items.push({start:[],key:t,sep:[]}):i.sep?i.value=t:Object.assign(i,{key:t,sep:[]});return}default:yield*this.pop(),yield*this.pop(t)}if((n.type==="document"||n.type==="block-map"||n.type==="block-seq")&&(t.type==="block-map"||t.type==="block-seq")){const i=t.items[t.items.length-1];i&&!i.sep&&!i.value&&i.start.length>0&&yi(i.start)===-1&&(t.indent===0||i.start.every(r=>r.type!=="comment"||r.indent<t.indent))&&(n.type==="document"?n.end=i.start:n.items.push({start:i.start}),t.items.splice(-1,1))}}}*stream(){switch(this.type){case"directive-line":yield{type:"directive",offset:this.offset,source:this.source};return;case"byte-order-mark":case"space":case"comment":case"newline":yield this.sourceToken;return;case"doc-mode":case"doc-start":{const e={type:"document",offset:this.offset,start:[]};this.type==="doc-start"&&e.start.push(this.sourceToken),this.stack.push(e);return}}yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document(e){if(e.value)return yield*this.lineEnd(e);switch(this.type){case"doc-start":{yi(e.start)!==-1?(yield*this.pop(),yield*this.step()):e.start.push(this.sourceToken);return}case"anchor":case"tag":case"space":case"comment":case"newline":e.start.push(this.sourceToken);return}const t=this.startBlockValue(e);t?this.stack.push(t):yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML document`,source:this.source}}*scalar(e){if(this.type==="map-value-ind"){const t=Wt(this.peek(2)),n=Ve(t);let i;e.end?(i=e.end,i.push(this.sourceToken),delete e.end):i=[this.sourceToken];const r={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:n,key:e,sep:i}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=r}else yield*this.lineEnd(e)}*blockScalar(e){switch(this.type){case"space":case"comment":case"newline":e.props.push(this.sourceToken);return;case"scalar":if(e.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let t=this.source.indexOf(`
137
137
  `)+1;for(;t!==0;)this.onNewLine(this.offset+t),t=this.source.indexOf(`
138
- `,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 i=e.items[e.items.length-2]?.value?.end;if(Array.isArray(i)){Array.prototype.push.apply(i,t.start),i.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,i=n&&(t.sep||t.explicitKey)&&this.type!=="seq-item-ind";let r=[];if(i&&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&&(r=t.sep.splice(o[1]))}switch(this.type){case"anchor":case"tag":i||t.value?(r.push(this.sourceToken),e.items.push({start:r}),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):i||t.value?(r.push(this.sourceToken),e.items.push({start:r,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(ke(t.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,key:null,sep:[this.sourceToken]}]});else if(bi(t.key)&&!ke(t.sep,"newline")){const o=He(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 r.length>0?t.sep=t.sep.concat(r,this.sourceToken):t.sep.push(this.sourceToken);else if(ke(t.start,"newline"))Object.assign(t,{key:null,sep:[this.sourceToken]});else{const o=He(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||i?e.items.push({start:r,key:null,sep:[this.sourceToken]}):ke(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);i||t.value?(e.items.push({start:r,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&&!ke(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:r});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 i=e.items[e.items.length-2]?.value?.end;if(Array.isArray(i)){Array.prototype.push.apply(i,t.start),i.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||ke(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 i=this.flowScalar(this.type);!t||t.value?e.items.push({start:[],key:i,sep:[]}):t.sep?this.stack.push(i):Object.assign(t,{key:i,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 i=Gt(n),r=He(i);Si(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:r,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(`
138
+ `,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 i=e.items[e.items.length-2]?.value?.end;if(Array.isArray(i)){Array.prototype.push.apply(i,t.start),i.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,i=n&&(t.sep||t.explicitKey)&&this.type!=="seq-item-ind";let r=[];if(i&&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&&(r=t.sep.splice(o[1]))}switch(this.type){case"anchor":case"tag":i||t.value?(r.push(this.sourceToken),e.items.push({start:r}),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):i||t.value?(r.push(this.sourceToken),e.items.push({start:r,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(Ce(t.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,key:null,sep:[this.sourceToken]}]});else if(wi(t.key)&&!Ce(t.sep,"newline")){const o=Ve(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 r.length>0?t.sep=t.sep.concat(r,this.sourceToken):t.sep.push(this.sourceToken);else if(Ce(t.start,"newline"))Object.assign(t,{key:null,sep:[this.sourceToken]});else{const o=Ve(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||i?e.items.push({start:r,key:null,sep:[this.sourceToken]}):Ce(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);i||t.value?(e.items.push({start:r,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&&!Ce(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:r});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 i=e.items[e.items.length-2]?.value?.end;if(Array.isArray(i)){Array.prototype.push.apply(i,t.start),i.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||Ce(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 i=this.flowScalar(this.type);!t||t.value?e.items.push({start:[],key:i,sep:[]}):t.sep?this.stack.push(i):Object.assign(t,{key:i,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 i=Wt(n),r=Ve(i);bi(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:r,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(`
139
139
  `)+1;for(;t!==0;)this.onNewLine(this.offset+t),t=this.source.indexOf(`
140
- `,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=Gt(e),n=He(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=Gt(e),n=He(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 Ci(s){const e=s.prettyErrors!==!1;return{lineCounter:s.lineCounter||e&&new yi||null,prettyErrors:e}}c(Ci,"parseOptions");function Uo(s,e={}){const{lineCounter:t,prettyErrors:n}=Ci(e),i=new _n(t?.addNewLine),r=new xn(e),o=Array.from(r.compose(i.parse(s)));if(n&&t)for(const a of o)a.errors.forEach(jt(s,t)),a.warnings.forEach(jt(s,t));return o.length>0?o:Object.assign([],{empty:!0},r.streamInfo())}c(Uo,"parseAllDocuments");function ki(s,e={}){const{lineCounter:t,prettyErrors:n}=Ci(e),i=new _n(t?.addNewLine),r=new xn(e);let o=null;for(const a of r.compose(i.parse(s),!0,s.length))if(!o)o=a;else if(o.options.logLevel!=="silent"){o.errors.push(new Le(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return n&&t&&(o.errors.forEach(jt(s,t)),o.warnings.forEach(jt(s,t))),o}c(ki,"parseDocument");function Jo(s,e,t){let n;typeof e=="function"?n=e:t===void 0&&e&&typeof e=="object"&&(t=e);const i=ki(s,t);if(!i)return null;if(i.warnings.forEach(r=>xs(i.options.logLevel,r)),i.errors.length>0){if(i.options.logLevel!=="silent")throw i.errors[0];i.errors=[]}return i.toJS(Object.assign({reviver:n},t))}c(Jo,"parse");function Wo(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 i=Math.round(t);t=i<1?void 0:i>8?{indent:8}:{indent:i}}if(s===void 0){const{keepUndefined:i}=t??e??{};if(!i)return}return Ne(s)&&!n?s.toString(t):new Xe(s,n,t).toString(t)}c(Wo,"stringify");var Go=Object.freeze({__proto__:null,Alias:kt,CST:Fo,Composer:xn,Document:Xe,Lexer:gi,LineCounter:yi,Pair:Q,Parser:_n,Scalar:D,Schema:Zt,YAMLError:Nn,YAMLMap:te,YAMLParseError:Le,YAMLSeq:Ce,YAMLWarning:ni,isAlias:Se,isCollection:q,isDocument:Ne,isMap:_e,isNode:U,isPair:F,isScalar:_,isSeq:Ke,parse:Jo,parseAllDocuments:Uo,parseDocument:ki,stringify:Wo,visit:Ae,visitAsync:Ct});const Y={Added:"added",Changed:"changed",Deleted:"deleted",Stopped:"stopped"},Vo={ignored:Er,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 Ho extends hs{static{c(this,"FileWatcher")}constructor(e){super(),this.options=e,this.membraneDir=bt(this.options.cwd)}isWatching=!1;watcher;membraneDir;contentCache={};async start(){this.isWatching||(x.existsSync(this.membraneDir)||x.mkdirSync(this.membraneDir,{recursive:!0}),this.initializeContentCache(),this.watcher=rr.watch(this.membraneDir,Vo),this.watcher.on("add",e=>this.handleFileSystemEvent(Y.Added,e)).on("change",e=>this.handleFileSystemEvent(Y.Changed,e)).on("unlink",e=>this.handleFileSystemEvent(Y.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.emit(Y.Stopped))}getCwd(){return this.options.cwd}handleFileSystemEvent(e,t){const n=R.relative(this.membraneDir,t);if(e===Y.Deleted){this.removeFromCache(n);const a={filePath:t,relativePath:n,data:void 0};N.info(`[local] ${e}: ${a.relativePath}`),this.emit(e,a);return}const i=this.readFileContent(t);if(!this.hasContentChanged(n,i,e))return;const o=this.processFileEvent(t,i);this.updateCache(n,i),o&&(N.info(`[local] ${e}: ${o.relativePath}`),this.emit(e,o))}readFileContent(e){return x.readFileSync(e,"utf8")}processFileEvent(e,t){const n=R.relative(this.membraneDir,e);let i;try{i=t?Go.parse(t):void 0}catch{i=void 0}return{filePath:e,relativePath:n,data:i}}hasContentChanged(e,t,n){if(n==="added")return!0;if(!t)return this.contentCache[e]!==void 0;const i=this.getContentHash(t);return this.contentCache[e]!==i}getContentHash(e){return sr.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(){x.existsSync(this.membraneDir)&&this.scanDirectoryForCache(this.membraneDir)}scanDirectoryForCache(e){const t=x.readdirSync(e,{withFileTypes:!0});for(const n of t){const i=R.join(e,n.name);if(n.isDirectory())this.scanDirectoryForCache(i);else if(n.isFile())try{const r=x.readFileSync(i,"utf8"),o=R.relative(this.membraneDir,i);this.updateCache(o,r)}catch{}}}}const X={UPDATE:"update",DELETE:"delete",CREATE:"create"},re={INCOMING:"incoming",OUTGOING:"outgoing"};async function Yo(s,e="full"){const t={};N.info("[connectors] Getting remote workspace data");const n=await pe.withThrottle(()=>s.integrations.findAll());t.integration=n.map(i=>Kn("integration",i));for(const i of Object.keys(ne)){const r=ne[i];if(r.exportable===!1)continue;const o=[];N.info(`[connectors] Reading ${r.elements} from remote workspace`);const a=await pe.withThrottle(()=>s[r.elements].findAll());if(o.push(...a.map(l=>Kn(i,l))),r.integrationSpecific)for(const l of n){const u=await pe.withThrottle(()=>s[r.elements].findAll({integrationId:l.id}));o.push(...u.map(p=>(p.integrationKey=l.key,Kn(i,p))))}o.length>0&&e=="full"&&(console.table(o.map(l=>({key:l.key,integrationKey:l.integrationKey,universal:!l.integrationKey})).reduce((l,u)=>(l||(l={}),l[u.key]||(l[u.key]={}),u.universal&&(l[u.key].universal=!0),u.integrationKey&&(l[u.key].integration?l[u.key].integration+=` ${u.integrationKey}`:l[u.key].integration=u.integrationKey),l),{})),console.groupEnd()),t[i]=o}return N.success("[connectors] Remote workspace data retrieved successfully"),t}c(Yo,"getWorkspaceData");function Kn(s,e){return e=Cr(e),ne[s].exportCleanup?ne[s].exportCleanup(e):e}c(Kn,"cleanUpForExport");const ut="connectors",ft="development",jn={};async function zo({integrations:s,allConnectors:e=!1}){const t=Nr(),n=await ue.getClient(process.cwd()),i=new Set,r={};for(const o of s){const a=o.connectorId,l=o.connectorVersion;if(!r[a]?.has(o.connectorVersion)){const u=await Ei({client:n,connectorId:a}),d=!!u.workspaceId||e;if(!u?.key){N.error(`[connectors] Connector ${a} has no key. Skipping..`);continue}d&&(i.has(a)||(await ta({basePath:t,connector:u}),i.add(a)),r[a]||(r[a]=new Set),r[a].has(l)||(await na({client:n,connector:u,connectorVersion:l,basePath:t}),r[a].add(l)))}}}c(zo,"pullConnectors");async function Qo(){const s=await ue.getClient(process.cwd()),e=await Yo(s,"minified"),n=(await s.get("org-workspace-id")).id,i={};N.info("[connectors] Loading custom connectors");const r=s,o=await r.get(`/connectors?workspaceId=${n}`);N.info("[connectors] Loading public connectors"),e.connector=o;const a=Fn(),u=(P.existsSync(a)?P.readdirSync(a):[]).filter(p=>{if(p.startsWith("."))return!1;const d=B.join(a,p);try{return P.statSync(d).isDirectory()}catch{return!1}});for(const p of u){N.info(`[connectors] Loading connector from: ${p}`);const d=P.readdirSync(B.join(a,p)),h=await Bn(p);if("baseUri"in h&&delete h.baseUri,h.uuid&&e.connector?.find(w=>w.uuid==h.uuid))i[h.id]=e.connector.find(w=>w.uuid==h.uuid).id,N.info(`[connectors] Matched ${h.name} uuid: ${h.uuid}`);else if(!i[h.id]){let w=!1;try{const f=await Ei({client:s,connectorId:h.id});f&&!f.workspaceId&&(w=!0)}catch{}if(!w){N.info(`[connectors] Creating custom connector ${h.name} (${h.key})`);const f=await r.post("connectors",{...h,workspaceId:n});i[h.id]=f.id}}const g=d.filter(w=>P.statSync(B.join(a,p,w)).isDirectory());for(const w of g)await ea({client:s,connector:h,version:w,connectorId:i[h.id]})}return i}c(Qo,"pushConnectors");function Fn(){const s=ln();return B.join(s.membraneDirPath,ut)}c(Fn,"getConnectorsPath");async function Bn(s){return Te.load(P.readFileSync(B.join(Fn(),s,`${s}.yml`),"utf8"))}c(Bn,"readConnector");async function Xo(s,e){return N.info(`[connectors] Zipping ${s} into ${e}`),new Promise((t,n)=>{const i=P.createWriteStream(e),r=or("zip",{zlib:{level:9}});i.on("close",()=>{N.success(`[connectors] Successfully created ${e}`),t()}),i.on("end",()=>{N.info("[connectors] Data has been drained")}),r.on("warning",a=>{a.code==="ENOENT"?console.warn(a):n(a)}),r.on("error",a=>{n(a)}),r.pipe(i);const o=P.readdirSync(s);for(const a of o){const l=B.join(s,a),u=P.statSync(l);u.isFile()?r.file(l,{name:a}):u.isDirectory()&&r.directory(l,a)}r.finalize()})}c(Xo,"createZipArchive");async function Zo(s,e){return N.info(`[connectors] Unzipping into ${e}`),new Promise((t,n)=>{const i=cr.Parse();i.on("entry",r=>{const o=r.path;if(r.type==="Directory"){const l=B.join(e,o);P.mkdirSync(l,{recursive:!0}),r.autodrain()}else{const l=B.join(e,o),u=B.dirname(l);P.mkdirSync(u,{recursive:!0});const p=P.createWriteStream(l);r.pipe(p),p.on("finish",()=>{})}}),i.on("end",()=>{N.success(`[connectors] Successfully extracted to ${e}`),t()}),i.on("error",r=>{n(r)}),i.write(s),i.end()})}c(Zo,"extractZipArchive");async function ea({client:s,connector:e,version:t,connectorId:n}){const i=B.join(Fn(),Vt(e),vi(t)),r=B.join(i,"src"),o=B.join(i,"src.zip"),a=P.existsSync(o);if(P.existsSync(r)&&(N.info(`[connectors] Archiving source code for ${e.name} version ${t}`),await Xo(r,o)),!P.existsSync(o)){N.warning(`[connectors] No source code found for ${e.name} version ${t}`);return}try{const l=new ar;if(l.append("file",P.createReadStream(o),"file.zip"),N.info(`[connectors] Pushing connector version ${t} for ${e.name}`),t==ft)N.info(`[connectors] Uploading connector ${n}`),await s.post(`connectors/${n}/upload`,l,{headers:{...l.getHeaders()}});else{if(l.append("version",t),l.append("changelog","Imported Version"),(await s.get(`/connectors/${n}/versions`)).find(p=>p.version==t)){N.info(`[connectors] Version ${t} already published`);return}N.info(`[connectors] Publishing version ${t} of connector ${n}`),await s.post(`connectors/${n}/publish-version`,l,{headers:{...l.getHeaders()}})}N.success(`Successfully pushed connector version ${t} for ${e.name}`)}catch(l){N.error(`Error pushing connector version ${t} for ${e.name}: ${l}`)}finally{!a&&P.existsSync(o)&&(N.info(`[connectors] Cleaning up temporary zip file for ${e.name} version ${t}`),P.unlinkSync(o))}}c(ea,"pushConnectorVersion");async function Ei({client:s,connectorId:e}){if(jn[e])return jn[e];const t=await s.get(`connectors/${e}`);return jn[e]=t,t}c(Ei,"getConnector");async function ta({basePath:s,connector:e}){const t=Vt(e),n=B.join(s,ut,t);P.mkdirSync(n,{recursive:!0});const i=B.join(n,`${Vt(e)}.yml`);P.writeFileSync(i,Te.dump(e)),N.info(`[connectors] Pulled connector ${e.name}`)}c(ta,"pullConnector");async function na({client:s,connector:e,connectorVersion:t,basePath:n}){const i=Vt(e),r=vi(t),o=B.join(n,"connectors",i,r),a=await s.get(`connectors/${e.id}/download`,{version:t},{responseType:"arraybuffer",headers:{Accept:"application/zip"},timeout:1e6});P.mkdirSync(o,{recursive:!0});const l=B.join(o,"src.zip");if(P.writeFileSync(l,a),!t){const u=B.join(o,"src");P.mkdirSync(u,{recursive:!0}),await Zo(a,u)}N.info(`[connectors] Pulled connector version: ${e.name} (${r})`)}c(na,"pullConnectorVersion");function Vt(s){return s.key}c(Vt,"getConnectorDirName");function vi(s){return s??ft}c(vi,"getConnectorVersionDirName");function sa(s){return s.match(`${ut}/[^/]+/${ft}/src/.*`)!==null}c(sa,"isConnectorSourceFile");async function ia(s){const e=s.match(`${ut}/([^/]+)/${ft}/src/(.*)`);if(!e)return;const t=e[1],n=e[2],i=await Bn(t);if(!i){N.warning(`[connectors] Connector ${t} not found. Ignoring file change`);return}const r=i.id,o=P.readFileSync(s,"utf-8");await(await ue.getClient()).put(`connectors/${r}/files/${n}`,o,{headers:{"Content-Type":"text/plain"}}),N.info(`[connectors] Pushed file ${n} for connector ${i.name}`)}c(ia,"putConnectorFile");async function ra(s){const e=s.match(`${ut}/([^/]+)/${ft}/src/(.*)`);if(!e)return;const t=e[1],n=e[2],i=await Bn(t);if(!i){N.warning(`[connectors] Connector ${t} not found. Ignoring file change`);return}const r=i.id;await(await ue.getClient()).delete(`connectors/${r}/files/${n}`),N.info(`[connectors] Deleted file ${n} for connector ${i.name}`)}c(ra,"deleteConnectorFile");class mt{static{c(this,"ElementSyncService")}fileWatcher=void 0;notifier;changes=[];localCache;remoteCache;localRepo;remoteRepo;constructor(){this.notifier=de,this.localCache=new ws,this.remoteCache=new ws,this.localRepo=new Pr(this.localCache),this.remoteRepo=new Mr(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),i=this.getCache(t);try{const r=await n.putElement(e);i.put(r)}catch(r){throw N.error(`Failed to update element ${e.id}: ${r}`),r}}async deleteElement(e,t){const n=this.getHandler(t),i=this.getCache(t);try{await n.deleteElement(e,{elements:n.cache.getAll(),connectorsMapping:n.connectorsMapping}),i.remove(e)}catch(r){throw N.error(`Failed to delete element ${e.id}: ${r}`),r}}async pullConnectors(e=!1){await zo({integrations:this.remoteCache.getElementsByType(M.Integration).map(t=>t.data),allConnectors:e})}async pushConnectors(){const e=await Qo();this.remoteRepo.setConnectorsMapping(e)}getHandler(e){return e===re.INCOMING?this.localRepo:this.remoteRepo}getCache(e){return e===re.INCOMING?this.localCache:this.remoteCache}async startWatching(){this.fileWatcher=new Ho({cwd:process.cwd()}),this.fileWatcher.on(Y.Added,e=>this.handleLocalEvent(e,Y.Added)),this.fileWatcher.on(Y.Changed,e=>this.handleLocalEvent(e,Y.Changed)),this.fileWatcher.on(Y.Deleted,e=>this.handleLocalEvent(e,Y.Deleted)),await this.fileWatcher.start(),N.success("[local] Tracking changes..")}async stopWatching(){await this.fileWatcher?.stop(),this.fileWatcher=void 0}async handleLocalEvent(e,t){try{if(sa(e.filePath))switch(t){case Y.Added:case Y.Changed:await ia(e.filePath);break;case Y.Deleted:await ra(e.filePath);break}else{let n=G.fromPathAndData(e.filePath,e.data);if(!n){const i=G.idFromPath(e.filePath);if(!i||(n=this.remoteCache.get(i),!n))return}switch(N.info(`[resolver][${this.getDirectionLabel(re.OUTGOING)}] ${t}: ${n.id}`),t){case Y.Added:case Y.Changed:await this.updateElement(n,re.OUTGOING);break;case Y.Deleted:await this.deleteElement(n,re.OUTGOING);break}}}catch(n){N.error(`[sync] Error handling local event: ${n}`)}}detectIncomingChanges(){this.clearChanges();const e=mt.getChanges(re.INCOMING,this.remoteCache,this.localCache);return this.updateChanges(e),e}detectOutgoingChanges(){this.clearChanges();const e=mt.getChanges(re.OUTGOING,this.localCache,this.remoteCache);return this.updateChanges(e),e}getChange(e){const t=this.localCache.get(e.id),n=this.remoteCache.get(e.id);return!t&&n?{type:X.CREATE,element:n,direction:re.INCOMING,isConflict:!1}:t&&!n?{type:X.DELETE,element:t,direction:re.OUTGOING,isConflict:!0}:t&&n&&!t.isEqual(n)?{type:X.UPDATE,element:t,direction:re.OUTGOING,isConflict:!0}:null}async resolveChanges(){if(!this.needsSync())return;N.info("[resolver] Resolving changes..");const e=this.changes.filter(r=>r.element.type===M.Integration),t=this.changes.filter(r=>r.element.type!==M.Integration),n=t.filter(r=>r.element.hasParent()),i=t.filter(r=>!r.element.hasParent());await Promise.all(e.map(async r=>this.resolveChange(r))),await Promise.all(i.map(async r=>this.resolveChange(r))),await Promise.all(n.map(async r=>this.resolveChange(r))),N.success(`[resolver] Resolved ${this.changes.length} changes`)}async resolveChange(e){switch(e.type){case X.DELETE:return N.info(`[resolver][${this.getDirectionLabel(e.direction)}] Deleting ${e.element.id}`),this.deleteElement(e.element,e.direction);case X.CREATE:return N.info(`[resolver][${this.getDirectionLabel(e.direction)}] Creating ${e.element.id}`),this.updateElement(e.element,e.direction);case X.UPDATE:return N.info(`[resolver][${this.getDirectionLabel(e.direction)}] Updating ${e.element.id}`),this.updateElement(e.element,e.direction)}}static getChanges(e,t,n){const i=t.getAllIds(),r=n.getAllIds(),o=new Set([...i,...r]),a=[];for(const l of o){const u=t.get(l),p=n.get(l),d=mt.detectChangeForElement(u,p,e);d&&a.push(d)}return a}updateChanges(e){this.changes=e;for(const t of e)N.info(`[resolver][${this.getDirectionLabel(t.direction)}] ${this.getTypeLabel(t.type)} ${t.element.id}`);if(this.needsForcedSync()){const t=e.filter(n=>n.isConflict);N.warning("[resolver] Conflicts detected"),this.notifier.setConflicts(t)}}clearChanges(){this.changes=[]}getDirectionLabel(e){switch(e){case re.INCOMING:return"local\u2190remote";case re.OUTGOING:return"local\u2192remote"}}getTypeLabel(e){switch(e){case X.CREATE:return"ADD";case X.UPDATE:return"UPD";case X.DELETE:return"DEL"}}static detectChangeForElement(e,t,n){return e&&!t?{type:X.CREATE,element:e,direction:n,isConflict:!1}:!e&&t?{type:X.DELETE,element:t,direction:n,isConflict:!0}:e&&t&&!e.isEqual(t)?{type:X.UPDATE,element:e,direction:n,isConflict:!0}:null}}const Ee=R.join(lr.tmpdir(),"membrane-mcp-status"),Ii=3e4;class oa{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=Ht(void 0,e),n=Ti(e);t&&de.setMcpStatus(t),await de.setMcpServers(n)}catch{N.error("Failed to check MCP status")}}}function Ht(s,e){try{const t=e||process.cwd();if(!s){const i=Ti(t);return i.length===0?null:i[0]}const n=Jn(s,t);if(x.existsSync(n)){const i=x.statSync(n),r=new Date;if(r.getTime()-i.mtime.getTime()>Ii)return ht(s,t),null;const a=x.readFileSync(n,"utf8"),l=JSON.parse(a);if(l.isRunning){const u=new Date(l.lastActivity).getTime();if(r.getTime()-u>Ii)return ht(s,t),null}return l}}catch{s&&e&&ht(s,e)}return null}c(Ht,"getMcpStatus");function Ti(s){try{const e=s||process.cwd(),t=Un(e);if(!x.existsSync(Ee))return[];const n=x.readdirSync(Ee),i=[];for(const r of n){const o=r.match(new RegExp(`^mcp-${t}-(\\d+)\\.json$`));if(o){const a=parseInt(o[1],10),l=Ht(a,e);l&&i.push(l)}}return i.sort((r,o)=>new Date(o.startTime).getTime()-new Date(r.startTime).getTime())}catch{return[]}}c(Ti,"getAllMcpStatusFiles");function qn(s){try{const t={...Ht(s.processId,s.cwd)||{isRunning:!1,startTime:new Date().toISOString(),lastActivity:new Date().toISOString(),toolsCount:0,totalRequests:0,processId:s.processId,cwd:s.cwd,agentName:process.env.AGENT_NAME||"Unnamed Agent"},...s};x.existsSync(Ee)||x.mkdirSync(Ee,{recursive:!0});const n=Jn(s.processId,s.cwd);x.writeFileSync(n,JSON.stringify(t,null,2))}catch{}}c(qn,"updateMcpStatus");function ht(s,e){try{const t=e||process.cwd();if(s){const n=Jn(s,t);x.existsSync(n)&&x.unlinkSync(n)}else{const n=Un(t);if(x.existsSync(Ee)){const i=x.readdirSync(Ee);for(const r of i)r.match(new RegExp(`^mcp-${n}-\\d+\\.json$`))&&x.unlinkSync(R.join(Ee,r))}}}catch{}}c(ht,"clearMcpStatus");function aa(s,e){const t=Ht(s,e);t&&qn({processId:s,cwd:e,totalRequests:t.totalRequests+1,lastRequestTime:new Date().toISOString(),lastActivity:new Date().toISOString()})}c(aa,"trackToolExecution");function Un(s){return ir("md5").update(s).digest("hex").slice(0,8)}c(Un,"getCwdHash");function Jn(s,e){const t=Un(e);return R.join(Ee,`mcp-${t}-${s}.json`)}c(Jn,"getStatusFilePath");const dt={Agent:"agent",Cli:"cli"},L={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 Ni{static{c(this,"MembraneCLIService")}constructor(e,t,n=()=>process.exit(0)){this.mode=e,this.cwd=t,this.onShutdown=n,this.notifier=de,this.mcpStatusService=new oa,this.syncService=new mt,this.setupProcessCleanup()}initialized=!1;notifier;mcpStatusService;syncService;isShuttingDown=!1;currentConfig=null;get config(){return this.currentConfig}async pullWorkspace(e={}){try{if(await this.notifier.setState(L.PULLING),await this.syncService.fetchElements(),this.syncService.detectIncomingChanges(),this.syncService.needsForcedSync()&&!e.force)return this.notifier.setState(L.CONFLICTS);await this.syncService.pullConnectors(e.allConnectors),await this.syncWorkspaces(e)}catch(t){N.error(`Failed to pull workspace: ${t}`),await this.notifier.setState(L.ERROR),e?.onComplete?.()}}async pushWorkspace(e={}){try{if(await this.notifier.setState(L.PUSHING),await this.syncService.fetchElements(),this.syncService.detectOutgoingChanges(),this.syncService.needsForcedSync()&&!e.force)return await this.notifier.setState(L.CONFLICTS);await this.syncService.pushConnectors(),await this.syncWorkspaces(e)}catch(t){N.error(`Failed to push workspace: ${t}`),await this.notifier.setState(L.ERROR),e?.onComplete?.()}}async syncWorkspaces(e={}){try{await this.notifier.setState(L.RESOLVING),this.syncService.needsSync()&&await this.syncService.resolveChanges();const t=await this.syncService.getStats();this.notifier.setStats(t),await this.notifier.setState(L.SYNCED),e.watch&&(await this.notifier.setState(L.WATCHING),await this.syncService.startWatching()),e.onComplete?.()}catch(t){N.error(`Failed to sync local and remote workspaces: ${t}`),await this.notifier.setState(L.ERROR),e?.onComplete?.()}}async init({force:e=!1}={}){if(!(this.initialized&&!e)){await this.notifier.setState(L.NOT_INITIALIZED);try{await this.loadConfig(),et.isCacheDefined()?(await this.initServices(),this.initialized=!0,await this.notifier.setState(L.INITIALIZED)):(this.initialized=!1,await this.notifier.setState(L.SETTING_UP))}catch(t){N.error(`Failed to initialize services: ${t}`),await this.notifier.setState(L.ERROR),this.onShutdown()}}}async loadConfig(){this.currentConfig=et.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 i=et.updateConfig(t);this.currentConfig=i,await this.init({force:!0})}async shutdown(){!this.initialized||this.isShuttingDown||(this.isShuttingDown=!0,this.mode===dt.Agent&&(await this.notifier.cleanup(),await this.mcpStatusService.stop()),this.initialized=!1,this.onShutdown())}async initServices(){this.mode===dt.Agent&&(await this.notifier.connectToRemote(),await this.mcpStatusService.start()),this.syncService.clear()}async stopServices(){this.mode===dt.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 Ai=ss(null);function ca({children:s,membraneCLIService:e}){const{data:t}=rs("/account"),[n,i]=j(L.NOT_INITIALIZED),[r,o]=j([]),[a,l]=j({}),[u,p]=j([]),[d,h]=j(null),w=t?.workspaces?.find(f=>f.workspaceKey===d?.workspaceKey)||null;return Ie(()=>{const f=c(({state:I})=>i(I),"handleStateChanged"),y=c(({stats:I})=>l(I),"handleStatsChanged"),C=c(({log:I})=>p(O=>[...O,I]),"handleLogAdded"),E=c(({conflicts:I})=>o(I),"handleConflictsUpdated"),A=c(({config:I})=>h(I),"handleConfigChanged");return e.notifier.on(J.StateChanged,f),e.notifier.on(J.StatsChanged,y),e.notifier.on(J.LogAdded,C),e.notifier.on(J.ConflictsChanged,E),e.notifier.on(J.ConfigChanged,A),e.init(),()=>{e.notifier.off(J.StateChanged,f),e.notifier.off(J.StatsChanged,y),e.notifier.off(J.LogAdded,C),e.notifier.off(J.ConflictsChanged,E),e.notifier.off(J.ConfigChanged,A)}},[]),m(Ai.Provider,{value:{state:n,stats:a,logs:u,currentWorkspace:w,conflicts:r,config:d,updateConfig:c(f=>e.updateConfig(f),"updateConfig"),resolveConflicts:c(f=>e.syncWorkspaces(f),"resolveConflicts"),pull:c(f=>e.pullWorkspace(f),"pull"),push:c(f=>e.pushWorkspace(f),"push"),exit:c(()=>e.shutdown(),"exit")},children:s})}c(ca,"MembraneCLIServiceProvider");function ce(){const s=is(Ai);if(!s)throw new Error("useMembraneCLIService must be used within MembraneCLIServiceProvider");return s}c(ce,"useMembraneCLIService");const Oi=ss(process.cwd());function la({cwd:s,children:e}){return m(Oi.Provider,{value:s,children:e})}c(la,"CwdProvider");function ua(){return is(Oi)}c(ua,"useCwd");function Yt({cwd:s,children:e,membraneCLIService:t}){const n=s||process.cwd();return m(la,{cwd:n,children:m(Vi,{value:{fetcher:$r()},children:m(ca,{membraneCLIService:t,children:e})})})}c(Yt,"Layout");const Wn=[{id:"claude-code",name:"Claude Code",description:"Anthropic Claude Code agent",actionDescription:"Adding membrane MCP to .mcp.json in the current directory",addConfig:c(()=>{const s=R.join(process.cwd(),".mcp.json"),e={mcpServers:{membrane:{command:"membrane",args:["mcp"],env:{AGENT_NAME:"Claude Code"}}}};let t={};if(x.existsSync(s))try{t=JSON.parse(x.readFileSync(s,"utf8"))}catch{t={}}const n={...t,mcpServers:{...t.mcpServers,...e.mcpServers}};return x.writeFileSync(s,JSON.stringify(n,null,2)),`MCP server configuration added to ${s}`},"addConfig")},{id:"cursor",name:"Cursor",description:"Cursor AI editor",actionDescription:"Adding membrane MCP to .cursor/mcp.json in the current directory",addConfig:c(()=>{const s=R.join(process.cwd(),".cursor"),e=R.join(s,"mcp.json");x.existsSync(s)||x.mkdirSync(s);const t={mcpServers:{membrane:{command:"membrane",args:["mcp"],env:{AGENT_NAME:"Cursor"}}}};let n={};if(x.existsSync(e))try{n=JSON.parse(x.readFileSync(e,"utf8"))}catch{n={}}const i={...n,mcpServers:{...n.mcpServers,...t.mcpServers}};return x.writeFileSync(e,JSON.stringify(i,null,2)),`MCP server configuration added to ${e}`},"addConfig")}];function fa({onExit:s,onComplete:e}){const[t,n]=j(0),[i,r]=j(!1),[o,a]=j(null),[l,u]=j(""),[p,d]=j("");Pe((w,f)=>{if(l||p){(f.escape||w==="q"||f.return)&&e();return}if(i)f.return||w===" "?h(o):f.escape&&(r(!1),a(null));else if(f.escape)s();else if(f.upArrow||w==="k")n(Math.max(0,t-1));else if(f.downArrow||w==="j")n(Math.min(Wn.length-1,t+1));else if(f.return||w===" "){const y=Wn[t];a(y),r(!0)}});const h=c(w=>{try{const f=w.addConfig();u(f)}catch(f){d(`Failed to write configuration: ${f.message||f}`)}},"addMcpConfiguration"),g=Math.min(80,process.stdout.columns||80);return l?v(b,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:g,children:[m(b,{marginTop:-1,marginBottom:1,children:v(S,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",m(S,{color:"green",children:"Success"})]})}),v(b,{flexDirection:"column",paddingLeft:2,children:[m(S,{color:"green",children:l}),m(b,{marginTop:1,children:m(S,{color:"grey",children:"The agent will now be able to use Membrane's integration capabilities."})})]}),m(b,{marginTop:1,paddingLeft:2,children:m(S,{color:"white",children:"[esc/q/enter: exit]"})})]}):p?v(b,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:g,children:[m(b,{marginTop:-1,marginBottom:1,children:v(S,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",m(S,{color:"red",children:"Error"})]})}),m(b,{flexDirection:"column",paddingLeft:2,children:m(S,{color:"red",children:p})}),m(b,{marginTop:1,children:m(S,{color:"grey",children:"[esc/q/enter: exit]"})})]}):i&&o?v(b,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:g,children:[m(b,{marginTop:-1,marginBottom:1,children:v(S,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",m(S,{color:"cyan",children:"Confirmation"})]})}),v(b,{flexDirection:"column",paddingLeft:2,children:[v(S,{children:["Connect ",m(S,{bold:!0,children:o.name})," to Membrane via MCP?"]}),m(b,{marginTop:1,children:m(S,{color:"grey",children:"This will add an MCP server configuration that allows the agent to use Membrane's integration capabilities."})}),m(b,{marginTop:1,children:m(S,{color:"yellow",bold:!0,children:o.actionDescription})}),m(b,{marginTop:2,marginBottom:1,children:v(S,{children:[m(S,{color:"white",bold:!0,children:"[Enter] Confirm"})," ",m(S,{color:"gray",children:"[Esc] Cancel"})]})})]})]}):v(b,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:g,children:[m(b,{marginTop:-1,marginBottom:1,children:v(S,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",m(S,{color:"cyan",children:"Select Agent"})]})}),v(b,{flexDirection:"column",paddingLeft:2,children:[m(S,{color:"grey",children:"Choose an agent to connect to Membrane via MCP:"}),m(b,{marginTop:1,children:m(S,{color:"grey",children:"This will add an MCP server configuration that allows the agent to use Membrane's integration capabilities."})}),m(b,{marginTop:1,flexDirection:"column",children:Wn.map((w,f)=>v(b,{children:[v(S,{color:t===f?"cyan":"white",children:[t===f?"\u25B6 ":" ",w.name]}),v(S,{color:"grey",children:[" \u2014 ",w.description]})]},w.id))})]}),m(b,{marginTop:1,children:m(S,{color:"grey",children:"[\u2191\u2193: select] [enter: choose] [esc: exit]"})})]})}c(fa,"AddMcpServerScreen");function ha(){const[s,e]=j(null),[t,n]=j([]),[i,r]=j(null);return Ie(()=>{const o=c(({status:l})=>{e(l),r(null)},"handleMcpStatusChanged"),a=c(({servers:l})=>{n(l),r(null)},"handleMcpServersChanged");return de.on(J.McpStatusChanged,o),de.on(J.McpServersChanged,a),()=>{de.off(J.McpStatusChanged,o),de.off(J.McpServersChanged,a)}},[]),{mcpStatus:s,allMcpServers:t,error:i,isRunning:s?.isRunning||!1,toolsCount:s?.toolsCount||0,totalRequests:s?.totalRequests||0,lastActivity:s?.lastActivity,processId:s?.processId,serverCount:t.length}}c(ha,"useMcpStatus");function da(){const{error:s,serverCount:e,allMcpServers:t}=ha(),n=Math.min(100,process.stdout.columns||100);return v(b,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:n,children:[m(b,{marginTop:-1,marginBottom:0,flexDirection:"column",children:v(S,{bold:!0,children:["\u{1F916} Connected AI Agents:"," ",s?m(S,{color:"red",children:"error reading status"}):e===0?m(S,{color:"yellow",children:"none"}):m(S,{color:"green",children:e})]})}),!s&&e===0&&m(b,{marginTop:1,children:v(S,{color:"grey",children:["Connect your AI agents to Membrane.",m(Wi,{}),"It will give them tools and context to build integrations."]})}),t.length>0&&m(b,{flexDirection:"column",paddingLeft:2,marginTop:1,children:t.map((i,r)=>m(b,{children:v(S,{color:"grey",children:["#",r+1," ",i.agentName,": ",i.totalRequests," calls"]})},i.processId))}),m(b,{marginTop:1,children:m(S,{color:"grey",children:"[a: connect an agent]"})})]})}c(da,"Agent");const zt=c(s=>{switch(s){case"error":return"red";case"success":return"green";case"warning":return"yellow";default:return}},"getLogColor");function $i(s,e){return e<3?s.slice(0,Math.max(0,e)):s.length<=e?s:`${s.slice(0,e-3)}...`}c($i,"truncateText");function Gn({children:s}){const{state:e,logs:t}=ce();if(!e||e===L.NOT_INITIALIZED)return v(b,{gap:1,flexDirection:"row",children:[m(fr,{type:"dots"}),m(S,{children:"Initializing..."})]});if(e===L.SETTING_UP)return m(b,{gap:1,flexDirection:"row",children:m(S,{children:"No workspace selected. Please run `membrane init` to select a workspace."})});if(e===L.ERROR){const n=t.filter(i=>i.type==="error");return m(b,{gap:1,flexDirection:"row",children:n.slice().map((i,r)=>m(S,{color:zt(i.type),children:i.message},i.timestamp+r))})}return s}c(Gn,"EnsureInitialized");function Li({onExit:s,showEscOption:e=!0}){const[t,n]=j(""),{data:i,error:r,isLoading:o}=rs("/account"),{updateConfig:a}=ce(),l=i?.workspaces,u=o;if(Pe((f,y)=>{y.escape&&s?.()}),u)return v(b,{children:[m(wt,{}),m(S,{children:" Fetching workspaces..."})]});if(r)return v(b,{flexDirection:"column",children:[v(S,{color:"red",children:["Error: ",r.message]}),m(b,{marginTop:1,children:m(S,{color:"grey",children:"Press ESC to go back"})})]});const p=l?.filter(f=>f.name.toLowerCase().includes(t.toLowerCase()))??[],d=p.map(f=>({label:f.name,value:f.id})),h=d.length,g=l?.length??0;async function w(f){const y=p.find(A=>A.id===f);if(!y)return;const{key:C,secret:E}=y;!C||!E||(await a({workspaceKey:C,workspaceSecret:E}),s?.())}return c(w,"handleSelect"),v(b,{flexDirection:"column",borderStyle:"round",borderTop:!0,width:70,paddingX:1,children:[m(b,{marginTop:-1,children:m(S,{bold:!0,children:"\u{1F4C1} Select your workspace"})}),v(b,{marginTop:1,children:[m(S,{children:"Search: "}),m(hr,{placeholder:"Enter a search query...",onChange:n})]}),g>5&&v(S,{children:["Showing ",h," of ",g," workspaces."]}),m(b,{marginTop:1,children:m(dr,{options:d,onChange:c(f=>{f&&w(f)},"onChange")})}),e&&m(b,{marginTop:1,children:m(S,{color:"grey",children:"Press ESC to go back"})})]})}c(Li,"SelectWorkspace");function pa({currentPat:s,onSubmit:e}){const[t,n]=j(""),[i,r]=j(!1),[o,a]=j(null);return v(b,{flexDirection:"column",borderStyle:"round",borderTop:!0,width:70,paddingX:1,children:[m(b,{marginTop:-1,marginBottom:1,children:m(S,{bold:!0,children:"\u{1F511} Enter your Personal Access Token"})}),m(S,{children:"Please provide your Personal Access Token. You can find it here:"}),m(b,{marginTop:1,marginBottom:1,children:m(S,{color:"yellow",children:"https://console.integration.app/w/0/manage-account/api-token"})}),s&&m(S,{dimColor:!0,children:"Press Enter to keep your current token or type a new one."}),m(pr,{mask:"*",placeholder:`${s?"******":"Enter your token here..."}`,value:t,onChange:n,onSubmit:c(async u=>{a(null),r(!0);try{await e(u),n("")}catch{a("Invalid token. Please try again.")}finally{r(!1)}},"handleSubmit")}),i&&m(b,{marginTop:1,children:v(S,{children:[m(wt,{type:"dots"})," Validating token..."]})}),o&&m(S,{color:"red",children:o})]})}c(pa,"PersonalAccessTokenInput");var pt=(s=>(s[s.Authenticate=0]="Authenticate",s[s.ConnectWorkspace=1]="ConnectWorkspace",s))(pt||{});const ma={0:"Authenticate in Membrane",1:"Connect a Membrane Workspace"},Vn=[pt.Authenticate,pt.ConnectWorkspace];function Di({onComplete:s}){const{config:e}=ce(),[t,n]=j(!1),[i,r]=j(0),o=!!(e?.workspaceKey&&e?.workspaceSecret),a=ps(),l=Vn[i],u=i+1,p=Vn.length,d=Vn.map((w,f)=>{let y="pending";return f<i?y="done":f===i&&(y="current"),{id:w,label:ma[w],status:y}});async function h(w){const f=a&&w===""?a:w,y=new ms;try{await y.request("/account",{headers:{Authorization:`Bearer ${f}`}}),Or(f),r(C=>C+1)}catch(C){console.error(C)}}c(h,"handlePatSubmit");function g(){n(!0),s&&s()}return c(g,"handleWorkspaceSelected"),Pe((w,f)=>{o&&f.escape&&s&&s()}),t?m(b,{children:m(S,{children:"\u2705 Setup complete. You are ready to go!"})}):v(b,{flexDirection:"column",alignSelf:"flex-start",gap:1,children:[v(b,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:70,children:[m(b,{marginTop:-1,marginBottom:1,children:v(S,{bold:!0,children:["\u{1F6E0}\uFE0F Setup \u2014"," ",v(S,{color:"cyan",children:["Step ",u," of ",p]}),o&&m(S,{color:"grey",children:" [esc: go back]"})]})}),m(b,{flexDirection:"column",paddingLeft:2,children:d.map(w=>m(ga,{status:w.status,label:w.label},w.id))})]}),l===pt.Authenticate&&m(pa,{currentPat:a,onSubmit:h}),l===pt.ConnectWorkspace&&m(Li,{onExit:g,showEscOption:!1})]})}c(Di,"Setup");function ga({status:s,label:e}){return v(b,{children:[v(b,{width:2,children:[s==="current"&&m(wt,{type:"dots"}),s==="done"&&m(S,{children:"\u2705"})]}),m(S,{dimColor:s!=="current",children:e})]})}c(ga,"StepDisplay");function Hn(){const{stats:s}=ce(),e=Object.entries(s).filter(([t,n])=>n>0);return e.length===0?null:v(b,{flexDirection:"column",children:[m(b,{children:m(b,{width:12,children:m(S,{color:"grey",children:"Elements:"})})}),m(b,{flexDirection:"column",marginLeft:1,children:e.map(([t,n])=>v(b,{children:[m(b,{width:20,children:v(S,{children:[t,":"]})}),m(S,{color:"green",children:n})]},t))})]})}c(Hn,"ElementStats");const Yn=5,ya=6;function wa(){const{logs:s}=ce(),[e,t]=j(0),n=Math.min(100,process.stdout.columns||100),i=Yn,r=Math.max(0,s.length-i-e),o=s.length-e,a=s.slice(r,o),l=n-ya,u=e<s.length-i,p=e>0;return Pe((d,h)=>{if(s.length!==0)if(h.upArrow){const g=Math.max(0,s.length-i);t(w=>Math.min(g,w+1))}else h.downArrow?t(g=>Math.max(0,g-1)):(d==="G"||d==="g")&&t(0)}),v(b,{flexDirection:"column",paddingTop:1,children:[v(S,{color:"grey",children:["Recent Activity (",r+1,"-",o," of ",s.length,"):",s.length>Yn&&m(S,{color:"grey",children:" [arrows: scroll] [g: end]"})]}),a.map((d,h)=>m(b,{marginLeft:1,children:m(S,{color:zt(d.type),children:$i(d.message,l)})},d.timestamp+h)),s.length>Yn&&v(b,{marginLeft:1,flexDirection:"row",children:[u&&m(S,{color:"grey",children:"\u2191 "}),p&&m(S,{color:"grey",children:"\u2193 "})]})]})}c(wa,"Logs");const Qt=[{value:"sync",label:"Continue (overwrite/delete)",key:""},{value:"exit",label:"Cancel",key:""}];function ba(){const{state:s,resolveConflicts:e,exit:t}=ce(),[n,i]=j(0),[r,o]=j(!1),[a,l]=j(!1);return Pe((u,p)=>{if(!r){if(p.ctrl&&u.toLowerCase()==="r"){l(!a);return}p.upArrow?i(d=>d>0?d-1:Qt.length-1):p.downArrow?i(d=>d<Qt.length-1?d+1:0):u.toLowerCase()==="y"?i(0):u.toLowerCase()==="n"?i(1):(p.return||u===" ")&&(o(!0),Qt[n].value==="sync"?e({watch:!0}):t())}}),Ie(()=>{s!==L.CONFLICTS&&r&&o(!1)},[s,r]),v(b,{flexDirection:"column",paddingTop:1,children:[m(b,{children:m(b,{flexDirection:"row",gap:2,children:m(S,{bold:!0,color:"white",children:"Conflicts with remote"})})}),m(b,{children:m(S,{color:"grey",children:"The remote workspace has changes that aren't in your local workspace:"})}),m(b,{marginTop:1,marginLeft:2,children:m(zn,{isExpanded:a})}),v(b,{marginTop:2,flexDirection:"row",gap:1,children:[m(S,{color:"white",bold:!0,children:"What would you like to do?"}),m(S,{color:"grey",children:"[up/down, enter]"})]}),m(b,{children:r?v(b,{flexDirection:"row",gap:1,children:[m(wt,{type:"dots"}),m(S,{color:"blue",bold:!0,children:"Syncing with remote..."})]}):m(b,{flexDirection:"column",children:Qt.map((u,p)=>m(b,{flexDirection:"column",children:v(b,{flexDirection:"row",gap:1,children:[m(S,{color:n===p?"cyan":"grey",children:n===p?"\u25B6":" "}),m(S,{color:n===p?"cyan":"grey",bold:n===p,children:u.label})]})},u.value))})})]})}c(ba,"ResolveChangesUI");const Sa={[X.UPDATE]:{incoming:{label:"Elements updated in remote",description:"(to be overwritten from remote)"},outgoing:{label:"Elements updated locally",description:"(to be pushed to remote)"}},[X.DELETE]:{incoming:{label:"Elements not existing in remote",description:"(to be deleted locally)"},outgoing:{label:"Elements deleted locally",description:"(to be deleted from remote)"}},[X.CREATE]:{incoming:{label:"Elements created in remote",description:"(to be created locally)"},outgoing:{label:"Elements created locally",description:"(to be created in remote)"}}};function zn({isExpanded:s}){const{conflicts:e}=ce(),t=5,n=Hi(()=>{const i={};return e.forEach(r=>{const o=`${r.type}-${r.direction}`;i[o]||(i[o]=[]),i[o].push(r)}),i},[e]);return m(b,{flexDirection:"column",children:Object.entries(n).map(([i,r])=>{if(r.length===0)return null;const[o,a]=i.split("-"),l=Sa[o][a];return v(b,{flexDirection:"column",children:[v(b,{flexDirection:"row",gap:1,children:[v(S,{color:"yellow",children:[l.label," (",r.length,")"]}),m(S,{color:"white",children:l.description})]}),(s?r:r.slice(0,t)).map(u=>m(b,{marginLeft:2,children:v(S,{color:"grey",children:["\u2022 ",u.element.id," (",u.element.relativePath,")"]})},u.element.id)),!s&&r.length>t&&m(b,{marginLeft:2,children:v(S,{color:"cyan",children:["... and ",r.length-t," more (press Ctrl+R to show all)"]})}),s&&r.length>t&&m(b,{marginLeft:2,children:m(S,{color:"cyan",children:"(press Ctrl+R to collapse)"})})]},i)})})}c(zn,"Conflicts");function Ca(){const{config:s,state:e,logs:t,currentWorkspace:n,pull:i}=ce(),r=n?.name,o=r?$i(r,30):s?.workspaceKey,a=Math.min(100,process.stdout.columns||100);return Ie(()=>{i({watch:!0})},[]),v(b,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:a,children:[m(b,{marginTop:-1,marginBottom:1,children:v(b,{flexDirection:"row",gap:1,children:[m(S,{bold:!0,children:"\u{1F504} Workspace"}),v(S,{color:Ea(e),children:[" [",ka(e),"] "]})]})}),v(b,{children:[m(b,{width:12,children:m(S,{color:"grey",children:"Local:"})}),m(S,{color:"grey",children:process.cwd()})]}),v(b,{children:[m(b,{width:12,children:m(S,{color:"grey",children:"Remote:"})}),s?.workspaceKey?v(S,{color:"grey",children:[o," [o: open in console] [w: change]"]}):v(S,{children:[m(S,{color:"yellow",children:"not selected"})," [w: select]"]})]}),e===L.CONFLICTS?m(ba,{}):v(en,{children:[m(b,{paddingTop:1,children:m(Hn,{})}),t.length>0&&m(wa,{})]})]})}c(Ca,"Workspace");function ka(s){switch(s){case L.PULLING:return"pulling";case L.PUSHING:return"pushing";case L.CONFLICTS:return"conflicts";case L.SYNCED:return"synced";case L.ERROR:return"error";case L.WATCHING:return"tracking changes";case L.RESOLVING:return"resolving";case L.NOT_SYNCED:return"not synced";case L.INITIALIZED:return"initialized";case L.SETTING_UP:return"setup required";default:return"unknown"}}c(ka,"getStatusDisplay");function Ea(s){switch(s){case L.PULLING:return"yellow";case L.PUSHING:return"yellow";case L.CONFLICTS:return"red";case L.SYNCED:return"green";case L.ERROR:return"red";case L.WATCHING:return"green";case L.RESOLVING:return"yellow";case L.NOT_SYNCED:return"grey";case L.SETTING_UP:return"yellow";default:return"grey"}}c(Ea,"getStatusColor");const va="https://console.integration.app/w";function Ia(){const s=ua(),e=Yi(!0),{exit:t,state:n}=ce(),[i,r]=j(null),o=i??(n===L.SETTING_UP?"setup":"main");Pe(l=>{o==="main"&&(l==="w"&&r("workspace-selection"),l==="a"&&r("add-mcp-server"),l==="o"&&n===L.INITIALIZED&&a(),l==="s"&&r("setup"))});async function a(){try{const l=await gs(s),u=`${va}/${l}`,p=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";ur(`${p} "${u}"`)}catch(l){console.error("Failed to open workspace:",l),t()}}return c(a,"handleOpenWorkspace"),Ie(()=>(e.current=!0,()=>{e.current=!1}),[]),o==="workspace-selection"?m(Li,{onExit:c(()=>r(null),"onExit")}):o==="add-mcp-server"?m(fa,{onExit:c(()=>r(null),"onExit"),onComplete:c(()=>r(null),"onComplete")}):o==="setup"?m(Di,{onComplete:c(()=>r(null),"onComplete")},Date.now()):m(Gn,{children:v(b,{flexDirection:"column",children:[m(b,{flexGrow:1,children:m(da,{})}),m(Ca,{}),m(b,{paddingLeft:2,children:m(S,{color:"grey",children:"[s: (re-)setup]"})})]})})}c(Ia,"Main");const xi=Gi(process.argv.slice(2)),Pi=xi.cwd?qi(xi.cwd):process.cwd(),Ta=new Ni(dt.Agent,Pi),Na=c(()=>m(Yt,{cwd:Pi,membraneCLIService:Ta,children:m(Ia,{})}),"App");function Aa(){gt(m(Na,{}))}c(Aa,"runAgent");function Oa(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(`
141
- `)).action(t=>{t.key&&t.secret?et.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)):gt(Re.createElement(Yt,{membraneCLIService:e,children:Re.createElement(Di,{onComplete:c(()=>process.exit(0),"onComplete")})}))})}c(Oa,"setupInitCommand");async function Ri(s,e){const t={iss:s,exp:Math.floor(Date.now()/1e3)+600,isAdmin:!0};return rn.sign(t,e)}c(Ri,"generateAdminAccessToken");async function $a(s,e){return(await on.get(`${s}/docs-json`,{headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}})).data}c($a,"fetchOpenApiSchema");function Mi(s,e=!0){if(!s)return e?z.string():z.string().optional();let t;switch(s.type){case"integer":t=z.coerce.number().int();break;case"number":t=z.coerce.number();break;case"boolean":t=z.coerce.boolean();break;case"string":default:t=z.string();break}return s.format==="uuid"?t=z.string().uuid():s.format==="email"?t=z.string().email():s.format==="date"?t=z.string().regex(/^\d{4}-\d{2}-\d{2}$/):s.format==="date-time"&&(t=z.string().datetime()),s.enum&&(t=z.enum(s.enum)),(s.type==="integer"||s.type==="number")&&(s.minimum!==void 0&&(t=t.min(s.minimum)),s.maximum!==void 0&&(t=t.max(s.maximum))),s.type==="string"&&(s.minLength!==void 0&&(t=t.min(s.minLength)),s.maxLength!==void 0&&(t=t.max(s.maxLength))),e?t:t.optional()}c(Mi,"convertOpenApiSchemaToZod");function _i(s){const e=s.match(/\{([^}]+)\}/g);return e?e.map(t=>t.slice(1,-1)):[]}c(_i,"extractPathParameters");function La(s,e,t,n,i,r){const o=s.operationId||`${t}_${e.replace(/[^a-zA-Z0-9]/g,"_")}`,a=s.description||s.summary||`${t.toUpperCase()} ${e}`,l={},u={},p={};if(s.parameters){for(const h of s.parameters)if(h.in==="path")u[h.name]=Mi(h.schema,!0).describe(h.description||`Path parameter: ${h.name}`);else if(h.in==="query"){const g=h.required===!0;p[h.name]=Mi(h.schema,g).describe(h.description||`Query parameter: ${h.name}`)}}Object.keys(u).length>0&&(l.params=z.object(u).describe("Path parameters")),Object.keys(p).length>0&&(l.query=z.object(p).describe("Query parameters")),s.requestBody&&s.requestBody.content&&s.requestBody.content["application/json"]&&(l.body=z.any().describe("Request body"));const d=Object.keys(l).length>0?z.object(l):z.object({});return{name:o,description:a,parameters:d,async execute(h){try{const g=_i(e);if(g.length>0){if(!h.params)throw new Error(`Missing required path parameters: ${g.join(", ")}`);const I=g.filter(O=>!(O in h.params));if(I.length>0)throw new Error(`Missing required path parameters: ${I.join(", ")}`)}let w=`${n}${e}`;if(h.params)for(const[I,O]of Object.entries(h.params)){const $=`{${I}}`;w.includes($)&&(w=w.replace($,String(O)))}const f=_i(w);if(f.length>0)throw new Error(`Unresolved path parameters: ${f.join(", ")}`);const y=new URLSearchParams;if(h.query)for(const[I,O]of Object.entries(h.query))O!=null&&y.append(I,String(O));y.toString()&&(w+=`?${y.toString()}`);const C=await Ri(i,r),E={method:t.toUpperCase(),headers:{Authorization:`Bearer ${C}`,"Content-Type":"application/json"}};h.body&&t.toLowerCase()!=="get"&&(E.data=h.body);const A=await on.request({url:w,...E});return{content:[{type:"text",text:JSON.stringify(A.data,null,2)}]}}catch(g){return on.isAxiosError(g)?{content:[{type:"text",text:`Error: ${g.response?.data?`HTTP ${g.response.status}: ${g.response.statusText} - ${JSON.stringify(g.response.data)}`:`HTTP ${g.response?.status||"unknown"}: ${g.message}`}`}],isError:!0}:g instanceof Error?{content:[{type:"text",text:`Error: API call failed: ${g.message}`}],isError:!0}:{content:[{type:"text",text:"Error: API call failed with unknown error"}],isError:!0}}}}}c(La,"createApiTool");function Da(s,e,t,n){const i=[];if(!s.paths)return i;for(const[r,o]of Object.entries(s.paths))if(typeof o=="object"&&o!==null){for(const[a,l]of Object.entries(o))if(["get","post","put","delete","patch"].includes(a)&&l&&typeof l=="object"){const u=La(l,r,a,e,t,n);i.push(u)}}return i}c(Da,"convertOpenApiToTools");function xa(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(`
142
- `)).action(async()=>{try{process.env.FASTMCP_SUPPRESS_WARNINGS="true";const e=St();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"),process.exit(1));const t=e.apiUri||cn,n=await Ri(e.workspaceKey,e.workspaceSecret),i=await $a(t,n),r=Da(i,t,e.workspaceKey,e.workspaceSecret),o=new yr({name:"Membrane API",instructions:`This MCP server lets you interact with Membrane to configure, run, and troubleshoot integrations.
140
+ `,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=Wt(e),n=Ve(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=Wt(e),n=Ve(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 Si(s){const e=s.prettyErrors!==!1;return{lineCounter:s.lineCounter||e&&new gi||null,prettyErrors:e}}c(Si,"parseOptions");function Bo(s,e={}){const{lineCounter:t,prettyErrors:n}=Si(e),i=new Mn(t?.addNewLine),r=new xn(e),o=Array.from(r.compose(i.parse(s)));if(n&&t)for(const a of o)a.errors.forEach(Kt(s,t)),a.warnings.forEach(Kt(s,t));return o.length>0?o:Object.assign([],{empty:!0},r.streamInfo())}c(Bo,"parseAllDocuments");function Ci(s,e={}){const{lineCounter:t,prettyErrors:n}=Si(e),i=new Mn(t?.addNewLine),r=new xn(e);let o=null;for(const a of r.compose(i.parse(s),!0,s.length))if(!o)o=a;else if(o.options.logLevel!=="silent"){o.errors.push(new $e(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return n&&t&&(o.errors.forEach(Kt(s,t)),o.warnings.forEach(Kt(s,t))),o}c(Ci,"parseDocument");function qo(s,e,t){let n;typeof e=="function"?n=e:t===void 0&&e&&typeof e=="object"&&(t=e);const i=Ci(s,t);if(!i)return null;if(i.warnings.forEach(r=>xs(i.options.logLevel,r)),i.errors.length>0){if(i.options.logLevel!=="silent")throw i.errors[0];i.errors=[]}return i.toJS(Object.assign({reviver:n},t))}c(qo,"parse");function Uo(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 i=Math.round(t);t=i<1?void 0:i>8?{indent:8}:{indent:i}}if(s===void 0){const{keepUndefined:i}=t??e??{};if(!i)return}return Te(s)&&!n?s.toString(t):new Qe(s,n,t).toString(t)}c(Uo,"stringify");var Jo=Object.freeze({__proto__:null,Alias:Ct,CST:Ko,Composer:xn,Document:Qe,Lexer:mi,LineCounter:gi,Pair:X,Parser:Mn,Scalar:x,Schema:Xt,YAMLError:Tn,YAMLMap:ne,YAMLParseError:$e,YAMLSeq:Se,YAMLWarning:ti,isAlias:be,isCollection:U,isDocument:Te,isMap:Me,isNode:J,isPair:B,isScalar:_,isSeq:_e,parse:qo,parseAllDocuments:Bo,parseDocument:Ci,stringify:Uo,visit:Ne,visitAsync:St});const z={Added:"added",Changed:"changed",Deleted:"deleted",Stopped:"stopped"},Wo={ignored:kr,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 Go extends fs{static{c(this,"FileWatcher")}constructor(e){super(),this.options=e,this.membraneDir=wt(this.options.cwd)}isWatching=!1;watcher;membraneDir;contentCache={};async start(){this.isWatching||(P.existsSync(this.membraneDir)||P.mkdirSync(this.membraneDir,{recursive:!0}),this.initializeContentCache(),this.watcher=ir.watch(this.membraneDir,Wo),this.watcher.on("add",e=>this.handleFileSystemEvent(z.Added,e)).on("change",e=>this.handleFileSystemEvent(z.Changed,e)).on("unlink",e=>this.handleFileSystemEvent(z.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.emit(z.Stopped))}getCwd(){return this.options.cwd}handleFileSystemEvent(e,t){const n=R.relative(this.membraneDir,t);if(e===z.Deleted){this.removeFromCache(n);const a={filePath:t,relativePath:n,data:void 0};N.info(`[local] ${e}: ${a.relativePath}`),this.emit(e,a);return}const i=this.readFileContent(t);if(!this.hasContentChanged(n,i,e))return;const o=this.processFileEvent(t,i);this.updateCache(n,i),o&&(N.info(`[local] ${e}: ${o.relativePath}`),this.emit(e,o))}readFileContent(e){return P.readFileSync(e,"utf8")}processFileEvent(e,t){const n=R.relative(this.membraneDir,e);let i;try{i=t?Jo.parse(t):void 0}catch{i=void 0}return{filePath:e,relativePath:n,data:i}}hasContentChanged(e,t,n){if(n==="added")return!0;if(!t)return this.contentCache[e]!==void 0;const i=this.getContentHash(t);return this.contentCache[e]!==i}getContentHash(e){return nr.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(){P.existsSync(this.membraneDir)&&this.scanDirectoryForCache(this.membraneDir)}scanDirectoryForCache(e){const t=P.readdirSync(e,{withFileTypes:!0});for(const n of t){const i=R.join(e,n.name);if(n.isDirectory())this.scanDirectoryForCache(i);else if(n.isFile())try{const r=P.readFileSync(i,"utf8"),o=R.relative(this.membraneDir,i);this.updateCache(o,r)}catch{}}}}const Z={UPDATE:"update",DELETE:"delete",CREATE:"create"},se={INCOMING:"incoming",OUTGOING:"outgoing"};async function Vo(s="full"){const e={};N.info("[connectors] Getting remote workspace data");const t=await F.withClient(n=>n.integrations.findAll());e.integration=t.map(n=>_n("integration",n));for(const n of Object.keys(ie)){const i=ie[n];if(i.exportable===!1)continue;const r=[];N.info(`[connectors] Reading ${i.elements} from remote workspace`);const o=await F.withClient(a=>a[i.elements].findAll());if(r.push(...o.map(a=>_n(n,a))),i.integrationSpecific)for(const a of t){const l=await F.withClient(u=>u[i.elements].findAll({integrationId:a.id}));r.push(...l.map(u=>(u.integrationKey=a.key,_n(n,u))))}r.length>0&&s=="full"&&(console.table(r.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]=r}return N.success("[connectors] Remote workspace data retrieved successfully"),e}c(Vo,"getWorkspaceData");function _n(s,e){return e=Sr(e),ie[s].exportCleanup?ie[s].exportCleanup(e):e}c(_n,"cleanUpForExport");const lt="connectors",ut="development",Kn={};async function Ho({integrations:s,allConnectors:e=!1}){const t=Tr(),n=new Set,i={};for(const r of s){const o=r.connectorId,a=r.connectorVersion;if(!i[o]?.has(r.connectorVersion)){const l=await ki({connectorId:o}),p=!!l.workspaceId||e;if(!l?.key){N.error(`[connectors] Connector ${o} has no key. Skipping..`);continue}p&&(n.has(o)||(await Zo({basePath:t,connector:l}),n.add(o)),i[o]||(i[o]=new Set),i[o].has(a)||(await ea({connector:l,connectorVersion:a,basePath:t}),i[o].add(a)))}}}c(Ho,"pullConnectors");async function Yo(){const s=await Vo("minified"),t=(await F.withClient(l=>l.get("org-workspace-id"))).id,n={};N.info("[connectors] Loading custom connectors");const i=await F.withClient(l=>l.get(`/connectors?workspaceId=${t}`));N.info("[connectors] Loading public connectors"),s.connector=i;const r=jn(),a=(D.existsSync(r)?D.readdirSync(r):[]).filter(l=>{if(l.startsWith("."))return!1;const u=q.join(r,l);try{return D.statSync(u).isDirectory()}catch{return!1}});for(const l of a){N.info(`[connectors] Loading connector from: ${l}`);const u=D.readdirSync(q.join(r,l)),p=await Fn(l);if("baseUri"in p&&delete p.baseUri,p.uuid&&s.connector?.find(h=>h.uuid==p.uuid))n[p.id]=s.connector.find(h=>h.uuid==p.uuid).id,N.info(`[connectors] Matched ${p.name} uuid: ${p.uuid}`);else if(!n[p.id]){let h=!1;try{const g=await ki({connectorId:p.id});g&&!g.workspaceId&&(h=!0)}catch{}if(!h){N.info(`[connectors] Creating custom connector ${p.name} (${p.key})`);const g=await F.withClient(w=>w.post("connectors",{...p,workspaceId:t}));n[p.id]=g.id}}const d=u.filter(h=>D.statSync(q.join(r,l,h)).isDirectory());for(const h of d)await Xo({connector:p,version:h,connectorId:n[p.id]})}return n}c(Yo,"pushConnectors");function jn(){const s=cn();return q.join(s.membraneDirPath,lt)}c(jn,"getConnectorsPath");async function Fn(s){return Ie.load(D.readFileSync(q.join(jn(),s,`${s}.yml`),"utf8"))}c(Fn,"readConnector");async function zo(s,e){return N.info(`[connectors] Zipping ${s} into ${e}`),new Promise((t,n)=>{const i=D.createWriteStream(e),r=rr("zip",{zlib:{level:9}});i.on("close",()=>{N.success(`[connectors] Successfully created ${e}`),t()}),i.on("end",()=>{N.info("[connectors] Data has been drained")}),r.on("warning",a=>{a.code==="ENOENT"?console.warn(a):n(a)}),r.on("error",a=>{n(a)}),r.pipe(i);const o=D.readdirSync(s);for(const a of o){const l=q.join(s,a),u=D.statSync(l);u.isFile()?r.file(l,{name:a}):u.isDirectory()&&r.directory(l,a)}r.finalize()})}c(zo,"createZipArchive");async function Qo(s,e){return N.info(`[connectors] Unzipping into ${e}`),new Promise((t,n)=>{const i=ar.Parse();i.on("entry",r=>{const o=r.path;if(r.type==="Directory"){const l=q.join(e,o);D.mkdirSync(l,{recursive:!0}),r.autodrain()}else{const l=q.join(e,o),u=q.dirname(l);D.mkdirSync(u,{recursive:!0});const p=D.createWriteStream(l);r.pipe(p),p.on("finish",()=>{})}}),i.on("end",()=>{N.success(`[connectors] Successfully extracted to ${e}`),t()}),i.on("error",r=>{n(r)}),i.write(s),i.end()})}c(Qo,"extractZipArchive");async function Xo({connector:s,version:e,connectorId:t}){const n=q.join(jn(),Gt(s),Ei(e)),i=q.join(n,"src"),r=q.join(n,"src.zip"),o=D.existsSync(r);if(D.existsSync(i)&&(N.info(`[connectors] Archiving source code for ${s.name} version ${e}`),await zo(i,r)),!D.existsSync(r)){N.warning(`[connectors] No source code found for ${s.name} version ${e}`);return}try{const a=new or;if(a.append("file",D.createReadStream(r),"file.zip"),N.info(`[connectors] Pushing connector version ${e} for ${s.name}`),e==ut)N.info(`[connectors] Uploading connector ${t}`),await F.withClient(l=>l.post(`connectors/${t}/upload`,a,{headers:{...a.getHeaders()}}));else{if(a.append("version",e),a.append("changelog","Imported Version"),(await F.withClient(u=>u.get(`/connectors/${t}/versions`))).find(u=>u.version==e)){N.info(`[connectors] Version ${e} already published`);return}N.info(`[connectors] Publishing version ${e} of connector ${t}`),await F.withClient(u=>u.post(`connectors/${t}/publish-version`,a,{headers:{...a.getHeaders()}}))}N.success(`Successfully pushed connector version ${e} for ${s.name}`)}catch(a){N.error(`Error pushing connector version ${e} for ${s.name}: ${a}`)}finally{!o&&D.existsSync(r)&&(N.info(`[connectors] Cleaning up temporary zip file for ${s.name} version ${e}`),D.unlinkSync(r))}}c(Xo,"pushConnectorVersion");async function ki({connectorId:s}){if(Kn[s])return Kn[s];const e=await F.withClient(t=>t.get(`connectors/${s}`));return Kn[s]=e,e}c(ki,"getConnector");async function Zo({basePath:s,connector:e}){const t=Gt(e),n=q.join(s,lt,t);D.mkdirSync(n,{recursive:!0});const i=q.join(n,`${Gt(e)}.yml`);D.writeFileSync(i,Ie.dump(e)),N.info(`[connectors] Pulled connector ${e.name}`)}c(Zo,"pullConnector");async function ea({connector:s,connectorVersion:e,basePath:t}){const n=Gt(s),i=Ei(e),r=q.join(t,"connectors",n,i),o=await F.withClient(l=>l.get(`connectors/${s.id}/download`,{version:e},{responseType:"arraybuffer",headers:{Accept:"application/zip"},timeout:1e6}));D.mkdirSync(r,{recursive:!0});const a=q.join(r,"src.zip");if(D.writeFileSync(a,o),!e){const l=q.join(r,"src");D.mkdirSync(l,{recursive:!0}),await Qo(o,l)}N.info(`[connectors] Pulled connector version: ${s.name} (${i})`)}c(ea,"pullConnectorVersion");function Gt(s){return s.key}c(Gt,"getConnectorDirName");function Ei(s){return s??ut}c(Ei,"getConnectorVersionDirName");function ta(s){return s.match(`${lt}/[^/]+/${ut}/src/.*`)!==null}c(ta,"isConnectorSourceFile");async function na(s){const e=s.match(`${lt}/([^/]+)/${ut}/src/(.*)`);if(!e)return;const t=e[1],n=e[2],i=await Fn(t);if(!i){N.warning(`[connectors] Connector ${t} not found. Ignoring file change`);return}const r=i.id,o=D.readFileSync(s,"utf-8");await F.withClient(a=>a.put(`connectors/${r}/files/${n}`,o,{headers:{"Content-Type":"text/plain"}})),N.info(`[connectors] Pushed file ${n} for connector ${i.name}`)}c(na,"putConnectorFile");async function sa(s){const e=s.match(`${lt}/([^/]+)/${ut}/src/(.*)`);if(!e)return;const t=e[1],n=e[2],i=await Fn(t);if(!i){N.warning(`[connectors] Connector ${t} not found. Ignoring file change`);return}const r=i.id;await F.withClient(o=>o.delete(`connectors/${r}/files/${n}`)),N.info(`[connectors] Deleted file ${n} for connector ${i.name}`)}c(sa,"deleteConnectorFile");class pt{static{c(this,"ElementSyncService")}fileWatcher=void 0;notifier;changes=[];localCache;remoteCache;localRepo;remoteRepo;constructor(){this.notifier=de,this.localCache=new ys,this.remoteCache=new ys,this.localRepo=new Pr(this.localCache),this.remoteRepo=new Dr(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),i=this.getCache(t);try{const r=await n.putElement(e);i.put(r)}catch(r){throw N.error(`Failed to update element ${e.id}: ${r}`),r}}async deleteElement(e,t){const n=this.getHandler(t),i=this.getCache(t);try{await n.deleteElement(e,{elements:n.cache.getAll(),connectorsMapping:n.connectorsMapping}),i.remove(e)}catch(r){throw N.error(`Failed to delete element ${e.id}: ${r}`),r}}async pullConnectors(e=!1){await Ho({integrations:this.remoteCache.getElementsByType(M.Integration).map(t=>t.data),allConnectors:e})}async pushConnectors(){const e=await Yo();this.remoteRepo.setConnectorsMapping(e)}getHandler(e){return e===se.INCOMING?this.localRepo:this.remoteRepo}getCache(e){return e===se.INCOMING?this.localCache:this.remoteCache}async startWatching(){this.fileWatcher=new Go({cwd:process.cwd()}),this.fileWatcher.on(z.Added,e=>this.handleLocalEvent(e,z.Added)),this.fileWatcher.on(z.Changed,e=>this.handleLocalEvent(e,z.Changed)),this.fileWatcher.on(z.Deleted,e=>this.handleLocalEvent(e,z.Deleted)),await this.fileWatcher.start(),N.success("[local] Tracking changes..")}async stopWatching(){await this.fileWatcher?.stop(),this.fileWatcher=void 0}async handleLocalEvent(e,t){try{if(ta(e.filePath))switch(t){case z.Added:case z.Changed:await na(e.filePath);break;case z.Deleted:await sa(e.filePath);break}else{let n=V.fromPathAndData(e.filePath,e.data);if(!n){const i=V.idFromPath(e.filePath);if(!i||(n=this.remoteCache.get(i),!n))return}switch(N.info(`[resolver][${this.getDirectionLabel(se.OUTGOING)}] ${t}: ${n.id}`),t){case z.Added:case z.Changed:await this.updateElement(n,se.OUTGOING);break;case z.Deleted:await this.deleteElement(n,se.OUTGOING);break}}}catch(n){N.error(`[sync] Error handling local event: ${n}`)}}detectIncomingChanges(){this.clearChanges();const e=pt.getChanges(se.INCOMING,this.remoteCache,this.localCache);return this.updateChanges(e),e}detectOutgoingChanges(){this.clearChanges();const e=pt.getChanges(se.OUTGOING,this.localCache,this.remoteCache);return this.updateChanges(e),e}getChange(e){const t=this.localCache.get(e.id),n=this.remoteCache.get(e.id);return!t&&n?{type:Z.CREATE,element:n,direction:se.INCOMING,isConflict:!1}:t&&!n?{type:Z.DELETE,element:t,direction:se.OUTGOING,isConflict:!0}:t&&n&&!t.isEqual(n)?{type:Z.UPDATE,element:t,direction:se.OUTGOING,isConflict:!0}:null}async resolveChanges(){if(!this.needsSync())return;N.info("[resolver] Resolving changes..");const e=this.changes.filter(i=>i.element.type===M.Integration);await Promise.all(e.map(async i=>this.resolveChange(i))),e.length>0&&(await this.fetchElements(),this.changes=this.changes.length>0&&this.changes[0]?.direction===se.INCOMING?this.detectIncomingChanges():this.detectOutgoingChanges(),this.changes=this.changes.filter(i=>i.element.type!==M.Integration));const t=this.changes.filter(i=>!i.element.hasParent()),n=this.changes.filter(i=>i.element.hasParent());await Promise.all(t.map(async i=>this.resolveChange(i))),await Promise.all(n.map(async i=>this.resolveChange(i))),N.success("[resolver] Resolved changes")}async resolveChange(e){switch(e.type){case Z.DELETE:return N.info(`[resolver][${this.getDirectionLabel(e.direction)}] Deleting ${e.element.id}`),this.deleteElement(e.element,e.direction);case Z.CREATE:return N.info(`[resolver][${this.getDirectionLabel(e.direction)}] Creating ${e.element.id}`),this.updateElement(e.element,e.direction);case Z.UPDATE:return N.info(`[resolver][${this.getDirectionLabel(e.direction)}] Updating ${e.element.id}`),this.updateElement(e.element,e.direction)}}static getChanges(e,t,n){const i=t.getAllIds(),r=n.getAllIds(),o=new Set([...i,...r]),a=[];for(const l of o){const u=t.get(l),p=n.get(l),d=pt.detectChangeForElement(u,p,e);d&&a.push(d)}return a}updateChanges(e){this.changes=e;for(const t of e)N.info(`[resolver][${this.getDirectionLabel(t.direction)}] ${this.getTypeLabel(t.type)} ${t.element.id}`);if(this.needsForcedSync()){const t=e.filter(n=>n.isConflict);N.warning("[resolver] Conflicts detected"),this.notifier.setConflicts(t)}}clearChanges(){this.changes=[]}getDirectionLabel(e){switch(e){case se.INCOMING:return"local\u2190remote";case se.OUTGOING:return"local\u2192remote"}}getTypeLabel(e){switch(e){case Z.CREATE:return"ADD";case Z.UPDATE:return"UPD";case Z.DELETE:return"DEL"}}static detectChangeForElement(e,t,n){return e&&!t?{type:Z.CREATE,element:e,direction:n,isConflict:!1}:!e&&t?{type:Z.DELETE,element:t,direction:n,isConflict:!0}:e&&t&&!e.isEqual(t)?{type:Z.UPDATE,element:e,direction:n,isConflict:!0}:null}}const ke=R.join(cr.tmpdir(),"membrane-mcp-status"),vi=3e4;class ia{static{c(this,"McpStatusService")}constructor(e=2e3){this.pollIntervalMs=e}isRunning=!1;pollInterval;async start(){this.isRunning||(this.isRunning=!0,this.pollInterval=setInterval(async()=>await this.checkStatus(),this.pollIntervalMs),await this.checkStatus())}async stop(){this.pollInterval&&(clearInterval(this.pollInterval),this.pollInterval=void 0,this.isRunning=!1)}async checkStatus(){try{const e=process.cwd(),t=Vt(void 0,e),n=Ii(e);t&&de.setMcpStatus(t),await de.setMcpServers(n)}catch{N.error("Failed to check MCP status")}}}function Vt(s,e){try{const t=e||process.cwd();if(!s){const i=Ii(t);return i.length===0?null:i[0]}const n=Un(s,t);if(P.existsSync(n)){const i=P.statSync(n),r=new Date;if(r.getTime()-i.mtime.getTime()>vi)return ft(s,t),null;const a=P.readFileSync(n,"utf8"),l=JSON.parse(a);if(l.isRunning){const u=new Date(l.lastActivity).getTime();if(r.getTime()-u>vi)return ft(s,t),null}return l}}catch{s&&e&&ft(s,e)}return null}c(Vt,"getMcpStatus");function Ii(s){try{const e=s||process.cwd(),t=qn(e);if(!P.existsSync(ke))return[];const n=P.readdirSync(ke),i=[];for(const r of n){const o=r.match(new RegExp(`^mcp-${t}-(\\d+)\\.json$`));if(o){const a=parseInt(o[1],10),l=Vt(a,e);l&&i.push(l)}}return i.sort((r,o)=>new Date(o.startTime).getTime()-new Date(r.startTime).getTime())}catch{return[]}}c(Ii,"getAllMcpStatusFiles");function Bn(s){try{const t={...Vt(s.processId,s.cwd)||{isRunning:!1,startTime:new Date().toISOString(),lastActivity:new Date().toISOString(),toolsCount:0,totalRequests:0,processId:s.processId,cwd:s.cwd,agentName:process.env.AGENT_NAME||"Unnamed Agent"},...s};P.existsSync(ke)||P.mkdirSync(ke,{recursive:!0});const n=Un(s.processId,s.cwd);P.writeFileSync(n,JSON.stringify(t,null,2))}catch{}}c(Bn,"updateMcpStatus");function ft(s,e){try{const t=e||process.cwd();if(s){const n=Un(s,t);P.existsSync(n)&&P.unlinkSync(n)}else{const n=qn(t);if(P.existsSync(ke)){const i=P.readdirSync(ke);for(const r of i)r.match(new RegExp(`^mcp-${n}-\\d+\\.json$`))&&P.unlinkSync(R.join(ke,r))}}}catch{}}c(ft,"clearMcpStatus");function ra(s,e){const t=Vt(s,e);t&&Bn({processId:s,cwd:e,totalRequests:t.totalRequests+1,lastRequestTime:new Date().toISOString(),lastActivity:new Date().toISOString()})}c(ra,"trackToolExecution");function qn(s){return sr("md5").update(s).digest("hex").slice(0,8)}c(qn,"getCwdHash");function Un(s,e){const t=qn(e);return R.join(ke,`mcp-${t}-${s}.json`)}c(Un,"getStatusFilePath");const ht={Agent:"agent",Cli:"cli"},L={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 Ti{static{c(this,"MembraneCLIService")}constructor(e,t,n=()=>process.exit(0)){this.mode=e,this.cwd=t,this.onShutdown=n,this.notifier=de,this.mcpStatusService=new ia,this.syncService=new pt,this.setupProcessCleanup()}initialized=!1;notifier;mcpStatusService;syncService;isShuttingDown=!1;currentConfig=null;get config(){return this.currentConfig}async pullWorkspace(e={}){try{if(await this.notifier.setState(L.PULLING),await this.syncService.fetchElements(),this.syncService.detectIncomingChanges(),this.syncService.needsForcedSync()&&!e.force)return this.notifier.setState(L.CONFLICTS);await this.syncService.pullConnectors(e.allConnectors),await this.syncWorkspaces(e)}catch(t){N.error(`Failed to pull workspace: ${t}`),await this.notifier.setState(L.ERROR),e?.onComplete?.()}}async pushWorkspace(e={}){try{if(await this.notifier.setState(L.PUSHING),await this.syncService.fetchElements(),this.syncService.detectOutgoingChanges(),this.syncService.needsForcedSync()&&!e.force)return await this.notifier.setState(L.CONFLICTS);await this.syncService.pushConnectors(),await this.syncWorkspaces(e)}catch(t){N.error(`Failed to push workspace: ${t}`),await this.notifier.setState(L.ERROR),e?.onComplete?.()}}async syncWorkspaces(e={}){try{await this.notifier.setState(L.RESOLVING),this.syncService.needsSync()&&await this.syncService.resolveChanges();const t=await this.syncService.getStats();this.notifier.setStats(t),await this.notifier.setState(L.SYNCED),e.watch&&(await this.notifier.setState(L.WATCHING),await this.syncService.startWatching()),e.onComplete?.()}catch(t){N.error(`Failed to sync local and remote workspaces: ${t}`),await this.notifier.setState(L.ERROR),e?.onComplete?.()}}async init({force:e=!1}={}){if(!(this.initialized&&!e)){await this.notifier.setState(L.NOT_INITIALIZED);try{await this.loadConfig(),Ze.isCacheDefined()?(await this.initServices(),this.initialized=!0,await this.notifier.setState(L.INITIALIZED)):(this.initialized=!1,await this.notifier.setState(L.SETTING_UP))}catch(t){N.error(`Failed to initialize services: ${t}`),await this.notifier.setState(L.ERROR),this.onShutdown()}}}async loadConfig(){this.currentConfig=Ze.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 i=Ze.updateConfig(t);this.currentConfig=i,await this.init({force:!0})}async shutdown(){!this.initialized||this.isShuttingDown||(this.isShuttingDown=!0,this.mode===ht.Agent&&(await this.notifier.cleanup(),await this.mcpStatusService.stop()),this.initialized=!1,this.onShutdown())}async initServices(){this.mode===ht.Agent&&(await this.notifier.connectToRemote(),await this.mcpStatusService.start()),this.syncService.clear()}async stopServices(){this.mode===ht.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 Ni=ns(null);function oa({children:s,membraneCLIService:e}){const{data:t}=is("/account"),[n,i]=j(L.NOT_INITIALIZED),[r,o]=j([]),[a,l]=j({}),[u,p]=j([]),[d,h]=j(null),w=t?.workspaces?.find(f=>f.workspaceKey===d?.workspaceKey)||null;return ve(()=>{const f=c(({state:I})=>i(I),"handleStateChanged"),y=c(({stats:I})=>l(I),"handleStatsChanged"),C=c(({log:I})=>p(O=>[...O,I]),"handleLogAdded"),E=c(({conflicts:I})=>o(I),"handleConflictsUpdated"),A=c(({config:I})=>h(I),"handleConfigChanged");return e.notifier.on(W.StateChanged,f),e.notifier.on(W.StatsChanged,y),e.notifier.on(W.LogAdded,C),e.notifier.on(W.ConflictsChanged,E),e.notifier.on(W.ConfigChanged,A),e.init(),()=>{e.notifier.off(W.StateChanged,f),e.notifier.off(W.StatsChanged,y),e.notifier.off(W.LogAdded,C),e.notifier.off(W.ConflictsChanged,E),e.notifier.off(W.ConfigChanged,A)}},[]),m(Ni.Provider,{value:{state:n,stats:a,logs:u,currentWorkspace:w,conflicts:r,config:d,updateConfig:c(f=>e.updateConfig(f),"updateConfig"),resolveConflicts:c(f=>e.syncWorkspaces(f),"resolveConflicts"),pull:c(f=>e.pullWorkspace(f),"pull"),push:c(f=>e.pushWorkspace(f),"push"),exit:c(()=>e.shutdown(),"exit")},children:s})}c(oa,"MembraneCLIServiceProvider");function le(){const s=ss(Ni);if(!s)throw new Error("useMembraneCLIService must be used within MembraneCLIServiceProvider");return s}c(le,"useMembraneCLIService");const Ai=ns(process.cwd());function aa({cwd:s,children:e}){return m(Ai.Provider,{value:s,children:e})}c(aa,"CwdProvider");function ca(){return ss(Ai)}c(ca,"useCwd");function Ht({cwd:s,children:e,membraneCLIService:t}){const n=s||process.cwd();return m(aa,{cwd:n,children:m(Gi,{value:{fetcher:Or()},children:m(oa,{membraneCLIService:t,children:e})})})}c(Ht,"Layout");const Jn=[{id:"claude-code",name:"Claude Code",description:"Anthropic Claude Code agent",actionDescription:"Adding membrane MCP to .mcp.json in the current directory",addConfig:c(()=>{const s=R.join(process.cwd(),".mcp.json"),e={mcpServers:{membrane:{command:"membrane",args:["mcp"],env:{AGENT_NAME:"Claude Code"}}}};let t={};if(P.existsSync(s))try{t=JSON.parse(P.readFileSync(s,"utf8"))}catch{t={}}const n={...t,mcpServers:{...t.mcpServers,...e.mcpServers}};return P.writeFileSync(s,JSON.stringify(n,null,2)),`MCP server configuration added to ${s}`},"addConfig")},{id:"cursor",name:"Cursor",description:"Cursor AI editor",actionDescription:"Adding membrane MCP to .cursor/mcp.json in the current directory",addConfig:c(()=>{const s=R.join(process.cwd(),".cursor"),e=R.join(s,"mcp.json");P.existsSync(s)||P.mkdirSync(s);const t={mcpServers:{membrane:{command:"membrane",args:["mcp"],env:{AGENT_NAME:"Cursor"}}}};let n={};if(P.existsSync(e))try{n=JSON.parse(P.readFileSync(e,"utf8"))}catch{n={}}const i={...n,mcpServers:{...n.mcpServers,...t.mcpServers}};return P.writeFileSync(e,JSON.stringify(i,null,2)),`MCP server configuration added to ${e}`},"addConfig")}];function la({onExit:s,onComplete:e}){const[t,n]=j(0),[i,r]=j(!1),[o,a]=j(null),[l,u]=j(""),[p,d]=j("");Pe((w,f)=>{if(l||p){(f.escape||w==="q"||f.return)&&e();return}if(i)f.return||w===" "?h(o):f.escape&&(r(!1),a(null));else if(f.escape)s();else if(f.upArrow||w==="k")n(Math.max(0,t-1));else if(f.downArrow||w==="j")n(Math.min(Jn.length-1,t+1));else if(f.return||w===" "){const y=Jn[t];a(y),r(!0)}});const h=c(w=>{try{const f=w.addConfig();u(f)}catch(f){d(`Failed to write configuration: ${f.message||f}`)}},"addMcpConfiguration"),g=Math.min(80,process.stdout.columns||80);return l?v(b,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:g,children:[m(b,{marginTop:-1,marginBottom:1,children:v(S,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",m(S,{color:"green",children:"Success"})]})}),v(b,{flexDirection:"column",paddingLeft:2,children:[m(S,{color:"green",children:l}),m(b,{marginTop:1,children:m(S,{color:"grey",children:"The agent will now be able to use Membrane's integration capabilities."})})]}),m(b,{marginTop:1,paddingLeft:2,children:m(S,{color:"white",children:"[esc/q/enter: exit]"})})]}):p?v(b,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:g,children:[m(b,{marginTop:-1,marginBottom:1,children:v(S,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",m(S,{color:"red",children:"Error"})]})}),m(b,{flexDirection:"column",paddingLeft:2,children:m(S,{color:"red",children:p})}),m(b,{marginTop:1,children:m(S,{color:"grey",children:"[esc/q/enter: exit]"})})]}):i&&o?v(b,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:g,children:[m(b,{marginTop:-1,marginBottom:1,children:v(S,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",m(S,{color:"cyan",children:"Confirmation"})]})}),v(b,{flexDirection:"column",paddingLeft:2,children:[v(S,{children:["Connect ",m(S,{bold:!0,children:o.name})," to Membrane via MCP?"]}),m(b,{marginTop:1,children:m(S,{color:"grey",children:"This will add an MCP server configuration that allows the agent to use Membrane's integration capabilities."})}),m(b,{marginTop:1,children:m(S,{color:"yellow",bold:!0,children:o.actionDescription})}),m(b,{marginTop:2,marginBottom:1,children:v(S,{children:[m(S,{color:"white",bold:!0,children:"[Enter] Confirm"})," ",m(S,{color:"gray",children:"[Esc] Cancel"})]})})]})]}):v(b,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:g,children:[m(b,{marginTop:-1,marginBottom:1,children:v(S,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",m(S,{color:"cyan",children:"Select Agent"})]})}),v(b,{flexDirection:"column",paddingLeft:2,children:[m(S,{color:"grey",children:"Choose an agent to connect to Membrane via MCP:"}),m(b,{marginTop:1,children:m(S,{color:"grey",children:"This will add an MCP server configuration that allows the agent to use Membrane's integration capabilities."})}),m(b,{marginTop:1,flexDirection:"column",children:Jn.map((w,f)=>v(b,{children:[v(S,{color:t===f?"cyan":"white",children:[t===f?"\u25B6 ":" ",w.name]}),v(S,{color:"grey",children:[" \u2014 ",w.description]})]},w.id))})]}),m(b,{marginTop:1,children:m(S,{color:"grey",children:"[\u2191\u2193: select] [enter: choose] [esc: exit]"})})]})}c(la,"AddMcpServerScreen");function ua(){const[s,e]=j(null),[t,n]=j([]),[i,r]=j(null);return ve(()=>{const o=c(({status:l})=>{e(l),r(null)},"handleMcpStatusChanged"),a=c(({servers:l})=>{n(l),r(null)},"handleMcpServersChanged");return de.on(W.McpStatusChanged,o),de.on(W.McpServersChanged,a),()=>{de.off(W.McpStatusChanged,o),de.off(W.McpServersChanged,a)}},[]),{mcpStatus:s,allMcpServers:t,error:i,isRunning:s?.isRunning||!1,toolsCount:s?.toolsCount||0,totalRequests:s?.totalRequests||0,lastActivity:s?.lastActivity,processId:s?.processId,serverCount:t.length}}c(ua,"useMcpStatus");function fa(){const{error:s,serverCount:e,allMcpServers:t}=ua(),n=Math.min(100,process.stdout.columns||100);return v(b,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:n,children:[m(b,{marginTop:-1,marginBottom:0,flexDirection:"column",children:v(S,{bold:!0,children:["\u{1F916} Connected AI Agents:"," ",s?m(S,{color:"red",children:"error reading status"}):e===0?m(S,{color:"yellow",children:"none"}):m(S,{color:"green",children:e})]})}),!s&&e===0&&m(b,{marginTop:1,children:v(S,{color:"grey",children:["Connect your AI agents to Membrane.",m(Ji,{}),"It will give them tools and context to build integrations."]})}),t.length>0&&m(b,{flexDirection:"column",paddingLeft:2,marginTop:1,children:t.map((i,r)=>m(b,{children:v(S,{color:"grey",children:["#",r+1," ",i.agentName,": ",i.totalRequests," calls"]})},i.processId))}),m(b,{marginTop:1,children:m(S,{color:"grey",children:"[a: connect an agent]"})})]})}c(fa,"Agent");const Yt=c(s=>{switch(s){case"error":return"red";case"success":return"green";case"warning":return"yellow";default:return}},"getLogColor");function Oi(s,e){return e<3?s.slice(0,Math.max(0,e)):s.length<=e?s:`${s.slice(0,e-3)}...`}c(Oi,"truncateText");function Wn({children:s}){const{state:e,logs:t}=le();if(!e||e===L.NOT_INITIALIZED)return v(b,{gap:1,flexDirection:"row",children:[m(ur,{type:"dots"}),m(S,{children:"Initializing..."})]});if(e===L.SETTING_UP)return m(b,{gap:1,flexDirection:"row",children:m(S,{children:"No workspace selected. Please run `membrane init` to select a workspace."})});if(e===L.ERROR){const n=t.filter(i=>i.type==="error");return m(b,{gap:1,flexDirection:"row",children:n.slice().map((i,r)=>m(S,{color:Yt(i.type),children:i.message},i.timestamp+r))})}return s}c(Wn,"EnsureInitialized");function $i({onExit:s,showEscOption:e=!0}){const[t,n]=j(""),{data:i,error:r,isLoading:o}=is("/account"),{updateConfig:a}=le(),l=i?.workspaces,u=o;if(Pe((f,y)=>{y.escape&&s?.()}),u)return v(b,{children:[m(yt,{}),m(S,{children:" Fetching workspaces..."})]});if(r)return v(b,{flexDirection:"column",children:[v(S,{color:"red",children:["Error: ",r.message]}),m(b,{marginTop:1,children:m(S,{color:"grey",children:"Press ESC to go back"})})]});const p=l?.filter(f=>f.name.toLowerCase().includes(t.toLowerCase()))??[],d=p.map(f=>({label:f.name,value:f.id})),h=d.length,g=l?.length??0;async function w(f){const y=p.find(A=>A.id===f);if(!y)return;const{key:C,secret:E}=y;!C||!E||(await a({workspaceKey:C,workspaceSecret:E}),s?.())}return c(w,"handleSelect"),v(b,{flexDirection:"column",borderStyle:"round",borderTop:!0,width:70,paddingX:1,children:[m(b,{marginTop:-1,children:m(S,{bold:!0,children:"\u{1F4C1} Select your workspace"})}),v(b,{marginTop:1,children:[m(S,{children:"Search: "}),m(fr,{placeholder:"Enter a search query...",onChange:n})]}),g>5&&v(S,{children:["Showing ",h," of ",g," workspaces."]}),m(b,{marginTop:1,children:m(hr,{options:d,onChange:c(f=>{f&&w(f)},"onChange")})}),e&&m(b,{marginTop:1,children:m(S,{color:"grey",children:"Press ESC to go back"})})]})}c($i,"SelectWorkspace");function ha({currentPat:s,onSubmit:e}){const[t,n]=j(""),[i,r]=j(!1),[o,a]=j(null);return v(b,{flexDirection:"column",borderStyle:"round",borderTop:!0,width:70,paddingX:1,children:[m(b,{marginTop:-1,marginBottom:1,children:m(S,{bold:!0,children:"\u{1F511} Enter your Personal Access Token"})}),m(S,{children:"Please provide your Personal Access Token. You can find it here:"}),m(b,{marginTop:1,marginBottom:1,children:m(S,{color:"yellow",children:"https://console.integration.app/w/0/manage-account/api-token"})}),s&&m(S,{dimColor:!0,children:"Press Enter to keep your current token or type a new one."}),m(dr,{mask:"*",placeholder:`${s?"******":"Enter your token here..."}`,value:t,onChange:n,onSubmit:c(async u=>{a(null),r(!0);try{await e(u),n("")}catch{a("Invalid token. Please try again.")}finally{r(!1)}},"handleSubmit")}),i&&m(b,{marginTop:1,children:v(S,{children:[m(yt,{type:"dots"})," Validating token..."]})}),o&&m(S,{color:"red",children:o})]})}c(ha,"PersonalAccessTokenInput");var dt=(s=>(s[s.Authenticate=0]="Authenticate",s[s.ConnectWorkspace=1]="ConnectWorkspace",s))(dt||{});const da={0:"Authenticate in Membrane",1:"Connect a Membrane Workspace"},Gn=[dt.Authenticate,dt.ConnectWorkspace];function Li({onComplete:s}){const{config:e}=le(),[t,n]=j(!1),[i,r]=j(0),o=!!(e?.workspaceKey&&e?.workspaceSecret),a=ds(),l=Gn[i],u=i+1,p=Gn.length,d=Gn.map((w,f)=>{let y="pending";return f<i?y="done":f===i&&(y="current"),{id:w,label:da[w],status:y}});async function h(w){const f=a&&w===""?a:w,y=new ps;try{await y.request("/account",{headers:{Authorization:`Bearer ${f}`}}),Ar(f),r(C=>C+1)}catch(C){console.error(C)}}c(h,"handlePatSubmit");function g(){n(!0),s&&s()}return c(g,"handleWorkspaceSelected"),Pe((w,f)=>{o&&f.escape&&s&&s()}),t?m(b,{children:m(S,{children:"\u2705 Setup complete. You are ready to go!"})}):v(b,{flexDirection:"column",alignSelf:"flex-start",gap:1,children:[v(b,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:70,children:[m(b,{marginTop:-1,marginBottom:1,children:v(S,{bold:!0,children:["\u{1F6E0}\uFE0F Setup \u2014"," ",v(S,{color:"cyan",children:["Step ",u," of ",p]}),o&&m(S,{color:"grey",children:" [esc: go back]"})]})}),m(b,{flexDirection:"column",paddingLeft:2,children:d.map(w=>m(pa,{status:w.status,label:w.label},w.id))})]}),l===dt.Authenticate&&m(ha,{currentPat:a,onSubmit:h}),l===dt.ConnectWorkspace&&m($i,{onExit:g,showEscOption:!1})]})}c(Li,"Setup");function pa({status:s,label:e}){return v(b,{children:[v(b,{width:2,children:[s==="current"&&m(yt,{type:"dots"}),s==="done"&&m(S,{children:"\u2705"})]}),m(S,{dimColor:s!=="current",children:e})]})}c(pa,"StepDisplay");function Vn(){const{stats:s}=le(),e=Object.entries(s).filter(([t,n])=>n>0);return e.length===0?null:v(b,{flexDirection:"column",children:[m(b,{children:m(b,{width:12,children:m(S,{color:"grey",children:"Elements:"})})}),m(b,{flexDirection:"column",marginLeft:1,children:e.map(([t,n])=>v(b,{children:[m(b,{width:20,children:v(S,{children:[t,":"]})}),m(S,{color:"green",children:n})]},t))})]})}c(Vn,"ElementStats");const Hn=5,ma=6;function ga(){const{logs:s}=le(),[e,t]=j(0),n=Math.min(100,process.stdout.columns||100),i=Hn,r=Math.max(0,s.length-i-e),o=s.length-e,a=s.slice(r,o),l=n-ma,u=e<s.length-i,p=e>0;return Pe((d,h)=>{if(s.length!==0)if(h.upArrow){const g=Math.max(0,s.length-i);t(w=>Math.min(g,w+1))}else h.downArrow?t(g=>Math.max(0,g-1)):(d==="G"||d==="g")&&t(0)}),v(b,{flexDirection:"column",paddingTop:1,children:[v(S,{color:"grey",children:["Recent Activity (",r+1,"-",o," of ",s.length,"):",s.length>Hn&&m(S,{color:"grey",children:" [arrows: scroll] [g: end]"})]}),a.map((d,h)=>m(b,{marginLeft:1,children:m(S,{color:Yt(d.type),children:Oi(d.message,l)})},d.timestamp+h)),s.length>Hn&&v(b,{marginLeft:1,flexDirection:"row",children:[u&&m(S,{color:"grey",children:"\u2191 "}),p&&m(S,{color:"grey",children:"\u2193 "})]})]})}c(ga,"Logs");const zt=[{value:"sync",label:"Continue (overwrite/delete)",key:""},{value:"exit",label:"Cancel",key:""}];function ya(){const{state:s,resolveConflicts:e,exit:t}=le(),[n,i]=j(0),[r,o]=j(!1),[a,l]=j(!1);return Pe((u,p)=>{if(!r){if(p.ctrl&&u.toLowerCase()==="r"){l(!a);return}p.upArrow?i(d=>d>0?d-1:zt.length-1):p.downArrow?i(d=>d<zt.length-1?d+1:0):u.toLowerCase()==="y"?i(0):u.toLowerCase()==="n"?i(1):(p.return||u===" ")&&(o(!0),zt[n].value==="sync"?e({watch:!0}):t())}}),ve(()=>{s!==L.CONFLICTS&&r&&o(!1)},[s,r]),v(b,{flexDirection:"column",paddingTop:1,children:[m(b,{children:m(b,{flexDirection:"row",gap:2,children:m(S,{bold:!0,color:"white",children:"Conflicts with remote"})})}),m(b,{children:m(S,{color:"grey",children:"The remote workspace has changes that aren't in your local workspace:"})}),m(b,{marginTop:1,marginLeft:2,children:m(Yn,{isExpanded:a})}),v(b,{marginTop:2,flexDirection:"row",gap:1,children:[m(S,{color:"white",bold:!0,children:"What would you like to do?"}),m(S,{color:"grey",children:"[up/down, enter]"})]}),m(b,{children:r?v(b,{flexDirection:"row",gap:1,children:[m(yt,{type:"dots"}),m(S,{color:"blue",bold:!0,children:"Syncing with remote..."})]}):m(b,{flexDirection:"column",children:zt.map((u,p)=>m(b,{flexDirection:"column",children:v(b,{flexDirection:"row",gap:1,children:[m(S,{color:n===p?"cyan":"grey",children:n===p?"\u25B6":" "}),m(S,{color:n===p?"cyan":"grey",bold:n===p,children:u.label})]})},u.value))})})]})}c(ya,"ResolveChangesUI");const wa={[Z.UPDATE]:{incoming:{label:"Elements updated in remote",description:"(to be overwritten from remote)"},outgoing:{label:"Elements updated locally",description:"(to be pushed to remote)"}},[Z.DELETE]:{incoming:{label:"Elements not existing in remote",description:"(to be deleted locally)"},outgoing:{label:"Elements deleted locally",description:"(to be deleted from remote)"}},[Z.CREATE]:{incoming:{label:"Elements created in remote",description:"(to be created locally)"},outgoing:{label:"Elements created locally",description:"(to be created in remote)"}}};function Yn({isExpanded:s}){const{conflicts:e}=le(),t=5,n=Vi(()=>{const i={};return e.forEach(r=>{const o=`${r.type}-${r.direction}`;i[o]||(i[o]=[]),i[o].push(r)}),i},[e]);return m(b,{flexDirection:"column",children:Object.entries(n).map(([i,r])=>{if(r.length===0)return null;const[o,a]=i.split("-"),l=wa[o][a];return v(b,{flexDirection:"column",children:[v(b,{flexDirection:"row",gap:1,children:[v(S,{color:"yellow",children:[l.label," (",r.length,")"]}),m(S,{color:"white",children:l.description})]}),(s?r:r.slice(0,t)).map(u=>m(b,{marginLeft:2,children:v(S,{color:"grey",children:["\u2022 ",u.element.id," (",u.element.relativePath,")"]})},u.element.id)),!s&&r.length>t&&m(b,{marginLeft:2,children:v(S,{color:"cyan",children:["... and ",r.length-t," more (press Ctrl+R to show all)"]})}),s&&r.length>t&&m(b,{marginLeft:2,children:m(S,{color:"cyan",children:"(press Ctrl+R to collapse)"})})]},i)})})}c(Yn,"Conflicts");function ba(){const{config:s,state:e,logs:t,currentWorkspace:n,pull:i}=le(),r=n?.name,o=r?Oi(r,30):s?.workspaceKey,a=Math.min(100,process.stdout.columns||100);return ve(()=>{i({watch:!0})},[]),v(b,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:a,children:[m(b,{marginTop:-1,marginBottom:1,children:v(b,{flexDirection:"row",gap:1,children:[m(S,{bold:!0,children:"\u{1F504} Workspace"}),v(S,{color:Ca(e),children:[" [",Sa(e),"] "]})]})}),v(b,{children:[m(b,{width:12,children:m(S,{color:"grey",children:"Local:"})}),m(S,{color:"grey",children:process.cwd()})]}),v(b,{children:[m(b,{width:12,children:m(S,{color:"grey",children:"Remote:"})}),s?.workspaceKey?v(S,{color:"grey",children:[o," [o: open in console] [w: change]"]}):v(S,{children:[m(S,{color:"yellow",children:"not selected"})," [w: select]"]})]}),e===L.CONFLICTS?m(ya,{}):v(Zt,{children:[m(b,{paddingTop:1,children:m(Vn,{})}),t.length>0&&m(ga,{})]})]})}c(ba,"Workspace");function Sa(s){switch(s){case L.PULLING:return"pulling";case L.PUSHING:return"pushing";case L.CONFLICTS:return"conflicts";case L.SYNCED:return"synced";case L.ERROR:return"error";case L.WATCHING:return"tracking changes";case L.RESOLVING:return"resolving";case L.NOT_SYNCED:return"not synced";case L.INITIALIZED:return"initialized";case L.SETTING_UP:return"setup required";default:return"unknown"}}c(Sa,"getStatusDisplay");function Ca(s){switch(s){case L.PULLING:return"yellow";case L.PUSHING:return"yellow";case L.CONFLICTS:return"red";case L.SYNCED:return"green";case L.ERROR:return"red";case L.WATCHING:return"green";case L.RESOLVING:return"yellow";case L.NOT_SYNCED:return"grey";case L.SETTING_UP:return"yellow";default:return"grey"}}c(Ca,"getStatusColor");const ka="https://console.integration.app/w";function Ea(){const s=ca(),e=Hi(!0),{exit:t,state:n}=le(),[i,r]=j(null),o=i??(n===L.SETTING_UP?"setup":"main");Pe(l=>{o==="main"&&(l==="w"&&r("workspace-selection"),l==="a"&&r("add-mcp-server"),l==="o"&&n===L.INITIALIZED&&a(),l==="s"&&r("setup"))});async function a(){try{const l=await ms(s),u=`${ka}/${l}`,p=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";lr(`${p} "${u}"`)}catch(l){console.error("Failed to open workspace:",l),t()}}return c(a,"handleOpenWorkspace"),ve(()=>(e.current=!0,()=>{e.current=!1}),[]),o==="workspace-selection"?m($i,{onExit:c(()=>r(null),"onExit")}):o==="add-mcp-server"?m(la,{onExit:c(()=>r(null),"onExit"),onComplete:c(()=>r(null),"onComplete")}):o==="setup"?m(Li,{onComplete:c(()=>r(null),"onComplete")},Date.now()):m(Wn,{children:v(b,{flexDirection:"column",children:[m(b,{flexGrow:1,children:m(fa,{})}),m(ba,{}),m(b,{paddingLeft:2,children:m(S,{color:"grey",children:"[s: (re-)setup]"})})]})})}c(Ea,"Main");const xi=Wi(process.argv.slice(2)),Pi=xi.cwd?Bi(xi.cwd):process.cwd(),va=new Ti(ht.Agent,Pi),Ia=c(()=>m(Ht,{cwd:Pi,membraneCLIService:va,children:m(Ea,{})}),"App");function Ta(){mt(m(Ia,{}))}c(Ta,"runAgent");function Na(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(`
141
+ `)).action(t=>{t.key&&t.secret?Ze.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)):mt(De.createElement(Ht,{membraneCLIService:e,children:De.createElement(Li,{onComplete:c(()=>process.exit(0),"onComplete")})}))})}c(Na,"setupInitCommand");async function Di(s,e){const t={iss:s,exp:Math.floor(Date.now()/1e3)+600,isAdmin:!0};return sn.sign(t,e)}c(Di,"generateAdminAccessToken");async function Aa(s,e){return(await rn.get(`${s}/docs-json`,{headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}})).data}c(Aa,"fetchOpenApiSchema");function Ri(s,e=!0){if(!s)return e?Q.string():Q.string().optional();let t;switch(s.type){case"integer":t=Q.coerce.number().int();break;case"number":t=Q.coerce.number();break;case"boolean":t=Q.coerce.boolean();break;case"string":default:t=Q.string();break}return s.format==="uuid"?t=Q.string().uuid():s.format==="email"?t=Q.string().email():s.format==="date"?t=Q.string().regex(/^\d{4}-\d{2}-\d{2}$/):s.format==="date-time"&&(t=Q.string().datetime()),s.enum&&(t=Q.enum(s.enum)),(s.type==="integer"||s.type==="number")&&(s.minimum!==void 0&&(t=t.min(s.minimum)),s.maximum!==void 0&&(t=t.max(s.maximum))),s.type==="string"&&(s.minLength!==void 0&&(t=t.min(s.minLength)),s.maxLength!==void 0&&(t=t.max(s.maxLength))),e?t:t.optional()}c(Ri,"convertOpenApiSchemaToZod");function Mi(s){const e=s.match(/\{([^}]+)\}/g);return e?e.map(t=>t.slice(1,-1)):[]}c(Mi,"extractPathParameters");function Oa(s,e,t,n,i,r){const o=s.operationId||`${t}_${e.replace(/[^a-zA-Z0-9]/g,"_")}`,a=s.description||s.summary||`${t.toUpperCase()} ${e}`,l={},u={},p={};if(s.parameters){for(const h of s.parameters)if(h.in==="path")u[h.name]=Ri(h.schema,!0).describe(h.description||`Path parameter: ${h.name}`);else if(h.in==="query"){const g=h.required===!0;p[h.name]=Ri(h.schema,g).describe(h.description||`Query parameter: ${h.name}`)}}Object.keys(u).length>0&&(l.params=Q.object(u).describe("Path parameters")),Object.keys(p).length>0&&(l.query=Q.object(p).describe("Query parameters")),s.requestBody&&s.requestBody.content&&s.requestBody.content["application/json"]&&(l.body=Q.any().describe("Request body"));const d=Object.keys(l).length>0?Q.object(l):Q.object({});return{name:o,description:a,parameters:d,async execute(h){try{const g=Mi(e);if(g.length>0){if(!h.params)throw new Error(`Missing required path parameters: ${g.join(", ")}`);const I=g.filter(O=>!(O in h.params));if(I.length>0)throw new Error(`Missing required path parameters: ${I.join(", ")}`)}let w=`${n}${e}`;if(h.params)for(const[I,O]of Object.entries(h.params)){const $=`{${I}}`;w.includes($)&&(w=w.replace($,String(O)))}const f=Mi(w);if(f.length>0)throw new Error(`Unresolved path parameters: ${f.join(", ")}`);const y=new URLSearchParams;if(h.query)for(const[I,O]of Object.entries(h.query))O!=null&&y.append(I,String(O));y.toString()&&(w+=`?${y.toString()}`);const C=await Di(i,r),E={method:t.toUpperCase(),headers:{Authorization:`Bearer ${C}`,"Content-Type":"application/json"}};h.body&&t.toLowerCase()!=="get"&&(E.data=h.body);const A=await rn.request({url:w,...E});return{content:[{type:"text",text:JSON.stringify(A.data,null,2)}]}}catch(g){return rn.isAxiosError(g)?{content:[{type:"text",text:`Error: ${g.response?.data?`HTTP ${g.response.status}: ${g.response.statusText} - ${JSON.stringify(g.response.data)}`:`HTTP ${g.response?.status||"unknown"}: ${g.message}`}`}],isError:!0}:g instanceof Error?{content:[{type:"text",text:`Error: API call failed: ${g.message}`}],isError:!0}:{content:[{type:"text",text:"Error: API call failed with unknown error"}],isError:!0}}}}}c(Oa,"createApiTool");function $a(s,e,t,n){const i=[];if(!s.paths)return i;for(const[r,o]of Object.entries(s.paths))if(typeof o=="object"&&o!==null){for(const[a,l]of Object.entries(o))if(["get","post","put","delete","patch"].includes(a)&&l&&typeof l=="object"){const u=Oa(l,r,a,e,t,n);i.push(u)}}return i}c($a,"convertOpenApiToTools");function La(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(`
142
+ `)).action(async()=>{try{process.env.FASTMCP_SUPPRESS_WARNINGS="true";const e=bt();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"),process.exit(1));const t=e.apiUri||an,n=await Di(e.workspaceKey,e.workspaceSecret),i=await Aa(t,n),r=$a(i,t,e.workspaceKey,e.workspaceSecret),o=new gr({name:"Membrane API",instructions:`This MCP server lets you interact with Membrane to configure, run, and troubleshoot integrations.
143
143
  Use it for anything related to Membrane or integrations.
144
- `,version:"1.0.0"});for(const u of r){const p=u.execute;u.execute=async d=>(aa(process.pid,process.cwd()),p(d)),o.addTool(u)}qn({isRunning:!0,startTime:new Date().toISOString(),toolsCount:r.length,lastActivity:new Date().toISOString(),processId:process.pid,cwd:process.cwd(),agentName:process.env.AGENT_NAME||"Unnamed Agent"});const a=setInterval(()=>{qn({processId:process.pid,cwd:process.cwd(),lastActivity:new Date().toISOString()})},5e3),l=c(async()=>{clearInterval(a),ht(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",()=>{ht(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(xa,"setupMcpCommand");const Pa={info:"\u{1F4DD}",success:"\u2728",warning:"\u26A0\uFE0F",error:"\u274C",debug:"\u{1F50D}"},Ra={info:k.blue,success:k.green,warning:k.yellow,error:k.red,debug:k.gray};class W{static{c(this,"Logger")}static formatMessage(e,t,n={}){const i=n.timestamp?`${k.gray(new Date().toISOString())} `:"",r=n.prefix?`${k.gray(n.prefix)} `:"",o=n.suffix?` ${k.gray(n.suffix)}`:"",a=Pa[t],l=Ra[t];return`${i}${a} ${r}${l(e)}${o}`}static info(e,t){let n=k.blue;if(t?.color&&(n=k[t.color.toLowerCase()]||k.blue),t?.timestamp){const i=new Date().toLocaleTimeString();console.debug(`${k.gray(`[${i}]`)} ${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?`
144
+ `,version:"1.0.0"});for(const u of r){const p=u.execute;u.execute=async d=>(ra(process.pid,process.cwd()),p(d)),o.addTool(u)}Bn({isRunning:!0,startTime:new Date().toISOString(),toolsCount:r.length,lastActivity:new Date().toISOString(),processId:process.pid,cwd:process.cwd(),agentName:process.env.AGENT_NAME||"Unnamed Agent"});const a=setInterval(()=>{Bn({processId:process.pid,cwd:process.cwd(),lastActivity:new Date().toISOString()})},5e3),l=c(async()=>{clearInterval(a),ft(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",()=>{ft(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(La,"setupMcpCommand");const xa={info:"\u{1F4DD}",success:"\u2728",warning:"\u26A0\uFE0F",error:"\u274C",debug:"\u{1F50D}"},Pa={info:k.blue,success:k.green,warning:k.yellow,error:k.red,debug:k.gray};class G{static{c(this,"Logger")}static formatMessage(e,t,n={}){const i=n.timestamp?`${k.gray(new Date().toISOString())} `:"",r=n.prefix?`${k.gray(n.prefix)} `:"",o=n.suffix?` ${k.gray(n.suffix)}`:"",a=xa[t],l=Pa[t];return`${i}${a} ${r}${l(e)}${o}`}static info(e,t){let n=k.blue;if(t?.color&&(n=k[t.color.toLowerCase()]||k.blue),t?.timestamp){const i=new Date().toLocaleTimeString();console.debug(`${k.gray(`[${i}]`)} ${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?`
145
145
  ${k.red(t.error)}`:""):console.debug(k.gray(e),t?.error?`
146
- ${k.red(t.error)}`:"")}static step(e,t){}static header(e){console.debug(),console.debug(k.bold.cyan(`\u25B6 ${e}`)),console.debug()}static table(e,t){if(e.length===0)return;const n=t||Object.keys(e[0]),i=e.map(r=>{const o={};return n.forEach(a=>{o[a]=r[a]}),o});console.table(i,n)}static divider(){}}function Ma(s){s.command("open").description("Open the workspace in the browser").addHelpText("after",["","Examples:"," membrane open # Open workspace in browser",""].join(`
147
- `)).action(async()=>{try{W.header("Opening Workspace in Browser"),W.info("Loading configuration...");const e=St();if(!e)throw new Error("No configuration found. Please set MEMBRANE_WORKSPACE_KEY and MEMBRANE_WORKSPACE_SECRET environment variables, or run `membrane init` first.");if(!e.workspaceKey||!e.workspaceSecret)throw new Error("Missing workspace credentials");W.info("Retrieving workspace ID...");const n=`https://console.integration.app/w/${await gs(process.cwd())}`;W.info(`Opening ${n}...`);const{default:i}=await import("open");await i(n),W.success("Browser opened successfully")}catch(e){e instanceof Error&&(W.error(e.message),process.exit(1)),W.error("An unknown error occurred"),process.exit(1)}})}c(Ma,"setupOpenCommand");function _a(s){return m(Gn,{children:m(Ka,{options:s})})}c(_a,"Pull");function Ka({options:s}){const{logs:e,state:t,conflicts:n,pull:i}=ce();Ie(()=>{i(s)},[]);const r=t===L.CONFLICTS;return v(b,{flexDirection:"column",children:[e.slice().map((o,a)=>m(S,{color:zt(o.type),children:o.message},o.timestamp+a)),r&&v(en,{children:[v(S,{color:"yellow",bold:!0,children:["Found ",n.length," conflicts with remote:"]}),m(zn,{isExpanded:!1}),m(S,{color:"red",children:"Out of sync with remote, use --force to overwrite conflict changes"})]}),t===L.SYNCED&&m(Hn,{})]})}c(Ka,"PullActivity");function Ki(){const s=setInterval(()=>{},3e4),e=c(()=>{clearInterval(s)},"cleanup");return process.on("SIGINT",()=>{e(),process.exit(0)}),process.on("SIGTERM",()=>{e(),process.exit(0)}),process.on("exit",e),()=>{}}c(Ki,"getWatchModeCallback");function ja(s,e){s.command("pull").description("Pull workspace data from specified workspace").option("--force","Overwrite conflicts with remote data",!1).option("--watch","Watch for changes and pull automatically",!1).option("--all-connectors","Include public connectors in export - to push to the self-hosted instance",!1).addHelpText("after",["","Examples:"," membrane pull # Pull from default workspace"," membrane pull --force # Overwrite conflicts with remote data"," membrane pull --all-connectors # Pull all connectors"," membrane pull --watch # Watch for changes and pull automatically",""].join(`
148
- `)).action(async t=>{const n=t.watch?Ki():()=>process.exit(0);gt(Re.createElement(Yt,{membraneCLIService:e,children:Re.createElement(_a,{force:t.force,watch:t.watch,allConnectors:t.allConnectors,onComplete:n})}))})}c(ja,"setupPullCommand");function Fa(s){return m(Gn,{children:m(Ba,{options:s})})}c(Fa,"Push");function Ba({options:s}){const{logs:e,state:t,conflicts:n,push:i}=ce();Ie(()=>{i(s)},[]);const r=t===L.CONFLICTS;return v(b,{flexDirection:"column",children:[e.slice().map((o,a)=>m(S,{color:zt(o.type),children:o.message},o.timestamp+a)),r&&v(en,{children:[v(S,{color:"yellow",bold:!0,children:["Found ",n.length," conflicts with remote:"]}),m(zn,{isExpanded:!1}),m(S,{color:"red",children:"Out of sync with remote, use --force to overwrite conflict changes"})]}),t===L.SYNCED&&m(Hn,{})]})}c(Ba,"PushActivity");function qa(s,e){s.command("push").description("Push workspace data to specified workspace").option("--force","Overwrite conflicts with local data",!1).option("--watch","Watch for changes and push automatically",!1).addHelpText("after",["","Examples:"," membrane push # Push to default workspace"," membrane push --force # Overwrite conflicts with local data",""].join(`
149
- `)).action(async t=>{const n=t.watch?Ki():()=>process.exit(0);gt(Re.createElement(Yt,{membraneCLIService:e,children:Re.createElement(Fa,{force:t.force,watch:t.watch,onComplete:n})}))})}c(qa,"setupPushCommand");class Ua{static{c(this,"BaseRunner")}constructor(e){if(this.options=e,this.fsPaths=ln(),e&&typeof e=="object"){const t=e;"client"in t&&t.client&&(this.client=t.client),"workspace"in t&&(this.workspace=t.workspace)}}client;workspace;fsPaths}const Ja="claude-sonnet-4-20250514";class ts{static{c(this,"TestEnvironment")}client;connectionId;testsDir;testBasePath;options;llm;state={};constructor({connectionId:e,testsDir:t,testBasePath:n,client:i,options:r,llm:o}){this.client=i,this.connectionId=e,this.testsDir=t,this.testBasePath=n,this.llm=o,this.options=r}static async create({connectionId:e,testBasePath:t,options:n}){const i=St();if(!i)throw new Error("No configuration found. Please set MEMBRANE_WORKSPACE_KEY and MEMBRANE_WORKSPACE_SECRET environment variables, or run `membrane init` first.");if(!i.workspaceKey||!i.workspaceSecret)throw new Error("Missing workspace credentials");if(!i.anthropicApiKey)throw new Error("Anthropic API key not configured. Run `membrane init` to set up testing.");const r=new os({token:await this.createMembraneToken(i),apiUri:i.apiUri}),o=new wr({apiKey:i.anthropicApiKey}),a={complete:c(async({prompt:l,maxTokens:u})=>{const p=await o.messages.create({model:Ja,max_tokens:u,messages:[{role:"user",content:l}]});return p.content[0].type==="text"?p.content[0].text:""},"complete")};return new ts({client:r,options:n,connectionId:e,testsDir:"src/testing/tests",testBasePath:t,llm:a})}async run(e){this.state={};const t={};for(const n of e)await n.run(),an(t,n.getResult());this.writeResults(t)}async readYaml(e){const t=B.join(this.testsDir,this.testBasePath,this.connectionId,e);if(P.existsSync(t))return Te.load(P.readFileSync(t,"utf8"))}async writeYaml(e,t){const n=B.join(this.testsDir,this.testBasePath,this.connectionId,e);P.mkdirSync(B.dirname(n),{recursive:!0}),P.writeFileSync(n,Te.dump(t,{noRefs:!0}))}writeResults(e){const t=B.join(this.testsDir,this.testBasePath,this.connectionId);P.mkdirSync(t,{recursive:!0});const n=B.join(t,"test-results.yaml");P.writeFileSync(n,Te.dump(e,{noRefs:!0})),console.debug(`[TestRunner] Results written to: ${n}`)}static async createMembraneToken(e){const t=e.testCustomerId||"test-customer",n={id:t,name:t},i={issuer:e.workspaceKey,expiresIn:7200,algorithm:"HS512"};return rn.sign(n,e.workspaceSecret,i)}}Sr.interpolate=/{{([\s\S]+?)}}/g;function Qn(s,e){if(typeof s=="string"){const t=br(s),n={state:e,random:{number:c(()=>Ze.number.int(),"number"),alphaNumeric:c(r=>Ze.string.alphanumeric(r),"alphaNumeric")},faker:{company:{name:c(()=>Ze.company.name(),"name"),catchPhrase:c(()=>Ze.company.catchPhrase(),"catchPhrase")},internet:{email:c(()=>Ze.internet.email(),"email")}},entries:e["journal-entries"],orders:e["purchase-orders"]||e["sales-orders"],bills:e["vendor-bills"]},i=t(n);return s.includes("{{")&&s.includes("}}")&&(console.debug(`[TEMPLATE] Input: ${s}`),console.debug(`[TEMPLATE] Output: ${i}`)),i}return Array.isArray(s)?s.map(t=>Qn(t,e)):typeof s=="object"&&s!==null?Object.fromEntries(Object.entries(s).map(([t,n])=>[t,Qn(n,e)])):s}c(Qn,"processNode");function Wa(s,e){return Qn(s,e)}c(Wa,"handleTemplate");class Ga{static{c(this,"BaseTestSuite")}result;environment;constructor({environment:e}){this.environment=e,this.result={}}async run(){}getResult(){return this.result}async runTest(e){console.debug(`${k.bold.cyan("[start]")} ${k.yellow(e.path)}`);let t=!1,n=!1,i={},r={},o;for(;!t;)try{r=await e.readTestCase(),r||(r=await e.generateConfig(),await this.environment.writeYaml(e.getTestCasePath(),r),console.debug(`${k.bold.yellow("[initialized]")} ${k.yellow(e.path)}`)),o=Wa(r,this.environment.state),await e.run(o),console.debug(`${k.bold.green("[success]")} ${k.yellow(e.path)}`),t=!0,i=e.getResult(),tn(this.result,e.path,i)}catch(l){if(console.error(`${k.bold.red("[error]")} ${k.yellow(e.path)}: ${l}`),this.environment.options.fix&&!n){n=!0;try{await e.fix(l);continue}catch(u){console.error(`${k.bold.red("[fix fail]")} ${k.yellow(e.path)}: ${u}`)}}tn(this.result,e.path,{error:le(l)}),t=!0,i={error:le(l)}}const a={...o,result:i};await this.environment.writeYaml(e.getTestCasePath(),a)}async runTestSuite(e){await e.run(),an(this.result,e.getResult())}}class ve{static{c(this,"BaseTester")}environment;level;logs;assertions;resultsLocator;path;constructor({environment:e,path:t}){this.environment=e,this.logs=[],this.assertions=[],this.path=t,this.level=0}async fix(e){const t=await this.readTestCase();if(!t)throw new Error(`No config found for test ${this.path}`);const n=await this.fixTestCase({config:t,error:e});console.debug(k.bold.yellow("[auto-fix]"),this.path),await this.environment.writeYaml(this.getTestCasePath(),n)}async readTestCase(){const e=this.getTestCasePath();return this.environment.readYaml(e)}async generateConfig(){return{}}async fixTestCase(e){throw new Error(`Auto-fix is not implemented for test ${this.path}`)}getResult(){return{logs:this.logs,assertions:this.assertions}}async assert(e,t,n){try{const i=await e();i?(this.logMsg(`\u2705 ${t}`),this.assertions.push({message:t,result:i})):(this.logMsg(`\u274C ${t}`),this.assertions.push({message:t,result:!1,details:n}))}catch(i){this.assertions.push({message:t,result:!1,details:le(i)}),this.logMsg(`\u274C ${t}: ${i.message}`)}}logMsg(e){console.debug(`${" ".repeat(this.level*2)}${e}`)}getTestCasePath(){return`${this.path}.test.yml`}}function Xn(s,e){const t={};for(const n in e){if(!(n in s)){t[n]=e[n];continue}const i=s[n],r=e[n];if(i&&r&&typeof i=="object"&&typeof r=="object"){if(Array.isArray(i)&&Array.isArray(r)){const o=r.filter(a=>!i.some(l=>{if(typeof l=="object"&&typeof a=="object"&&l!==null&&a!==null&&!Array.isArray(l)&&!Array.isArray(a)){for(const u in a)if(!(u in l)||!Zn(l[u],a[u]))return!1;return!0}else return JSON.stringify(l)===JSON.stringify(a)}));o.length>0&&(t[n]=o)}else if(!Array.isArray(i)&&!Array.isArray(r)){const o=Xn(i,r);o!==null&&(t[n]=o)}else t[n]=r;continue}Zn(i,r)||(t[n]=r)}return Object.keys(t).length===0?null:t}c(Xn,"getNotMatchingSubFields");function Zn(s,e){if(s==e||s?.toString?.()===e?.toString?.())return!0;const t=new Date(s),n=new Date(e);return!isNaN(t.getTime())&&!isNaN(n.getTime())?t.getTime()===n.getTime():!1}c(Zn,"softCompare");class Va extends ve{static{c(this,"DataCollectionCreateTester")}dataCollectionKey;dataCollection;constructor({environment:e,dataCollectionKey:t,dataCollection:n}){super({environment:e,path:`data/${t}/create`}),this.dataCollectionKey=t,this.dataCollection=n}async run(e){const t=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).create(e.input);await this.assert(()=>!!t.id,"Returned ID of a created record"),t.id&&(this.environment.state[this.dataCollectionKey]={createdRecordId:t.id});const n=nn(this.dataCollection);if(this.dataCollection.findById){const r=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).findById({id:t.id});await this.assert(()=>!!r.record,"Record is returned from findById"),r.record&&(this.environment.state[this.dataCollectionKey]={createdRecordId:t.id,createdRecord:r.record.fields});const o=as(n),a=yt(e.input.fields,o,{skipUnknownFields:!0}),l=yt(r.record.fields,o),u=Xn(l,a);await this.assert(()=>!u,"Returned fields match created fields",{difference:u,sentFields:a,receivedFields:l})}const i=Qi(n);if(i.length>0){const r={};i.forEach(a=>{const l=Xi(e.input.fields,a);typeof l<"u"&&tn(r,a,l)});const o=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).create({fields:r});await this.assert(()=>!!o.id,"Record can be created with schema-defined required fields only")}}async generateConfig(){const e=nn(this.dataCollection);if(!e?.properties)throw new Error("No fields schema found for data collection");return{input:{fields:await this.generateFieldsWithLLM(e)}}}async fixTestCase({config:e,error:t}){const n=le(t),i=nn(this.dataCollection),r=await this.getExampleRecordsForSchema(i),o=`I'm trying to create a data record in a data collection with the following fields schema:
146
+ ${k.red(t.error)}`:"")}static step(e,t){}static header(e){console.debug(),console.debug(k.bold.cyan(`\u25B6 ${e}`)),console.debug()}static table(e,t){if(e.length===0)return;const n=t||Object.keys(e[0]),i=e.map(r=>{const o={};return n.forEach(a=>{o[a]=r[a]}),o});console.table(i,n)}static divider(){}}function Da(s){s.command("open").description("Open the workspace in the browser").addHelpText("after",["","Examples:"," membrane open # Open workspace in browser",""].join(`
147
+ `)).action(async()=>{try{G.header("Opening Workspace in Browser"),G.info("Loading configuration...");const e=bt();if(!e)throw new Error("No configuration found. Please set MEMBRANE_WORKSPACE_KEY and MEMBRANE_WORKSPACE_SECRET environment variables, or run `membrane init` first.");if(!e.workspaceKey||!e.workspaceSecret)throw new Error("Missing workspace credentials");G.info("Retrieving workspace ID...");const n=`https://console.integration.app/w/${await ms(process.cwd())}`;G.info(`Opening ${n}...`);const{default:i}=await import("open");await i(n),G.success("Browser opened successfully")}catch(e){e instanceof Error&&(G.error(e.message),process.exit(1)),G.error("An unknown error occurred"),process.exit(1)}})}c(Da,"setupOpenCommand");function Ra(s){return m(Wn,{children:m(Ma,{options:s})})}c(Ra,"Pull");function Ma({options:s}){const{logs:e,state:t,conflicts:n,pull:i}=le();ve(()=>{i(s)},[]);const r=t===L.CONFLICTS;return v(b,{flexDirection:"column",children:[e.slice().map((o,a)=>m(S,{color:Yt(o.type),children:o.message},o.timestamp+a)),r&&v(Zt,{children:[v(S,{color:"yellow",bold:!0,children:["Found ",n.length," conflicts with remote:"]}),m(Yn,{isExpanded:!1}),m(S,{color:"red",children:"Out of sync with remote, use --force to overwrite conflict changes"})]}),t===L.SYNCED&&m(Vn,{})]})}c(Ma,"PullActivity");function _i(){const s=setInterval(()=>{},3e4),e=c(()=>{clearInterval(s)},"cleanup");return process.on("SIGINT",()=>{e(),process.exit(0)}),process.on("SIGTERM",()=>{e(),process.exit(0)}),process.on("exit",e),()=>{}}c(_i,"getWatchModeCallback");function _a(s,e){s.command("pull").description("Pull workspace data from specified workspace").option("--force","Overwrite conflicts with remote data",!1).option("--watch","Watch for changes and pull automatically",!1).option("--all-connectors","Include public connectors in export - to push to the self-hosted instance",!1).addHelpText("after",["","Examples:"," membrane pull # Pull from default workspace"," membrane pull --force # Overwrite conflicts with remote data"," membrane pull --all-connectors # Pull all connectors"," membrane pull --watch # Watch for changes and pull automatically",""].join(`
148
+ `)).action(async t=>{const n=t.watch?_i():()=>process.exit(0);mt(De.createElement(Ht,{membraneCLIService:e,children:De.createElement(Ra,{force:t.force,watch:t.watch,allConnectors:t.allConnectors,onComplete:n})}))})}c(_a,"setupPullCommand");function Ka(s){return m(Wn,{children:m(ja,{options:s})})}c(Ka,"Push");function ja({options:s}){const{logs:e,state:t,conflicts:n,push:i}=le();ve(()=>{i(s)},[]);const r=t===L.CONFLICTS;return v(b,{flexDirection:"column",children:[e.slice().map((o,a)=>m(S,{color:Yt(o.type),children:o.message},o.timestamp+a)),r&&v(Zt,{children:[v(S,{color:"yellow",bold:!0,children:["Found ",n.length," conflicts with remote:"]}),m(Yn,{isExpanded:!1}),m(S,{color:"red",children:"Out of sync with remote, use --force to overwrite conflict changes"})]}),t===L.SYNCED&&m(Vn,{})]})}c(ja,"PushActivity");function Fa(s,e){s.command("push").description("Push workspace data to specified workspace").option("--force","Overwrite conflicts with local data",!1).option("--watch","Watch for changes and push automatically",!1).addHelpText("after",["","Examples:"," membrane push # Push to default workspace"," membrane push --force # Overwrite conflicts with local data",""].join(`
149
+ `)).action(async t=>{const n=t.watch?_i():()=>process.exit(0);mt(De.createElement(Ht,{membraneCLIService:e,children:De.createElement(Ka,{force:t.force,watch:t.watch,onComplete:n})}))})}c(Fa,"setupPushCommand");class Ba{static{c(this,"BaseRunner")}constructor(e){if(this.options=e,this.fsPaths=cn(),e&&typeof e=="object"){const t=e;"client"in t&&t.client&&(this.client=t.client),"workspace"in t&&(this.workspace=t.workspace)}}client;workspace;fsPaths}const qa="claude-sonnet-4-20250514";class es{static{c(this,"TestEnvironment")}client;connectionId;testsDir;testBasePath;options;llm;state={};constructor({connectionId:e,testsDir:t,testBasePath:n,client:i,options:r,llm:o}){this.client=i,this.connectionId=e,this.testsDir=t,this.testBasePath=n,this.llm=o,this.options=r}static async create({connectionId:e,testBasePath:t,options:n}){const i=bt();if(!i)throw new Error("No configuration found. Please set MEMBRANE_WORKSPACE_KEY and MEMBRANE_WORKSPACE_SECRET environment variables, or run `membrane init` first.");if(!i.workspaceKey||!i.workspaceSecret)throw new Error("Missing workspace credentials");if(!i.anthropicApiKey)throw new Error("Anthropic API key not configured. Run `membrane init` to set up testing.");const r=new rs({token:await this.createMembraneToken(i),apiUri:i.apiUri}),o=new yr({apiKey:i.anthropicApiKey}),a={complete:c(async({prompt:l,maxTokens:u})=>{const p=await o.messages.create({model:qa,max_tokens:u,messages:[{role:"user",content:l}]});return p.content[0].type==="text"?p.content[0].text:""},"complete")};return new es({client:r,options:n,connectionId:e,testsDir:"src/testing/tests",testBasePath:t,llm:a})}async run(e){this.state={};const t={};for(const n of e)await n.run(),on(t,n.getResult());this.writeResults(t)}async readYaml(e){const t=q.join(this.testsDir,this.testBasePath,this.connectionId,e);if(D.existsSync(t))return Ie.load(D.readFileSync(t,"utf8"))}async writeYaml(e,t){const n=q.join(this.testsDir,this.testBasePath,this.connectionId,e);D.mkdirSync(q.dirname(n),{recursive:!0}),D.writeFileSync(n,Ie.dump(t,{noRefs:!0}))}writeResults(e){const t=q.join(this.testsDir,this.testBasePath,this.connectionId);D.mkdirSync(t,{recursive:!0});const n=q.join(t,"test-results.yaml");D.writeFileSync(n,Ie.dump(e,{noRefs:!0})),console.debug(`[TestRunner] Results written to: ${n}`)}static async createMembraneToken(e){const t=e.testCustomerId||"test-customer",n={id:t,name:t},i={issuer:e.workspaceKey,expiresIn:7200,algorithm:"HS512"};return sn.sign(n,e.workspaceSecret,i)}}br.interpolate=/{{([\s\S]+?)}}/g;function zn(s,e){if(typeof s=="string"){const t=wr(s),n={state:e,random:{number:c(()=>Xe.number.int(),"number"),alphaNumeric:c(r=>Xe.string.alphanumeric(r),"alphaNumeric")},faker:{company:{name:c(()=>Xe.company.name(),"name"),catchPhrase:c(()=>Xe.company.catchPhrase(),"catchPhrase")},internet:{email:c(()=>Xe.internet.email(),"email")}},entries:e["journal-entries"],orders:e["purchase-orders"]||e["sales-orders"],bills:e["vendor-bills"]},i=t(n);return s.includes("{{")&&s.includes("}}")&&(console.debug(`[TEMPLATE] Input: ${s}`),console.debug(`[TEMPLATE] Output: ${i}`)),i}return Array.isArray(s)?s.map(t=>zn(t,e)):typeof s=="object"&&s!==null?Object.fromEntries(Object.entries(s).map(([t,n])=>[t,zn(n,e)])):s}c(zn,"processNode");function Ua(s,e){return zn(s,e)}c(Ua,"handleTemplate");class Ja{static{c(this,"BaseTestSuite")}result;environment;constructor({environment:e}){this.environment=e,this.result={}}async run(){}getResult(){return this.result}async runTest(e){console.debug(`${k.bold.cyan("[start]")} ${k.yellow(e.path)}`);let t=!1,n=!1,i={},r={},o;for(;!t;)try{r=await e.readTestCase(),r||(r=await e.generateConfig(),await this.environment.writeYaml(e.getTestCasePath(),r),console.debug(`${k.bold.yellow("[initialized]")} ${k.yellow(e.path)}`)),o=Ua(r,this.environment.state),await e.run(o),console.debug(`${k.bold.green("[success]")} ${k.yellow(e.path)}`),t=!0,i=e.getResult(),en(this.result,e.path,i)}catch(l){if(console.error(`${k.bold.red("[error]")} ${k.yellow(e.path)}: ${l}`),this.environment.options.fix&&!n){n=!0;try{await e.fix(l);continue}catch(u){console.error(`${k.bold.red("[fix fail]")} ${k.yellow(e.path)}: ${u}`)}}en(this.result,e.path,{error:ue(l)}),t=!0,i={error:ue(l)}}const a={...o,result:i};await this.environment.writeYaml(e.getTestCasePath(),a)}async runTestSuite(e){await e.run(),on(this.result,e.getResult())}}class Ee{static{c(this,"BaseTester")}environment;level;logs;assertions;resultsLocator;path;constructor({environment:e,path:t}){this.environment=e,this.logs=[],this.assertions=[],this.path=t,this.level=0}async fix(e){const t=await this.readTestCase();if(!t)throw new Error(`No config found for test ${this.path}`);const n=await this.fixTestCase({config:t,error:e});console.debug(k.bold.yellow("[auto-fix]"),this.path),await this.environment.writeYaml(this.getTestCasePath(),n)}async readTestCase(){const e=this.getTestCasePath();return this.environment.readYaml(e)}async generateConfig(){return{}}async fixTestCase(e){throw new Error(`Auto-fix is not implemented for test ${this.path}`)}getResult(){return{logs:this.logs,assertions:this.assertions}}async assert(e,t,n){try{const i=await e();i?(this.logMsg(`\u2705 ${t}`),this.assertions.push({message:t,result:i})):(this.logMsg(`\u274C ${t}`),this.assertions.push({message:t,result:!1,details:n}))}catch(i){this.assertions.push({message:t,result:!1,details:ue(i)}),this.logMsg(`\u274C ${t}: ${i.message}`)}}logMsg(e){console.debug(`${" ".repeat(this.level*2)}${e}`)}getTestCasePath(){return`${this.path}.test.yml`}}function Qn(s,e){const t={};for(const n in e){if(!(n in s)){t[n]=e[n];continue}const i=s[n],r=e[n];if(i&&r&&typeof i=="object"&&typeof r=="object"){if(Array.isArray(i)&&Array.isArray(r)){const o=r.filter(a=>!i.some(l=>{if(typeof l=="object"&&typeof a=="object"&&l!==null&&a!==null&&!Array.isArray(l)&&!Array.isArray(a)){for(const u in a)if(!(u in l)||!Xn(l[u],a[u]))return!1;return!0}else return JSON.stringify(l)===JSON.stringify(a)}));o.length>0&&(t[n]=o)}else if(!Array.isArray(i)&&!Array.isArray(r)){const o=Qn(i,r);o!==null&&(t[n]=o)}else t[n]=r;continue}Xn(i,r)||(t[n]=r)}return Object.keys(t).length===0?null:t}c(Qn,"getNotMatchingSubFields");function Xn(s,e){if(s==e||s?.toString?.()===e?.toString?.())return!0;const t=new Date(s),n=new Date(e);return!isNaN(t.getTime())&&!isNaN(n.getTime())?t.getTime()===n.getTime():!1}c(Xn,"softCompare");class Wa extends Ee{static{c(this,"DataCollectionCreateTester")}dataCollectionKey;dataCollection;constructor({environment:e,dataCollectionKey:t,dataCollection:n}){super({environment:e,path:`data/${t}/create`}),this.dataCollectionKey=t,this.dataCollection=n}async run(e){const t=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).create(e.input);await this.assert(()=>!!t.id,"Returned ID of a created record"),t.id&&(this.environment.state[this.dataCollectionKey]={createdRecordId:t.id});const n=tn(this.dataCollection);if(this.dataCollection.findById){const r=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).findById({id:t.id});await this.assert(()=>!!r.record,"Record is returned from findById"),r.record&&(this.environment.state[this.dataCollectionKey]={createdRecordId:t.id,createdRecord:r.record.fields});const o=os(n),a=gt(e.input.fields,o,{skipUnknownFields:!0}),l=gt(r.record.fields,o),u=Qn(l,a);await this.assert(()=>!u,"Returned fields match created fields",{difference:u,sentFields:a,receivedFields:l})}const i=zi(n);if(i.length>0){const r={};i.forEach(a=>{const l=Qi(e.input.fields,a);typeof l<"u"&&en(r,a,l)});const o=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).create({fields:r});await this.assert(()=>!!o.id,"Record can be created with schema-defined required fields only")}}async generateConfig(){const e=tn(this.dataCollection);if(!e?.properties)throw new Error("No fields schema found for data collection");return{input:{fields:await this.generateFieldsWithLLM(e)}}}async fixTestCase({config:e,error:t}){const n=ue(t),i=tn(this.dataCollection),r=await this.getExampleRecordsForSchema(i),o=`I'm trying to create a data record in a data collection with the following fields schema:
150
150
 
151
151
  ${JSON.stringify(i,null,2)}
152
152
 
@@ -186,7 +186,7 @@ ${JSON.stringify(i,null,2)}`).join(`
186
186
 
187
187
  `)}.
188
188
 
189
- If you don't have an example for a given collection, leave the field empty instead of coming up with a fake record id.`}async findReferenceCollections(e){const t=new Set,n=[];return cs(e,i=>{if(i.referenceCollection){const r=i.referenceCollection.key,o=i.referenceCollection.parameters,a=`${r}:${JSON.stringify(o||{})}`;t.has(a)||(t.add(a),n.push({key:r,parameters:o}))}return i}),n}async fetchExampleRecords(e){return(await this.environment.client.connection(this.environment.connectionId).dataCollection(e.key).list({parameters:e.parameters})).records.map(n=>({id:n.id,fields:n.fields}))}async getExampleRecordsForSchema(e){const t=await this.findReferenceCollections(e),n={};for(const i of t){const r=ls(i);n[r]=await this.fetchExampleRecords(i)}return n}}class Ha extends ve{static{c(this,"DataCollectionDeleteTester")}dataCollectionKey;dataCollection;constructor({environment:e,dataCollectionKey:t,dataCollection:n}){super({environment:e,path:`data/${t}/delete`}),this.dataCollectionKey=t,this.dataCollection=n}async run(e){const t=this.environment.state[this.dataCollectionKey]?.createdRecordId||e?.input?.id;if(!t)throw new Error(`No ID found in state or config for ${this.dataCollectionKey} delete`);try{await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).delete({id:t})}catch(n){throw n}if(this.dataCollection.findById)try{await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).findById({id:t})}catch(n){if(n?.data?.data?.response?.status===404){await this.assert(()=>!0,"Record is not found after deletion");return}throw n}else await this.assert(()=>!0,"No findById capability, skipping verification")}async generateConfig(){let e=this.environment.state[this.dataCollectionKey]?.createdRecordId;if(!e){if(!this.dataCollection.list)throw new Error(`Can't find a record to test delete operation for ${this.dataCollectionKey}. List operation is not implemented for this data collection`);const t=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).list({});if(!t?.records?.length)throw new Error(`No records found to test delete for ${this.dataCollectionKey}`);e=t.records[0].id}return{input:{id:e}}}async fixTestCase({config:e,error:t}){const n=le(t),i=`I'm trying to delete a record from a data collection.
189
+ If you don't have an example for a given collection, leave the field empty instead of coming up with a fake record id.`}async findReferenceCollections(e){const t=new Set,n=[];return as(e,i=>{if(i.referenceCollection){const r=i.referenceCollection.key,o=i.referenceCollection.parameters,a=`${r}:${JSON.stringify(o||{})}`;t.has(a)||(t.add(a),n.push({key:r,parameters:o}))}return i}),n}async fetchExampleRecords(e){return(await this.environment.client.connection(this.environment.connectionId).dataCollection(e.key).list({parameters:e.parameters})).records.map(n=>({id:n.id,fields:n.fields}))}async getExampleRecordsForSchema(e){const t=await this.findReferenceCollections(e),n={};for(const i of t){const r=cs(i);n[r]=await this.fetchExampleRecords(i)}return n}}class Ga extends Ee{static{c(this,"DataCollectionDeleteTester")}dataCollectionKey;dataCollection;constructor({environment:e,dataCollectionKey:t,dataCollection:n}){super({environment:e,path:`data/${t}/delete`}),this.dataCollectionKey=t,this.dataCollection=n}async run(e){const t=this.environment.state[this.dataCollectionKey]?.createdRecordId||e?.input?.id;if(!t)throw new Error(`No ID found in state or config for ${this.dataCollectionKey} delete`);try{await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).delete({id:t})}catch(n){throw n}if(this.dataCollection.findById)try{await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).findById({id:t})}catch(n){if(n?.data?.data?.response?.status===404){await this.assert(()=>!0,"Record is not found after deletion");return}throw n}else await this.assert(()=>!0,"No findById capability, skipping verification")}async generateConfig(){let e=this.environment.state[this.dataCollectionKey]?.createdRecordId;if(!e){if(!this.dataCollection.list)throw new Error(`Can't find a record to test delete operation for ${this.dataCollectionKey}. List operation is not implemented for this data collection`);const t=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).list({});if(!t?.records?.length)throw new Error(`No records found to test delete for ${this.dataCollectionKey}`);e=t.records[0].id}return{input:{id:e}}}async fixTestCase({config:e,error:t}){const n=ue(t),i=`I'm trying to delete a record from a data collection.
190
190
 
191
191
  I tried to delete a record with this ID:
192
192
 
@@ -206,7 +206,7 @@ Format your response as a JSON object with two fields:
206
206
  "id": "fixed id"
207
207
  }.
208
208
 
209
- Only return the JSON object, no other text or wrapping (like \`\`\`json or \`\`\`).`,r=await this.environment.llm.complete({prompt:i,maxTokens:1e3}),o=JSON.parse(r.trim());return console.warn(k.bold.yellow("[auto-fix]"),`${this.path}:`,o.explanation),{input:{id:o.id}}}}class Ya extends ve{static{c(this,"DataCollectionFindByIdTester")}dataCollectionKey;dataCollection;constructor({environment:e,dataCollectionKey:t,dataCollection:n}){super({environment:e,path:`data/${t}/find-by-id`}),this.dataCollectionKey=t,this.dataCollection=n}async run(e){const t=this.environment.state[this.dataCollectionKey]?.createdRecordId||e?.input?.id;if(!t)throw new Error(`No ID found in state or config for ${this.dataCollectionKey} find-by-id`);const n=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).findById({id:t});await this.assert(()=>!!n.record,"Record is returned from findById"),await this.assert(()=>n.record.id===t,"Returned record ID matches requested ID")}async generateConfig(){let e=this.environment.state[this.dataCollectionKey]?.createdRecordId;if(!e){if(!this.dataCollection.list)throw new Error(`Can't find a record to test findById operation for ${this.dataCollectionKey}. List operation is not implemented for this data collection`);const t=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).list({});if(!t?.records?.length)throw new Error(`No records found to test findById for ${this.dataCollectionKey}`);e=t.records[0].id}return{input:{id:e}}}async fixTestCase({config:e,error:t}){const n=le(t),i=`I'm trying to find a record by ID in a data collection.
209
+ Only return the JSON object, no other text or wrapping (like \`\`\`json or \`\`\`).`,r=await this.environment.llm.complete({prompt:i,maxTokens:1e3}),o=JSON.parse(r.trim());return console.warn(k.bold.yellow("[auto-fix]"),`${this.path}:`,o.explanation),{input:{id:o.id}}}}class Va extends Ee{static{c(this,"DataCollectionFindByIdTester")}dataCollectionKey;dataCollection;constructor({environment:e,dataCollectionKey:t,dataCollection:n}){super({environment:e,path:`data/${t}/find-by-id`}),this.dataCollectionKey=t,this.dataCollection=n}async run(e){const t=this.environment.state[this.dataCollectionKey]?.createdRecordId||e?.input?.id;if(!t)throw new Error(`No ID found in state or config for ${this.dataCollectionKey} find-by-id`);const n=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).findById({id:t});await this.assert(()=>!!n.record,"Record is returned from findById"),await this.assert(()=>n.record.id===t,"Returned record ID matches requested ID")}async generateConfig(){let e=this.environment.state[this.dataCollectionKey]?.createdRecordId;if(!e){if(!this.dataCollection.list)throw new Error(`Can't find a record to test findById operation for ${this.dataCollectionKey}. List operation is not implemented for this data collection`);const t=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).list({});if(!t?.records?.length)throw new Error(`No records found to test findById for ${this.dataCollectionKey}`);e=t.records[0].id}return{input:{id:e}}}async fixTestCase({config:e,error:t}){const n=ue(t),i=`I'm trying to find a record by ID in a data collection.
210
210
 
211
211
  I tried to find a record with this ID:
212
212
 
@@ -226,7 +226,7 @@ Format your response as a JSON object with two fields:
226
226
  "id": "fixed id"
227
227
  }.
228
228
 
229
- Only return the JSON object, no other text or wrapping (like \`\`\`json or \`\`\`).`,r=await this.environment.llm.complete({prompt:i,maxTokens:1e3}),o=JSON.parse(r.trim());return console.warn(k.bold.yellow("[auto-fix]"),`${this.path}:`,o.explanation),{input:{id:o.id}}}}class za extends ve{static{c(this,"DataCollectionListTester")}dataCollectionKey;constructor({environment:e,dataCollectionKey:t}){super({environment:e,path:`data/${t}/list`}),this.dataCollectionKey=t}async run(e){const t=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).list(e.input);if(await this.assert(()=>Array.isArray(t.records),"Response has records field as array"),e.input.sort){const{field:n,direction:i}=e.input.sort,r=t.records;if(r.length>1)for(let o=1;o<r.length;o++){const a=r[o-1].fields[n],l=r[o].fields[n];a==null||l==null||(i==="asc"?await this.assert(()=>a<=l,`Records are sorted by ${n} in ascending order`):await this.assert(()=>a>=l,`Records are sorted by ${n} in descending order`))}}}async generateConfig(){return{input:{}}}async fixTestCase({config:e,error:t}){const n=le(t),i=`I'm trying to list records from a data collection.
229
+ Only return the JSON object, no other text or wrapping (like \`\`\`json or \`\`\`).`,r=await this.environment.llm.complete({prompt:i,maxTokens:1e3}),o=JSON.parse(r.trim());return console.warn(k.bold.yellow("[auto-fix]"),`${this.path}:`,o.explanation),{input:{id:o.id}}}}class Ha extends Ee{static{c(this,"DataCollectionListTester")}dataCollectionKey;constructor({environment:e,dataCollectionKey:t}){super({environment:e,path:`data/${t}/list`}),this.dataCollectionKey=t}async run(e){const t=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).list(e.input);if(await this.assert(()=>Array.isArray(t.records),"Response has records field as array"),e.input.sort){const{field:n,direction:i}=e.input.sort,r=t.records;if(r.length>1)for(let o=1;o<r.length;o++){const a=r[o-1].fields[n],l=r[o].fields[n];a==null||l==null||(i==="asc"?await this.assert(()=>a<=l,`Records are sorted by ${n} in ascending order`):await this.assert(()=>a>=l,`Records are sorted by ${n} in descending order`))}}}async generateConfig(){return{input:{}}}async fixTestCase({config:e,error:t}){const n=ue(t),i=`I'm trying to list records from a data collection.
230
230
 
231
231
  I tried to list records with these parameters:
232
232
 
@@ -246,7 +246,7 @@ Format your response as a JSON object with two fields:
246
246
  "input": { ... fixed parameters ... }
247
247
  }.
248
248
 
249
- Only return the JSON object, no other text or wrapping (like \`\`\`json or \`\`\`).`,r=await this.environment.llm.complete({prompt:i,maxTokens:1e3}),o=JSON.parse(r.trim());return console.warn(k.bold.yellow("[auto-fix]"),`${this.path}:`,o.explanation),{input:o.input}}}class Qa extends ve{static{c(this,"DataCollectionMatchTester")}dataCollectionKey;dataCollection;constructor({environment:e,dataCollectionKey:t,dataCollection:n}){super({environment:e,path:`data/${t}/match`}),this.dataCollectionKey=t,this.dataCollection=n}async run(e){const t=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).match(e.input);await this.assert(()=>!!t.record,"Response contains a record");const n=t.record,r=(await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).findById({id:n.id})).record;for(const[o,a]of Object.entries(e.input.query)){const l=r.fields[o];await this.assert(()=>Zn(l,a),`Record field ${o} matches input value - expected ${JSON.stringify(a)} got ${JSON.stringify(l)}`)}}async generateConfig(){if(!this.dataCollection.list)throw new Error(`Can't find a record to test match operation for ${this.dataCollectionKey}. List operation is not implemented for this data collection`);const e=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).list({});if(!e?.records?.length)throw new Error("No records found to test match");const t=e.records[0];if(!t?.fields)throw new Error("First record has no fields to match against");const n={},i=t.fields||{},r=Object.entries(i).filter(([o,a])=>o!=="links"&&a!=null&&a!=="").slice(0,1);if(r.length===0)throw new Error("No usable fields found in record for matching");for(const[o,a]of r)n[o]=a;return{input:{query:n}}}async fixTestCase({config:e,error:t}){const n=le(t),i=`I'm trying to match a record in a data collection.
249
+ Only return the JSON object, no other text or wrapping (like \`\`\`json or \`\`\`).`,r=await this.environment.llm.complete({prompt:i,maxTokens:1e3}),o=JSON.parse(r.trim());return console.warn(k.bold.yellow("[auto-fix]"),`${this.path}:`,o.explanation),{input:o.input}}}class Ya extends Ee{static{c(this,"DataCollectionMatchTester")}dataCollectionKey;dataCollection;constructor({environment:e,dataCollectionKey:t,dataCollection:n}){super({environment:e,path:`data/${t}/match`}),this.dataCollectionKey=t,this.dataCollection=n}async run(e){const t=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).match(e.input);await this.assert(()=>!!t.record,"Response contains a record");const n=t.record,r=(await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).findById({id:n.id})).record;for(const[o,a]of Object.entries(e.input.query)){const l=r.fields[o];await this.assert(()=>Xn(l,a),`Record field ${o} matches input value - expected ${JSON.stringify(a)} got ${JSON.stringify(l)}`)}}async generateConfig(){if(!this.dataCollection.list)throw new Error(`Can't find a record to test match operation for ${this.dataCollectionKey}. List operation is not implemented for this data collection`);const e=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).list({});if(!e?.records?.length)throw new Error("No records found to test match");const t=e.records[0];if(!t?.fields)throw new Error("First record has no fields to match against");const n={},i=t.fields||{},r=Object.entries(i).filter(([o,a])=>o!=="links"&&a!=null&&a!=="").slice(0,1);if(r.length===0)throw new Error("No usable fields found in record for matching");for(const[o,a]of r)n[o]=a;return{input:{query:n}}}async fixTestCase({config:e,error:t}){const n=ue(t),i=`I'm trying to match a record in a data collection.
250
250
 
251
251
  I tried to match a record with this query:
252
252
 
@@ -266,12 +266,12 @@ Format your response as a JSON object with two fields:
266
266
  "query": { ... fixed query ... }
267
267
  }.
268
268
 
269
- Only return the JSON object, no other text or wrapping (like \`\`\`json or \`\`\`).`,r=await this.environment.llm.complete({prompt:i,maxTokens:1e3}),o=JSON.parse(r.trim());return console.warn(k.bold.yellow("[auto-fix]"),`${this.path}:`,o.explanation),{input:{query:o.query}}}}class Xa extends ve{static{c(this,"DataCollectionSearchTester")}dataCollectionKey;dataCollection;constructor({environment:e,dataCollectionKey:t,dataCollection:n}){super({environment:e,path:`data/${t}/search`}),this.dataCollectionKey=t,this.dataCollection=n}async run(e){const t=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).search(e.input);await this.assert(()=>Array.isArray(t.records),"Response has records field as array");const n=t.records.some(i=>i.id===e.expectedRecordId);n||console.debug(k.yellow(`Search query "${e.input.query}" did not return expected record`)),await this.assert(()=>n,"Search returns expected record")}async generateConfig(){if(!this.dataCollection.list)throw new Error(`Can't find a record to test search operation for ${this.dataCollectionKey}. List operation is not implemented for this data collection`);const e=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).list({});if(!e.records.length)throw new Error("No records found to test search");const t=e.records[0],n=await this.getSearchQueryWithLLM(t.fields);if(!n)throw new Error("Unable to generate search query. LLM could not identify a suitable field value from the record to use as the search query.");return{input:{query:n},expectedRecordId:t.id}}async getSearchQueryWithLLM(e){const t=`You are given the fields of a record from a data collection. Identify the BEST single field value that a user is MOST likely to type when searching for this record (e.g. name, title, email, external id). Ignore null, empty strings, technical IDs, HTML, and timestamps unless they are obviously human-searchable. Make sure the field value is as unique as possible for this record. RETURN ONLY the field value as a plain string. No additional text, no JSON, no quotes.
269
+ Only return the JSON object, no other text or wrapping (like \`\`\`json or \`\`\`).`,r=await this.environment.llm.complete({prompt:i,maxTokens:1e3}),o=JSON.parse(r.trim());return console.warn(k.bold.yellow("[auto-fix]"),`${this.path}:`,o.explanation),{input:{query:o.query}}}}class za extends Ee{static{c(this,"DataCollectionSearchTester")}dataCollectionKey;dataCollection;constructor({environment:e,dataCollectionKey:t,dataCollection:n}){super({environment:e,path:`data/${t}/search`}),this.dataCollectionKey=t,this.dataCollection=n}async run(e){const t=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).search(e.input);await this.assert(()=>Array.isArray(t.records),"Response has records field as array");const n=t.records.some(i=>i.id===e.expectedRecordId);n||console.debug(k.yellow(`Search query "${e.input.query}" did not return expected record`)),await this.assert(()=>n,"Search returns expected record")}async generateConfig(){if(!this.dataCollection.list)throw new Error(`Can't find a record to test search operation for ${this.dataCollectionKey}. List operation is not implemented for this data collection`);const e=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).list({});if(!e.records.length)throw new Error("No records found to test search");const t=e.records[0],n=await this.getSearchQueryWithLLM(t.fields);if(!n)throw new Error("Unable to generate search query. LLM could not identify a suitable field value from the record to use as the search query.");return{input:{query:n},expectedRecordId:t.id}}async getSearchQueryWithLLM(e){const t=`You are given the fields of a record from a data collection. Identify the BEST single field value that a user is MOST likely to type when searching for this record (e.g. name, title, email, external id). Ignore null, empty strings, technical IDs, HTML, and timestamps unless they are obviously human-searchable. Make sure the field value is as unique as possible for this record. RETURN ONLY the field value as a plain string. No additional text, no JSON, no quotes.
270
270
 
271
271
  Record fields:
272
272
  ${JSON.stringify(e,null,2)}
273
273
 
274
- Field value:`;try{return(await this.environment.llm.complete({prompt:t,maxTokens:1e3})).trim()||null}catch{return null}}async fixTestCase({config:e,error:t}){const n=le(t),i=`I'm trying to search records in a data collection.
274
+ Field value:`;try{return(await this.environment.llm.complete({prompt:t,maxTokens:1e3})).trim()||null}catch{return null}}async fixTestCase({config:e,error:t}){const n=ue(t),i=`I'm trying to search records in a data collection.
275
275
 
276
276
  I tried to search records with these parameters:
277
277
 
@@ -291,7 +291,7 @@ Format your response as a JSON object with two fields:
291
291
  "input": { ... fixed parameters ... }
292
292
  }.
293
293
 
294
- Only return the JSON object, no other text or wrapping (like \`\`\`json or \`\`\`).`,r=await this.environment.llm.complete({prompt:i,maxTokens:1e3}),o=JSON.parse(r.trim());return console.warn(k.bold.yellow("[auto-fix]"),`${this.path}:`,o.explanation),{input:o.input,expectedRecordId:e.expectedRecordId}}}class Za extends ve{static{c(this,"DataCollectionSpecTester")}dataCollection;constructor({environment:e,dataCollectionKey:t,dataCollection:n}){super({environment:e,path:`data/${t}/spec`}),this.dataCollection=n}async run(){const e=Object.keys(this.dataCollection.fieldsSchema).length;await this.assert(()=>e>0,"Fields schema has field definitions")}}class ec extends ve{static{c(this,"DataCollectionUpdateTester")}dataCollectionKey;dataCollection;constructor({environment:e,dataCollectionKey:t,dataCollection:n}){super({environment:e,path:`data/${t}/update`}),this.dataCollectionKey=t,this.dataCollection=n}async run(e){const t=this.environment.state[this.dataCollectionKey]?.createdRecordId||e?.input?.id;if(!t)throw new Error(`No ID found in state or config for ${this.dataCollectionKey} update`);const n=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).update({...e.input,id:t});if(await this.assert(()=>!!n.id,"Returned ID of updated record"),this.environment.state[this.dataCollectionKey]||(this.environment.state[this.dataCollectionKey]={}),this.environment.state[this.dataCollectionKey].createdRecordId=n.id,this.dataCollection.findById){const i=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).findById({id:n.id});await this.assert(()=>!!i.record,"Record is returned from findById");const r=sn(this.dataCollection),o=as(r),a=yt(e.input.fields,o,{skipUnknownFields:!0}),l=yt(i.record.fields,o),u=Xn(l,a);await this.assert(()=>!u,"Returned fields match updated fields",{difference:u,sentFields:a,receivedFields:l})}}async generateConfig(){let e=this.environment.state[this.dataCollectionKey]?.createdRecordId;if(!e){if(!this.dataCollection.list)throw new Error(`Can't find a record to test update operation for ${this.dataCollectionKey}. List operation is not implemented for this data collection`);const i=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).list({});if(!i?.records?.length)throw new Error(`No records found to test update for ${this.dataCollectionKey}`);e=i.records[0].id}const t=sn(this.dataCollection);if(!t?.properties)throw new Error("No fields schema found for data collection");const n=await this.generateFieldsWithLLM(t);return{input:{id:e,fields:n}}}async fixTestCase({config:e,error:t}){const n=le(t),i=sn(this.dataCollection),r=await this.getExampleRecordsForSchema(i),o=`I'm trying to update a data record in a data collection with the following fields schema:
294
+ Only return the JSON object, no other text or wrapping (like \`\`\`json or \`\`\`).`,r=await this.environment.llm.complete({prompt:i,maxTokens:1e3}),o=JSON.parse(r.trim());return console.warn(k.bold.yellow("[auto-fix]"),`${this.path}:`,o.explanation),{input:o.input,expectedRecordId:e.expectedRecordId}}}class Qa extends Ee{static{c(this,"DataCollectionSpecTester")}dataCollection;constructor({environment:e,dataCollectionKey:t,dataCollection:n}){super({environment:e,path:`data/${t}/spec`}),this.dataCollection=n}async run(){const e=Object.keys(this.dataCollection.fieldsSchema).length;await this.assert(()=>e>0,"Fields schema has field definitions")}}class Xa extends Ee{static{c(this,"DataCollectionUpdateTester")}dataCollectionKey;dataCollection;constructor({environment:e,dataCollectionKey:t,dataCollection:n}){super({environment:e,path:`data/${t}/update`}),this.dataCollectionKey=t,this.dataCollection=n}async run(e){const t=this.environment.state[this.dataCollectionKey]?.createdRecordId||e?.input?.id;if(!t)throw new Error(`No ID found in state or config for ${this.dataCollectionKey} update`);const n=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).update({...e.input,id:t});if(await this.assert(()=>!!n.id,"Returned ID of updated record"),this.environment.state[this.dataCollectionKey]||(this.environment.state[this.dataCollectionKey]={}),this.environment.state[this.dataCollectionKey].createdRecordId=n.id,this.dataCollection.findById){const i=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).findById({id:n.id});await this.assert(()=>!!i.record,"Record is returned from findById");const r=nn(this.dataCollection),o=os(r),a=gt(e.input.fields,o,{skipUnknownFields:!0}),l=gt(i.record.fields,o),u=Qn(l,a);await this.assert(()=>!u,"Returned fields match updated fields",{difference:u,sentFields:a,receivedFields:l})}}async generateConfig(){let e=this.environment.state[this.dataCollectionKey]?.createdRecordId;if(!e){if(!this.dataCollection.list)throw new Error(`Can't find a record to test update operation for ${this.dataCollectionKey}. List operation is not implemented for this data collection`);const i=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).list({});if(!i?.records?.length)throw new Error(`No records found to test update for ${this.dataCollectionKey}`);e=i.records[0].id}const t=nn(this.dataCollection);if(!t?.properties)throw new Error("No fields schema found for data collection");const n=await this.generateFieldsWithLLM(t);return{input:{id:e,fields:n}}}async fixTestCase({config:e,error:t}){const n=ue(t),i=nn(this.dataCollection),r=await this.getExampleRecordsForSchema(i),o=`I'm trying to update a data record in a data collection with the following fields schema:
295
295
 
296
296
  ${JSON.stringify(i,null,2)}
297
297
 
@@ -331,9 +331,9 @@ ${JSON.stringify(i,null,2)}`).join(`
331
331
 
332
332
  `)}.
333
333
 
334
- If you don't have an example for a given collection, leave the field empty instead of coming up with a fake record id.`}async findReferenceCollections(e){const t=new Set,n=[];return cs(e,i=>{if(i.referenceCollection){const r=i.referenceCollection.key,o=i.referenceCollection.parameters,a=`${r}:${JSON.stringify(o||{})}`;t.has(a)||(t.add(a),n.push({key:r,parameters:o}))}return i}),n}async fetchExampleRecords(e){return(await this.environment.client.connection(this.environment.connectionId).dataCollection(e.key).list({parameters:e.parameters})).records.map(n=>({id:n.id,fields:n.fields}))}async getExampleRecordsForSchema(e){const t=await this.findReferenceCollections(e),n={};for(const i of t){const r=ls(i);n[r]=await this.fetchExampleRecords(i)}return n}}const es={spec:{testerClass:Za},create:{testerClass:Va,operationKey:"create"},"find-by-id":{testerClass:Ya,operationKey:"findById"},list:{testerClass:za,operationKey:"list"},match:{testerClass:Qa,operationKey:"match"},search:{testerClass:Xa,operationKey:"search"},update:{testerClass:ec,operationKey:"update"},delete:{testerClass:Ha,operationKey:"delete"}};class tc extends Ga{static{c(this,"DataCollectionTestSuite")}dataCollectionKey;testMethod;constructor({environment:e,dataCollectionKey:t,testMethod:n}){super({environment:e}),this.dataCollectionKey=t,this.testMethod=n}async run(){const e=await this.fetchDataCollection(),t=this.testMethod?[this.createTester(this.testMethod,e)]:this.createAllAvailableTesters(e);W.info("\u{1F680} Running tests...");for(const n of t)await this.runTest(n);this.displayTestSummary(t.length)}async fetchDataCollection(){return this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).get()}isOperationAvailable(e,t){return t?!!e[t]:!0}createTester(e,t){const n=es[e];if(!n)throw new Error(`Unknown test method "${e}". Available: ${this.getAvailableTestMethods(t).join(", ")}`);const i="operationKey"in n?n.operationKey:void 0;if(!this.isOperationAvailable(t,i))throw new Error(`${i} operation not available for data collection "${this.dataCollectionKey}"`);return this.instantiateTester(n,t)}createAllAvailableTesters(e){return Object.entries(es).filter(([,t])=>{const n="operationKey"in t?t.operationKey:void 0;return this.isOperationAvailable(e,n)}).map(([,t])=>this.instantiateTester(t,e))}instantiateTester(e,t){const n={environment:this.environment,dataCollectionKey:this.dataCollectionKey,dataCollection:t};return new e.testerClass(n)}getAvailableTestMethods(e){return Object.entries(es).filter(([,t])=>{const n="operationKey"in t?t.operationKey:void 0;return this.isOperationAvailable(e,n)}).map(([t])=>t)}displayTestSummary(e){W.info(`\u{1F4CA} ${e} test${e===1?"":"s"} executed`)}}class nc extends Ua{static{c(this,"TestRunner")}constructor(e){super(e)}async initialize(){W.debug("Initializing test runner",{prefix:"TestRunner"})}async run(){try{const{testPath:e,path:t,fix:n}=this.options,i=e.split("/");i.length<2&&(W.error("Invalid test path. Expected format: <type>/<name>[/additional/path][/method]"),process.exit(1));const[r,o,...a]=i;r!=="connectors"&&(W.error(`Test type "${r}" is not yet fully implemented. Currently only "connectors" is fully supported.`),W.error("Supported test types: connectors"),process.exit(1));const l=o,u=r,p=[...a,...t?t.split("/"):[]].join("/"),d=await ts.create({connectionId:l,testBasePath:u,options:{fix:n}}),g=await d.client.get(`connections/${l}/data`),w=[],f=p?p.split("/"):[];if(f.length===0||f[0]==="data"){f[0]==="data"&&f.shift();let C,E;f.length>=1&&(E=f[0],f.length>=2&&f[1].trim()!==""&&(C=f[1]));for(const A of g){if(E&&E!==A.key)continue;const I=new tc({environment:d,dataCollectionKey:A.key,testMethod:C});w.push(I)}}w.length===0&&(W.error(`No test suites found for path: ${e}${p?"/"+p:""}`),process.exit(1));const y={};for(const C of w){await C.run();const E=C.getResult();W.debug(`Suite ${C.constructor.name} result:`,{prefix:"TestRunner"}),an(y,E)}console.debug("[TestRunner] All results collected:",Object.keys(y)),d.writeResults(y)}catch(e){throw console.error("Error in TestRunner.run():",e),e}}}const Xt=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 test 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(`
335
- `),"createExperimentalWarning");function sc(s){s.command("test").description("\u26A0\uFE0F EXPERIMENTAL: Test management commands - This feature is experimental and will be changing rapidly. Use at your own risk.").addHelpText("after",Xt()).action(async()=>{console.warn(Xt()),W.error("Please specify a subcommand. Use --help for available options."),process.exit(1)}).command("run").description("Run integration tests for various membrane components").argument("<testPath>",'Test path (e.g., "connectors/netsuite", "actions/create-contact", "connectors/hubspot/data/contacts", "connectors/netsuite/data/contacts/create")').option("-p, --path <path>","Additional path filter within the test scope").option("--fix","Enable auto-fix for test issues").addHelpText("after",["",k.bold("Examples:"),` ${k.gray("\u25B8")} ${k.cyan("membrane test run connectors/netsuite")} # Test all data collections for netsuite connector`,` ${k.gray("\u25B8")} ${k.cyan("membrane test run connectors/netsuite/data/contacts")} # Test specific data collection`,` ${k.gray("\u25B8")} ${k.cyan("membrane test run connectors/netsuite/data/contacts/create")} # Test specific method for data collection`,` ${k.gray("\u25B8")} ${k.cyan("membrane test run connectors/netsuite/data/contacts/delete")} # Test delete method for data collection`,` ${k.gray("\u25B8")} ${k.cyan("membrane test run actions/create-contact")} # Test specific action`,` ${k.gray("\u25B8")} ${k.cyan("membrane test run connectors/hubspot/events")} # Test events for hubspot`,` ${k.gray("\u25B8")} ${k.cyan("membrane test run connectors/salesforce --fix")} # Run tests with auto-fix enabled`,"",k.gray("For more information, visit:"),k.blue(" https://docs.integration.app/cli"),"",Xt()].join(`
336
- `)).action(async(t,n)=>{try{console.warn(Xt()),t||(W.error("Test path is required"),process.exit(1)),W.header(`Testing: ${t}`);const i=new nc({testPath:t,path:n.path,fix:n.fix});await i.initialize(),await i.run(),W.success("Tests completed")}catch(i){i instanceof Error&&(W.error(i.message),process.exit(1)),W.error("An unknown error occurred"),process.exit(1)}})}c(sc,"setupTestCommand");const ic=c(()=>{try{const s=mr(import.meta.url),e=Ui(s),t=Ji(e,"..","package.json");return JSON.parse(Zi(t,"utf-8")).version}catch{return"1.0.0"}},"getPackageVersion"),ji=ic();function rc(){const s=new gr().name("membrane").description("Command-line interface for Membrane Agent").version(ji,"-v, --version","Output the version number");s.configureHelp({sortSubcommands:!0,subcommandTerm:c(t=>k.cyan(t.name()),"subcommandTerm"),commandUsage:c(t=>t.name()==="membrane"?`${k.cyan(t.name())} ${k.gray("[options]")} ${k.cyan("[command]")}`:t.usage(),"commandUsage"),optionTerm:c(t=>{const n=t.flags;return`${k.gray("\u25B8")} ${k.cyan(n)}`},"optionTerm"),subcommandDescription:c(t=>k.gray(t.description()),"subcommandDescription"),optionDescription:c(t=>k.gray(t.description),"optionDescription"),commandDescription:c(t=>k.gray(t.description()),"commandDescription")}),s.addHelpText("beforeAll",`
337
- ${k.bold.cyan("Membrane Agent CLI")} ${k.gray(`v${ji}`)}
334
+ If you don't have an example for a given collection, leave the field empty instead of coming up with a fake record id.`}async findReferenceCollections(e){const t=new Set,n=[];return as(e,i=>{if(i.referenceCollection){const r=i.referenceCollection.key,o=i.referenceCollection.parameters,a=`${r}:${JSON.stringify(o||{})}`;t.has(a)||(t.add(a),n.push({key:r,parameters:o}))}return i}),n}async fetchExampleRecords(e){return(await this.environment.client.connection(this.environment.connectionId).dataCollection(e.key).list({parameters:e.parameters})).records.map(n=>({id:n.id,fields:n.fields}))}async getExampleRecordsForSchema(e){const t=await this.findReferenceCollections(e),n={};for(const i of t){const r=cs(i);n[r]=await this.fetchExampleRecords(i)}return n}}const Zn={spec:{testerClass:Qa},create:{testerClass:Wa,operationKey:"create"},"find-by-id":{testerClass:Va,operationKey:"findById"},list:{testerClass:Ha,operationKey:"list"},match:{testerClass:Ya,operationKey:"match"},search:{testerClass:za,operationKey:"search"},update:{testerClass:Xa,operationKey:"update"},delete:{testerClass:Ga,operationKey:"delete"}};class Za extends Ja{static{c(this,"DataCollectionTestSuite")}dataCollectionKey;testMethod;constructor({environment:e,dataCollectionKey:t,testMethod:n}){super({environment:e}),this.dataCollectionKey=t,this.testMethod=n}async run(){const e=await this.fetchDataCollection(),t=this.testMethod?[this.createTester(this.testMethod,e)]:this.createAllAvailableTesters(e);G.info("\u{1F680} Running tests...");for(const n of t)await this.runTest(n);this.displayTestSummary(t.length)}async fetchDataCollection(){return this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).get()}isOperationAvailable(e,t){return t?!!e[t]:!0}createTester(e,t){const n=Zn[e];if(!n)throw new Error(`Unknown test method "${e}". Available: ${this.getAvailableTestMethods(t).join(", ")}`);const i="operationKey"in n?n.operationKey:void 0;if(!this.isOperationAvailable(t,i))throw new Error(`${i} operation not available for data collection "${this.dataCollectionKey}"`);return this.instantiateTester(n,t)}createAllAvailableTesters(e){return Object.entries(Zn).filter(([,t])=>{const n="operationKey"in t?t.operationKey:void 0;return this.isOperationAvailable(e,n)}).map(([,t])=>this.instantiateTester(t,e))}instantiateTester(e,t){const n={environment:this.environment,dataCollectionKey:this.dataCollectionKey,dataCollection:t};return new e.testerClass(n)}getAvailableTestMethods(e){return Object.entries(Zn).filter(([,t])=>{const n="operationKey"in t?t.operationKey:void 0;return this.isOperationAvailable(e,n)}).map(([t])=>t)}displayTestSummary(e){G.info(`\u{1F4CA} ${e} test${e===1?"":"s"} executed`)}}class ec extends Ba{static{c(this,"TestRunner")}constructor(e){super(e)}async initialize(){G.debug("Initializing test runner",{prefix:"TestRunner"})}async run(){try{const{testPath:e,path:t,fix:n}=this.options,i=e.split("/");i.length<2&&(G.error("Invalid test path. Expected format: <type>/<name>[/additional/path][/method]"),process.exit(1));const[r,o,...a]=i;r!=="connectors"&&(G.error(`Test type "${r}" is not yet fully implemented. Currently only "connectors" is fully supported.`),G.error("Supported test types: connectors"),process.exit(1));const l=o,u=r,p=[...a,...t?t.split("/"):[]].join("/"),d=await es.create({connectionId:l,testBasePath:u,options:{fix:n}}),g=await d.client.get(`connections/${l}/data`),w=[],f=p?p.split("/"):[];if(f.length===0||f[0]==="data"){f[0]==="data"&&f.shift();let C,E;f.length>=1&&(E=f[0],f.length>=2&&f[1].trim()!==""&&(C=f[1]));for(const A of g){if(E&&E!==A.key)continue;const I=new Za({environment:d,dataCollectionKey:A.key,testMethod:C});w.push(I)}}w.length===0&&(G.error(`No test suites found for path: ${e}${p?"/"+p:""}`),process.exit(1));const y={};for(const C of w){await C.run();const E=C.getResult();G.debug(`Suite ${C.constructor.name} result:`,{prefix:"TestRunner"}),on(y,E)}console.debug("[TestRunner] All results collected:",Object.keys(y)),d.writeResults(y)}catch(e){throw console.error("Error in TestRunner.run():",e),e}}}const Qt=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 test 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(`
335
+ `),"createExperimentalWarning");function tc(s){s.command("test").description("\u26A0\uFE0F EXPERIMENTAL: Test management commands - This feature is experimental and will be changing rapidly. Use at your own risk.").addHelpText("after",Qt()).action(async()=>{console.warn(Qt()),G.error("Please specify a subcommand. Use --help for available options."),process.exit(1)}).command("run").description("Run integration tests for various membrane components").argument("<testPath>",'Test path (e.g., "connectors/netsuite", "actions/create-contact", "connectors/hubspot/data/contacts", "connectors/netsuite/data/contacts/create")').option("-p, --path <path>","Additional path filter within the test scope").option("--fix","Enable auto-fix for test issues").addHelpText("after",["",k.bold("Examples:"),` ${k.gray("\u25B8")} ${k.cyan("membrane test run connectors/netsuite")} # Test all data collections for netsuite connector`,` ${k.gray("\u25B8")} ${k.cyan("membrane test run connectors/netsuite/data/contacts")} # Test specific data collection`,` ${k.gray("\u25B8")} ${k.cyan("membrane test run connectors/netsuite/data/contacts/create")} # Test specific method for data collection`,` ${k.gray("\u25B8")} ${k.cyan("membrane test run connectors/netsuite/data/contacts/delete")} # Test delete method for data collection`,` ${k.gray("\u25B8")} ${k.cyan("membrane test run actions/create-contact")} # Test specific action`,` ${k.gray("\u25B8")} ${k.cyan("membrane test run connectors/hubspot/events")} # Test events for hubspot`,` ${k.gray("\u25B8")} ${k.cyan("membrane test run connectors/salesforce --fix")} # Run tests with auto-fix enabled`,"",k.gray("For more information, visit:"),k.blue(" https://docs.integration.app/cli"),"",Qt()].join(`
336
+ `)).action(async(t,n)=>{try{console.warn(Qt()),t||(G.error("Test path is required"),process.exit(1)),G.header(`Testing: ${t}`);const i=new ec({testPath:t,path:n.path,fix:n.fix});await i.initialize(),await i.run(),G.success("Tests completed")}catch(i){i instanceof Error&&(G.error(i.message),process.exit(1)),G.error("An unknown error occurred"),process.exit(1)}})}c(tc,"setupTestCommand");const nc=c(()=>{try{const s=pr(import.meta.url),e=qi(s),t=Ui(e,"..","package.json");return JSON.parse(Xi(t,"utf-8")).version}catch{return"1.0.0"}},"getPackageVersion"),Ki=nc();function sc(){const s=new mr().name("membrane").description("Command-line interface for Membrane Agent").version(Ki,"-v, --version","Output the version number");s.configureHelp({sortSubcommands:!0,subcommandTerm:c(t=>k.cyan(t.name()),"subcommandTerm"),commandUsage:c(t=>t.name()==="membrane"?`${k.cyan(t.name())} ${k.gray("[options]")} ${k.cyan("[command]")}`:t.usage(),"commandUsage"),optionTerm:c(t=>{const n=t.flags;return`${k.gray("\u25B8")} ${k.cyan(n)}`},"optionTerm"),subcommandDescription:c(t=>k.gray(t.description()),"subcommandDescription"),optionDescription:c(t=>k.gray(t.description),"optionDescription"),commandDescription:c(t=>k.gray(t.description()),"commandDescription")}),s.addHelpText("beforeAll",`
337
+ ${k.bold.cyan("Membrane Agent CLI")} ${k.gray(`v${Ki}`)}
338
338
 
339
- `);const e=new Ni(dt.Cli,process.cwd());ja(s,e),qa(s,e),Oa(s,e),Ma(s),sc(s),xa(s),process.argv.length===2&&(s.outputHelp(),process.exit(0)),s.parse()}c(rc,"runCLI");const Fi=["--cwd"];function oc(){const s=process.argv.slice(2);return s.some((e,t)=>t>0&&Fi.includes(s[t-1])?!1:!Fi.includes(e))}c(oc,"hasCLIArguments"),oc()?rc():Aa();
339
+ `);const e=new Ti(ht.Cli,process.cwd());_a(s,e),Fa(s,e),Na(s,e),Da(s),tc(s),La(s),process.argv.length===2&&(s.outputHelp(),process.exit(0)),s.parse()}c(sc,"runCLI");const ji=["--cwd"];function ic(){const s=process.argv.slice(2);return s.some((e,t)=>t>0&&ji.includes(s[t-1])?!1:!ji.includes(e))}c(ic,"hasCLIArguments"),ic()?sc():Ta();