@membranehq/cli 0.2.5 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +150 -149
- package/package.json +2 -2
package/dist/index.js
CHANGED
|
@@ -1,151 +1,152 @@
|
|
|
1
|
-
var yr=Object.defineProperty;var l=(n,e)=>yr(n,"name",{value:e,configurable:!0});import{jsx as y,jsxs as I}from"react/jsx-runtime";import*as J from"node:path";import{resolve as wr,dirname as br,join as Sr}from"node:path";import{useInput as Qe,Box as A,Text as k,Newline as kr,render as sn}from"ink";import Cr from"minimist";import{SWRConfig as vr}from"swr";import Ar from"os";import K from"path";import Or from"conf";import ht,{createContext as as,useContext as cs,useState as D,useEffect as pt,useCallback as ls}from"react";import*as j from"node:fs";import{readFileSync as Er}from"node:fs";import oe from"js-yaml";import{z as F}from"zod";import{exec as Tr}from"node:child_process";import*as $r from"node:crypto";import{createHash as Ir}from"node:crypto";import*as Nr from"node:os";import{TextInput as _r,Select as Lr}from"@inkjs/ui";import rn from"ink-spinner";import us from"swr/immutable";import xr from"ink-text-input";import{EventEmitter as on}from"node:events";import{WorkspaceElementSpecs as ee,WorkspaceElementType as M,IntegrationAppClient as an,setValueAtLocator as cn,extractIntegrationAppErrorData as ae,getDataCollectionCreateFields as ln,excludeWriteOnlyFieldsFromSchema as fs,valueToSchema as mt,getRequiredFieldsFromSchema as Pr,getValueAtLocator as jr,walkSchema as ds,makeDataLocationPath as hs,getDataCollectionUpdateFields as un}from"@membranehq/sdk";import gt from"jsonwebtoken";import Kr from"chokidar";import P from"fs";import Dr from"archiver";import Mr from"form-data";import Rr from"unzipper";import v from"chalk";import{fileURLToPath as Br}from"node:url";import{Command as Fr}from"commander";import fn from"axios";import{FastMCP as qr}from"fastmcp";import dn from"lodash/merge.js";import Ur from"@anthropic-ai/sdk";import{faker as Xe}from"@faker-js/faker";import Jr from"lodash/template.js";import Vr from"lodash/templateSettings.js";const Wr="membrane",zr="membrane.config.yml",hn="https://api.integration.app";function et(){const n=process.cwd(),e=J.join(n,Wr),t=J.join(n,zr),s=e,i=J.join(s,"workspace.yaml");return{membraneDirPath:e,configPath:t,payloadDirPath:s,workspaceDataFilePath:i}}l(et,"getPaths");function Hr(){return et().membraneDirPath}l(Hr,"getBasePath");const Gr={pat:{type:"string"},workspace:{type:"object"}},ps=new Or({schema:Gr,configName:"config",cwd:K.join(Ar.homedir(),".membrane")}),Yr=l(n=>{ps.set("pat",n)},"setPat"),ms=l(()=>ps.get("pat"),"getPat");class gs{static{l(this,"AccountApiClient")}constructor(e=hn){this.apiBaseUrl=e}async request(e,t={}){const s=t.headers?t.headers instanceof Headers?new Headers(t.headers):new Headers(t.headers):new Headers;if(!s.has("Authorization")){const o=ms();if(!o)throw new Error("Personal Access Token not found.");s.set("Authorization",`Bearer ${o}`)}t.body&&!s.has("Content-Type")&&s.set("Content-Type","application/json");const i=await fetch(`${this.apiBaseUrl}${e}`,{...t,headers:s});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 Zr=l(n=>{const e=new gs(hn);return t=>e.get(t)},"createAccountApiFetcher"),ys=as(process.cwd());function Qr({cwd:n,children:e}){return y(ys.Provider,{value:n,children:e})}l(Qr,"CwdProvider");function ws(){return cs(ys)}l(ws,"useCwd");const Xr="membrane.config.yml";function be(n){const e=J.join(n??process.cwd(),Xr);try{const t=j.readFileSync(e,"utf8"),s=oe.load(t),i=bs.safeParse(s);return i.success?i.data:null}catch{return null}}l(be,"readProjectConfig");const eo="membrane.config.yml",bs=F.object({workspaceKey:F.string().optional(),workspaceSecret:F.string().optional(),apiUri:F.string().optional(),testCustomerId:F.string().optional(),anthropicApiKey:F.string().optional()});F.enum(["pull"]);const Ss=as(void 0);function to({children:n}){const e=ws(),[t,s]=D(null),[i,r]=D(!0);pt(()=>{const u=be(e);s(u),r(!1)},[e]);const o=ls(u=>{const d=J.join(e,eo),h={...be(e)??{},...u},m=bs.safeParse(h);return m.success?(j.writeFileSync(d,oe.dump(m.data)),s(m.data),!0):!1},[e]),a=ls(()=>!!(t?.workspaceKey&&t?.workspaceSecret),[t]),c={config:t,isLoading:i,updateConfig:o,validateConfig:a};return y(Ss.Provider,{value:c,children:n})}l(to,"ProjectConfigProvider");function pn(){const n=cs(Ss);if(n===void 0)throw new Error("useProjectConfig must be used within a ProjectConfigProvider");return n}l(pn,"useProjectConfig");function mn({cwd:n,children:e}){const t=n||process.cwd();return y(Qr,{cwd:t,children:y(to,{children:y(vr,{value:{fetcher:Zr()},children:e})})})}l(mn,"Layout");const gn=[{id:"claude-code",name:"Claude Code",description:"Anthropic Claude Code agent",actionDescription:"Adding membrane MCP to .mcp.json in the current directory",addConfig:l(()=>{const n=J.join(process.cwd(),".mcp.json"),e={mcpServers:{membrane:{command:"membrane",args:["mcp"],env:{AGENT_NAME:"Claude Code"}}}};let t={};if(j.existsSync(n))try{t=JSON.parse(j.readFileSync(n,"utf8"))}catch{t={}}const s={...t,mcpServers:{...t.mcpServers,...e.mcpServers}};return j.writeFileSync(n,JSON.stringify(s,null,2)),`MCP server configuration added to ${n}`},"addConfig")},{id:"cursor",name:"Cursor",description:"Cursor AI editor",actionDescription:"Adding membrane MCP to .cursor/mcp.json in the current directory",addConfig:l(()=>{const n=J.join(process.cwd(),".cursor"),e=J.join(n,"mcp.json");j.existsSync(n)||j.mkdirSync(n);const t={mcpServers:{membrane:{command:"membrane",args:["mcp"],env:{AGENT_NAME:"Cursor"}}}};let s={};if(j.existsSync(e))try{s=JSON.parse(j.readFileSync(e,"utf8"))}catch{s={}}const i={...s,mcpServers:{...s.mcpServers,...t.mcpServers}};return j.writeFileSync(e,JSON.stringify(i,null,2)),`MCP server configuration added to ${e}`},"addConfig")}],no=l(({onExit:n,onComplete:e})=>{const[t,s]=D(0),[i,r]=D(!1),[o,a]=D(null),[c,u]=D(""),[d,f]=D("");Qe((w,p)=>{if(c||d){(p.escape||w==="q"||p.return)&&e();return}if(i)p.return||w===" "?h(o):p.escape&&(r(!1),a(null));else if(p.escape)n();else if(p.upArrow||w==="k")s(Math.max(0,t-1));else if(p.downArrow||w==="j")s(Math.min(gn.length-1,t+1));else if(p.return||w===" "){const g=gn[t];a(g),r(!0)}});const h=l(w=>{try{const p=w.addConfig();u(p)}catch(p){f(`Failed to write configuration: ${p.message||p}`)}},"addMcpConfiguration"),m=Math.min(80,process.stdout.columns||80);return c?I(A,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:m,children:[y(A,{marginTop:-1,marginBottom:1,children:I(k,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",y(k,{color:"green",children:"Success"})]})}),I(A,{flexDirection:"column",paddingLeft:2,children:[y(k,{color:"green",children:c}),y(A,{marginTop:1,children:y(k,{color:"grey",children:"The agent will now be able to use Membrane's integration capabilities."})})]}),y(A,{marginTop:1,paddingLeft:2,children:y(k,{color:"white",children:"[esc/q/enter: exit]"})})]}):d?I(A,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:m,children:[y(A,{marginTop:-1,marginBottom:1,children:I(k,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",y(k,{color:"red",children:"Error"})]})}),y(A,{flexDirection:"column",paddingLeft:2,children:y(k,{color:"red",children:d})}),y(A,{marginTop:1,children:y(k,{color:"grey",children:"[esc/q/enter: exit]"})})]}):i&&o?I(A,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:m,children:[y(A,{marginTop:-1,marginBottom:1,children:I(k,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",y(k,{color:"cyan",children:"Confirmation"})]})}),I(A,{flexDirection:"column",paddingLeft:2,children:[I(k,{children:["Connect ",y(k,{bold:!0,children:o.name})," to Membrane via MCP?"]}),y(A,{marginTop:1,children:y(k,{color:"grey",children:"This will add an MCP server configuration that allows the agent to use Membrane's integration capabilities."})}),y(A,{marginTop:1,children:y(k,{color:"yellow",bold:!0,children:o.actionDescription})}),y(A,{marginTop:2,marginBottom:1,children:I(k,{children:[y(k,{color:"white",bold:!0,children:"[Enter] Confirm"})," ",y(k,{color:"gray",children:"[Esc] Cancel"})]})})]})]}):I(A,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:m,children:[y(A,{marginTop:-1,marginBottom:1,children:I(k,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",y(k,{color:"cyan",children:"Select Agent"})]})}),I(A,{flexDirection:"column",paddingLeft:2,children:[y(k,{color:"grey",children:"Choose an agent to connect to Membrane via MCP:"}),y(A,{marginTop:1,children:y(k,{color:"grey",children:"This will add an MCP server configuration that allows the agent to use Membrane's integration capabilities."})}),y(A,{marginTop:1,flexDirection:"column",children:gn.map((w,p)=>I(A,{children:[I(k,{color:t===p?"cyan":"white",children:[t===p?"\u25B6 ":" ",w.name]}),I(k,{color:"grey",children:[" \u2014 ",w.description]})]},w.id))})]}),y(A,{marginTop:1,children:y(k,{color:"grey",children:"[\u2191\u2193: select] [enter: choose] [esc: exit]"})})]})},"AddMcpServerScreen"),he=J.join(Nr.tmpdir(),"membrane-mcp-status"),ks=3e4;function yn(n){return Ir("md5").update(n).digest("hex").slice(0,8)}l(yn,"getCwdHash");function wn(n,e){const t=yn(e);return J.join(he,`mcp-${t}-${n}.json`)}l(wn,"getStatusFilePath");function Te(n,e){try{const t=e||process.cwd();if(!n){const i=yt(t);return i.length===0?null:i[0]}const s=wn(n,t);if(j.existsSync(s)){const i=j.statSync(s),r=new Date;if(r.getTime()-i.mtime.getTime()>ks)return tt(n,t),null;const a=j.readFileSync(s,"utf8"),c=JSON.parse(a);if(c.isRunning){const u=new Date(c.lastActivity).getTime();if(r.getTime()-u>ks)return tt(n,t),null}return c}}catch{n&&e&&tt(n,e)}return null}l(Te,"getMcpStatus");function yt(n){try{const e=n||process.cwd(),t=yn(e);if(!j.existsSync(he))return[];const s=j.readdirSync(he),i=[];for(const r of s){const o=r.match(new RegExp(`^mcp-${t}-(\\d+)\\.json$`));if(o){const a=parseInt(o[1],10),c=Te(a,e);c&&i.push(c)}}return i.sort((r,o)=>new Date(o.startTime).getTime()-new Date(r.startTime).getTime())}catch{return[]}}l(yt,"getAllMcpStatusFiles");function bn(n){try{const t={...Te(n.processId,n.cwd)||{isRunning:!1,startTime:new Date().toISOString(),lastActivity:new Date().toISOString(),toolsCount:0,totalRequests:0,processId:n.processId,cwd:n.cwd,agentName:process.env.AGENT_NAME||"Unnamed Agent"},...n};j.existsSync(he)||j.mkdirSync(he,{recursive:!0});const s=wn(n.processId,n.cwd);j.writeFileSync(s,JSON.stringify(t,null,2))}catch{}}l(bn,"updateMcpStatus");function tt(n,e){try{const t=e||process.cwd();if(n){const s=wn(n,t);j.existsSync(s)&&j.unlinkSync(s)}else{const s=yn(t);if(j.existsSync(he)){const i=j.readdirSync(he);for(const r of i)r.match(new RegExp(`^mcp-${s}-\\d+\\.json$`))&&j.unlinkSync(J.join(he,r))}}}catch{}}l(tt,"clearMcpStatus");function so(n,e){const t=Te(n,e);t&&bn({processId:n,cwd:e,totalRequests:t.totalRequests+1,lastRequestTime:new Date().toISOString(),lastActivity:new Date().toISOString()})}l(so,"trackToolExecution");function io(){const[n,e]=D(Te()),[t,s]=D(yt()),[i,r]=D(null);return pt(()=>{try{const a=process.cwd();e(Te(void 0,a)),s(yt(a)),r(null)}catch(a){r("Failed to read MCP status:"+a),e(null),s([])}const o=setInterval(()=>{try{const a=process.cwd(),c=Te(void 0,a),u=yt(a);e(c),s(u),r(null)}catch(a){r("Failed to read MCP status: "+a),e(null),s([])}},2e3);return()=>clearInterval(o)},[]),{mcpStatus:n,allMcpServers:t,error:i,isRunning:n?.isRunning||!1,toolsCount:n?.toolsCount||0,totalRequests:n?.totalRequests||0,lastActivity:n?.lastActivity,processId:n?.processId,serverCount:t.length}}l(io,"useMcpStatus");const ro=l(()=>{const n=Math.min(100,process.stdout.columns||100),{error:e,serverCount:t,allMcpServers:s}=io();return I(A,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:n,children:[y(A,{marginTop:-1,marginBottom:0,flexDirection:"column",children:I(k,{bold:!0,children:["\u{1F916} Connected AI Agents:"," ",e?y(k,{color:"red",children:"error reading status"}):t===0?y(k,{color:"yellow",children:"none"}):y(k,{color:"green",children:t})]})}),!e&&t===0&&y(A,{marginTop:1,children:I(k,{color:"grey",children:["Connect your AI agents to Membrane.",y(kr,{}),"It will give them tools and context to build integrations."]})}),s.length>0&&y(A,{flexDirection:"column",paddingLeft:2,marginTop:1,children:s.map((i,r)=>y(A,{children:I(k,{color:"grey",children:["#",r+1," ",i.agentName,": ",i.totalRequests," calls"]})},i.processId))}),y(A,{marginTop:1,children:y(k,{color:"grey",children:"[a: connect an agent]"})})]})},"AgentStatus"),Cs=l(({onExit:n,showEscOption:e=!0})=>{const[t,s]=D(""),{data:i,error:r,isLoading:o}=us("/account"),{updateConfig:a,isLoading:c}=pn(),u=i?.workspaces,d=o||c;if(Qe((g,S)=>{S.escape&&n?.()}),d)return I(A,{children:[y(rn,{}),y(k,{children:" Fetching workspaces..."})]});if(r)return I(A,{flexDirection:"column",children:[I(k,{color:"red",children:["Error: ",r.message]}),y(A,{marginTop:1,children:y(k,{color:"grey",children:"Press ESC to go back"})})]});const f=u?.filter(g=>g.name.toLowerCase().includes(t.toLowerCase()))??[],h=f.map(g=>({label:g.name,value:g.id})),m=h.length,w=u?.length??0,p=l(async g=>{const S=f.find(T=>T.id===g);if(!S)return;const{key:b,secret:C}=S;!b||!C||(await a({workspaceKey:b,workspaceSecret:C}),n?.())},"handleSelect");return I(A,{flexDirection:"column",borderStyle:"round",borderTop:!0,width:70,paddingX:1,children:[y(A,{marginTop:-1,children:y(k,{bold:!0,children:"\u{1F4C1} Select your workspace"})}),I(A,{marginTop:1,children:[y(k,{children:"Search: "}),y(_r,{placeholder:"Enter a search query...",onChange:s})]}),w>5&&I(k,{children:["Showing ",m," of ",w," workspaces."]}),y(A,{marginTop:1,children:y(Lr,{options:h,onChange:l(g=>{g&&p(g)},"onChange")})}),e&&y(A,{marginTop:1,children:y(k,{color:"grey",children:"Press ESC to go back"})})]})},"SelectWorkspace"),oo=l(({currentPat:n,onSubmit:e})=>{const[t,s]=D(""),[i,r]=D(!1),[o,a]=D(null);return I(A,{flexDirection:"column",borderStyle:"round",borderTop:!0,width:70,paddingX:1,children:[y(A,{marginTop:-1,marginBottom:1,children:y(k,{bold:!0,children:"\u{1F511} Enter your Personal Access Token"})}),y(k,{children:"Please provide your Personal Access Token. You can find it here:"}),y(A,{marginTop:1,marginBottom:1,children:y(k,{color:"yellow",children:"https://console.integration.app/w/0/manage-account/api-token"})}),n&&y(k,{dimColor:!0,children:"Press Enter to keep your current token or type a new one."}),y(xr,{mask:"*",placeholder:`${n?"******":"Enter your token here..."}`,value:t,onChange:s,onSubmit:l(async u=>{a(null),r(!0);try{await e(u),s("")}catch{a("Invalid token. Please try again.")}finally{r(!1)}},"handleSubmit")}),i&&y(A,{marginTop:1,children:I(k,{children:[y(rn,{type:"dots"})," Validating token..."]})}),o&&y(k,{color:"red",children:o})]})},"PersonalAccessTokenInput");var nt=(n=>(n[n.Authenticate=0]="Authenticate",n[n.ConnectWorkspace=1]="ConnectWorkspace",n))(nt||{});const ao={0:"Authenticate in Membrane",1:"Connect a Membrane Workspace"},vs=l(()=>{const{config:n}=pn(),e=!!(n?.workspaceKey&&n?.workspaceSecret);return{workspaceIsConfigured:e,isSetupComplete:e}},"useSetup"),co=l(({status:n,label:e})=>I(A,{children:[I(A,{width:2,children:[n==="current"&&y(rn,{type:"dots"}),n==="done"&&y(k,{children:"\u2705"})]}),y(k,{dimColor:n!=="current",children:e})]}),"StepDisplay"),Sn=[nt.Authenticate,nt.ConnectWorkspace],As=l(({onComplete:n})=>{const[e,t]=D(!1),[s,i]=D(0),[r,o]=D(!1),[a,c]=D(null),[u,d]=D(""),{isSetupComplete:f}=vs(),h=Sn[s],m=s+1,w=Sn.length,p=Sn.map((C,T)=>{let O="pending";return T<s?O="done":T===s&&(O="current"),{id:C,label:ao[C],status:O}}),g=ms();g&&"*".repeat(g.length);const S=l(async C=>{c(null),o(!0);const T=g&&C===""?g:C,O=new gs;try{await O.request("/account",{headers:{Authorization:`Bearer ${T}`}}),Yr(T),i($=>$+1),d("")}catch($){console.log($),c("Invalid token. Please try again.")}finally{o(!1)}},"handlePatSubmit"),b=l(()=>{t(!0),n&&n()},"handleWorkspaceSelected");return Qe((C,T)=>{f&&T.escape&&n&&n()}),e?y(A,{children:y(k,{children:"\u2705 Setup complete. You are ready to go!"})}):I(A,{flexDirection:"column",alignSelf:"flex-start",gap:1,children:[I(A,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:70,children:[y(A,{marginTop:-1,marginBottom:1,children:I(k,{bold:!0,children:["\u{1F6E0}\uFE0F Setup \u2014"," ",I(k,{color:"cyan",children:["Step ",m," of ",w]}),f&&y(k,{color:"grey",children:" [esc: go back]"})]})}),y(A,{flexDirection:"column",paddingLeft:2,children:p.map(C=>y(co,{status:C.status,label:C.label},C.id))})]}),h===nt.Authenticate&&y(oo,{currentPat:g,onSubmit:S}),h===nt.ConnectWorkspace&&y(Cs,{onExit:b,showEscOption:!1})]})},"Setup"),Os=l(()=>{const{isSetupComplete:n}=vs(),{config:e}=pn();return{isSetupComplete:n,workspaceKey:e?.workspaceKey,config:e}},"useStatus"),lo="membrane",uo=["**/node_modules/**","**/.git/**","**/.DS_Store","**/Thumbs.db","**/*.tmp","**/*.swp","**/*.swo","**/*.log","**/*.lock","**/dist/**","**/build/**","**/.cache/**","**/.next/**","**/.vscode/**","**/.idea/**"];function Es(n){return J.join(n,lo)}l(Es,"getMembraneDir");class fo extends on{static{l(this,"WorkspaceLogger")}_logs=[];get logs(){return[...this._logs]}get latestLogs(){return this._logs.slice(this._logs.length-5)}log(e,t="info"){const s={timestamp:new Date().toISOString(),message:e,type:t};this._logs.push(s),this._logs=this._logs.slice(0,1e3),this.emit("logAdded")}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=[],this.emit("logAdded")}}const V=new fo;class ho{static{l(this,"LocalElementsManagerService")}elements={};basePath;constructor(){this.basePath=Es(process.cwd())}async read(){for(const e of Object.keys(ee)){const t=await this.readElements(e);this.elements[e]=t}}async readElements(e){const t=J.join(this.basePath,ee[e].apiPath),s=j.readdirSync(t);return Promise.all(s.map(i=>this.readElement(J.join(t,i))))}async readElement(e){const t=j.readFileSync(e,"utf8");return oe.load(t)}async writeElement(e,t){const s=this.getElementDir(e,t),i=J.join(s,"spec.yaml"),r=J.join(this.basePath,s),o=J.join(r,"spec.yaml");V.info(`Writing ${i}`),j.existsSync(r)||j.mkdirSync(r,{recursive:!0}),j.writeFileSync(o,oe.dump(t))}getElementDir(e,t){const s=this.getElementTypeDir(e);let i=J.join(s,t.key);const r=this.getIntegrationKey(t);if(r){const o=`${this.getElementTypeDir(M.Integration)}/${r}`;i=J.join(o,i)}return i}getElementTypeDir(e){return ee[e].apiPath}getIntegrationKey(e){return e.integration?e.integration.key:e.integrationKey}}function po(n){if(!yo(n)&&go(n))return mo(n)}l(po,"getTypeAndKeyFromPath");function mo(n){const e=Object.values(ee).map(o=>o.apiPath),t=new RegExp(`^(?<elementTypePlural>${e.join("|")})/(?<elementKey>[^/]+)/spec.y[a]*ml$`),s=n.match(t);if(s&&s.groups){const{elementTypePlural:o,elementKey:a}=s.groups,c=Ts(o);if(c)return{key:a,type:c}}const i=new RegExp(`^integrations/(?<integrationKey>[^/]+)/(?<elementTypePlural>${e.join("|")})/(?<elementKey>[^/]+)/spec.y[a]*ml$`),r=n.match(i);if(r&&r.groups){const{elementTypePlural:o,elementKey:a}=r.groups,c=Ts(o);if(c)return{key:a,type:c}}}l(mo,"extractWorkspaceElementKeyReference");function go(n){return n.endsWith(".yml")||n.endsWith(".yaml")}l(go,"isWorkspaceElementFile");function yo(n){const[e]=n.split(J.sep);return e===ee[M.Connector].apiPath}l(yo,"isConnectorFile");function Ts(n){return Object.values(M).find(e=>wo(e)===n)}l(Ts,"getWorkspaceElementTypeFromFolderName");function wo(n){return ee[n].apiPath}l(wo,"getWorkspaceElementTypeFolderName");var L={},wt={},$s;function Is(){if($s)return wt;$s=1,Object.defineProperty(wt,"__esModule",{value:!0});function n(e){return e===void 0&&(e=""),e?String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/[^A-Za-z0-9]+/g,"$").replace(/([a-z])([A-Z])/g,function(t,s,i){return s+"$"+i}).toLowerCase().replace(/(\$)(\w)/g,function(t,s,i){return i.toUpperCase()}):""}return l(n,"toCamelCase"),wt.default=n,wt}l(Is,"requireJsCamelcase");var bt={},Ns;function _s(){if(Ns)return bt;Ns=1,Object.defineProperty(bt,"__esModule",{value:!0});function n(e){return e===void 0&&(e=""),e?String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/([a-z])([A-Z])/g,function(t,s,i){return s+"_"+i.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g,"_").toLowerCase():""}return l(n,"toSnakeCase"),bt.default=n,bt}l(_s,"requireJsSnakecase");var St={},Ls;function xs(){if(Ls)return St;Ls=1,Object.defineProperty(St,"__esModule",{value:!0});function n(e){return e===void 0&&(e=""),e?String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"$").replace(/[^A-Za-z0-9]+/g,"$").replace(/([a-z])([A-Z])/g,function(t,s,i){return s+"$"+i}).toLowerCase().replace(/(\$)(\w?)/g,function(t,s,i){return i.toUpperCase()}):""}return l(n,"toPascalCase"),St.default=n,St}l(xs,"requireJsPascalcase");var kt={},Ps;function bo(){if(Ps)return kt;Ps=1,Object.defineProperty(kt,"__esModule",{value:!0});function n(e){return e===void 0&&(e=""),e?String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/([a-z])([A-Z])/g,function(t,s,i){return s+"_"+i.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g,".").toLowerCase():""}return l(n,"toDotCase"),kt.default=n,kt}l(bo,"requireJsDotcase");var Ct={},js;function So(){if(js)return Ct;js=1,Object.defineProperty(Ct,"__esModule",{value:!0});function n(e){return e===void 0&&(e=""),e?String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/([a-z])([A-Z])/g,function(t,s,i){return s+"_"+i.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g,"/").toLowerCase():""}return l(n,"toPathCase"),Ct.default=n,Ct}l(So,"requireJsPathcase");var vt={},Ks;function ko(){if(Ks)return vt;Ks=1,Object.defineProperty(vt,"__esModule",{value:!0});function n(e){return e===void 0&&(e=""),e?String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/([a-z])([A-Z])/g,function(t,s,i){return s+"_"+i.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g," ").toLowerCase():""}return l(n,"toTextCase"),vt.default=n,vt}l(ko,"requireJsTextcase");var At={},Ds;function Co(){if(Ds)return At;Ds=1,Object.defineProperty(At,"__esModule",{value:!0});function n(e){if(e===void 0&&(e=""),!e)return"";var t=String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/([a-z])([A-Z])/g,function(s,i,r){return i+"_"+r.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g," ").toLowerCase();return t.charAt(0).toUpperCase()+t.slice(1)}return l(n,"toSentenceCase"),At.default=n,At}l(Co,"requireJsSentencecase");var Ot={},Ms;function vo(){if(Ms)return Ot;Ms=1,Object.defineProperty(Ot,"__esModule",{value:!0});function n(e){return e===void 0&&(e=""),e?String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/([a-z])([A-Z])/g,function(t,s,i){return s+"_"+i.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g," ").toLowerCase().replace(/( ?)(\w+)( ?)/g,function(t,s,i,r){return s+i.charAt(0).toUpperCase()+i.slice(1)+r}):""}return l(n,"toHeaderCase"),Ot.default=n,Ot}l(vo,"requireJsHeadercase");var Et={},Rs;function Bs(){if(Rs)return Et;Rs=1,Object.defineProperty(Et,"__esModule",{value:!0});function n(e){return e===void 0&&(e=""),e?String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/([a-z])([A-Z])/g,function(t,s,i){return s+"_"+i.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g,"-").toLowerCase():""}return l(n,"toKebabCase"),Et.default=n,Et}l(Bs,"requireJsKebabcase");var $e={},kn={},Fs;function Ie(){return Fs||(Fs=1,function(n){Object.defineProperty(n,"__esModule",{value:!0}),n.belongToTypes=n.isValidObject=n.isArrayObject=n.validateOptions=n.DefaultOption=void 0,n.DefaultOption={recursive:!1,recursiveInArray:!1,keepTypesOnRecursion:[]},n.validateOptions=function(e){return e===void 0&&(e=n.DefaultOption),e.recursive==null?e=n.DefaultOption:e.recursiveInArray==null&&(e.recursiveInArray=!1),e},n.isArrayObject=function(e){return e!=null&&Array.isArray(e)},n.isValidObject=function(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)},n.belongToTypes=function(e,t){return(t||[]).some(function(s){return e instanceof s})}}(kn)),kn}l(Ie,"requireUtils");var qs;function Ao(){if(qs)return $e;qs=1;var n=$e&&$e.__spreadArrays||function(){for(var s=0,i=0,r=arguments.length;i<r;i++)s+=arguments[i].length;for(var o=Array(s),a=0,i=0;i<r;i++)for(var c=arguments[i],u=0,d=c.length;u<d;u++,a++)o[a]=c[u];return o};Object.defineProperty($e,"__esModule",{value:!0});var e=Ie();function t(s,i){if(i===void 0&&(i=e.DefaultOption),!e.isValidObject(s))return null;i=e.validateOptions(i);var r={};return Object.keys(s).forEach(function(o){var a=s[o],c=o.toLowerCase();i.recursive&&(e.isValidObject(a)?e.belongToTypes(a,i.keepTypesOnRecursion)||(a=t(a,i)):i.recursiveInArray&&e.isArrayObject(a)&&(a=n(a).map(function(u){var d=u;if(e.isValidObject(u))e.belongToTypes(d,i.keepTypesOnRecursion)||(d=t(u,i));else if(e.isArrayObject(u)){var f=t({key:u},i);d=f.key}return d}))),r[c]=a}),r}return l(t,"lowerKeys"),$e.default=t,$e}l(Ao,"requireLowercaseKeysObject");var Ne={},Us;function Oo(){if(Us)return Ne;Us=1;var n=Ne&&Ne.__spreadArrays||function(){for(var s=0,i=0,r=arguments.length;i<r;i++)s+=arguments[i].length;for(var o=Array(s),a=0,i=0;i<r;i++)for(var c=arguments[i],u=0,d=c.length;u<d;u++,a++)o[a]=c[u];return o};Object.defineProperty(Ne,"__esModule",{value:!0});var e=Ie();function t(s,i){if(i===void 0&&(i=e.DefaultOption),!e.isValidObject(s))return null;i=e.validateOptions(i);var r={};return Object.keys(s).forEach(function(o){var a=s[o],c=o.toUpperCase();i.recursive&&(e.isValidObject(a)?e.belongToTypes(a,i.keepTypesOnRecursion)||(a=t(a,i)):i.recursiveInArray&&e.isArrayObject(a)&&(a=n(a).map(function(u){var d=u;if(e.isValidObject(u))e.belongToTypes(d,i.keepTypesOnRecursion)||(d=t(u,i));else if(e.isArrayObject(u)){var f=t({key:u},i);d=f.key}return d}))),r[c]=a}),r}return l(t,"upperKeys"),Ne.default=t,Ne}l(Oo,"requireUppercaseKeysObject");var _e={},Js;function Eo(){if(Js)return _e;Js=1;var n=_e&&_e.__spreadArrays||function(){for(var i=0,r=0,o=arguments.length;r<o;r++)i+=arguments[r].length;for(var a=Array(i),c=0,r=0;r<o;r++)for(var u=arguments[r],d=0,f=u.length;d<f;d++,c++)a[c]=u[d];return a};Object.defineProperty(_e,"__esModule",{value:!0});var e=Ie(),t=Is();function s(i,r){if(r===void 0&&(r=e.DefaultOption),!e.isValidObject(i))return null;r=e.validateOptions(r);var o={};return Object.keys(i).forEach(function(a){var c=i[a],u=t.default(a);r.recursive&&(e.isValidObject(c)?e.belongToTypes(c,r.keepTypesOnRecursion)||(c=s(c,r)):r.recursiveInArray&&e.isArrayObject(c)&&(c=n(c).map(function(d){var f=d;if(e.isValidObject(d))e.belongToTypes(f,r.keepTypesOnRecursion)||(f=s(d,r));else if(e.isArrayObject(d)){var h=s({key:d},r);f=h.key}return f}))),o[u]=c}),o}return l(s,"camelKeys"),_e.default=s,_e}l(Eo,"requireCamelcaseKeysObject");var Le={},Vs;function To(){if(Vs)return Le;Vs=1;var n=Le&&Le.__spreadArrays||function(){for(var i=0,r=0,o=arguments.length;r<o;r++)i+=arguments[r].length;for(var a=Array(i),c=0,r=0;r<o;r++)for(var u=arguments[r],d=0,f=u.length;d<f;d++,c++)a[c]=u[d];return a};Object.defineProperty(Le,"__esModule",{value:!0});var e=Ie(),t=_s();function s(i,r){if(r===void 0&&(r=e.DefaultOption),!e.isValidObject(i))return null;r=e.validateOptions(r);var o={};return Object.keys(i).forEach(function(a){var c=i[a],u=t.default(a);r.recursive&&(e.isValidObject(c)?e.belongToTypes(c,r.keepTypesOnRecursion)||(c=s(c,r)):r.recursiveInArray&&e.isArrayObject(c)&&(c=n(c).map(function(d){var f=d;if(e.isValidObject(d))e.belongToTypes(f,r.keepTypesOnRecursion)||(f=s(d,r));else if(e.isArrayObject(d)){var h=s({key:d},r);f=h.key}return f}))),o[u]=c}),o}return l(s,"snakeKeys"),Le.default=s,Le}l(To,"requireSnakecaseKeysObject");var xe={},Ws;function $o(){if(Ws)return xe;Ws=1;var n=xe&&xe.__spreadArrays||function(){for(var i=0,r=0,o=arguments.length;r<o;r++)i+=arguments[r].length;for(var a=Array(i),c=0,r=0;r<o;r++)for(var u=arguments[r],d=0,f=u.length;d<f;d++,c++)a[c]=u[d];return a};Object.defineProperty(xe,"__esModule",{value:!0});var e=Ie(),t=xs();function s(i,r){if(r===void 0&&(r=e.DefaultOption),!e.isValidObject(i))return null;r=e.validateOptions(r);var o={};return Object.keys(i).forEach(function(a){var c=i[a],u=t.default(a);r.recursive&&(e.isValidObject(c)?e.belongToTypes(c,r.keepTypesOnRecursion)||(c=s(c,r)):r.recursiveInArray&&e.isArrayObject(c)&&(c=n(c).map(function(d){var f=d;if(e.isValidObject(d))e.belongToTypes(f,r.keepTypesOnRecursion)||(f=s(d,r));else if(e.isArrayObject(d)){var h=s({key:d},r);f=h.key}return f}))),o[u]=c}),o}return l(s,"pascalKeys"),xe.default=s,xe}l($o,"requirePascalcaseKeysObject");var Pe={},zs;function Io(){if(zs)return Pe;zs=1;var n=Pe&&Pe.__spreadArrays||function(){for(var i=0,r=0,o=arguments.length;r<o;r++)i+=arguments[r].length;for(var a=Array(i),c=0,r=0;r<o;r++)for(var u=arguments[r],d=0,f=u.length;d<f;d++,c++)a[c]=u[d];return a};Object.defineProperty(Pe,"__esModule",{value:!0});var e=Ie(),t=Bs();function s(i,r){if(r===void 0&&(r=e.DefaultOption),!e.isValidObject(i))return null;r=e.validateOptions(r);var o={};return Object.keys(i).forEach(function(a){var c=i[a],u=t.default(a);r.recursive&&(e.isValidObject(c)?e.belongToTypes(c,r.keepTypesOnRecursion)||(c=s(c,r)):r.recursiveInArray&&e.isArrayObject(c)&&(c=n(c).map(function(d){var f=d;if(e.isValidObject(d))e.belongToTypes(f,r.keepTypesOnRecursion)||(f=s(d,r));else if(e.isArrayObject(d)){var h=s({key:d},r);f=h.key}return f}))),o[u]=c}),o}return l(s,"kebabKeys"),Pe.default=s,Pe}l(Io,"requireKebabcaseKeysObject");var Hs;function No(){if(Hs)return L;Hs=1,Object.defineProperty(L,"__esModule",{value:!0}),L.kebabKeys=L.pascalKeys=L.snakeKeys=L.camelKeys=L.upperKeys=L.lowerKeys=L.toLowerCase=L.toUpperCase=L.toKebabCase=L.toHeaderCase=L.toSentenceCase=L.toTextCase=L.toPathCase=L.toDotCase=L.toPascalCase=L.toSnakeCase=L.toCamelCase=void 0;var n=Is();L.toCamelCase=n.default;var e=_s();L.toSnakeCase=e.default;var t=xs();L.toPascalCase=t.default;var s=bo();L.toDotCase=s.default;var i=So();L.toPathCase=i.default;var r=ko();L.toTextCase=r.default;var o=Co();L.toSentenceCase=o.default;var a=vo();L.toHeaderCase=a.default;var c=Bs();L.toKebabCase=c.default;var u=Ao();L.lowerKeys=u.default;var d=Oo();L.upperKeys=d.default;var f=Eo();L.camelKeys=f.default;var h=To();L.snakeKeys=h.default;var m=$o();L.pascalKeys=m.default;var w=Io();L.kebabKeys=w.default;var p=l(function(b){return String(b||"").toLowerCase()},"toLowerCase");L.toLowerCase=p;var g=l(function(b){return String(b||"").toUpperCase()},"toUpperCase");L.toUpperCase=g;var S={toCamelCase:n.default,toSnakeCase:e.default,toPascalCase:t.default,toDotCase:s.default,toPathCase:i.default,toTextCase:r.default,toSentenceCase:o.default,toHeaderCase:a.default,toKebabCase:c.default,toUpperCase:g,toLowerCase:p,lowerKeys:u.default,upperKeys:d.default,camelKeys:f.default,snakeKeys:h.default,pascalKeys:m.default,kebabKeys:w.default};return L.default=S,L}l(No,"requireLib");var Cn,Gs;function _o(){return Gs||(Gs=1,Cn=No()),Cn}l(_o,"requireJsConvertCase");var je=_o();const H={[M.Integration]:{element:"integration",elements:"integrations",exportable:!1,exportCleanup:l(n=>({id:n.id,key:n.key,name:n.name,connectorId:n.connectorId,baseUri:n.baseUri,connectorVersion:n.connectorVersion}),"exportCleanup")},[M.Connector]:{element:"connector",elements:"connectors",exportable:!1},[M.Action]:{element:"action",elements:"actions",integrationSpecific:!0,exportCleanup:l(n=>(delete n.integration,n),"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",integrationSpecific:!0},[M.FieldMapping]:{element:"fieldMapping",elements:"fieldMappings",integrationSpecific:!0,exportCleanup:l(n=>(delete n.dataSourceId,n),"exportCleanup")},[M.Flow]:{element:"flow",elements:"flows",integrationSpecific:!0}};function Lo(n){return delete n.workspaceId,delete n.createdAt,delete n.updatedAt,delete n.revision,delete n.parentRevision,Object.keys(n).map(e=>{e.match(/universal.*Revision/g)&&delete n[e]}),n}l(Lo,"baseExportCleanup");class xo{static{l(this,"MembraneClient")}client=null;currentConfig=null;tokenExpiry=0;async generateAccessToken(e,t){return gt.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=be(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 an({token:t,apiUri:e.apiUri})}async getClient(e){const t=this.getCurrentConfig(e);if(!t)throw new Error("Unable to create IntegrationAppClient: No workspace configuration found.");const s=!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||s||i)&&(this.client=await this.createClient(t)),this.client}clearClient(){this.client=null,this.currentConfig=null,this.tokenExpiry=0}getCurrentConfigInfo(){return this.currentConfig}}const vn=new xo;async function Ys(n){const e=await vn.getClient(n);if(!e)throw new Error("No workspace configuration found");return(await e.get("org-workspace-id")).id}l(Ys,"getWorkspaceId");class Po{static{l(this,"RemoteElementsManagerService")}client;elementsCache={};async pull(){this.elementsCache[M.Integration]=await this.getIntegrations();const e=[M.Integration,M.Connector];for(const t of Object.keys(H)){if(e.includes(t))continue;V.info(`Pulling ${t}...`);const s=await this.pullElements(t);this.elementsCache[t]=s,V.success(`Pulled ${s.length} ${t}${s.length!==1?"s":""}`)}return this.elementsCache}async pullElements(e){const s=(await this.findAll(e)).map(i=>this.cleanup(e,i));if(!this.canBeIntegrationSpecific(e))return s;for(const i of this.elementsCache[M.Integration]){V.info(`Pulling ${e} elements for integration ${i.key}`);const o=(await this.findAll(e,{integrationKey:i.key})).map(a=>({integrationKey:i.key,...this.cleanup(e,a)}));s.push(...o)}return s}async pushElement(e,t){if(!H[e])throw new Error(`Unknown element type: ${e}`);const i={...t};await this.pull(),delete i.integrationId;const r=this.matchElement(i,e);r?await this.handleExistingElement(e,i,r):await this.handleNewElement(e,i)}cleanup(e,t){return H[e]?.exportCleanup?H[e].exportCleanup(t):this.baseExportCleanup(t)}canBeIntegrationSpecific(e){return H[e]?.integrationSpecific}baseExportCleanup(e){return delete e.workspaceId,delete e.createdAt,delete e.updatedAt,delete e.revision,delete e.parentRevision,Object.keys(e).map(t=>{t.match(/universal.*Revision/g)&&delete e[t]}),e}findIntegrationId(e){const s=this.elementsCache.integration?.find(i=>i.key===e);if(!s)throw new Error(`Integration with key ${e} not found`);return s.id}matchElement(e,t){const s=this.elementsCache[t]?.filter(i=>i.key===e.key&&i.integrationKey===e.integrationKey&&!i.archivedAt);if(!(!s||s.length===0)){if(s.length>1)throw new Error(`More than one ${e.integrationKey||"universal"} ${t} with key ${e.key} found in the workspace`);return s[0]}}async handleExistingElement(e,t,s){const i=H[e],r=await this.getClient(),o=je.toCamelCase(ee[e].name);if(!this.hasParent(t)||this.elementIsCustomized(t)&&this.hasParent(t))await r[o](s.id).put(t),V.info(`Updated ${t.integrationKey||"universal"} ${i.element} ${t.key}`);else if(this.hasParent(t))try{await r[o](s.id).reset(),V.info(`Customization reset ${t.integrationKey||"universal"} ${i.element} ${t.key}`)}catch(a){throw V.error(`Error resetting element: ${s.id} ${t.key}`),a}else V.warning(`Corrupted element detected. Manual migration required: ${t.integrationKey||"universal"} ${i.element} ${t.key}`)}async handleNewElement(e,t){const s=H[e],i=await this.getClient(),r=je.toCamelCase(ee[e].name),o=je.toCamelCase(ee[e].namePlural);if(this.hasParent(t)){try{await i[r]({key:t.key}).apply([t.integrationKey])}catch{try{await i[r]({key:t.key,integrationKey:t.integrationKey}).put(t)}catch{const u=this.findIntegrationId(t.integrationKey);await i[o].create({...t,integrationId:u})}}if(this.elementIsCustomized(t))try{await i[r]({key:t.key,integrationKey:t.integrationKey}).put(t),V.success(`Applied & Customized ${t.integrationKey||"universal"} ${s.element} ${t.key}`)}catch(a){throw V.error(`Error customizing element: ${t.key}`),a}else V.success(`Applied universal ${s.element} ${t.key} to ${t.integrationKey}`)}else try{if(t.integrationKey){delete t.integration;const a=this.findIntegrationId(t.integrationKey);t.integrationId=a}await i[o].create(t),V.success(`Created ${t.integrationKey||"universal"} ${s.element} ${t.key}`)}catch(a){throw V.error(`Error creating element ${e} ${t.key} for integration ${t.integrationKey}`),a}}hasParent(e){return Object.keys(e).some(t=>/universal.*Id/g.test(t)||/parentId/g.test(t))}elementIsCustomized(e){return!!(e.integrationKey&&(e.customized||e.isCustomized))}async findById(e,t){return(await this.getClient())[e](t).get()}async findByKey(e,t,s={}){return(await this.getClient())[e](t).get(s)}async findAll(e,t={}){return(await this.getClient())[H[e].elements].findAll(t)}async create(e,t){return(await this.getClient())[e].create(t)}async update(e,t){if(!t.id)throw new Error("Element must have an id to update");return(await this.getClient())[e](t.id).put(t)}async put(e,t){return t.id?this.update(e,t):this.create(e,t)}async reset(e,t){if(!t.id)throw new Error("Element must have an id to reset");return(await this.getClient())[e](t.id).reset()}async apply(e,t){if(!t.id)throw new Error("Element must have an id to apply");return(await this.getClient())[e](t.id).apply()}async archive(e,t){if(!t.id)throw new Error("Element must have an id to archive");await(await this.getClient())[e](t.id).archive()}async getIntegrations(){return(await this.getClient()).integrations.findAll()}async exists(e,t){try{return await this.findById(e,t),!0}catch{return!1}}async getClient(){return this.client||(this.client=await vn.getClient(process.cwd())),this.client}}const An=Symbol.for("yaml.alias"),On=Symbol.for("yaml.document"),pe=Symbol.for("yaml.map"),Zs=Symbol.for("yaml.pair"),ce=Symbol.for("yaml.scalar"),Ke=Symbol.for("yaml.seq"),ne=Symbol.for("yaml.node.type"),me=l(n=>!!n&&typeof n=="object"&&n[ne]===An,"isAlias"),Se=l(n=>!!n&&typeof n=="object"&&n[ne]===On,"isDocument"),De=l(n=>!!n&&typeof n=="object"&&n[ne]===pe,"isMap"),B=l(n=>!!n&&typeof n=="object"&&n[ne]===Zs,"isPair"),R=l(n=>!!n&&typeof n=="object"&&n[ne]===ce,"isScalar$1"),Me=l(n=>!!n&&typeof n=="object"&&n[ne]===Ke,"isSeq");function q(n){if(n&&typeof n=="object")switch(n[ne]){case pe:case Ke:return!0}return!1}l(q,"isCollection$1");function U(n){if(n&&typeof n=="object")switch(n[ne]){case An:case pe:case ce:case Ke:return!0}return!1}l(U,"isNode");const Qs=l(n=>(R(n)||q(n))&&!!n.anchor,"hasAnchor"),X=Symbol("break visit"),Xs=Symbol("skip children"),le=Symbol("remove node");function ke(n,e){const t=ei(e);Se(n)?Re(null,n.contents,t,Object.freeze([n]))===le&&(n.contents=null):Re(null,n,t,Object.freeze([]))}l(ke,"visit$1"),ke.BREAK=X,ke.SKIP=Xs,ke.REMOVE=le;function Re(n,e,t,s){const i=ti(n,e,t,s);if(U(i)||B(i))return ni(n,s,i),Re(n,i,t,s);if(typeof i!="symbol"){if(q(e)){s=Object.freeze(s.concat(e));for(let r=0;r<e.items.length;++r){const o=Re(r,e.items[r],t,s);if(typeof o=="number")r=o-1;else{if(o===X)return X;o===le&&(e.items.splice(r,1),r-=1)}}}else if(B(e)){s=Object.freeze(s.concat(e));const r=Re("key",e.key,t,s);if(r===X)return X;r===le&&(e.key=null);const o=Re("value",e.value,t,s);if(o===X)return X;o===le&&(e.value=null)}}return i}l(Re,"visit_");async function Tt(n,e){const t=ei(e);Se(n)?await Be(null,n.contents,t,Object.freeze([n]))===le&&(n.contents=null):await Be(null,n,t,Object.freeze([]))}l(Tt,"visitAsync"),Tt.BREAK=X,Tt.SKIP=Xs,Tt.REMOVE=le;async function Be(n,e,t,s){const i=await ti(n,e,t,s);if(U(i)||B(i))return ni(n,s,i),Be(n,i,t,s);if(typeof i!="symbol"){if(q(e)){s=Object.freeze(s.concat(e));for(let r=0;r<e.items.length;++r){const o=await Be(r,e.items[r],t,s);if(typeof o=="number")r=o-1;else{if(o===X)return X;o===le&&(e.items.splice(r,1),r-=1)}}}else if(B(e)){s=Object.freeze(s.concat(e));const r=await Be("key",e.key,t,s);if(r===X)return X;r===le&&(e.key=null);const o=await Be("value",e.value,t,s);if(o===X)return X;o===le&&(e.value=null)}}return i}l(Be,"visitAsync_");function ei(n){return typeof n=="object"&&(n.Collection||n.Node||n.Value)?Object.assign({Alias:n.Node,Map:n.Node,Scalar:n.Node,Seq:n.Node},n.Value&&{Map:n.Value,Scalar:n.Value,Seq:n.Value},n.Collection&&{Map:n.Collection,Seq:n.Collection},n):n}l(ei,"initVisitor");function ti(n,e,t,s){if(typeof t=="function")return t(n,e,s);if(De(e))return t.Map?.(n,e,s);if(Me(e))return t.Seq?.(n,e,s);if(B(e))return t.Pair?.(n,e,s);if(R(e))return t.Scalar?.(n,e,s);if(me(e))return t.Alias?.(n,e,s)}l(ti,"callVisitor");function ni(n,e,t){const s=e[e.length-1];if(q(s))s.items[n]=t;else if(B(s))n==="key"?s.key=t:s.value=t;else if(Se(s))s.contents=t;else{const i=me(s)?"alias":"scalar";throw new Error(`Cannot replace node with ${i} parent`)}}l(ni,"replaceNode");const jo={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},Ko=l(n=>n.replace(/[!,[\]{}]/g,e=>jo[e]),"escapeTagName");class Q{static{l(this,"Directives")}constructor(e,t){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},Q.defaultYaml,e),this.tags=Object.assign({},Q.defaultTags,t)}clone(){const e=new Q(this.yaml,this.tags);return e.docStart=this.docStart,e}atDocument(){const e=new Q(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:Q.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},Q.defaultTags);break}return e}add(e,t){this.atNextDocument&&(this.yaml={explicit:Q.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},Q.defaultTags),this.atNextDocument=!1);const s=e.trim().split(/[ \t]+/),i=s.shift();switch(i){case"%TAG":{if(s.length!==2&&(t(0,"%TAG directive should contain exactly two parts"),s.length<2))return!1;const[r,o]=s;return this.tags[r]=o,!0}case"%YAML":{if(this.yaml.explicit=!0,s.length!==1)return t(0,"%YAML directive should contain exactly one part"),!1;const[r]=s;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[,s,i]=e.match(/^(.*!)([^!]*)$/s);i||t(`The ${e} tag has no suffix`);const r=this.tags[s];if(r)try{return r+decodeURIComponent(i)}catch(o){return t(String(o)),null}return s==="!"?e:(t(`Could not resolve tag: ${e}`),null)}tagString(e){for(const[t,s]of Object.entries(this.tags))if(e.startsWith(s))return t+Ko(e.substring(s.length));return e[0]==="!"?e:`!<${e}>`}toString(e){const t=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],s=Object.entries(this.tags);let i;if(e&&s.length>0&&U(e.contents)){const r={};ke(e.contents,(o,a)=>{U(a)&&a.tag&&(r[a.tag]=!0)}),i=Object.keys(r)}else i=[];for(const[r,o]of s)r==="!!"&&o==="tag:yaml.org,2002:"||(!e||i.some(a=>a.startsWith(o)))&&t.push(`%TAG ${r} ${o}`);return t.join(`
|
|
2
|
-
`)}}Q.defaultYaml={explicit:!1,version:"1.2"},Q.defaultTags={"!!":"tag:yaml.org,2002:"};function si(n){if(/[\x00-\x19\s,[\]{}]/.test(n)){const t=`Anchor must not contain whitespace or control characters: ${JSON.stringify(n)}`;throw new Error(t)}return!0}l(si,"anchorIsValid");function ii(n){const e=new Set;return ke(n,{Value(t,s){s.anchor&&e.add(s.anchor)}}),e}l(ii,"anchorNames");function ri(n,e){for(let t=1;;++t){const s=`${n}${t}`;if(!e.has(s))return s}}l(ri,"findNewAnchor");function Do(n,e){const t=[],s=new Map;let i=null;return{onAnchor:l(r=>{t.push(r),i??(i=ii(n));const o=ri(e,i);return i.add(o),o},"onAnchor"),setAnchors:l(()=>{for(const r of t){const o=s.get(r);if(typeof o=="object"&&o.anchor&&(R(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:s}}l(Do,"createNodeAnchors");function Fe(n,e,t,s){if(s&&typeof s=="object")if(Array.isArray(s))for(let i=0,r=s.length;i<r;++i){const o=s[i],a=Fe(n,s,String(i),o);a===void 0?delete s[i]:a!==o&&(s[i]=a)}else if(s instanceof Map)for(const i of Array.from(s.keys())){const r=s.get(i),o=Fe(n,s,i,r);o===void 0?s.delete(i):o!==r&&s.set(i,o)}else if(s instanceof Set)for(const i of Array.from(s)){const r=Fe(n,s,i,i);r===void 0?s.delete(i):r!==i&&(s.delete(i),s.add(r))}else for(const[i,r]of Object.entries(s)){const o=Fe(n,s,i,r);o===void 0?delete s[i]:o!==r&&(s[i]=o)}return n.call(e,t,s)}l(Fe,"applyReviver");function se(n,e,t){if(Array.isArray(n))return n.map((s,i)=>se(s,String(i),t));if(n&&typeof n.toJSON=="function"){if(!t||!Qs(n))return n.toJSON(e,t);const s={aliasCount:0,count:1,res:void 0};t.anchors.set(n,s),t.onCreate=r=>{s.res=r,delete t.onCreate};const i=n.toJSON(e,t);return t.onCreate&&t.onCreate(i),i}return typeof n=="bigint"&&!t?.keep?Number(n):n}l(se,"toJS");class En{static{l(this,"NodeBase")}constructor(e){Object.defineProperty(this,ne,{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:s,onAnchor:i,reviver:r}={}){if(!Se(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 s=="number"?s:100},a=se(this,"",o);if(typeof i=="function")for(const{count:c,res:u}of o.anchors.values())i(u,c);return typeof r=="function"?Fe(r,{"":a},"",a):a}}class $t extends En{static{l(this,"Alias")}constructor(e){super(An),this.source=e,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(e,t){let s;t?.aliasResolveCache?s=t.aliasResolveCache:(s=[],ke(e,{Node:l((r,o)=>{(me(o)||Qs(o))&&s.push(o)},"Node")}),t&&(t.aliasResolveCache=s));let i;for(const r of s){if(r===this)break;r.anchor===this.source&&(i=r)}return i}toJSON(e,t){if(!t)return{source:this.source};const{anchors:s,doc:i,maxAliasCount:r}=t,o=this.resolve(i,t);if(!o){const c=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(c)}let a=s.get(o);if(a||(se(o,null,t),a=s.get(o)),!a||a.res===void 0){const c="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(c)}if(r>=0&&(a.count+=1,a.aliasCount===0&&(a.aliasCount=It(i,o,s)),a.count*a.aliasCount>r)){const c="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(c)}return a.res}toString(e,t,s){const i=`*${this.source}`;if(e){if(si(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 It(n,e,t){if(me(e)){const s=e.resolve(n),i=t&&s&&t.get(s);return i?i.count*i.aliasCount:0}else if(q(e)){let s=0;for(const i of e.items){const r=It(n,i,t);r>s&&(s=r)}return s}else if(B(e)){const s=It(n,e.key,t),i=It(n,e.value,t);return Math.max(s,i)}return 1}l(It,"getAliasCount");const oi=l(n=>!n||typeof n!="function"&&typeof n!="object","isScalarValue");class _ extends En{static{l(this,"Scalar")}constructor(e){super(ce),this.value=e}toJSON(e,t){return t?.keep?this.value:se(this.value,e,t)}toString(){return String(this.value)}}_.BLOCK_FOLDED="BLOCK_FOLDED",_.BLOCK_LITERAL="BLOCK_LITERAL",_.PLAIN="PLAIN",_.QUOTE_DOUBLE="QUOTE_DOUBLE",_.QUOTE_SINGLE="QUOTE_SINGLE";const Mo="tag:yaml.org,2002:";function Ro(n,e,t){if(e){const s=t.filter(r=>r.tag===e),i=s.find(r=>!r.format)??s[0];if(!i)throw new Error(`Tag ${e} not found`);return i}return t.find(s=>s.identify?.(n)&&!s.format)}l(Ro,"findTagObject");function st(n,e,t){if(Se(n)&&(n=n.contents),U(n))return n;if(B(n)){const f=t.schema[pe].createNode?.(t.schema,null,t);return f.items.push(n),f}(n instanceof String||n instanceof Number||n instanceof Boolean||typeof BigInt<"u"&&n instanceof BigInt)&&(n=n.valueOf());const{aliasDuplicateObjects:s,onAnchor:i,onTagObj:r,schema:o,sourceObjects:a}=t;let c;if(s&&n&&typeof n=="object"){if(c=a.get(n),c)return c.anchor??(c.anchor=i(n)),new $t(c.anchor);c={anchor:null,node:null},a.set(n,c)}e?.startsWith("!!")&&(e=Mo+e.slice(2));let u=Ro(n,e,o.tags);if(!u){if(n&&typeof n.toJSON=="function"&&(n=n.toJSON()),!n||typeof n!="object"){const f=new _(n);return c&&(c.node=f),f}u=n instanceof Map?o[pe]:Symbol.iterator in Object(n)?o[Ke]:o[pe]}r&&(r(u),delete t.onTagObj);const d=u?.createNode?u.createNode(t.schema,n,t):typeof u?.nodeClass?.from=="function"?u.nodeClass.from(t.schema,n,t):new _(n);return e?d.tag=e:u.default||(d.tag=u.tag),c&&(c.node=d),d}l(st,"createNode");function Nt(n,e,t){let s=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]=s,s=o}else s=new Map([[r,s]])}return st(s,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:l(()=>{throw new Error("This should not happen, please report a bug.")},"onAnchor"),schema:n,sourceObjects:new Map})}l(Nt,"collectionFromPath");const it=l(n=>n==null||typeof n=="object"&&!!n[Symbol.iterator]().next().done,"isEmptyPath");class ai extends En{static{l(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(s=>U(s)||B(s)?s.clone(e):s),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(it(e))this.add(t);else{const[s,...i]=e,r=this.get(s,!0);if(q(r))r.addIn(i,t);else if(r===void 0&&this.schema)this.set(s,Nt(this.schema,i,t));else throw new Error(`Expected YAML collection at ${s}. Remaining path: ${i}`)}}deleteIn(e){const[t,...s]=e;if(s.length===0)return this.delete(t);const i=this.get(t,!0);if(q(i))return i.deleteIn(s);throw new Error(`Expected YAML collection at ${t}. Remaining path: ${s}`)}getIn(e,t){const[s,...i]=e,r=this.get(s,!0);return i.length===0?!t&&R(r)?r.value:r:q(r)?r.getIn(i,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!B(t))return!1;const s=t.value;return s==null||e&&R(s)&&s.value==null&&!s.commentBefore&&!s.comment&&!s.tag})}hasIn(e){const[t,...s]=e;if(s.length===0)return this.has(t);const i=this.get(t,!0);return q(i)?i.hasIn(s):!1}setIn(e,t){const[s,...i]=e;if(i.length===0)this.set(s,t);else{const r=this.get(s,!0);if(q(r))r.setIn(i,t);else if(r===void 0&&this.schema)this.set(s,Nt(this.schema,i,t));else throw new Error(`Expected YAML collection at ${s}. Remaining path: ${i}`)}}}const Bo=l(n=>n.replace(/^(?!$)(?: $)?/gm,"#"),"stringifyComment");function ue(n,e){return/^\n+$/.test(n)?n.substring(1):e?n.replace(/^(?! *$)/gm,e):n}l(ue,"indentComment");const Ce=l((n,e,t)=>n.endsWith(`
|
|
3
|
-
`)?
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
var Fi=Object.defineProperty;var c=(s,e)=>Fi(s,"name",{value:e,configurable:!0});import{jsx as m,jsxs as I,Fragment as Yt}from"react/jsx-runtime";import*as D from"node:path";import{resolve as Bi,dirname as Ui,join as qi}from"node:path";import{useInput as xe,Box as b,Text as S,Newline as Ji,render as dt}from"ink";import Wi from"minimist";import{SWRConfig as Gi}from"swr";import Vi from"os";import F from"path";import Hi from"conf";import De,{createContext as zt,useContext as Qt,useState as K,useEffect as ye,useCallback as ts,useMemo as Yi,useRef as zi}from"react";import*as x from"node:fs";import{readFileSync as Qi}from"node:fs";import de from"js-yaml";import{z as B}from"zod";import{exec as Xi}from"node:child_process";import*as Zi from"node:crypto";import{createHash as er}from"node:crypto";import*as tr from"node:os";import{TextInput as nr,Select as sr}from"@inkjs/ui";import ht from"ink-spinner";import ns from"swr/immutable";import ir from"ink-text-input";import{EventEmitter as rr}from"events";import{WorkspaceElementType as U,IntegrationAppClient as ss,WorkspaceElementSpecs as he,setValueAtLocator as Xt,extractIntegrationAppErrorData as ce,getDataCollectionCreateFields as Zt,excludeWriteOnlyFieldsFromSchema as is,valueToSchema as pt,getRequiredFieldsFromSchema as or,getValueAtLocator as ar,walkSchema as rs,makeDataLocationPath as os,getDataCollectionUpdateFields as en}from"@membranehq/sdk";import j from"fs";import cr from"archiver";import lr from"form-data";import ur from"unzipper";import tn from"jsonwebtoken";import fr from"lodash/isEqual.js";import dr from"chokidar";import{fileURLToPath as hr}from"node:url";import k from"chalk";import{Command as pr}from"commander";import nn from"axios";import{FastMCP as mr}from"fastmcp";import sn from"lodash/merge.js";import gr from"@anthropic-ai/sdk";import{faker as Xe}from"@faker-js/faker";import yr from"lodash/template.js";import wr from"lodash/templateSettings.js";const br="membrane",Sr="membrane.config.yml",rn="https://api.integration.app";function on(){const s=process.cwd(),e=D.join(s,br),t=D.join(s,Sr),n=e,i=D.join(n,"workspace.yaml");return{membraneDirPath:e,configPath:t,payloadDirPath:n,workspaceDataFilePath:i}}c(on,"getPaths");function Cr(){return on().membraneDirPath}c(Cr,"getBasePath");const kr={pat:{type:"string"},workspace:{type:"object"}},as=new Hi({schema:kr,configName:"config",cwd:F.join(Vi.homedir(),".membrane")}),vr=c(s=>{as.set("pat",s)},"setPat"),cs=c(()=>as.get("pat"),"getPat");class ls{static{c(this,"AccountApiClient")}constructor(e=rn){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=cs();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 Er=c(s=>{const e=new ls(rn);return t=>e.get(t)},"createAccountApiFetcher"),us=zt(process.cwd());function Tr({cwd:s,children:e}){return m(us.Provider,{value:s,children:e})}c(Tr,"CwdProvider");function fs(){return Qt(us)}c(fs,"useCwd");const Ir="membrane.config.yml";function Pe(s){const e=D.join(s??process.cwd(),Ir);try{const t=x.readFileSync(e,"utf8"),n=de.load(t),i=ds.safeParse(n);return i.success?i.data:null}catch{return null}}c(Pe,"readProjectConfig");const Nr="membrane.config.yml",ds=B.object({workspaceKey:B.string().optional(),workspaceSecret:B.string().optional(),apiUri:B.string().optional(),testCustomerId:B.string().optional(),anthropicApiKey:B.string().optional()});B.enum(["pull"]);const hs=zt(void 0);function Ar({children:s}){const e=fs(),[t,n]=K(null),[i,r]=K(!0);ye(()=>{const u=Pe(e);n(u),r(!1)},[e]);const o=ts(u=>{const p=D.join(e,Nr),f={...Pe(e)??{},...u},g=ds.safeParse(f);return g.success?(x.writeFileSync(p,de.dump(g.data)),n(g.data),!0):!1},[e]),a=ts(()=>!!(t?.workspaceKey&&t?.workspaceSecret),[t]),l={config:t,isLoading:i,updateConfig:o,validateConfig:a};return m(hs.Provider,{value:l,children:s})}c(Ar,"ProjectConfigProvider");function Ze(){const s=Qt(hs);if(s===void 0)throw new Error("useProjectConfig must be used within a ProjectConfigProvider");return s}c(Ze,"useProjectConfig");function mt({cwd:s,children:e}){const t=s||process.cwd();return m(Tr,{cwd:t,children:m(Ar,{children:m(Gi,{value:{fetcher:Er()},children:e})})})}c(mt,"Layout");const an=[{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=D.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=D.join(process.cwd(),".cursor"),e=D.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 Or({onExit:s,onComplete:e}){const[t,n]=K(0),[i,r]=K(!1),[o,a]=K(null),[l,u]=K(""),[p,d]=K("");xe((w,h)=>{if(l||p){(h.escape||w==="q"||h.return)&&e();return}if(i)h.return||w===" "?f(o):h.escape&&(r(!1),a(null));else if(h.escape)s();else if(h.upArrow||w==="k")n(Math.max(0,t-1));else if(h.downArrow||w==="j")n(Math.min(an.length-1,t+1));else if(h.return||w===" "){const y=an[t];a(y),r(!0)}});const f=c(w=>{try{const h=w.addConfig();u(h)}catch(h){d(`Failed to write configuration: ${h.message||h}`)}},"addMcpConfiguration"),g=Math.min(80,process.stdout.columns||80);return l?I(b,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:g,children:[m(b,{marginTop:-1,marginBottom:1,children:I(S,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",m(S,{color:"green",children:"Success"})]})}),I(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?I(b,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:g,children:[m(b,{marginTop:-1,marginBottom:1,children:I(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?I(b,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:g,children:[m(b,{marginTop:-1,marginBottom:1,children:I(S,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",m(S,{color:"cyan",children:"Confirmation"})]})}),I(b,{flexDirection:"column",paddingLeft:2,children:[I(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:I(S,{children:[m(S,{color:"white",bold:!0,children:"[Enter] Confirm"})," ",m(S,{color:"gray",children:"[Esc] Cancel"})]})})]})]}):I(b,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:g,children:[m(b,{marginTop:-1,marginBottom:1,children:I(S,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",m(S,{color:"cyan",children:"Select Agent"})]})}),I(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:an.map((w,h)=>I(b,{children:[I(S,{color:t===h?"cyan":"white",children:[t===h?"\u25B6 ":" ",w.name]}),I(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(Or,"AddMcpServerScreen");const we=D.join(tr.tmpdir(),"membrane-mcp-status"),ps=3e4;function cn(s){return er("md5").update(s).digest("hex").slice(0,8)}c(cn,"getCwdHash");function ln(s,e){const t=cn(e);return D.join(we,`mcp-${t}-${s}.json`)}c(ln,"getStatusFilePath");function Me(s,e){try{const t=e||process.cwd();if(!s){const i=gt(t);return i.length===0?null:i[0]}const n=ln(s,t);if(x.existsSync(n)){const i=x.statSync(n),r=new Date;if(r.getTime()-i.mtime.getTime()>ps)return et(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>ps)return et(s,t),null}return l}}catch{s&&e&&et(s,e)}return null}c(Me,"getMcpStatus");function gt(s){try{const e=s||process.cwd(),t=cn(e);if(!x.existsSync(we))return[];const n=x.readdirSync(we),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=Me(a,e);l&&i.push(l)}}return i.sort((r,o)=>new Date(o.startTime).getTime()-new Date(r.startTime).getTime())}catch{return[]}}c(gt,"getAllMcpStatusFiles");function un(s){try{const t={...Me(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(we)||x.mkdirSync(we,{recursive:!0});const n=ln(s.processId,s.cwd);x.writeFileSync(n,JSON.stringify(t,null,2))}catch{}}c(un,"updateMcpStatus");function et(s,e){try{const t=e||process.cwd();if(s){const n=ln(s,t);x.existsSync(n)&&x.unlinkSync(n)}else{const n=cn(t);if(x.existsSync(we)){const i=x.readdirSync(we);for(const r of i)r.match(new RegExp(`^mcp-${n}-\\d+\\.json$`))&&x.unlinkSync(D.join(we,r))}}}catch{}}c(et,"clearMcpStatus");function $r(s,e){const t=Me(s,e);t&&un({processId:s,cwd:e,totalRequests:t.totalRequests+1,lastRequestTime:new Date().toISOString(),lastActivity:new Date().toISOString()})}c($r,"trackToolExecution");function Lr(){const[s,e]=K(Me()),[t,n]=K(gt()),[i,r]=K(null);return ye(()=>{try{const a=process.cwd();e(Me(void 0,a)),n(gt(a)),r(null)}catch(a){r("Failed to read MCP status:"+a),e(null),n([])}const o=setInterval(()=>{try{const a=process.cwd(),l=Me(void 0,a),u=gt(a);e(l),n(u),r(null)}catch(a){r("Failed to read MCP status: "+a),e(null),n([])}},2e3);return()=>clearInterval(o)},[]),{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(Lr,"useMcpStatus");function xr(){const{error:s,serverCount:e,allMcpServers:t}=Lr(),n=Math.min(100,process.stdout.columns||100);return I(b,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:n,children:[m(b,{marginTop:-1,marginBottom:0,flexDirection:"column",children:I(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:I(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:I(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(xr,"Agent");function ms({onExit:s,showEscOption:e=!0}){const[t,n]=K(""),{data:i,error:r,isLoading:o}=ns("/account"),{updateConfig:a,isLoading:l}=Ze(),u=i?.workspaces,p=o||l;if(xe((y,C)=>{C.escape&&s?.()}),p)return I(b,{children:[m(ht,{}),m(S,{children:" Fetching workspaces..."})]});if(r)return I(b,{flexDirection:"column",children:[I(S,{color:"red",children:["Error: ",r.message]}),m(b,{marginTop:1,children:m(S,{color:"grey",children:"Press ESC to go back"})})]});const d=u?.filter(y=>y.name.toLowerCase().includes(t.toLowerCase()))??[],f=d.map(y=>({label:y.name,value:y.id})),g=f.length,w=u?.length??0;async function h(y){const C=d.find(T=>T.id===y);if(!C)return;const{key:v,secret:A}=C;!v||!A||(await a({workspaceKey:v,workspaceSecret:A}),s?.())}return c(h,"handleSelect"),I(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"})}),I(b,{marginTop:1,children:[m(S,{children:"Search: "}),m(nr,{placeholder:"Enter a search query...",onChange:n})]}),w>5&&I(S,{children:["Showing ",g," of ",w," workspaces."]}),m(b,{marginTop:1,children:m(sr,{options:f,onChange:c(y=>{y&&h(y)},"onChange")})}),e&&m(b,{marginTop:1,children:m(S,{color:"grey",children:"Press ESC to go back"})})]})}c(ms,"SelectWorkspace");function Dr({currentPat:s,onSubmit:e}){const[t,n]=K(""),[i,r]=K(!1),[o,a]=K(null);return I(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(ir,{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:I(S,{children:[m(ht,{type:"dots"})," Validating token..."]})}),o&&m(S,{color:"red",children:o})]})}c(Dr,"PersonalAccessTokenInput");var tt=(s=>(s[s.Authenticate=0]="Authenticate",s[s.ConnectWorkspace=1]="ConnectWorkspace",s))(tt||{});const Pr={0:"Authenticate in Membrane",1:"Connect a Membrane Workspace"},gs=c(()=>{const{config:s}=Ze(),e=!!(s?.workspaceKey&&s?.workspaceSecret);return{workspaceIsConfigured:e,isSetupComplete:e}},"useSetup"),fn=[tt.Authenticate,tt.ConnectWorkspace];function ys({onComplete:s}){const[e,t]=K(!1),[n,i]=K(0),{isSetupComplete:r}=gs(),o=cs(),a=fn[n],l=n+1,u=fn.length,p=fn.map((g,w)=>{let h="pending";return w<n?h="done":w===n&&(h="current"),{id:g,label:Pr[g],status:h}});async function d(g){const w=o&&g===""?o:g,h=new ls;try{await h.request("/account",{headers:{Authorization:`Bearer ${w}`}}),vr(w),i(y=>y+1)}catch(y){console.error(y)}}c(d,"handlePatSubmit");function f(){t(!0),s&&s()}return c(f,"handleWorkspaceSelected"),xe((g,w)=>{r&&w.escape&&s&&s()}),e?m(b,{children:m(S,{children:"\u2705 Setup complete. You are ready to go!"})}):I(b,{flexDirection:"column",alignSelf:"flex-start",gap:1,children:[I(b,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:70,children:[m(b,{marginTop:-1,marginBottom:1,children:I(S,{bold:!0,children:["\u{1F6E0}\uFE0F Setup \u2014"," ",I(S,{color:"cyan",children:["Step ",l," of ",u]}),r&&m(S,{color:"grey",children:" [esc: go back]"})]})}),m(b,{flexDirection:"column",paddingLeft:2,children:p.map(g=>m(Mr,{status:g.status,label:g.label},g.id))})]}),a===tt.Authenticate&&m(Dr,{currentPat:o,onSubmit:d}),a===tt.ConnectWorkspace&&m(ms,{onExit:f,showEscOption:!1})]})}c(ys,"Setup");function Mr({status:s,label:e}){return I(b,{children:[I(b,{width:2,children:[s==="current"&&m(ht,{type:"dots"}),s==="done"&&m(S,{children:"\u2705"})]}),m(S,{dimColor:s!=="current",children:e})]})}c(Mr,"StepDisplay");const te={LogAdded:"logAdded",StateChanged:"stateChanged",StatsChanged:"statsChanged",ConflictsChanged:"conflictsChanged"};class ws extends rr{static{c(this,"TypedEventEmitter")}on(e,t){return super.on(e,t)}emit(e,...t){return super.emit(e,...t)}off(e,t){return super.off(e,t)}once(e,t){return super.once(e,t)}}class jr extends ws{static{c(this,"WorkspaceNotifications")}constructor(){super()}setState(e){this.emit(te.StateChanged,{state:e})}setConflicts(e){this.emit(te.ConflictsChanged,{conflicts:e})}setStats(e){this.emit(te.StatsChanged,{stats:e})}addLog(e){this.emit(te.LogAdded,{log:e})}}const re=new jr,ne={[U.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")},[U.Connector]:{element:"connector",elements:"connectors",exportable:!1},[U.Action]:{element:"action",elements:"actions",integrationSpecific:!0,exportCleanup:c(s=>(delete s.integration,s),"exportCleanup")},[U.AppDataSchema]:{element:"appDataSchema",elements:"appDataSchemas"},[U.AppEventType]:{element:"appEventType",elements:"appEventTypes"},[U.DataLinkTable]:{element:"dataLinkTable",elements:"dataLinkTables"},[U.DataSource]:{element:"dataSource",elements:"dataSources",parentKey:"universalDataSourceId",integrationSpecific:!0},[U.FieldMapping]:{element:"fieldMapping",elements:"fieldMappings",integrationSpecific:!0,parentKey:"universalFieldMappingId",exportCleanup:c(s=>(delete s.dataSourceId,s),"exportCleanup")},[U.Flow]:{element:"flow",elements:"flows",integrationSpecific:!0,parentKey:"universalFlowId"}};function Rr(s){return delete s.workspaceId,delete s.createdAt,delete s.updatedAt,delete s.revision,delete s.parentRevision,Object.keys(s).map(e=>{e.match(/universal.*Revision/g)&&delete s[e]}),s}c(Rr,"baseExportCleanup");class bs{static{c(this,"ElementsCache")}elements=new Map;typeIndex=new Map;constructor(e){e&&this.addAll(e)}add(e){const t=e.id;this.elements.set(t,e),this.typeIndex.has(e.type)||this.typeIndex.set(e.type,new Set),this.typeIndex.get(e.type).add(t)}remove(e){const t=e.id,n=this.elements.delete(t);if(n){const i=this.typeIndex.get(e.type);i&&(i.delete(t),i.size===0&&this.typeIndex.delete(e.type))}return n}put(e){this.elements.has(e.id)&&this.remove(e),this.add(e)}get(e){return this.elements.get(e)}getElementsByType(e){const t=this.typeIndex.get(e);return t?Array.from(t).map(n=>this.elements.get(n)).filter(n=>n!==void 0):[]}getAll(){return Array.from(this.elements.values())??[]}getTypes(){return Array.from(this.typeIndex.keys())}addAll(e){for(const t of e)t&&this.add(t)}removeAll(e){for(const t of e)this.remove(t)}getElementIdsByType(e){return this.typeIndex.get(e)}clear(){this.elements.clear(),this.typeIndex.clear()}getAllIds(){return new Set(this.elements.keys())}}class Kr{static{c(this,"WorkspaceLogger")}_logs;workspaceNotifications;constructor(){this._logs=[],this.workspaceNotifications=re}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 $=new Kr;class Ss{static{c(this,"ElementsManager")}cache;handler;constructor(e){this.cache=new bs,this.handler=e}async refresh(){try{const e=new bs,t=await this.handler.getIntegrations();e.addAll(t);const n=[U.Integration,U.Connector],i=Object.keys(ne),r=await Promise.all(i.filter(o=>!n.includes(o)).map(async o=>this.handler.getElementsByType(o,t)));for(const o of r)e.addAll(o);this.cache.clear(),this.cache.addAll(e.getAll())}catch(e){$.error(`Failed to refresh elements: ${e instanceof Error?e.message:"Unknown error"}`)}}async putElement(e){let t;try{e.data.id?t=await this.handler.updateElement(e):t=await this.handler.createElement(e),this.cache.put(t)}catch(n){$.error(`Failed to ${e.data.id?"update":"create"} element: ${n instanceof Error?n.message:"Unknown error"}`)}}async deleteElement(e){try{await this.handler.deleteElement(e),this.cache.remove(e)}catch(t){$.error(`Failed to delete element: ${t instanceof Error?t.message:"Unknown error"}`)}}}async function _r(s,e="full"){const t={};$.info("[connectors] Getting remote workspace data");const n=await s.integrations.findAll();t.integration=n.map(i=>dn("integration",i));for(const i of Object.keys(ne)){const r=ne[i];if(r.exportable===!1)continue;const o=[];$.info(`[connectors] Reading ${r.elements} from remote workspace`);const a=await s[r.elements].findAll();if(o.push(...a.map(l=>dn(i,l))),r.integrationSpecific)for(const l of n){const u=await s[r.elements].findAll({integrationId:l.id});o.push(...u.map(p=>(p.integrationKey=l.key,dn(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 $.success("[connectors] Remote workspace data retrieved successfully"),t}c(_r,"getWorkspaceData");function dn(s,e){return e=Rr(e),ne[s].exportCleanup?ne[s].exportCleanup(e):e}c(dn,"cleanUpForExport");class Fr{static{c(this,"MembraneClient")}client=null;currentConfig=null;tokenExpiry=0;async generateAccessToken(e,t){return tn.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=Pe(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 ss({token:t,apiUri:e.apiUri})}async getClient(e){const t=this.getCurrentConfig(e);if(!t)throw new Error("Unable to create IntegrationAppClient: No workspace configuration found.");const n=!this.currentConfig||this.currentConfig.workspaceKey!==t.workspaceKey||this.currentConfig.workspaceSecret!==t.workspaceSecret||this.currentConfig.apiUri!==t.apiUri,i=!this.isTokenValid()||this.tokenExpiry-Date.now()<3e5;return(!this.client||n||i)&&(this.client=await this.createClient(t)),this.client}clearClient(){this.client=null,this.currentConfig=null,this.tokenExpiry=0}getCurrentConfigInfo(){return this.currentConfig}}const yt=new Fr;async function Cs(s){const e=await yt.getClient(s);if(!e)throw new Error("No workspace configuration found");return(await e.get("org-workspace-id")).id}c(Cs,"getWorkspaceId");const ks="connectors",vs="development",hn={};async function Br({integrations:s,allConnectors:e=!1}){const t=Cr(),n=await yt.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 Es({client:n,connectorId:a});(!!u.workspaceId||e)&&(i.has(a)||(await Vr({basePath:t,connector:u}),i.add(a)),r[a]||(r[a]=new Set),r[a].has(l)||(await Hr({client:n,connector:u,connectorVersion:l,basePath:t}),r[a].add(l)))}}}c(Br,"pullConnectors");async function Ur(){const s=await yt.getClient(process.cwd()),e=await _r(s,"minified"),n=(await s.get("org-workspace-id")).id,i={};$.info("[connectors] Loading custom connectors");const r=s,o=await r.get(`/connectors?workspaceId=${n}`);$.info("[connectors] Loading public connectors"),e.connector=o;const a=pn(),u=(j.existsSync(a)?j.readdirSync(a):[]).filter(p=>{if(p.startsWith("."))return!1;const d=F.join(a,p);try{return j.statSync(d).isDirectory()}catch{return!1}});for(const p of u){$.info(`[connectors] Loading connector from: ${p}`);const d=j.readdirSync(F.join(a,p)),f=await qr(p);if("baseUri"in f&&delete f.baseUri,f.uuid&&e.connector?.find(w=>w.uuid==f.uuid))i[f.id]=e.connector.find(w=>w.uuid==f.uuid).id,$.info(`[connectors] Matched ${f.name} uuid: ${f.uuid}`);else if(!i[f.id])if(!!(await Es({client:s,connectorId:f.id})).workspaceId){$.info(`[connectors] Creating custom connector ${f.name} (${f.key})`);const y=await r.post("connectors",{...f,workspaceId:n});i[f.id]=y.id}else{$.info(`[connectors] Skipping public connector ${f.name} (${f.key})`);continue}const g=d.filter(w=>j.statSync(F.join(a,p,w)).isDirectory());for(const w of g)await Gr({client:s,connector:f,version:w,connectorId:i[f.id]})}}c(Ur,"pushConnectors");function pn(){const s=on();return F.join(s.membraneDirPath,ks)}c(pn,"getConnectorsPath");async function qr(s){return de.load(j.readFileSync(F.join(pn(),s,`${s}.yml`),"utf8"))}c(qr,"readConnector");async function Jr(s,e){return $.info(`[connectors] Zipping ${s} into ${e}`),new Promise((t,n)=>{const i=j.createWriteStream(e),r=cr("zip",{zlib:{level:9}});i.on("close",()=>{$.success(`[connectors] Successfully created ${e}`),t()}),i.on("end",()=>{$.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=j.readdirSync(s);for(const a of o){const l=F.join(s,a),u=j.statSync(l);u.isFile()?r.file(l,{name:a}):u.isDirectory()&&r.directory(l,a)}r.finalize()})}c(Jr,"createZipArchive");async function Wr(s,e){return $.info(`[connectors] Unzipping into ${e}`),new Promise((t,n)=>{const i=ur.Parse();i.on("entry",r=>{const o=r.path;if(r.type==="Directory"){const l=F.join(e,o);j.mkdirSync(l,{recursive:!0}),r.autodrain()}else{const l=F.join(e,o),u=F.dirname(l);j.mkdirSync(u,{recursive:!0});const p=j.createWriteStream(l);r.pipe(p),p.on("finish",()=>{console.debug(`Extracted: ${o}`)})}}),i.on("end",()=>{$.success(`[connectors] Successfully extracted to ${e}`),t()}),i.on("error",r=>{n(r)}),i.write(s),i.end()})}c(Wr,"extractZipArchive");async function Gr({client:s,connector:e,version:t,connectorId:n}){const i=F.join(pn(),wt(e),Ts(t)),r=F.join(i,"src"),o=F.join(i,"src.zip"),a=j.existsSync(o);if(j.existsSync(r)&&($.info(`[connectors] Archiving source code for ${e.name} version ${t}`),await Jr(r,o)),!j.existsSync(o)){$.warning(`[connectors] No source code found for ${e.name} version ${t}`);return}try{const l=new lr;if(l.append("file",j.createReadStream(o),"file.zip"),$.info(`[connectors] Pushing connector version ${t} for ${e.name}`),t==vs)$.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)){$.info(`[connectors] Version ${t} already published`);return}$.info(`[connectors] Publishing version ${t} of connector ${n}`),await s.post(`connectors/${n}/publish-version`,l,{headers:{...l.getHeaders()}})}$.success(`Successfully pushed connector version ${t} for ${e.name}`)}catch{$.error(`Error pushing connector version ${t} for ${e.name}`)}finally{!a&&j.existsSync(o)&&($.info(`[connectors] Cleaning up temporary zip file for ${e.name} version ${t}`),j.unlinkSync(o))}}c(Gr,"pushConnectorVersion");async function Es({client:s,connectorId:e}){if(hn[e])return hn[e];const t=await s.get(`connectors/${e}`);return hn[e]=t,t}c(Es,"getConnector");async function Vr({basePath:s,connector:e}){const t=wt(e),n=F.join(s,ks,t);j.mkdirSync(n,{recursive:!0});const i=F.join(n,`${wt(e)}.yml`);j.writeFileSync(i,de.dump(e)),$.info(`[connectors] Pulled connector ${e.name}`)}c(Vr,"pullConnector");async function Hr({client:s,connector:e,connectorVersion:t,basePath:n}){const i=wt(e),r=Ts(t),o=F.join(n,"connectors",i,r),a=await s.get(`connectors/${e.id}/download`,{version:t},{responseType:"arraybuffer",headers:{Accept:"application/zip"},timeout:1e6});j.mkdirSync(o,{recursive:!0});const l=F.join(o,"src.zip");j.writeFileSync(l,a);const u=F.join(o,"src");j.existsSync(u)&&await Wr(a,u),$.info(`[connectors] Pulled connector version: ${e.name} (${r})`)}c(Hr,"pullConnectorVersion");function wt(s){return s.key}c(wt,"getConnectorDirName");function Ts(s){return s??vs}c(Ts,"getConnectorVersionDirName");const P={NOT_SYNCED:"not_synced",PULLING:"pulling",PUSHING:"pushing",RESOLVING:"resolving",CONFLICTS:"conflicts",SYNCED:"synced",WATCHING:"watching",ERROR:"error"},Yr="membrane",zr=["**/node_modules/**","**/.git/**","**/.DS_Store","**/Thumbs.db","**/*.tmp","**/*.swp","**/*.swo","**/*.log","**/*.lock","**/dist/**","**/build/**","**/.cache/**","**/.next/**","**/.vscode/**","**/.idea/**"];function bt(s){return D.join(s,Yr)}c(bt,"getMembraneDir");const Qr=["id","workspaceId","integrationId","createdAt","updatedAt","revision","parentRevision","archivedAt","baseUri","state"],Is=[U.Action,U.FieldMapping,U.Flow,U.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=he[this.type].apiPath;if(this.integrationKey){const t=he[U.Integration].apiPath;return D.join(t,this.integrationKey,e,this.key)}return D.join(e,this.key)}get path(){return D.join(this.dirPath,"spec.yaml")}get relativePath(){return D.relative(bt(process.cwd()),this.path)}isEqual(e){if(this.id!==e.id)return!1;const t=this.clean(),n=e.clean();return fr(t,n)}hasParent(){const e=this.getParentKey();return!!e&&!!this.data?.[e]}clean(){const e={...this.data};return Qr.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 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;if(n)return V.new(n.type,i,n.integrationKey,t)}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===U.Integration?`${e}:${t}`:V.isIntegrationSpecific(e)?`${n||"universal"}:${e}:${t}`:`${e}:${t}`}static parsePath(e){const t=this.getRelativePath(e);if(this.isConnectorFile(t)||!this.isElementFile(t))return;const n=Object.values(he).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 isConnectorFile(e){const[t]=e.split(D.sep);return t===he[U.Connector].apiPath}static getElementTypeFromPath(e){return Object.values(U).find(t=>he[t].apiPath===e)}static getRelativePath(e){return D.relative(bt(process.cwd()),e)}static isIntegrationSpecific(e){return Is.includes(e)}static canBeIntegrationSpecific(e){return Is.includes(e)}}class Xr{static{c(this,"LocalElementsHandler")}basePath;constructor(){this.basePath=bt(process.cwd())}async getElementsByType(e,t){const n=[],i=D.join(this.basePath,he[e].apiPath),r=await this.readElementsInDir(i);n.push(...r);for(const o of t){const a=D.join(this.basePath,he[U.Integration].apiPath,o.key,he[e].apiPath),l=await this.readElementsInDir(a);n.push(...l)}return n.length>0&&$.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)}async updateElement(e){if(!e.data)throw new Error("Element must have data to write");const t=D.join(this.basePath,e.dirPath),n=D.join(this.basePath,e.path);return x.existsSync(t)||x.mkdirSync(t,{recursive:!0}),x.writeFileSync(n,de.dump(e.data)),$.info(`[local] Written ${e.relativePath}`),e}async deleteElement(e){const t=D.join(this.basePath,e.path),n=D.join(this.basePath,e.dirPath);x.existsSync(t)&&x.rmSync(t,{force:!0}),this.pruneEmptyDir(n),$.info(`[local] Deleted ${e.relativePath}`)}async getIntegrations(){const e=D.join(this.basePath,he[U.Integration].apiPath);return this.readElementsInDir(e)}async readElement(e){if(!x.existsSync(e))return;const t=x.readFileSync(e,"utf8"),n=de.load(t);if(n)return V.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=D.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(D.dirname(e))}catch(t){console.warn(`Failed to prune empty directory ${e}:`,t)}}}class Zr{static{c(this,"RemoteElementsHandler")}client;async getElementsByType(e,t){const n=await this.findAll(e);if(!V.canBeIntegrationSpecific(e))return n;for(const i of t){const r=i.key,o=i.data.id,a=await this.findAll(e,{integrationKey:r,integrationId:o});n.push(...a)}return n.length>0&&$.success(`[remote] Fetched ${n.length} ${e}${n.length!==1?"s":""}`),n}async getElement(e){const n=await(await this.getClient())[ne[e.type].element](e.data.id).get();return V.fromData(e.type,n)}async createElement(e){const t=e.clean(),i=await(await this.getClient())[ne[e.type].elements].create(t),r=V.fromData(e.type,i);return $.info(`[remote] Created ${r.id}`),r}async updateElement(e){if(!e.data.id)throw new Error("Element must have an id to update");const t=e.clean(),i=await(await this.getClient())[ne[e.type].element](e.data.id).put(t),r=V.fromData(e.type,i);return $.info(`[remote] Updated ${e.id}`),r}async deleteElement(e){if(!e.data.id)throw new Error("Element must have an id to delete");await(await this.getClient())[ne[e.type].element](e.data.id).archive(),$.info(`[remote] Deleted ${e.id}`)}async getIntegrations(){const n=(await(await this.getClient()).integrations.findAll()).map(i=>V.fromData(U.Integration,i));return n.length>0&&$.success(`[remote] Fetched ${n.length} integrations`),n}async findAll(e,t={}){return(await(await this.getClient())[ne[e].elements].findAll(t)).map(r=>V.fromData(e,r))}async getClient(){return this.client||(this.client=await yt.getClient(process.cwd())),this.client}}const mn=Symbol.for("yaml.alias"),gn=Symbol.for("yaml.document"),be=Symbol.for("yaml.map"),Ns=Symbol.for("yaml.pair"),le=Symbol.for("yaml.scalar"),je=Symbol.for("yaml.seq"),se=Symbol.for("yaml.node.type"),Se=c(s=>!!s&&typeof s=="object"&&s[se]===mn,"isAlias"),Ee=c(s=>!!s&&typeof s=="object"&&s[se]===gn,"isDocument"),Re=c(s=>!!s&&typeof s=="object"&&s[se]===be,"isMap"),_=c(s=>!!s&&typeof s=="object"&&s[se]===Ns,"isPair"),R=c(s=>!!s&&typeof s=="object"&&s[se]===le,"isScalar$1"),Ke=c(s=>!!s&&typeof s=="object"&&s[se]===je,"isSeq");function q(s){if(s&&typeof s=="object")switch(s[se]){case be:case je:return!0}return!1}c(q,"isCollection$1");function J(s){if(s&&typeof s=="object")switch(s[se]){case mn:case be:case le:case je:return!0}return!1}c(J,"isNode");const As=c(s=>(R(s)||q(s))&&!!s.anchor,"hasAnchor"),X=Symbol("break visit"),Os=Symbol("skip children"),ue=Symbol("remove node");function Te(s,e){const t=$s(e);Ee(s)?_e(null,s.contents,t,Object.freeze([s]))===ue&&(s.contents=null):_e(null,s,t,Object.freeze([]))}c(Te,"visit$1"),Te.BREAK=X,Te.SKIP=Os,Te.REMOVE=ue;function _e(s,e,t,n){const i=Ls(s,e,t,n);if(J(i)||_(i))return xs(s,n,i),_e(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=_e(r,e.items[r],t,n);if(typeof o=="number")r=o-1;else{if(o===X)return X;o===ue&&(e.items.splice(r,1),r-=1)}}}else if(_(e)){n=Object.freeze(n.concat(e));const r=_e("key",e.key,t,n);if(r===X)return X;r===ue&&(e.key=null);const o=_e("value",e.value,t,n);if(o===X)return X;o===ue&&(e.value=null)}}return i}c(_e,"visit_");async function St(s,e){const t=$s(e);Ee(s)?await Fe(null,s.contents,t,Object.freeze([s]))===ue&&(s.contents=null):await Fe(null,s,t,Object.freeze([]))}c(St,"visitAsync"),St.BREAK=X,St.SKIP=Os,St.REMOVE=ue;async function Fe(s,e,t,n){const i=await Ls(s,e,t,n);if(J(i)||_(i))return xs(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===X)return X;o===ue&&(e.items.splice(r,1),r-=1)}}}else if(_(e)){n=Object.freeze(n.concat(e));const r=await Fe("key",e.key,t,n);if(r===X)return X;r===ue&&(e.key=null);const o=await Fe("value",e.value,t,n);if(o===X)return X;o===ue&&(e.value=null)}}return i}c(Fe,"visitAsync_");function $s(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($s,"initVisitor");function Ls(s,e,t,n){if(typeof t=="function")return t(s,e,n);if(Re(e))return t.Map?.(s,e,n);if(Ke(e))return t.Seq?.(s,e,n);if(_(e))return t.Pair?.(s,e,n);if(R(e))return t.Scalar?.(s,e,n);if(Se(e))return t.Alias?.(s,e,n)}c(Ls,"callVisitor");function xs(s,e,t){const n=e[e.length-1];if(q(n))n.items[s]=t;else if(_(n))s==="key"?n.key=t:n.value=t;else if(Ee(n))n.contents=t;else{const i=Se(n)?"alias":"scalar";throw new Error(`Cannot replace node with ${i} parent`)}}c(xs,"replaceNode");const eo={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},to=c(s=>s.replace(/[!,[\]{}]/g,e=>eo[e]),"escapeTagName");class Q{static{c(this,"Directives")}constructor(e,t){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},Q.defaultYaml,e),this.tags=Object.assign({},Q.defaultTags,t)}clone(){const e=new Q(this.yaml,this.tags);return e.docStart=this.docStart,e}atDocument(){const e=new Q(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:Q.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},Q.defaultTags);break}return e}add(e,t){this.atNextDocument&&(this.yaml={explicit:Q.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},Q.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+to(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={};Te(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
|
+
`)}}Q.defaultYaml={explicit:!1,version:"1.2"},Q.defaultTags={"!!":"tag:yaml.org,2002:"};function Ds(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(Ds,"anchorIsValid");function Ps(s){const e=new Set;return Te(s,{Value(t,n){n.anchor&&e.add(n.anchor)}}),e}c(Ps,"anchorNames");function Ms(s,e){for(let t=1;;++t){const n=`${s}${t}`;if(!e.has(n))return n}}c(Ms,"findNewAnchor");function no(s,e){const t=[],n=new Map;let i=null;return{onAnchor:c(r=>{t.push(r),i??(i=Ps(s));const o=Ms(e,i);return i.add(o),o},"onAnchor"),setAnchors:c(()=>{for(const r of t){const o=n.get(r);if(typeof o=="object"&&o.anchor&&(R(o.node)||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(no,"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||!As(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 yn{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(!Ee(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 Ct extends yn{static{c(this,"Alias")}constructor(e){super(mn),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=[],Te(e,{Node:c((r,o)=>{(Se(o)||As(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=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(Ds(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(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=kt(s,i,t);r>n&&(n=r)}return n}else if(_(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 js=c(s=>!s||typeof s!="function"&&typeof s!="object","isScalarValue");class L extends yn{static{c(this,"Scalar")}constructor(e){super(le),this.value=e}toJSON(e,t){return t?.keep?this.value:ie(this.value,e,t)}toString(){return String(this.value)}}L.BLOCK_FOLDED="BLOCK_FOLDED",L.BLOCK_LITERAL="BLOCK_LITERAL",L.PLAIN="PLAIN",L.QUOTE_DOUBLE="QUOTE_DOUBLE",L.QUOTE_SINGLE="QUOTE_SINGLE";const so="tag:yaml.org,2002:";function io(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(io,"findTagObject");function nt(s,e,t){if(Ee(s)&&(s=s.contents),J(s))return s;if(_(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 Ct(l.anchor);l={anchor:null,node:null},a.set(s,l)}e?.startsWith("!!")&&(e=so+e.slice(2));let u=io(s,e,o.tags);if(!u){if(s&&typeof s.toJSON=="function"&&(s=s.toJSON()),!s||typeof s!="object"){const d=new L(s);return l&&(l.node=d),d}u=s instanceof Map?o[be]:Symbol.iterator in Object(s)?o[je]: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 L(s);return e?p.tag=e:u.default||(p.tag=u.tag),l&&(l.node=p),p}c(nt,"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 nt(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 st=c(s=>s==null||typeof s=="object"&&!!s[Symbol.iterator]().next().done,"isEmptyPath");class Rs extends yn{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)||_(n)?n.clone(e):n),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(st(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)?r.value:r:q(r)?r.getIn(i,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!_(t))return!1;const n=t.value;return n==null||e&&R(n)&&n.value==null&&!n.commentBefore&&!n.comment&&!n.tag})}hasIn(e){const[t,...n]=e;if(n.length===0)return this.has(t);const i=this.get(t,!0);return 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 ro=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 Ie=c((s,e,t)=>s.endsWith(`
|
|
4
|
+
`)?pe(t,e):t.includes(`
|
|
4
5
|
`)?`
|
|
5
|
-
`+
|
|
6
|
-
`)t===
|
|
7
|
-
`&&
|
|
8
|
-
`&&T!==" "&&(h
|
|
9
|
-
${e}${
|
|
10
|
-
${e}${
|
|
11
|
-
`);
|
|
12
|
-
`){if(r-o>
|
|
13
|
-
|
|
14
|
-
`;t[
|
|
15
|
-
`,
|
|
16
|
-
`)||/[ \t]\n|\n[ \t]/.test(
|
|
17
|
-
${t}`)+"'";return e.implicitKey?
|
|
6
|
+
`+pe(t,e):(s.endsWith(" ")?"":" ")+t,"lineComment"),Ks="flow",wn="block",Et="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 f,g,w=!1,h=-1,y=-1,C=-1;t===wn&&(h=_s(s,h,e.length),h!==-1&&(d=h+l));for(let A;A=s[h+=1];){if(t===Et&&A==="\\"){switch(y=h,s[h+1]){case"x":h+=3;break;case"u":h+=5;break;case"U":h+=9;break;default:h+=1}C=h}if(A===`
|
|
7
|
+
`)t===wn&&(h=_s(s,h,e.length)),d=h+e.length+l,f=void 0;else{if(A===" "&&g&&g!==" "&&g!==`
|
|
8
|
+
`&&g!==" "){const T=s[h+1];T&&T!==" "&&T!==`
|
|
9
|
+
`&&T!==" "&&(f=h)}if(h>=d)if(f)u.push(f),d=f+l,f=void 0;else if(t===Et){for(;g===" "||g===" ";)g=A,A=s[h+=1],w=!0;const T=h>C+1?h-2:y-1;if(p[T])return s;u.push(T),p[T]=!0,d=T+l,f=void 0}else w=!0}g=A}if(w&&a&&a(),u.length===0)return s;o&&o();let v=s.slice(0,u[0]);for(let A=0;A<u.length;++A){const T=u[A],N=u[A+1]||s.length;T===0?v=`
|
|
10
|
+
${e}${s.slice(0,N)}`:(t===Et&&p[T]&&(v+=`${s[T]}\\`),v+=`
|
|
11
|
+
${e}${s.slice(T+1,N)}`)}return v}c(Tt,"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 It=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 oo(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(oo,"lineLengthOverLimit");function it(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
|
+
|
|
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,Et,It(e,!1))}c(it,"doubleQuotedString");function bn(s,e){if(e.options.singleQuote===!1||e.implicitKey&&s.includes(`
|
|
17
|
+
`)||/[ \t]\n|\n[ \t]/.test(s))return it(s,e);const t=e.indent||(Nt(s)?" ":""),n="'"+s.replace(/'/g,"''").replace(/\n+/g,`$&
|
|
18
|
+
${t}`)+"'";return e.implicitKey?n:Tt(n,t,Ks,It(e,!1))}c(bn,"singleQuotedString");function Ue(s,e){const{singleQuote:t}=e.options;let n;if(t===!1)n=it;else{const i=s.includes('"'),r=s.includes("'");i&&!r?n=bn:r&&!i?n=it:n=t?bn:it}return n(s,e)}c(Ue,"quotedString");let Sn;try{Sn=new RegExp(`(^|(?<!
|
|
18
19
|
))
|
|
19
20
|
+(?!
|
|
20
|
-
|$)`,"g")}catch{
|
|
21
|
+
|$)`,"g")}catch{Sn=/\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 Ue(t,n);const u=n.indent||(n.forceBlockIndent||Nt(t)?" ":""),p=o==="literal"?!0:o==="folded"||e===L.BLOCK_FOLDED?!1:e===L.BLOCK_LITERAL?!0:!oo(t,l,u.length);if(!t)return p?`|
|
|
21
22
|
`:`>
|
|
22
|
-
`;let f
|
|
23
|
-
`&&
|
|
24
|
-
`);w===-1?
|
|
25
|
-
`&&(
|
|
26
|
-
`)
|
|
27
|
-
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${u}`);let
|
|
23
|
+
`;let d,f;for(f=t.length;f>0;--f){const N=t[f-1];if(N!==`
|
|
24
|
+
`&&N!==" "&&N!==" ")break}let g=t.substring(f);const w=g.indexOf(`
|
|
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(Sn,`$&${u}`));let h=!1,y,C=-1;for(y=0;y<t.length;++y){const N=t[y];if(N===" ")h=!0;else if(N===`
|
|
27
|
+
`)C=y;else break}let v=t.substring(0,C<y?C+1:y);v&&(t=t.substring(v.length),v=v.replace(/\n+/g,`$&${u}`));let T=(h?u?"2":"1":"")+d;if(s&&(T+=" "+a(s.replace(/ ?[\r\n]+/g," ")),i&&i()),!p){const N=t.replace(/\n+/g,`
|
|
28
|
+
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${u}`);let O=!1;const M=It(n,!0);o!=="folded"&&e!==L.BLOCK_FOLDED&&(M.onOverflow=()=>{O=!0});const E=Tt(`${v}${N}${g}`,u,wn,M);if(!O)return`>${T}
|
|
28
29
|
${u}${E}`}return t=t.replace(/\n+/g,`$&${u}`),`|${T}
|
|
29
|
-
${u}${
|
|
30
|
-
`)||
|
|
31
|
-
`)?
|
|
32
|
-
`))return
|
|
33
|
-
${
|
|
34
|
-
${e.indent}${a}`:a}
|
|
35
|
-
${a}:`):(
|
|
36
|
-
`:"",
|
|
37
|
-
${
|
|
38
|
-
`&&(
|
|
39
|
-
|
|
40
|
-
`)
|
|
41
|
-
${t.indent}`}else if(!
|
|
42
|
-
`),
|
|
43
|
-
${t.indent}`)}}else(
|
|
44
|
-
`)&&(
|
|
45
|
-
${
|
|
46
|
-
`}}return
|
|
47
|
-
`+
|
|
48
|
-
`))&&(u=!0),
|
|
49
|
-
${r}${i}${
|
|
30
|
+
${u}${v}${t}${g}`}c(At,"blockString");function ao(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 Ue(r,e);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(r))return a||p||!r.includes(`
|
|
32
|
+
`)?Ue(r,e):At(s,e,t,n);if(!a&&!p&&i!==L.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 Ue(r,e)}const d=r.replace(/\n+/g,`$&
|
|
34
|
+
${l}`);if(o){const f=c(h=>h.default&&h.tag!=="tag:yaml.org,2002:str"&&h.test?.test(d),"test"),{compat:g,tags:w}=e.doc.schema;if(w.some(f)||g?.some(f))return Ue(r,e)}return a?d:Tt(d,l,Ks,It(e,!1))}c(ao,"plainString");function rt(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!==L.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(a=L.QUOTE_DOUBLE);const l=c(p=>{switch(p){case L.BLOCK_FOLDED:case L.BLOCK_LITERAL:return i||r?Ue(o.value,e):At(o,e,t,n);case L.QUOTE_DOUBLE:return it(o.value,e);case L.QUOTE_SINGLE:return bn(o.value,e);case L.PLAIN:return ao(o,e,t,n);default:return null}},"_stringify");let u=l(a);if(u===null){const{defaultKeyType:p,defaultStringType:d}=e.options,f=i&&p||d;if(u=l(f),u===null)throw new Error(`Unsupported default string type ${f}`)}return u}c(rt,"stringifyString");function Fs(s,e){const t=Object.assign({blockQuote:!0,commentString:ro,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(Fs,"createStringifyContext");function co(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(R(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(co,"getTagObject");function lo(s,e,{anchors:t,doc:n}){if(!n.directives)return"";const i=[],r=(R(s)||q(s))&&s.anchor;r&&Ds(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(lo,"stringifyProps");function qe(s,e,t,n){if(_(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=J(s)?s:e.doc.createNode(s,{onTagObj:c(l=>i=l,"onTagObj")});i??(i=co(e.doc.schema.tags,r));const o=lo(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(r)?rt(r,e,t,n):r.toString(e,t,n);return o?R(r)||a[0]==="{"||a[0]==="["?`${o} ${a}`:`${o}
|
|
35
|
+
${e.indent}${a}`:a}c(qe,"stringify$2");function uo({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 f=J(s)&&s.comment||null;if(d){if(f)throw new Error("With simple keys, key nodes cannot have comments");if(q(s)||!J(s)&&typeof s=="object"){const M="With simple keys, collection cannot be used as a key value";throw new Error(M)}}let g=!d&&(!s||f&&e==null&&!t.inFlow||q(s)||(R(s)?s.type===L.BLOCK_FOLDED||s.type===L.BLOCK_LITERAL:typeof s=="object"));t=Object.assign({},t,{allNullValues:!1,implicitKey:!g&&(d||!r),indent:a+l});let w=!1,h=!1,y=qe(s,t,()=>w=!0,()=>h=!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}`,f&&!w?y+=Ie(y,t.indent,u(f)):h&&i&&i(),y;w&&(f=null),g?(f&&(y+=Ie(y,t.indent,u(f))),y=`? ${y}
|
|
36
|
+
${a}:`):(y=`${y}:`,f&&(y+=Ie(y,t.indent,u(f))));let C,v,A;J(e)?(C=!!e.spaceBefore,v=e.commentBefore,A=e.comment):(C=!1,v=null,A=null,e&&typeof e=="object"&&(e=o.createNode(e))),t.implicitKey=!1,!g&&!f&&R(e)&&(t.indentAtStart=y.length+1),h=!1,!p&&l.length>=2&&!t.inFlow&&!g&&Ke(e)&&!e.flow&&!e.tag&&!e.anchor&&(t.indent=t.indent.substring(2));let T=!1;const N=qe(e,t,()=>T=!0,()=>h=!0);let O=" ";if(f||C||v){if(O=C?`
|
|
37
|
+
`:"",v){const M=u(v);O+=`
|
|
38
|
+
${pe(M,t.indent)}`}N===""&&!t.inFlow?O===`
|
|
39
|
+
`&&(O=`
|
|
40
|
+
|
|
41
|
+
`):O+=`
|
|
42
|
+
${t.indent}`}else if(!g&&q(e)){const M=N[0],E=N.indexOf(`
|
|
43
|
+
`),W=E!==-1,ge=t.inFlow??e.flow??e.items.length===0;if(W||!ge){let Le=!1;if(W&&(M==="&"||M==="!")){let H=N.indexOf(" ");M==="&"&&H!==-1&&H<E&&N[H+1]==="!"&&(H=N.indexOf(" ",H+1)),(H===-1||E<H)&&(Le=!0)}Le||(O=`
|
|
44
|
+
${t.indent}`)}}else(N===""||N[0]===`
|
|
45
|
+
`)&&(O="");return y+=O+N,t.inFlow?T&&n&&n():A&&!T?y+=Ie(y,t.indent,u(A)):h&&i&&i(),y}c(uo,"stringifyPair");function Bs(s,e){(s==="debug"||s==="warn")&&console.warn(e)}c(Bs,"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 L(Symbol(Ot)),{addToJSMap:Us}),"resolve"),stringify:c(()=>Ot,"stringify")},fo=c((s,e)=>(me.identify(e)||R(e)&&(!e.type||e.type===L.PLAIN)&&me.identify(e.value))&&s?.doc.schema.tags.some(t=>t.tag===me.tag&&t.default),"isMergeKey");function Us(s,e,t){if(t=s&&Se(t)?t.resolve(s.doc):t,Ke(t))for(const n of t.items)Cn(s,e,n);else if(Array.isArray(t))for(const n of t)Cn(s,e,n);else Cn(s,e,t)}c(Us,"addMergeToJSMap");function Cn(s,e,t){const n=s&&Se(t)?t.resolve(s.doc):t;if(!Re(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(Cn,"mergeValue");function qs(s,e,{key:t,value:n}){if(J(t)&&t.addToJSMap)t.addToJSMap(s,e,n);else if(fo(s,t))Us(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=ho(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(qs,"addPairToJSMap");function ho(s,e,t){if(e===null)return"";if(typeof e!="object")return String(e);if(J(s)&&t?.doc){const n=Fs(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)+'..."'),Bs(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(ho,"stringifyKey");function kn(s,e,t){const n=nt(s,void 0,t),i=nt(e,void 0,t);return new Y(n,i)}c(kn,"createPair");class Y{static{c(this,"Pair")}constructor(e,t=null){Object.defineProperty(this,se,{value:Ns}),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 Y(t,n)}toJSON(e,t){const n=t?.mapAsMap?new Map:{};return qs(t,n,this)}toString(e,t,n){return e?.doc?uo(this,e,t,n):JSON.stringify(this)}}function Js(s,e,t){return(e.inFlow??s.flow?mo:po)(s,e,t)}c(Js,"stringifyCollection");function po({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 f=[];for(let w=0;w<e.length;++w){const h=e[w];let y=null;if(J(h))!d&&h.spaceBefore&&f.push(""),$t(t,f,h.commentBefore,d),h.comment&&(y=h.comment);else if(_(h)){const v=J(h.key)?h.key:null;v&&(!d&&v.spaceBefore&&f.push(""),$t(t,f,v.commentBefore,d))}d=!1;let C=qe(h,p,()=>y=null,()=>d=!0);y&&(C+=Ie(C,r,u(y))),d&&y&&(d=!1),f.push(n+C)}let g;if(f.length===0)g=i.start+i.end;else{g=f[0];for(let w=1;w<f.length;++w){const h=f[w];g+=h?`
|
|
46
|
+
${l}${h}`:`
|
|
47
|
+
`}}return s?(g+=`
|
|
48
|
+
`+pe(u(s),l),a&&a()):d&&o&&o(),g}c(po,"stringifyBlockCollection");function mo({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 h=s[w];let y=null;if(J(h))h.spaceBefore&&d.push(""),$t(e,d,h.commentBefore,!1),h.comment&&(y=h.comment);else if(_(h)){const v=J(h.key)?h.key:null;v&&(v.spaceBefore&&d.push(""),$t(e,d,v.commentBefore,!1),v.comment&&(u=!0));const A=J(h.value)?h.value:null;A?(A.comment&&(y=A.comment),A.commentBefore&&(u=!0)):h.value==null&&v?.comment&&(y=v.comment)}y&&(u=!0);let C=qe(h,l,()=>y=null);w<s.length-1&&(C+=","),y&&(C+=Ie(C,n,a(y))),!u&&(d.length>p||C.includes(`
|
|
49
|
+
`))&&(u=!0),d.push(C),p=d.length}const{start:f,end:g}=t;if(d.length===0)return f+g;if(!u){const w=d.reduce((h,y)=>h+y.length+2,2);u=e.options.lineWidth>0&&w>e.options.lineWidth}if(u){let w=f;for(const h of d)w+=h?`
|
|
50
|
+
${r}${i}${h}`:`
|
|
50
51
|
`;return`${w}
|
|
51
|
-
${i}${
|
|
52
|
-
`:" ")}return
|
|
53
|
-
${i.key.commentBefore}`:
|
|
54
|
-
${r.comment}`:s.comment}s=i}n.items[t]=B(s)?s:new Y(s)}}else e("Expected a sequence for this tag");return n}l(vi,"resolvePairs");function Ai(n,e,t){const{replacer:s}=t,i=new ge(n);i.tag="tag:yaml.org,2002:pairs";let r=0;if(e&&Symbol.iterator in Object(e))for(let o of e){typeof s=="function"&&(o=s.call(e,String(r++),o));let a,c;if(Array.isArray(o))if(o.length===2)a=o[0],c=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],c=o[a];else throw new TypeError(`Expected tuple with one key, not ${u.length} keys`)}else a=o;i.items.push(_n(a,c,t))}return i}l(Ai,"createPairs");const jn={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:vi,createNode:Ai};class Ge extends ge{static{l(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=Ge.tag}toJSON(e,t){if(!t)return super.toJSON(e);const s=new Map;t?.onCreate&&t.onCreate(s);for(const i of this.items){let r,o;if(B(i)?(r=se(i.key,"",t),o=se(i.value,r,t)):r=se(i,"",t),s.has(r))throw new Error("Ordered maps must not include duplicate keys");s.set(r,o)}return s}static from(e,t,s){const i=Ai(e,t,s),r=new this;return r.items=i.items,r}}Ge.tag="tag:yaml.org,2002:omap";const Kn={collection:"seq",identify:l(n=>n instanceof Map,"identify"),nodeClass:Ge,default:!1,tag:"tag:yaml.org,2002:omap",resolve(n,e){const t=vi(n,e),s=[];for(const{key:i}of t.items)R(i)&&(s.includes(i.value)?e(`Ordered maps must not include duplicate keys: ${i.value}`):s.push(i.value));return Object.assign(new Ge,t)},createNode:l((n,e,t)=>Ge.from(n,e,t),"createNode")};function Oi({value:n,source:e},t){return e&&(n?Ei:Ti).test.test(e)?e:n?t.options.trueStr:t.options.falseStr}l(Oi,"boolStringify");const Ei={identify:l(n=>n===!0,"identify"),default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:l(()=>new _(!0),"resolve"),stringify:Oi},Ti={identify:l(n=>n===!1,"identify"),default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:l(()=>new _(!1),"resolve"),stringify:Oi},ea={identify:l(n=>typeof n=="number","identify"),default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:l(n=>n.slice(-3).toLowerCase()==="nan"?NaN:n[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,"resolve"),stringify:ie},ta={identify:l(n=>typeof n=="number","identify"),default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:l(n=>parseFloat(n.replace(/_/g,"")),"resolve"),stringify(n){const e=Number(n.value);return isFinite(e)?e.toExponential():ie(n)}},na={identify:l(n=>typeof n=="number","identify"),default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(n){const e=new _(parseFloat(n.replace(/_/g,""))),t=n.indexOf(".");if(t!==-1){const s=n.substring(t+1).replace(/_/g,"");s[s.length-1]==="0"&&(e.minFractionDigits=s.length)}return e},stringify:ie},at=l(n=>typeof n=="bigint"||Number.isInteger(n),"intIdentify");function Ut(n,e,t,{intAsBigInt:s}){const i=n[0];if((i==="-"||i==="+")&&(e+=1),n=n.substring(e).replace(/_/g,""),s){switch(t){case 2:n=`0b${n}`;break;case 8:n=`0o${n}`;break;case 16:n=`0x${n}`;break}const o=BigInt(n);return i==="-"?BigInt(-1)*o:o}const r=parseInt(n,t);return i==="-"?-1*r:r}l(Ut,"intResolve");function Dn(n,e,t){const{value:s}=n;if(at(s)){const i=s.toString(e);return s<0?"-"+t+i.substr(1):t+i}return ie(n)}l(Dn,"intStringify");const sa={identify:at,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:l((n,e,t)=>Ut(n,2,2,t),"resolve"),stringify:l(n=>Dn(n,2,"0b"),"stringify")},ia={identify:at,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:l((n,e,t)=>Ut(n,1,8,t),"resolve"),stringify:l(n=>Dn(n,8,"0"),"stringify")},ra={identify:at,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:l((n,e,t)=>Ut(n,0,10,t),"resolve"),stringify:ie},oa={identify:at,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:l((n,e,t)=>Ut(n,2,16,t),"resolve"),stringify:l(n=>Dn(n,16,"0x"),"stringify")};class Ye extends te{static{l(this,"YAMLSet")}constructor(e){super(e),this.tag=Ye.tag}add(e){let t;B(e)?t=e:e&&typeof e=="object"&&"key"in e&&"value"in e&&e.value===null?t=new Y(e.key,null):t=new Y(e,null),ve(this.items,t.key)||this.items.push(t)}get(e,t){const s=ve(this.items,e);return!t&&B(s)?R(s.key)?s.key.value:s.key:s}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 s=ve(this.items,e);s&&!t?this.items.splice(this.items.indexOf(s),1):!s&&t&&this.items.push(new Y(e))}toJSON(e,t){return super.toJSON(e,t,Set)}toString(e,t,s){if(!e)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},e,{allNullValues:!0}),t,s);throw new Error("Set items must all have null values")}static from(e,t,s){const{replacer:i}=s,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(_n(o,null,s));return r}}Ye.tag="tag:yaml.org,2002:set";const Mn={collection:"map",identify:l(n=>n instanceof Set,"identify"),nodeClass:Ye,default:!1,tag:"tag:yaml.org,2002:set",createNode:l((n,e,t)=>Ye.from(n,e,t),"createNode"),resolve(n,e){if(De(n)){if(n.hasAllNullValues(!0))return Object.assign(new Ye,n);e("Set items must all have null values")}else e("Expected a mapping for this tag");return n}};function Rn(n,e){const t=n[0],s=t==="-"||t==="+"?n.substring(1):n,i=l(o=>e?BigInt(o):Number(o),"num"),r=s.replace(/_/g,"").split(":").reduce((o,a)=>o*i(60)+i(a),i(0));return t==="-"?i(-1)*r:r}l(Rn,"parseSexagesimal");function $i(n){let{value:e}=n,t=l(o=>o,"num");if(typeof e=="bigint")t=l(o=>BigInt(o),"num");else if(isNaN(e)||!isFinite(e))return ie(n);let s="";e<0&&(s="-",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))),s+r.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}l($i,"stringifySexagesimal");const Ii={identify:l(n=>typeof n=="bigint"||Number.isInteger(n),"identify"),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:l((n,e,{intAsBigInt:t})=>Rn(n,t),"resolve"),stringify:$i},Ni={identify:l(n=>typeof n=="number","identify"),default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:l(n=>Rn(n,!1),"resolve"),stringify:$i},Jt={identify:l(n=>n 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(n){const e=n.match(Jt.test);if(!e)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");const[,t,s,i,r,o,a]=e.map(Number),c=e[7]?Number((e[7]+"00").substr(1,3)):0;let u=Date.UTC(t,s-1,i,r||0,o||0,a||0,c);const d=e[8];if(d&&d!=="Z"){let f=Rn(d,!1);Math.abs(f)<30&&(f*=60),u-=6e4*f}return new Date(u)},stringify:l(({value:n})=>n?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??"","stringify")},_i=[Je,Ve,Rt,Bt,Ei,Ti,sa,ia,ra,oa,ea,ta,na,Pn,fe,Kn,jn,Mn,Ii,Ni,Jt],Li=new Map([["core",Yo],["failsafe",[Je,Ve,Rt]],["json",Xo],["yaml11",_i],["yaml-1.1",_i]]),xi={binary:Pn,bool:Ln,float:yi,floatExp:gi,floatNaN:mi,floatTime:Ni,int:Si,intHex:ki,intOct:bi,intTime:Ii,map:Je,merge:fe,null:Bt,omap:Kn,pairs:jn,seq:Ve,set:Mn,timestamp:Jt},aa={"tag:yaml.org,2002:binary":Pn,"tag:yaml.org,2002:merge":fe,"tag:yaml.org,2002:omap":Kn,"tag:yaml.org,2002:pairs":jn,"tag:yaml.org,2002:set":Mn,"tag:yaml.org,2002:timestamp":Jt};function Bn(n,e,t){const s=Li.get(e);if(s&&!n)return t&&!s.includes(fe)?s.concat(fe):s.slice();let i=s;if(!i)if(Array.isArray(n))i=[];else{const r=Array.from(Li.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(n))for(const r of n)i=i.concat(r);else typeof n=="function"&&(i=n(i.slice()));return t&&(i=i.concat(fe)),i.reduce((r,o)=>{const a=typeof o=="string"?xi[o]:o;if(!a){const c=JSON.stringify(o),u=Object.keys(xi).map(d=>JSON.stringify(d)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${u}`)}return r.includes(a)||r.push(a),r},[])}l(Bn,"getTags");const ca=l((n,e)=>n.key<e.key?-1:n.key>e.key?1:0,"sortMapEntriesByKey");class nn{static{l(this,"Schema")}constructor({compat:e,customTags:t,merge:s,resolveKnownTags:i,schema:r,sortMapEntries:o,toStringDefaults:a}){this.compat=Array.isArray(e)?Bn(e,"compat"):e?Bn(null,e):null,this.name=typeof r=="string"&&r||"core",this.knownTags=i?aa:{},this.tags=Bn(t,this.name,s),this.toStringOptions=a??null,Object.defineProperty(this,pe,{value:Je}),Object.defineProperty(this,ce,{value:Rt}),Object.defineProperty(this,Ke,{value:Ve}),this.sortMapEntries=typeof o=="function"?o:o===!0?ca:null}clone(){const e=Object.create(nn.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}}function la(n,e){const t=[];let s=e.directives===!0;if(e.directives!==!1&&n.directives){const c=n.directives.toString(n);c?(t.push(c),s=!0):n.directives.docStart&&(s=!0)}s&&t.push("---");const i=ui(n,e),{commentString:r}=i.options;if(n.commentBefore){t.length!==1&&t.unshift("");const c=r(n.commentBefore);t.unshift(ue(c,""))}let o=!1,a=null;if(n.contents){if(U(n.contents)){if(n.contents.spaceBefore&&s&&t.push(""),n.contents.commentBefore){const d=r(n.contents.commentBefore);t.push(ue(d,""))}i.forceBlockIndent=!!n.comment,a=n.contents.comment}const c=a?void 0:()=>o=!0;let u=Ue(n.contents,i,()=>a=null,c);a&&(u+=Ce(u,"",r(a))),(u[0]==="|"||u[0]===">")&&t[t.length-1]==="---"?t[t.length-1]=`--- ${u}`:t.push(u)}else t.push(Ue(n.contents,i));if(n.directives?.docEnd)if(n.comment){const c=r(n.comment);c.includes(`
|
|
55
|
-
`)?(t.push("..."),t.push(
|
|
52
|
+
${i}${g}`}else return`${f}${o}${d.join(" ")}${o}${g}`}c(mo,"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 Ne(s,e){const t=R(e)?e.value:e;for(const n of s)if(_(n)&&(n.key===e||n.key===t||R(n.key)&&n.key.value===t))return n}c(Ne,"findPair");class ee extends Rs{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(kn(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;_(e)?n=e:!e||typeof e!="object"||!("key"in e)?n=new Y(e,e?.value):n=new Y(e.key,e.value);const i=Ne(this.items,n.key),r=this.schema?.sortMapEntries;if(i){if(!t)throw new Error(`Key ${n.key} already set`);R(i.value)&&js(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=Ne(this.items,e);return t?this.items.splice(this.items.indexOf(t),1).length>0:!1}get(e,t){const i=Ne(this.items,e)?.value;return(!t&&R(i)?i.value:i)??void 0}has(e){return!!Ne(this.items,e)}set(e,t){this.add(new Y(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)qs(t,i,r);return i}toString(e,t,n){if(!e)return JSON.stringify(this);for(const i of this.items)if(!_(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})),Js(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:n,onComment:t})}}const Je={collection:"map",default:!0,nodeClass:ee,tag:"tag:yaml.org,2002:map",resolve(s,e){return Re(s)||e("Expected a mapping for this tag"),s},createNode:c((s,e,t)=>ee.from(s,e,t),"createNode")};class Ce extends Rs{static{c(this,"YAMLSeq")}static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(je,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&&R(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];R(i)&&js(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?Js(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(nt(a,void 0,n))}}return r}}function Lt(s){let e=R(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 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),rt(s,e,t,n)}},Dt={identify:c(s=>s==null,"identify"),createNode:c(()=>new L(null),"createNode"),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:c(()=>new L(null),"resolve"),stringify:c(({source:s},e)=>typeof s=="string"&&Dt.test.test(s)?s:e.options.nullStr,"stringify")},vn={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 L(s[0]==="t"||s[0]==="T"),"resolve"),stringify({source:s,value:e},t){if(s&&vn.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 Ws={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},Gs={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)}},Vs={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 L(parseFloat(s)),t=s.indexOf(".");return t!==-1&&s[s.length-1]==="0"&&(e.minFractionDigits=s.length-t-1),e},stringify:oe},Pt=c(s=>typeof s=="bigint"||Number.isInteger(s),"intIdentify$2"),En=c((s,e,t,{intAsBigInt:n})=>n?BigInt(s):parseInt(s.substring(e),t),"intResolve$1");function Hs(s,e,t){const{value:n}=s;return Pt(n)&&n>=0?t+n.toString(e):oe(s)}c(Hs,"intStringify$1");const Ys={identify:c(s=>Pt(s)&&s>=0,"identify"),default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:c((s,e,t)=>En(s,2,8,t),"resolve"),stringify:c(s=>Hs(s,8,"0o"),"stringify")},zs={identify:Pt,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:c((s,e,t)=>En(s,0,10,t),"resolve"),stringify:oe},Qs={identify:c(s=>Pt(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)=>En(s,2,16,t),"resolve"),stringify:c(s=>Hs(s,16,"0x"),"stringify")},go=[Je,We,xt,Dt,vn,Ys,zs,Qs,Ws,Gs,Vs];function Xs(s){return typeof s=="bigint"||Number.isInteger(s)}c(Xs,"intIdentify$1");const Mt=c(({value:s})=>JSON.stringify(s),"stringifyJSON"),yo=[{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 L(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:Xs,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})=>Xs(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}],wo={default:!0,tag:"",test:/^/,resolve(s,e){return e(`Unresolved plain scalar ${JSON.stringify(s)}`),s}},bo=[Je,We].concat(yo,wo),Tn={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=L.BLOCK_LITERAL),e!==L.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,f=0;d<u;++d,f+=l)p[d]=a.substr(f,l);a=p.join(e===L.BLOCK_LITERAL?`
|
|
53
|
+
`:" ")}return rt({comment:s,type:e,value:a},n,i,r)}};function Zs(s,e){if(Ke(s))for(let t=0;t<s.items.length;++t){let n=s.items[t];if(!_(n)){if(Re(n)){n.items.length>1&&e("Each pair must have its own sequence indicator");const i=n.items[0]||new Y(new L(null));if(n.commentBefore&&(i.key.commentBefore=i.key.commentBefore?`${n.commentBefore}
|
|
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]=_(n)?n:new Y(n)}}else e("Expected a sequence for this tag");return s}c(Zs,"resolvePairs");function ei(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(kn(a,l,t))}return i}c(ei,"createPairs");const In={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:Zs,createNode:ei};class Ye extends Ce{static{c(this,"YAMLOMap")}constructor(){super(),this.add=ee.prototype.add.bind(this),this.delete=ee.prototype.delete.bind(this),this.get=ee.prototype.get.bind(this),this.has=ee.prototype.has.bind(this),this.set=ee.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(_(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=ei(e,t,n),r=new this;return r.items=i.items,r}}Ye.tag="tag:yaml.org,2002:omap";const Nn={collection:"seq",identify:c(s=>s instanceof Map,"identify"),nodeClass:Ye,default:!1,tag:"tag:yaml.org,2002:omap",resolve(s,e){const t=Zs(s,e),n=[];for(const{key:i}of t.items)R(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 ti({value:s,source:e},t){return e&&(s?ni:si).test.test(e)?e:s?t.options.trueStr:t.options.falseStr}c(ti,"boolStringify");const ni={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 L(!0),"resolve"),stringify:ti},si={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 L(!1),"resolve"),stringify:ti},So={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},Co={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)}},ko={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 L(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},ot=c(s=>typeof s=="bigint"||Number.isInteger(s),"intIdentify");function jt(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(jt,"intResolve");function An(s,e,t){const{value:n}=s;if(ot(n)){const i=n.toString(e);return n<0?"-"+t+i.substr(1):t+i}return oe(s)}c(An,"intStringify");const vo={identify:ot,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:c((s,e,t)=>jt(s,2,2,t),"resolve"),stringify:c(s=>An(s,2,"0b"),"stringify")},Eo={identify:ot,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:c((s,e,t)=>jt(s,1,8,t),"resolve"),stringify:c(s=>An(s,8,"0"),"stringify")},To={identify:ot,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:c((s,e,t)=>jt(s,0,10,t),"resolve"),stringify:oe},Io={identify:ot,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:c((s,e,t)=>jt(s,2,16,t),"resolve"),stringify:c(s=>An(s,16,"0x"),"stringify")};class ze extends ee{static{c(this,"YAMLSet")}constructor(e){super(e),this.tag=ze.tag}add(e){let t;_(e)?t=e:e&&typeof e=="object"&&"key"in e&&"value"in e&&e.value===null?t=new Y(e.key,null):t=new Y(e,null),Ne(this.items,t.key)||this.items.push(t)}get(e,t){const n=Ne(this.items,e);return!t&&_(n)?R(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=Ne(this.items,e);n&&!t?this.items.splice(this.items.indexOf(n),1):!n&&t&&this.items.push(new Y(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(kn(o,null,n));return r}}ze.tag="tag:yaml.org,2002:set";const On={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(Re(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 $n(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($n,"parseSexagesimal");function ii(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(ii,"stringifySexagesimal");const ri={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})=>$n(s,t),"resolve"),stringify:ii},oi={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=>$n(s,!1),"resolve"),stringify:ii},Rt={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(Rt.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=$n(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")},ai=[Je,We,xt,Dt,ni,si,vo,Eo,To,Io,So,Co,ko,Tn,me,Nn,In,On,ri,oi,Rt],ci=new Map([["core",go],["failsafe",[Je,We,xt]],["json",bo],["yaml11",ai],["yaml-1.1",ai]]),li={binary:Tn,bool:vn,float:Vs,floatExp:Gs,floatNaN:Ws,floatTime:oi,int:zs,intHex:Qs,intOct:Ys,intTime:ri,map:Je,merge:me,null:Dt,omap:Nn,pairs:In,seq:We,set:On,timestamp:Rt},No={"tag:yaml.org,2002:binary":Tn,"tag:yaml.org,2002:merge":me,"tag:yaml.org,2002:omap":Nn,"tag:yaml.org,2002:pairs":In,"tag:yaml.org,2002:set":On,"tag:yaml.org,2002:timestamp":Rt};function Ln(s,e,t){const n=ci.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(ci.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"?li[o]:o;if(!a){const l=JSON.stringify(o),u=Object.keys(li).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(Ln,"getTags");const Ao=c((s,e)=>s.key<e.key?-1:s.key>e.key?1:0,"sortMapEntriesByKey");class Ht{static{c(this,"Schema")}constructor({compat:e,customTags:t,merge:n,resolveKnownTags:i,schema:r,sortMapEntries:o,toStringDefaults:a}){this.compat=Array.isArray(e)?Ln(e,"compat"):e?Ln(null,e):null,this.name=typeof r=="string"&&r||"core",this.knownTags=i?No:{},this.tags=Ln(t,this.name,n),this.toStringOptions=a??null,Object.defineProperty(this,be,{value:Je}),Object.defineProperty(this,le,{value:xt}),Object.defineProperty(this,je,{value:We}),this.sortMapEntries=typeof o=="function"?o:o===!0?Ao:null}clone(){const e=Object.create(Ht.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}}function Oo(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=Fs(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+=Ie(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(`
|
|
56
57
|
`)+`
|
|
57
|
-
`}
|
|
58
|
-
`),o=a+o}if(/[^ ]/.test(o)){let a=1;const
|
|
58
|
+
`}c(Oo,"stringifyDocument");class Qe{static{c(this,"Document")}constructor(e,t,n){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,se,{value:gn});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 Q({version:o}),this.setSchema(o,n),this.contents=e===void 0?null:this.createNode(e,i,n)}clone(){const e=Object.create(Qe.prototype,{[se]:{value:gn}});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){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=Ps(this);e.anchor=!t||n.has(t)?Ms(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(v=>typeof v=="number"||v instanceof String||v 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:f,sourceObjects:g}=no(this,o||"a"),w={aliasDuplicateObjects:r??!0,keepUndefined:l??!1,onAnchor:d,onTagObj:u,replacer:i,schema:this.schema,sourceObjects:g},h=nt(e,p,w);return a&&q(h)&&(h.flow=!0),f(),h}createPair(e,t,n={}){const i=this.createNode(e,null,n),r=this.createNode(t,null,n);return new Y(i,r)}delete(e){return Ge(this.contents)?this.contents.delete(e):!1}deleteIn(e){return st(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 st(e)?!t&&R(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 st(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){st(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 Q({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 Q({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 Ht(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 Oo(this,e)}}function Ge(s){if(q(s))return!0;throw new Error("Expected a YAML collection as document contents")}c(Ge,"assertCollection");class xn 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 Ae extends xn{static{c(this,"YAMLParseError")}constructor(e,t,n){super("YAMLParseError",e,t,n)}}class ui extends xn{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
|
+
`),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+=`:
|
|
59
60
|
|
|
60
61
|
${o}
|
|
61
62
|
${u}
|
|
62
|
-
`}},"prettifyError");function
|
|
63
|
-
`))return!0;if(
|
|
64
|
-
`+
|
|
65
|
-
`+
|
|
66
|
-
|
|
67
|
-
`+
|
|
68
|
-
`+
|
|
69
|
-
`+
|
|
70
|
-
`.repeat(Math.max(1,o.length-1)):"";let
|
|
71
|
-
`;for(let p
|
|
72
|
-
`):
|
|
73
|
-
`:!
|
|
74
|
-
`&&(
|
|
75
|
-
|
|
76
|
-
`),f
|
|
77
|
-
`,
|
|
78
|
-
`?
|
|
79
|
-
`:
|
|
80
|
-
`:(f
|
|
81
|
-
`+o[
|
|
82
|
-
`&&(
|
|
83
|
-
`);break;default:
|
|
84
|
-
`}const w=
|
|
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="",f="",g=!1,w=!1,h=null,y=null,C=null,v=null,A=null,T=null,N=null;for(const E of s)switch(w&&(E.type!=="space"&&E.type!=="newline"&&E.type!=="comma"&&r(E.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),w=!1),h&&(u&&E.type!=="comment"&&E.type!=="newline"&&r(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),h=null),E.type){case"space":!e&&(t!=="doc-start"||n?.type!=="flow-collection")&&E.source.includes(" ")&&(h=E),p=!0;break;case"comment":{p||r(E,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");const W=E.source.substring(1)||" ";d?d+=f+W:d=W,f="",u=!1;break}case"newline":u?d?d+=E.source:(!T||t!=="seq-item-ind")&&(l=!0):f+=E.source,u=!0,g=!0,(y||C)&&(v=E),p=!0;break;case"anchor":y&&r(E,"MULTIPLE_ANCHORS","A node can have at most one anchor"),E.source.endsWith(":")&&r(E.offset+E.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),y=E,N??(N=E.offset),u=!1,p=!1,w=!0;break;case"tag":{C&&r(E,"MULTIPLE_TAGS","A node can have at most one tag"),C=E,N??(N=E.offset),u=!1,p=!1,w=!0;break}case t:(y||C)&&r(E,"BAD_PROP_ORDER",`Anchors and tags must be after the ${E.source} indicator`),T&&r(E,"UNEXPECTED_TOKEN",`Unexpected ${E.source} in ${e??"collection"}`),T=E,u=t==="seq-item-ind"||t==="explicit-key-ind",p=!1;break;case"comma":if(e){A&&r(E,"UNEXPECTED_TOKEN",`Unexpected , in ${e}`),A=E,u=!1,p=!1;break}default:r(E,"UNEXPECTED_TOKEN",`Unexpected ${E.type} token`),u=!1,p=!1}const O=s[s.length-1],M=O?O.offset+O.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"),h&&(u&&h.indent<=o||n?.type==="block-map"||n?.type==="block-seq")&&r(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:A,found:T,spaceBefore:l,comment:d,hasNewline:g,anchor:y,tag:C,newlineAfterProp:v,end:M,start:N??M}}c(Ve,"resolveProps");function at(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(at(e.key)||at(e.value))return!0}return!1;default:return!0}}c(at,"containsNewline");function Dn(s,e,t){if(e?.type==="flow-collection"){const n=e.end[0];n.indent===s&&(n.source==="]"||n.source==="}")&&at(e)&&t(n,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}c(Dn,"flowIndentCheck");function fi(s,e,t){const{uniqueKeys:n}=s.options;if(n===!1)return!1;const i=typeof n=="function"?n:(r,o)=>r===o||R(r)&&R(o)&&r.value===o.value;return e.some(r=>i(r.key,t))}c(fi,"mapIncludes");const di="All mapping items must start at the same column";function $o({composeNode:s,composeEmptyNode:e},t,n,i,r){const o=r?.nodeClass??ee,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:f,sep:g,value:w}=p,h=Ve(d,{indicator:"explicit-key-ind",next:f??g?.[0],offset:l,onError:i,parentIndent:n.indent,startOnNewline:!0}),y=!h.found;if(y){if(f&&(f.type==="block-seq"?i(l,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in f&&f.indent!==n.indent&&i(l,"BAD_INDENT",di)),!h.anchor&&!h.tag&&!g){u=h.end,h.comment&&(a.comment?a.comment+=`
|
|
65
|
+
`+h.comment:a.comment=h.comment);continue}(h.newlineAfterProp||at(f))&&i(f??d[d.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else h.found?.indent!==n.indent&&i(l,"BAD_INDENT",di);t.atKey=!0;const C=h.end,v=f?s(t,f,h,i):e(t,C,d,null,h,i);t.schema.compat&&Dn(n.indent,f,i),t.atKey=!1,fi(t,a.items,v)&&i(C,"DUPLICATE_KEY","Map keys must be unique");const A=Ve(g??[],{indicator:"map-value-ind",next:w,offset:v.range[2],onError:i,parentIndent:n.indent,startOnNewline:!f||f.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&&h.start<A.found.offset-1024&&i(v.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));const T=w?s(t,w,A,i):e(t,l,g,null,A,i);t.schema.compat&&Dn(n.indent,w,i),l=T.range[2];const N=new Y(v,T);t.options.keepSourceTokens&&(N.srcToken=p),a.items.push(N)}else{y&&i(v.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),A.comment&&(v.comment?v.comment+=`
|
|
66
|
+
`+A.comment:v.comment=A.comment);const T=new Y(v);t.options.keepSourceTokens&&(T.srcToken=p),a.items.push(T)}}return u&&u<l&&i(u,"IMPOSSIBLE","Map comment with trailing content"),a.range=[n.offset,l,u??l],a}c($o,"resolveBlockMap");function Lo({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 f=Ve(p,{indicator:"seq-item-ind",next:d,offset:l,onError:i,parentIndent:n.indent,startOnNewline:!0});if(!f.found)if(f.anchor||f.tag||d)d&&d.type==="block-seq"?i(f.end,"BAD_INDENT","All sequence items must start at the same column"):i(l,"MISSING_CHAR","Sequence item without - indicator");else{u=f.end,f.comment&&(a.comment=f.comment);continue}const g=d?s(t,d,f,i):e(t,f.end,p,null,f,i);t.schema.compat&&Dn(n.indent,d,i),l=g.range[2],a.items.push(g)}return a.range=[n.offset,l,u??l],a}c(Lo,"resolveBlockSeq");function ct(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(ct,"resolveEnd");const Pn="Block collections are not allowed within flow collections",Mn=c(s=>s&&(s.type==="block-map"||s.type==="block-seq"),"isBlock");function xo({composeNode:s,composeEmptyNode:e},t,n,i,r){const o=n.start.source==="{",a=o?"flow map":"flow sequence",l=r?.nodeClass??(o?ee: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:v,key:A,sep:T,value:N}=C,O=Ve(v,{flow:a,indicator:"explicit-key-ind",next:A??T?.[0],offset:d,onError:i,parentIndent:n.indent,startOnNewline:!1});if(!O.found){if(!O.anchor&&!O.tag&&!T&&!N){y===0&&O.comma?i(O.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`):y<n.items.length-1&&i(O.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${a}`),O.comment&&(u.comment?u.comment+=`
|
|
67
|
+
`+O.comment:u.comment=O.comment),d=O.end;continue}!o&&t.options.strict&&at(A)&&i(A,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(y===0)O.comma&&i(O.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`);else if(O.comma||i(O.start,"MISSING_CHAR",`Missing , between ${a} items`),O.comment){let M="";e:for(const E of v)switch(E.type){case"comma":case"space":break;case"comment":M=E.source.substring(1);break e;default:break e}if(M){let E=u.items[u.items.length-1];_(E)&&(E=E.value??E.key),E.comment?E.comment+=`
|
|
68
|
+
`+M:E.comment=M,O.comment=O.comment.substring(M.length+1)}}if(!o&&!T&&!O.found){const M=N?s(t,N,O,i):e(t,O.end,T,null,O,i);u.items.push(M),d=M.range[2],Mn(N)&&i(M.range,"BLOCK_IN_FLOW",Pn)}else{t.atKey=!0;const M=O.end,E=A?s(t,A,O,i):e(t,M,v,null,O,i);Mn(A)&&i(E.range,"BLOCK_IN_FLOW",Pn),t.atKey=!1;const W=Ve(T??[],{flow:a,indicator:"map-value-ind",next:N,offset:E.range[2],onError:i,parentIndent:n.indent,startOnNewline:!1});if(W.found){if(!o&&!O.found&&t.options.strict){if(T)for(const H of T){if(H===W.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}}O.start<W.found.offset-1024&&i(W.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else N&&("source"in N&&N.source&&N.source[0]===":"?i(N,"MISSING_CHAR",`Missing space after : in ${a}`):i(W.start,"MISSING_CHAR",`Missing , or : between ${a} items`));const ge=N?s(t,N,W,i):W.found?e(t,W.end,T,null,W,i):null;ge?Mn(N)&&i(ge.range,"BLOCK_IN_FLOW",Pn):W.comment&&(E.comment?E.comment+=`
|
|
69
|
+
`+W.comment:E.comment=W.comment);const Le=new Y(E,ge);if(t.options.keepSourceTokens&&(Le.srcToken=C),o){const H=u;fi(t,H.items,E)&&i(M,"DUPLICATE_KEY","Map keys must be unique"),H.items.push(Le)}else{const H=new ee(t.schema);H.flow=!0,H.items.push(Le);const es=(ge??E).range;H.range=[E.range[0],es[1],es[2]],u.items.push(H)}d=ge?ge.range[2]:W.end}}const f=o?"}":"]",[g,...w]=n.end;let h=d;if(g&&g.source===f)h=g.offset+g.source.length;else{const y=a[0].toUpperCase()+a.substring(1),C=p?`${y} must end with a ${f}`:`${y} in block collection must be sufficiently indented and end with a ${f}`;i(d,p?"MISSING_CHAR":"BAD_INDENT",C),g&&g.source.length!==1&&w.unshift(g)}if(w.length>0){const y=ct(w,h,t.options.strict,i);y.comment&&(u.comment?u.comment+=`
|
|
70
|
+
`+y.comment:u.comment=y.comment),u.range=[n.offset,h,y.offset]}else u.range=[n.offset,h,h];return u}c(xo,"resolveFlowCollection");function jn(s,e,t,n,i,r){const o=t.type==="block-map"?$o(s,e,t,n,r):t.type==="block-seq"?Lo(s,e,t,n,r):xo(s,e,t,n,r),a=o.constructor;return i==="!"||i===a.tagName?(o.tag=a.tagName,o):(i&&(o.tag=i),o)}c(jn,"resolveCollection");function Do(s,e,t,n,i){const r=n.tag,o=r?e.directives.tagName(r.source,f=>i(r,"TAG_RESOLVE_FAILED",f)):null;if(t.type==="block-seq"){const{anchor:f,newlineAfterProp:g}=n,w=f&&r?f.offset>r.offset?f:r:f??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===ee.tagName&&a==="map"||o===Ce.tagName&&a==="seq")return jn(s,e,t,i,o);let l=e.schema.tags.find(f=>f.tag===o&&f.collection===a);if(!l){const f=e.schema.knownTags[o];if(f&&f.collection===a)e.schema.tags.push(Object.assign({},f,{default:!1})),l=f;else return f?i(r,"BAD_COLLECTION_TYPE",`${f.tag} used for ${a} collection, but expects ${f.collection??"scalar"}`,!0):i(r,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),jn(s,e,t,i,o)}const u=jn(s,e,t,i,o,l),p=l.resolve?.(u,f=>i(r,"TAG_RESOLVE_FAILED",f),e.options)??u,d=J(p)?p:new L(p);return d.range=u.range,d.tag=o,l?.format&&(d.format=l.format),d}c(Do,"composeCollection");function hi(s,e,t){const n=e.offset,i=Po(e,s.options.strict,t);if(!i)return{value:"",type:null,comment:"",range:[n,n,n]};const r=i.mode===">"?L.BLOCK_FOLDED:L.BLOCK_LITERAL,o=e.source?Mo(e.source):[];let a=o.length;for(let h=o.length-1;h>=0;--h){const y=o[h][1];if(y===""||y==="\r")a=h;else break}if(a===0){const h=i.chomp==="+"&&o.length>0?`
|
|
71
|
+
`.repeat(Math.max(1,o.length-1)):"";let y=n+i.length;return e.source&&(y+=e.source.length),{value:h,type:r,comment:i.comment,range:[n,y,y]}}let l=e.indent+i.indent,u=e.offset+i.length,p=0;for(let h=0;h<a;++h){const[y,C]=o[h];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=h,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 h=o.length-1;h>=a;--h)o[h][0].length>l&&(a=h+1);let d="",f="",g=!1;for(let h=0;h<p;++h)d+=o[h][0].slice(l)+`
|
|
72
|
+
`;for(let h=p;h<a;++h){let[y,C]=o[h];u+=y.length+C.length+1;const v=C[C.length-1]==="\r";if(v&&(C=C.slice(0,-1)),C&&y.length<l){const T=`Block scalar lines must not be less indented than their ${i.indent?"explicit indentation indicator":"first line"}`;t(u-C.length-(v?2:1),"BAD_INDENT",T),y=""}r===L.BLOCK_LITERAL?(d+=f+y.slice(l)+C,f=`
|
|
73
|
+
`):y.length>l||C[0]===" "?(f===" "?f=`
|
|
74
|
+
`:!g&&f===`
|
|
75
|
+
`&&(f=`
|
|
76
|
+
|
|
77
|
+
`),d+=f+y.slice(l)+C,f=`
|
|
78
|
+
`,g=!0):C===""?f===`
|
|
79
|
+
`?d+=`
|
|
80
|
+
`:f=`
|
|
81
|
+
`:(d+=f+C,f=" ",g=!1)}switch(i.chomp){case"-":break;case"+":for(let h=a;h<o.length;++h)d+=`
|
|
82
|
+
`+o[h][0].slice(l);d[d.length-1]!==`
|
|
83
|
+
`&&(d+=`
|
|
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(hi,"resolveBlockScalar");function Po({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 f=1;f<i.length;++f){const g=i[f];if(!a&&(g==="-"||g==="+"))a=g;else{const w=Number(g);!o&&w?o=w:l===-1&&(l=s+f)}}l!==-1&&n(l,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${i}`);let u=!1,p="",d=i.length;for(let f=1;f<e.length;++f){const g=e[f];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 h=g.source;h&&typeof h=="string"&&(d+=h.length)}}}return{mode:r,indent:o,chomp:a,comment:p,length:d}}c(Po,"parseBlockScalarHeader");function Mo(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(Mo,"splitLines");function pi(s,e,t){const{offset:n,type:i,source:r,end:o}=s;let a,l;const u=c((f,g,w)=>t(n+f,g,w),"_onError");switch(i){case"scalar":a=L.PLAIN,l=jo(r,u);break;case"single-quoted-scalar":a=L.QUOTE_SINGLE,l=Ro(r,u);break;case"double-quoted-scalar":a=L.QUOTE_DOUBLE,l=Ko(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=ct(o,p,e,t);return{value:l,type:a,comment:d.comment,range:[n,p,d.offset]}}c(pi,"resolveFlowScalar");function jo(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}`),mi(s)}c(jo,"plainValue");function Ro(s,e){return(s[s.length-1]!=="'"||s.length===1)&&e(s.length,"MISSING_CHAR","Missing closing 'quote"),mi(s.slice(1,-1)).replace(/''/g,"'")}c(Ro,"singleQuotedValue");function mi(s){let e,t;try{e=new RegExp(`(.*?)(?<![ ])[ ]*\r?
|
|
85
86
|
`,"sy"),t=new RegExp(`[ ]*(.*?)(?:(?<![ ])[ ]*)?\r?
|
|
86
|
-
`,"sy")}catch{e=/(.*?)[ \t]*\r?\n/sy,t=/[ \t]*(.*?)[ \t]*\r?\n/sy}let
|
|
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===`
|
|
87
88
|
`?i+=r:r=`
|
|
88
|
-
`:(i+=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(mi,"foldLines");function Ko(s,e){let t="";for(let n=1;n<s.length-1;++n){const i=s[n];if(!(i==="\r"&&s[n+1]===`
|
|
89
90
|
`))if(i===`
|
|
90
|
-
`){const{fold:r,offset:o}=
|
|
91
|
-
`)for(r=n
|
|
92
|
-
`)for(r=
|
|
93
|
-
`&&!(o==="\r"&&n
|
|
94
|
-
`)&&(t+=
|
|
95
|
-
`||
|
|
96
|
-
`);)
|
|
91
|
+
`){const{fold:r,offset:o}=_o(s,n);t+=r,n=o}else if(i==="\\"){let r=s[++n];const o=Fo[r];if(o)t+=o;else if(r===`
|
|
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+=Bo(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
|
+
`&&!(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(Ko,"doubleQuotedValue");function _o(s,e){let t="",n=s[e+1];for(;(n===" "||n===" "||n===`
|
|
96
|
+
`||n==="\r")&&!(n==="\r"&&s[e+2]!==`
|
|
97
|
+
`);)n===`
|
|
97
98
|
`&&(t+=`
|
|
98
|
-
`),e+=1,s
|
|
99
|
-
`,r:"\r",t:" ",v:"\v",N:"\x85",_:"\xA0",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function
|
|
99
|
+
`),e+=1,n=s[e+1];return t||(t=" "),{fold:t,offset:e}}c(_o,"foldNewline");const Fo={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 Bo(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(Bo,"parseCharCode");function gi(s,e,t,n){const{value:i,type:r,comment:o,range:a}=e.type==="block-scalar"?hi(s,e,n):pi(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[le]:l?u=Uo(s.schema,i,l,t,n):e.type==="scalar"?u=qo(s,i,e,n):u=s.schema[le];let p;try{const d=u.resolve(i,f=>n(t??e,"TAG_RESOLVE_FAILED",f),s.options);p=R(d)?d:new L(d)}catch(d){const f=d instanceof Error?d.message:String(d);n(t??e,"TAG_RESOLVE_FAILED",f),p=new L(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(gi,"composeScalar");function Uo(s,e,t,n,i){if(t==="!")return s[le];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[le])}c(Uo,"findScalarTagByName");function qo({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[le];if(t.compat){const a=t.compat.find(l=>l.default&&l.test?.test(n))??t[le];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(qo,"findScalarTagByTest");function Jo(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(Jo,"emptyScalarPosition");const Wo={composeNode:yi,composeEmptyNode:Rn};function yi(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=Go(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=gi(s,e,l,n),a&&(u.anchor=a.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":u=Do(Wo,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=Rn(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&&(!R(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(yi,"composeNode");function Rn(s,e,t,n,{spaceBefore:i,comment:r,anchor:o,tag:a,end:l},u){const p={type:"scalar",offset:Jo(e,t,n),indent:-1,source:""},d=gi(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(Rn,"composeEmptyNode");function Go({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=ct(n,o,s.strict,i);return r.range=[e,o,a.offset],a.comment&&(r.comment=a.comment),r}c(Go,"composeAlias");function Vo(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=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?yi(u,i,p,o):Rn(u,p.end,n,null,p,o);const d=l.contents.range[2],f=ct(r,d,!1,o);return f.comment&&(l.comment=f.comment),l.range=[t,d,f.offset],l}c(Vo,"composeDoc");function lt(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(lt,"getErrorPos");function wi(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?`
|
|
100
101
|
|
|
101
102
|
`:`
|
|
102
|
-
`)+(r.substring(1)||" "),t=!0,
|
|
103
|
-
${
|
|
104
|
-
${a}`:
|
|
105
|
-
${o}`:
|
|
106
|
-
${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.push(new Ae(
|
|
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(wi,"parsePrelude");class Kn{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=lt(t);r?this.warnings.push(new ui(o,n,i)):this.errors.push(new Ae(o,n,i))},this.directives=new Q({version:e.version||"1.2"}),this.options=e}decorate(e,t){const{comment:n,afterEmptyLine:i}=wi(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];_(o)&&(o=o.key);const a=o.commentBefore;o.commentBefore=a?`${n}
|
|
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:wi(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=lt(e);r[0]+=t,this.onError(r,"BAD_DIRECTIVE",n,i)}),this.prelude.push(e.source),this.atDirectives=!0;break;case"document":{const t=Vo(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 Ae(lt(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 Ae(lt(e),"UNEXPECTED_TOKEN",n));break}this.doc.directives.docEnd=!0;const t=ct(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 Ae(lt(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 Ho(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 Ae([a,a+1],r,o)},"_onError");switch(s.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return pi(s,e,n);case"block-scalar":return hi({options:{strict:e}},s,n)}}return null}c(Ho,"resolveAsScalar");function Yo(s,e){const{implicitKey:t=!1,indent:n,inFlow:i=!1,offset:r=-1,type:o="PLAIN"}=e,a=rt({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:`
|
|
107
108
|
`}];switch(a[0]){case"|":case">":{const u=a.indexOf(`
|
|
108
|
-
`),
|
|
109
|
-
`,
|
|
110
|
-
`}),{type:"block-scalar",offset:r,indent:
|
|
111
|
-
`),
|
|
112
|
-
`;if(
|
|
113
|
-
`});for(const
|
|
114
|
-
`};delete
|
|
109
|
+
`),p=a.substring(0,u),d=a.substring(u+1)+`
|
|
110
|
+
`,f=[{type:"block-scalar-header",offset:r,indent:n,source:p}];return bi(f,l)||f.push({type:"newline",offset:-1,indent:n,source:`
|
|
111
|
+
`}),{type:"block-scalar",offset:r,indent:n,props:f,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(Yo,"createScalarToken");function zo(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=rt({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">":Qo(s,l);break;case'"':_n(s,l,"double-quoted-scalar");break;case"'":_n(s,l,"single-quoted-scalar");break;default:_n(s,l,"scalar")}}c(zo,"setScalarValue");function Qo(s,e){const t=e.indexOf(`
|
|
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}];bi(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(Qo,"setBlockScalarValue");function bi(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(bi,"addEndtoBlockProps");function _n(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(_n,"setFlowScalarValue");const Xo=c(s=>"type"in s?_t(s):Ft(s),"stringify$1");function _t(s){switch(s.type){case"block-scalar":{let e="";for(const t of s.props)e+=_t(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(_t,"stringifyToken");function Ft({start:s,key:e,sep:t,value:n}){let i="";for(const r of s)i+=r.source;if(e&&(i+=_t(e)),t)for(const r of t)i+=r.source;return n&&(i+=_t(n)),i}c(Ft,"stringifyItem");const Fn=Symbol("break visit"),Zo=Symbol("skip children"),Si=Symbol("remove item");function Oe(s,e){"type"in s&&s.type==="document"&&(s={start:s.start,value:s.value}),Ci(Object.freeze([]),s,e)}c(Oe,"visit"),Oe.BREAK=Fn,Oe.SKIP=Zo,Oe.REMOVE=Si,Oe.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},Oe.parentCollection=(s,e)=>{const t=Oe.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 Ci(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=Ci(Object.freeze(s.concat([[i,o]])),r.items[o],t);if(typeof a=="number")o=a-1;else{if(a===Fn)return Fn;a===Si&&(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(Ci,"_visit");const Bt="\uFEFF",Ut="",qt="",ut="",ea=c(s=>!!s&&"items"in s,"isCollection"),ta=c(s=>!!s&&(s.type==="scalar"||s.type==="single-quoted-scalar"||s.type==="double-quoted-scalar"||s.type==="block-scalar"),"isScalar");function na(s){switch(s){case Bt:return"<BOM>";case Ut:return"<DOC>";case qt:return"<FLOW_END>";case ut:return"<SCALAR>";default:return JSON.stringify(s)}}c(na,"prettyToken");function ki(s){switch(s){case Bt:return"byte-order-mark";case Ut:return"doc-mode";case qt:return"flow-error-end";case ut:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case`
|
|
115
116
|
`:case`\r
|
|
116
|
-
`: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(
|
|
117
|
-
`:case"\r":case" ":return!0;default:return!1}}
|
|
118
|
-
\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(ki,"tokenType");var sa=Object.freeze({__proto__:null,BOM:Bt,DOCUMENT:Ut,FLOW_END:qt,SCALAR:ut,createScalarToken:Yo,isCollection:ea,isScalar:ta,prettyToken:na,resolveAsScalar:Ho,setScalarValue:zo,stringify:Xo,tokenType:ki,visit:Oe});function ae(s){switch(s){case void 0:case" ":case`
|
|
118
|
+
`:case"\r":case" ":return!0;default:return!1}}c(ae,"isEmpty");const vi=new Set("0123456789ABCDEFabcdef"),ia=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),Jt=new Set(",[]{}"),ra=new Set(` ,[]{}
|
|
119
|
+
\r `),Bn=c(s=>!s||ra.has(s),"isNotAnchorChar");class Ei{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===`
|
|
119
120
|
`?!0:t==="\r"?this.buffer[e+1]===`
|
|
120
|
-
`:!1}charAt(e){return this.buffer[this.pos+e]}continueScalar(e){let t=this.buffer[e];if(this.indentNext>0){let
|
|
121
|
-
`||!i&&!this.atEnd)return e+
|
|
122
|
-
`||
|
|
123
|
-
`,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]===
|
|
124
|
-
`,this.pos);if(i!==-1){for(;i!==-1;){const r=this.continueScalar(i+1);if(r===-1)break;i=
|
|
125
|
-
`,r)}i!==-1&&(t=i-(
|
|
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
|
+
`||!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]===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 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(Bn),"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 qt,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(Bn),"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(`
|
|
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
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===`
|
|
127
|
-
`)break}default:break e}if(!
|
|
128
|
-
`,r)}while(e!==-1);if(e===-1){if(!this.atEnd)return this.setNext("block-scalar");e=this.buffer.length}}let i=e+1;for(
|
|
129
|
-
`;)
|
|
130
|
-
`&&r>=this.pos&&r+1+t>a)e=r;else break}while(!0);return yield
|
|
131
|
-
`?(
|
|
132
|
-
`,r=this.buffer[
|
|
133
|
-
`){const o=this.continueScalar(
|
|
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
|
+
`,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
|
+
`;)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 ut,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&&Jt.has(r))break;t=n}else if(ae(i)){let r=this.buffer[n+1];if(i==="\r"&&(r===`
|
|
132
|
+
`?(n+=1,i=`
|
|
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 ut,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(Bn))+(yield*this.pushSpaces(!0))+(yield*this.pushIndicators());case"-":case"?":case":":{const e=this.flowLevel>0,t=this.charAt(1);if(ae(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(;!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(ia.has(t))t=this.buffer[++e];else if(t==="%"&&vi.has(this.buffer[e+1])&&vi.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===`
|
|
134
135
|
`?yield*this.pushCount(1):e==="\r"&&this.charAt(1)===`
|
|
135
|
-
`?yield*this.pushCount(2):0}*pushSpaces(e){let t=this.pos-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 Ti{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 Ii(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(Ii,"findNonEmptyIndex");function Ni(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(Ni,"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 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 Ai(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,Ni(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(Ai,"fixFlowSeqItems");class Un{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 Ei,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=ki(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"&&Ai(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&&Ii(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":{Ii(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=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
137
|
`)+1;for(;t!==0;)this.onNewLine(this.offset+t),t=this.source.indexOf(`
|
|
137
|
-
`,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
|
|
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(Ni(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=Wt(n),r=He(i);Ai(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
139
|
`)+1;for(;t!==0;)this.onNewLine(this.offset+t),t=this.source.indexOf(`
|
|
139
|
-
`,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=Qt(e),s=He(t);return s.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:s,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;const t=Qt(e),s=He(t);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:s,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,t){return this.type!=="comment"||this.indent<=t?!1:e.every(s=>s.type==="newline"||s.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 Xi(n){const e=n.prettyErrors!==!1;return{lineCounter:n.lineCounter||e&&new Gi||null,prettyErrors:e}}l(Xi,"parseOptions");function Ba(n,e={}){const{lineCounter:t,prettyErrors:s}=Xi(e),i=new Zn(t?.addNewLine),r=new zn(e),o=Array.from(r.compose(i.parse(n)));if(s&&t)for(const a of o)a.errors.forEach(Vt(n,t)),a.warnings.forEach(Vt(n,t));return o.length>0?o:Object.assign([],{empty:!0},r.streamInfo())}l(Ba,"parseAllDocuments");function er(n,e={}){const{lineCounter:t,prettyErrors:s}=Xi(e),i=new Zn(t?.addNewLine),r=new zn(e);let o=null;for(const a of r.compose(i.parse(n),!0,n.length))if(!o)o=a;else if(o.options.logLevel!=="silent"){o.errors.push(new Ae(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return s&&t&&(o.errors.forEach(Vt(n,t)),o.warnings.forEach(Vt(n,t))),o}l(er,"parseDocument");function Fa(n,e,t){let s;typeof e=="function"?s=e:t===void 0&&e&&typeof e=="object"&&(t=e);const i=er(n,t);if(!i)return null;if(i.warnings.forEach(r=>fi(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:s},t))}l(Fa,"parse");function qa(n,e,t){let s=null;if(typeof e=="function"||Array.isArray(e)?s=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(n===void 0){const{keepUndefined:i}=t??e??{};if(!i)return}return Se(n)&&!s?n.toString(t):new Ze(n,s,t).toString(t)}l(qa,"stringify");var Ua=Object.freeze({__proto__:null,Alias:$t,CST:Da,Composer:zn,Document:Ze,Lexer:Hi,LineCounter:Gi,Pair:Y,Parser:Zn,Scalar:_,Schema:nn,YAMLError:Fn,YAMLMap:te,YAMLParseError:Ae,YAMLSeq:ge,YAMLWarning:Pi,isAlias:me,isCollection:q,isDocument:Se,isMap:De,isNode:U,isPair:B,isScalar:R,isSeq:Me,parse:Fa,parseAllDocuments:Ba,parseDocument:er,stringify:qa,visit:ke,visitAsync:Tt});const Ja={ignored:uo,persistent:!0,ignoreInitial:!0,followSymlinks:!1,depth:10,awaitWriteFinish:{stabilityThreshold:500,pollInterval:100},ignorePermissionErrors:!0,atomic:!0,usePolling:!1,alwaysStat:!1,interval:1e3,binaryInterval:300};class Va extends on{static{l(this,"FileWatcher")}constructor(e){super(),this.options=e,this.membraneDir=Es(this.options.cwd)}isWatching=!1;watcher;membraneDir;contentCache={};async start(){this.isWatching||(j.existsSync(this.membraneDir)||j.mkdirSync(this.membraneDir,{recursive:!0}),this.watcher=Kr.watch(this.membraneDir,Ja),this.watcher.on("add",e=>this.handleFileSystemEvent("added",e)).on("change",e=>this.handleFileSystemEvent("changed",e)).on("unlink",e=>this.handleFileSystemEvent("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("stopped"))}getCwd(){return this.options.cwd}handleFileSystemEvent(e,t){const s=J.relative(this.membraneDir,t);if(e==="deleted"){this.removeFromCache(s);const a={filePath:t,relativePath:s,data:void 0};this.emit(e,a);return}const i=this.readFileContent(t);if(!this.hasContentChanged(s,i,e))return;const o=this.processFileEvent(t,i);this.updateCache(s,i),this.emit(e,o)}readFileContent(e){return j.readFileSync(e,"utf8")}processFileEvent(e,t){const s=J.relative(this.membraneDir,e);let i;try{i=t?Ua.parse(t):void 0}catch{i=void 0}return{filePath:e,relativePath:s,data:i}}hasContentChanged(e,t,s){if(s==="added")return!0;if(!t)return this.contentCache[e]!==void 0;const i=this.getContentHash(t);return this.contentCache[e]!==i}getContentHash(e){return $r.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]})}}const Wa={info:"\u{1F4DD}",success:"\u2728",warning:"\u26A0\uFE0F",error:"\u274C",debug:"\u{1F50D}"},za={info:v.blue,success:v.green,warning:v.yellow,error:v.red,debug:v.gray};class N{static{l(this,"Logger")}static formatMessage(e,t,s={}){const i=s.timestamp?`${v.gray(new Date().toISOString())} `:"",r=s.prefix?`${v.gray(s.prefix)} `:"",o=s.suffix?` ${v.gray(s.suffix)}`:"",a=Wa[t],c=za[t];return`${i}${a} ${r}${c(e)}${o}`}static info(e,t){let s=v.blue;if(t?.color&&(s=v[t.color.toLowerCase()]||v.blue),t?.timestamp){const i=new Date().toLocaleTimeString();console.debug(`${v.gray(`[${i}]`)} ${s(e)}`)}else console.debug(s(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(v.gray(`[${t.prefix}] ${e}`),t.error?`
|
|
140
|
-
${
|
|
141
|
-
${v.red(t.error)}`:"")}static step(e,t){}static header(e){console.debug(),console.debug(v.bold.cyan(`\u25B6 ${e}`)),console.debug()}static table(e,t){if(e.length===0)return;const s=t||Object.keys(e[0]),i=e.map(r=>{const o={};return s.forEach(a=>{o[a]=r[a]}),o});console.table(i,s)}static divider(){}}async function Ha(n,e="full"){const t={};N.info("Getting remote workspace data");const s=await n.integrations.findAll();t.integration=s.map(i=>Qn("integration",i));for(const i of Object.keys(H)){const r=H[i];if(r.exportable===!1)continue;const o=[];N.info(`Reading ${r.elements} from remote workspace`);const a=await n[r.elements].findAll();if(o.push(...a.map(c=>Qn(i,c))),r.integrationSpecific)for(const c of s){const u=await n[r.elements].findAll({integrationId:c.id});o.push(...u.map(d=>(d.integrationKey=c.key,Qn(i,d))))}o.length>0&&e=="full"&&(console.table(o.map(c=>({key:c.key,integrationKey:c.integrationKey,universal:!c.integrationKey})).reduce((c,u)=>(c||(c={}),c[u.key]||(c[u.key]={}),u.universal&&(c[u.key].universal=!0),u.integrationKey&&(c[u.key].integration?c[u.key].integration+=` ${u.integrationKey}`:c[u.key].integration=u.integrationKey),c),{})),console.groupEnd()),t[i]=o}return N.success("Remote workspace data retrieved successfully"),t}l(Ha,"getWorkspaceData");function Ga(n){const e={},t={};for(const s of Object.keys(n))if(e[s]=[],t[s]=[],H[s]?.integrationSpecific)for(const r of n[s])r.integrationKey||r.integration||r.integrationId?t[s].push(r):e[s].push(r);else e[s].push(...n[s]);return{universalElements:e,integrationSpecificElements:t}}l(Ga,"splitWorkspaceData");function Qn(n,e){return e=Lo(e),H[n].exportCleanup?H[n].exportCleanup(e):e}l(Qn,"cleanUpForExport");function dt(n){return Object.keys(n).some(e=>/universal.*Id/g.test(e)||/parentId/g.test(e))}l(dt,"hasParent");function Z(n,e){console.debug("\x1B[0m",`\x1B[${{Reset:"\x1B[0m",Bright:"\x1B[1m",Dim:"\x1B[2m",Underscore:"\x1B[4m",Blink:"\x1B[5m",Reverse:"\x1B[7m",Hidden:"\x1B[8m",Black:"\x1B[30m",Red:"\x1B[31m",Green:"\x1B[32m",Yellow:"\x1B[33m",Blue:"\x1B[34m",Magenta:"\x1B[35m",Cyan:"\x1B[36m",White:"\x1B[37m",Gray:"\x1B[90m",BgBlack:"\x1B[40m",BgRed:"\x1B[41m",BgGreen:"\x1B[42m",BgYellow:"\x1B[43m",BgBlue:"\x1B[44m",BgMagenta:"\x1B[45m",BgCyan:"\x1B[46m",BgWhite:"\x1B[47m",BgGray:"\x1B[100m"}[e]}`,n,"\x1B[0m")}l(Z,"coloredLog");const tr="connectors",nr="development",Xn={};async function Ya({integrations:n,allConnectors:e=!1}){const t=Hr(),s=await vn.getClient(process.cwd()),i=new Set,r={};for(const o of n){const a=o.connectorId,c=o.connectorVersion;if(!r[a]?.has(o.connectorVersion)){const u=await nc({client:s,connectorId:a});(!!u.workspaceId||e)&&(i.has(a)||(await sc({basePath:t,connector:u}),i.add(a)),r[a]||(r[a]=new Set),r[a].has(c)||(await ic({client:s,connector:u,connectorVersion:c,basePath:t}),r[a].add(c)))}}}l(Ya,"pullConnectors");async function Za({client:n,workspaceData:e,pushContext:t,workspaceId:s}){const i={};console.debug("[Push] Loading custom connectors");const r=n,o=await r.get(`/connectors?workspaceId=${s}`);console.debug("[Push] Loading public connectors"),e.connector=o;const a=es(),c=P.existsSync(a)?P.readdirSync(a):[];for(const u of c){console.debug(`[Push] Loading connector from: ${u}`);const d=P.readdirSync(K.join(a,u)),f=await Qa(u);if(delete f.baseUri,f.uuid&&e.connector?.find(m=>m.uuid==f.uuid))i[f.id]=e.connector.find(m=>m.uuid==f.uuid).id,Z(`Matched ${f.name} uuid: ${f.uuid}`,"Blue");else if(!i[f.id]){console.debug(`Creating connector ${f.name} (${f.key})`);const m=await r.post("connectors",{...f,workspaceId:s});i[f.id]=m.id}const h=d.filter(m=>P.statSync(K.join(a,u,m)).isDirectory());for(const m of h)await tc({client:n,connector:f,version:m,connectorId:i[f.id]})}t.connectorsMapping=i}l(Za,"pushConnectors");function es(){const n=et();return K.join(n.membraneDirPath,tr)}l(es,"getConnectorsPath");async function Qa(n){return oe.load(P.readFileSync(K.join(es(),n,`${n}.yml`),"utf8"))}l(Qa,"readConnector");async function Xa(n,e){return console.debug(`Zipping ${n} into ${e}`),new Promise((t,s)=>{const i=P.createWriteStream(e),r=Dr("zip",{zlib:{level:9}});i.on("close",()=>{Z(`Successfully created ${e}`,"Green"),t()}),i.on("end",()=>{console.debug("Data has been drained")}),r.on("warning",a=>{a.code==="ENOENT"?console.warn(a):s(a)}),r.on("error",a=>{s(a)}),r.pipe(i);const o=P.readdirSync(n);for(const a of o){const c=K.join(n,a),u=P.statSync(c);u.isFile()?r.file(c,{name:a}):u.isDirectory()&&r.directory(c,a)}r.finalize()})}l(Xa,"createZipArchive");async function ec(n,e){return console.debug(`Unzipping into ${e}`),new Promise((t,s)=>{const i=Rr.Parse();i.on("entry",r=>{const o=r.path;if(r.type==="Directory"){const c=K.join(e,o);P.mkdirSync(c,{recursive:!0}),r.autodrain()}else{const c=K.join(e,o),u=K.dirname(c);P.mkdirSync(u,{recursive:!0});const d=P.createWriteStream(c);r.pipe(d),d.on("finish",()=>{console.debug(`Extracted: ${o}`)})}}),i.on("end",()=>{Z(`Successfully extracted to ${e}`,"Green"),t()}),i.on("error",r=>{s(r)}),i.write(n),i.end()})}l(ec,"extractZipArchive");async function tc({client:n,connector:e,version:t,connectorId:s}){const i=K.join(es(),Xt(e),sr(t)),r=K.join(i,"src"),o=K.join(i,"src.zip");if(P.existsSync(r)&&(console.debug(`Archiving source code for ${e.name} version ${t}`),await Xa(r,o)),!P.existsSync(o)){N.warning(`No source code found for ${e.name} version ${t}`);return}try{const a=new Mr;if(a.append("file",P.createReadStream(o),"file.zip"),console.debug(`Pushing connector version ${t} for ${e.name}`),t==nr)console.debug(`Uploading connector ${s}`),await n.post(`connectors/${s}/upload`,a,{headers:{...a.getHeaders()}});else{if(a.append("version",t),a.append("changelog","Imported Version"),(await n.get(`/connectors/${s}/versions`)).find(u=>u.version==t)){Z(`Version ${t} already published`,"Blue");return}console.debug(`Publishing version ${t} of connector ${s}`),await n.post(`connectors/${s}/publish-version`,a,{headers:{...a.getHeaders()}})}N.success(`Successfully pushed connector version ${t} for ${e.name}`)}catch(a){N.error(`Error pushing connector version ${t} for ${e.name}`,a)}finally{P.existsSync(o)&&P.unlinkSync(o)}}l(tc,"pushConnectorVersion");async function nc({client:n,connectorId:e}){if(Xn[e])return Xn[e];const t=await n.get(`connectors/${e}`);return Xn[e]=t,t}l(nc,"getConnector");async function sc({basePath:n,connector:e}){const t=Xt(e),s=K.join(n,tr,t);P.mkdirSync(s,{recursive:!0});const i=K.join(s,`${Xt(e)}.yml`);P.writeFileSync(i,oe.dump(e)),N.info(`Pulled connector ${e.name}`)}l(sc,"pullConnector");async function ic({client:n,connector:e,connectorVersion:t,basePath:s}){const i=Xt(e),r=sr(t),o=K.join(s,"connectors",i,r),a=await n.get(`connectors/${e.id}/download`,{version:t},{responseType:"arraybuffer",headers:{Accept:"application/zip"},timeout:1e6});P.mkdirSync(o,{recursive:!0});const c=K.join(o,"src.zip");P.writeFileSync(c,a);const u=K.join(o,"src");P.existsSync(u)&&await ec(a,u),N.info(`[Pull] Connector Version: ${e.name} (${r})`)}l(ic,"pullConnectorVersion");function Xt(n){return n.key}l(Xt,"getConnectorDirName");function sr(n){return n??nr}l(sr,"getConnectorVersionDirName");class rc extends on{static{l(this,"WorkspaceService")}localManager;remoteManager;_status="idle";_elementCounts={};constructor(){super(),this.remoteManager=new Po,this.localManager=new ho,V.on("logAdded",()=>this.emit("logAdded"))}get status(){return this._status}get elementCounts(){return{...this._elementCounts}}get logs(){return V.logs}get latestLogs(){return V.latestLogs}setStatus(e){this._status!==e&&(this._status=e,this.emit("statusChanged"))}incrementCounter(e,t){this._elementCounts[e]=(this._elementCounts[e]||0)+t,this.emit("counterChanged")}resetPullState(){this._status="idle",this._elementCounts={},V.clear(),this.emit("statusChanged"),this.emit("counterChanged")}async start({cwd:e}){await this.pullWorkspace();const t=new Va({cwd:e});t.on("added",s=>this.processElementChange(s,"added")),t.on("changed",s=>this.processElementChange(s,"changed")),t.on("deleted",s=>this.processElementChange(s,"deleted"))}async pullWorkspace({allConnectors:e=!1}={}){this.resetPullState(),this.setStatus("pulling"),V.info("Starting pull..."),V.info("Pulling remote elements...");try{const t=await this.remoteManager.pull();V.info("Pulling connectors..."),await Ya({integrations:t[M.Integration],allConnectors:e});for(const s of Object.keys(t)){const i=t[s];this.incrementCounter(s,i.length);for(const r of i)await this.localManager.writeElement(s,r)}this.setStatus("finished"),V.success("Finished pulling workspace.")}catch(t){throw this.setStatus("error"),V.error(`Error: ${t.message||t}`),t}}async processElementChange(e,t){try{const s=po(e.relativePath);if(!s||!s.key||!s.type){console.debug(`Skipping file change - could not extract element reference from: ${e.relativePath}`);return}switch(console.debug(`Processing ${t} element: ${s.key} of type ${s.type}`),t){case"added":case"changed":await this.remoteManager.pushElement(s.type,{...e.data,key:s.key});break;case"deleted":break}}catch(s){console.error(`Failed to process event ${t} for element ${e.relativePath}:`,s)}}}const W=new rc,ir=l(n=>{switch(n){case"error":return"red";case"success":return"green";case"warning":return"yellow";default:return}},"getLogColor");function oc(n,e=30){return n.length<=e?n:n.slice(0,e-3)+"..."}l(oc,"truncateWorkspaceName");const ac=l(n=>{switch(n){case"pulling":return y(k,{color:"yellow",children:"pulling remote workspace"});case"finished":return y(k,{color:"green",children:"in sync"});case"error":return y(k,{color:"red",children:"error"});default:return y(k,{color:"green",children:"in sync"})}},"getStatusText"),cc=l((n,e)=>{const t=e-6;return n.length<=t?n:n.slice(0,t-3)+"..."},"truncateLogMessage"),lc=l(()=>{const{workspaceKey:n,cwd:e}=Os(),t=Math.min(100,process.stdout.columns||100),[s,i]=D({}),[r,o]=D([]),[a,c]=D(0),[,u]=D({}),d=5,{data:f}=us("/account"),w=f?.workspaces?.find(O=>O.key===n)?.name,p=w?oc(w):n;pt(()=>{const O=l(()=>{u({})},"handleStatusChanged"),$=l(()=>{i(W.elementCounts)},"handleCounterChanged"),x=l(()=>{const E=W.logs,z=a===0;o(E),z&&c(0)},"handleLogAdded");return i(W.elementCounts),o(W.logs),W.on("statusChanged",O),W.on("counterChanged",$),W.on("logAdded",x),()=>{W.off("statusChanged",O),W.off("counterChanged",$),W.off("logAdded",x)}},[a]),Qe((O,$)=>{if(r.length!==0)if($.upArrow){const x=Math.max(0,r.length-d);c(E=>Math.min(x,E+1))}else $.downArrow?c(x=>Math.max(0,x-1)):(O==="G"||O==="g")&&c(0)});const g=Math.max(0,r.length-d-a),S=r.length-a,b=r.slice(g,S),C=a<r.length-d,T=a>0;return I(A,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:t,children:[y(A,{marginTop:-1,marginBottom:1,children:I(k,{bold:!0,children:["\u{1F504} Workspaces \u2014 ",ac(W.status)]})}),I(A,{children:[y(A,{width:12,children:y(k,{color:"grey",children:"Local:"})}),y(k,{color:"grey",children:e})]}),I(A,{children:[y(A,{width:12,children:y(k,{color:"grey",children:"Remote:"})}),n?I(k,{color:"grey",children:[p," [o: open in console] [w: change]"]}):I(k,{children:[y(k,{color:"yellow",children:"not selected"})," [w: select]"]})]}),Object.keys(s).length>0&&I(A,{flexDirection:"column",paddingTop:1,children:[y(A,{children:y(A,{width:12,children:y(k,{color:"grey",children:"Elements:"})})}),y(A,{flexDirection:"column",marginLeft:1,children:Object.entries(s).filter(([O,$])=>$>0).map(([O,$])=>I(A,{children:[y(A,{width:20,children:I(k,{children:[O,":"]})}),y(k,{color:"green",children:$})]},O))})]}),r.length>0&&I(A,{flexDirection:"column",paddingTop:1,children:[I(k,{color:"grey",children:["Recent Activity (",g+1,"-",S," of ",r.length,"):",r.length>5&&y(k,{color:"grey",children:" [arrows: scroll] [g: end]"})]}),b.map((O,$)=>{const x=cc(O.message,t);return y(A,{marginLeft:1,children:y(k,{color:ir(O.type),children:x})},O.timestamp+$)}),r.length>5&&I(A,{marginLeft:1,flexDirection:"row",children:[C&&y(k,{color:"grey",children:"\u2191 "}),T&&y(k,{color:"grey",children:"\u2193 "})]})]})]})},"WorkspaceSync"),uc=l(()=>{const{isSetupComplete:n,workspaceKey:e,config:t}=Os(),[s,i]=D(!1),[r,o]=D(!1),[a,c]=D(!1),u=ws();return Qe(d=>{!s&&!r&&!a&&(d==="w"&&i(!0),d==="a"&&c(!0),d==="o"&&e&&t?.workspaceSecret&&(async()=>{try{const h=`https://console.integration.app/w/${await Ys(u)}`,m=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";Tr(`${m} "${h}"`)}catch(f){console.error("Failed to open workspace:",f)}})(),d==="s"&&o(!0))}),s?y(Cs,{onExit:l(()=>i(!1),"onExit")}):a?y(no,{onExit:l(()=>c(!1),"onExit"),onComplete:l(()=>c(!1),"onComplete")}):r||!n?y(As,{onComplete:l(()=>o(!1),"onComplete")},Date.now()):I(A,{flexDirection:"column",children:[y(A,{flexGrow:1,children:y(ro,{})}),y(lc,{}),y(A,{paddingLeft:2,children:y(k,{color:"grey",children:"[s: (re-)setup]"})})]})},"Main"),rr=Cr(process.argv.slice(2)),or=rr.cwd?wr(rr.cwd):process.cwd();async function fc(){try{await W.start({cwd:or})}catch(n){N.error(n.toString()),process.exit(1)}}l(fc,"startBackgroundServices");const dc=l(()=>y(mn,{cwd:or,children:y(uc,{})}),"App");function hc(){fc(),sn(y(dc,{}))}l(hc,"runAgent");function pc(n){n.command("init").description("Run interactive setup for Membrane project").addHelpText("after",["","Examples:"," membrane init # Run interactive setup",""].join(`
|
|
142
|
-
`)).action(()=>{sn(ht.createElement(mn,null,ht.createElement(As,{onComplete:l(()=>process.exit(0),"onComplete")})))})}l(pc,"setupInitCommand");async function mc(n,e){const t={iss:n,exp:Math.floor(Date.now()/1e3)+3600,isAdmin:!0};return gt.sign(t,e)}l(mc,"generateAdminAccessToken");async function gc(n,e){return(await fn.get(`${n}/docs-json`,{headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}})).data}l(gc,"fetchOpenApiSchema");function ar(n,e=!0){if(!n)return e?F.string():F.string().optional();let t;switch(n.type){case"integer":t=F.coerce.number().int();break;case"number":t=F.coerce.number();break;case"boolean":t=F.coerce.boolean();break;case"string":default:t=F.string();break}return n.format==="uuid"?t=F.string().uuid():n.format==="email"?t=F.string().email():n.format==="date"?t=F.string().regex(/^\d{4}-\d{2}-\d{2}$/):n.format==="date-time"&&(t=F.string().datetime()),n.enum&&(t=F.enum(n.enum)),(n.type==="integer"||n.type==="number")&&(n.minimum!==void 0&&(t=t.min(n.minimum)),n.maximum!==void 0&&(t=t.max(n.maximum))),n.type==="string"&&(n.minLength!==void 0&&(t=t.min(n.minLength)),n.maxLength!==void 0&&(t=t.max(n.maxLength))),e?t:t.optional()}l(ar,"convertOpenApiSchemaToZod");function cr(n){const e=n.match(/\{([^}]+)\}/g);return e?e.map(t=>t.slice(1,-1)):[]}l(cr,"extractPathParameters");function yc(n,e,t,s,i){const r=n.operationId||`${t}_${e.replace(/[^a-zA-Z0-9]/g,"_")}`,o=n.description||n.summary||`${t.toUpperCase()} ${e}`,a={},c={},u={};if(n.parameters){for(const f of n.parameters)if(f.in==="path")c[f.name]=ar(f.schema,!0).describe(f.description||`Path parameter: ${f.name}`);else if(f.in==="query"){const h=f.required===!0;u[f.name]=ar(f.schema,h).describe(f.description||`Query parameter: ${f.name}`)}}Object.keys(c).length>0&&(a.params=F.object(c).describe("Path parameters")),Object.keys(u).length>0&&(a.query=F.object(u).describe("Query parameters")),n.requestBody&&n.requestBody.content&&n.requestBody.content["application/json"]&&(a.body=F.any().describe("Request body"));const d=Object.keys(a).length>0?F.object(a):F.object({});return{name:r,description:o,parameters:d,async execute(f){try{const h=cr(e);if(h.length>0){if(!f.params)throw new Error(`Missing required path parameters: ${h.join(", ")}`);const b=h.filter(C=>!(C in f.params));if(b.length>0)throw new Error(`Missing required path parameters: ${b.join(", ")}`)}let m=`${s}${e}`;if(f.params)for(const[b,C]of Object.entries(f.params)){const T=`{${b}}`;m.includes(T)&&(m=m.replace(T,String(C)))}const w=cr(m);if(w.length>0)throw new Error(`Unresolved path parameters: ${w.join(", ")}`);const p=new URLSearchParams;if(f.query)for(const[b,C]of Object.entries(f.query))C!=null&&p.append(b,String(C));p.toString()&&(m+=`?${p.toString()}`);const g={method:t.toUpperCase(),headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json"}};f.body&&t.toLowerCase()!=="get"&&(g.data=f.body);const S=await fn.request({url:m,...g});return{content:[{type:"text",text:JSON.stringify(S.data,null,2)}]}}catch(h){return fn.isAxiosError(h)?{content:[{type:"text",text:`Error: ${h.response?.data?`HTTP ${h.response.status}: ${h.response.statusText} - ${JSON.stringify(h.response.data)}`:`HTTP ${h.response?.status||"unknown"}: ${h.message}`}`}],isError:!0}:h instanceof Error?{content:[{type:"text",text:`Error: API call failed: ${h.message}`}],isError:!0}:{content:[{type:"text",text:"Error: API call failed with unknown error"}],isError:!0}}}}}l(yc,"createApiTool");function wc(n,e,t){const s=[];if(!n.paths)return s;for(const[i,r]of Object.entries(n.paths))if(typeof r=="object"&&r!==null){for(const[o,a]of Object.entries(r))if(["get","post","put","delete","patch"].includes(o)&&a&&typeof a=="object"){const c=yc(a,i,o,e,t);s.push(c)}}return s}l(wc,"convertOpenApiToTools");function bc(n){n.command("mcp").description("Launch MCP server with OpenAPI endpoints as tools (API URI is read from membrane.config.yml)").addHelpText("after",["","Examples:"," membrane mcp # Launch MCP server using API URI from membrane.config.yml",""].join(`
|
|
143
|
-
`)).action(async()=>{try{process.env.FASTMCP_SUPPRESS_WARNINGS="true";const e=be();e||(console.error("No membrane.config.yml found. Please run `membrane init` first."),process.exit(1)),(!e.workspaceKey||!e.workspaceSecret)&&(console.error("Missing workspace credentials"),process.exit(1));const t=e.apiUri||hn,s=await mc(e.workspaceKey,e.workspaceSecret),i=await gc(t,s),r=wc(i,t,s),o=new qr({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=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=Wt(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 Oi(s){const e=s.prettyErrors!==!1;return{lineCounter:s.lineCounter||e&&new Ti||null,prettyErrors:e}}c(Oi,"parseOptions");function oa(s,e={}){const{lineCounter:t,prettyErrors:n}=Oi(e),i=new Un(t?.addNewLine),r=new Kn(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(oa,"parseAllDocuments");function $i(s,e={}){const{lineCounter:t,prettyErrors:n}=Oi(e),i=new Un(t?.addNewLine),r=new Kn(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 Ae(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($i,"parseDocument");function aa(s,e,t){let n;typeof e=="function"?n=e:t===void 0&&e&&typeof e=="object"&&(t=e);const i=$i(s,t);if(!i)return null;if(i.warnings.forEach(r=>Bs(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(aa,"parse");function ca(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 Ee(s)&&!n?s.toString(t):new Qe(s,n,t).toString(t)}c(ca,"stringify");var la=Object.freeze({__proto__:null,Alias:Ct,CST:sa,Composer:Kn,Document:Qe,Lexer:Ei,LineCounter:Ti,Pair:Y,Parser:Un,Scalar:L,Schema:Ht,YAMLError:xn,YAMLMap:ee,YAMLParseError:Ae,YAMLSeq:Ce,YAMLWarning:ui,isAlias:Se,isCollection:q,isDocument:Ee,isMap:Re,isNode:J,isPair:_,isScalar:R,isSeq:Ke,parse:aa,parseAllDocuments:oa,parseDocument:$i,stringify:ca,visit:Te,visitAsync:St});const Z={Added:"added",Changed:"changed",Deleted:"deleted",Stopped:"stopped"},ua={ignored:zr,persistent:!0,ignoreInitial:!0,followSymlinks:!1,depth:10,awaitWriteFinish:{stabilityThreshold:500,pollInterval:100},ignorePermissionErrors:!0,atomic:!0,usePolling:!1,alwaysStat:!1,interval:1e3,binaryInterval:300};class fa extends ws{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=dr.watch(this.membraneDir,ua),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=D.relative(this.membraneDir,t);if(e===Z.Deleted){this.removeFromCache(n);const a={filePath:t,relativePath:n,data:void 0};$.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&&($.info(`[local] ${e}: ${o.relativePath}`),this.emit(e,o))}readFileContent(e){return x.readFileSync(e,"utf8")}processFileEvent(e,t){const n=D.relative(this.membraneDir,e);let i;try{i=t?la.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 Zi.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=D.join(e,n.name);if(n.isDirectory())this.scanDirectoryForCache(i);else if(n.isFile())try{const r=x.readFileSync(i,"utf8"),o=D.relative(this.membraneDir,i);this.updateCache(o,r)}catch{}}}}const z={UPDATE:"update",DELETE:"delete",CREATE:"create"},fe={INCOMING:"incoming",OUTGOING:"outgoing"};class ft{static{c(this,"ElementSyncService")}constructor(e,t){this.localManager=e,this.remoteManager=t,this.notifier=re}fileWatcher=void 0;notifier;changes=[];hasConflicts(){return this.changes.some(e=>e.isConflict)}hasChanges(){return this.changes.length>0}async startWatching(){this.fileWatcher=new fa({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(),$.success("[local] Tracking changes..")}async stopWatching(){await this.fileWatcher?.stop(),this.fileWatcher=void 0}async handleLocalEvent(e,t){let n=V.fromPathAndData(e.filePath,e.data);if(!n){const r=V.idFromPath(e.filePath);if(!r||(n=this.remoteManager.cache.get(r),!n))return}const i=this.getManager(fe.OUTGOING);switch($.info(`[resolver][${this.getDirectionLabel(fe.OUTGOING)}] ${t}: ${n.id}`),t){case Z.Added:case Z.Changed:await i.putElement(n);break;case Z.Deleted:await i.deleteElement(n);break}}detectIncomingChanges(){this.clearChanges();const e=ft.getChanges(fe.INCOMING,this.remoteManager.cache,this.localManager.cache);return this.updateChanges(e),e}detectOutgoingChanges(){this.clearChanges();const e=ft.getChanges(fe.OUTGOING,this.localManager.cache,this.remoteManager.cache);return this.updateChanges(e),e}getChange(e){const t=this.localManager.cache.get(e.id),n=this.remoteManager.cache.get(e.id);return!t&&n?{type:z.CREATE,element:n,direction:fe.INCOMING,isConflict:!1}:t&&!n?{type:z.DELETE,element:t,direction:fe.OUTGOING,isConflict:!0}:t&&n&&!t.isEqual(n)?{type:z.UPDATE,element:t,direction:fe.OUTGOING,isConflict:!0}:null}async resolveChanges(){this.hasChanges()&&($.info("[resolver] Resolving changes.."),await Promise.all(this.changes.map(e=>this.resolveChange(e))),$.success(`[resolver] Resolved ${this.changes.length} changes`))}async resolveChange(e){const t=this.getManager(e.direction);switch(e.type){case z.DELETE:return $.info(`[resolver][${this.getDirectionLabel(e.direction)}] Deleting ${e.element.id}`),t.deleteElement(e.element);case z.CREATE:return $.info(`[resolver][${this.getDirectionLabel(e.direction)}] Creating ${e.element.id}`),t.putElement(e.element);case z.UPDATE:return $.info(`[resolver][${this.getDirectionLabel(e.direction)}] Updating ${e.element.id}`),t.putElement(e.element)}}getManager(e){return e===fe.INCOMING?this.localManager:this.remoteManager}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=ft.detectChangeForElement(u,p,e);d&&a.push(d)}return a}updateChanges(e){this.changes=e;for(const t of e)$.info(`[resolver][${this.getDirectionLabel(t.direction)}] ${this.getTypeLabel(t.type)} ${t.element.id}`);if(this.hasConflicts()){const t=e.filter(n=>n.isConflict);$.warning("[resolver] Conflicts detected"),this.notifier.setConflicts(t)}}clearChanges(){this.changes=[]}getDirectionLabel(e){switch(e){case fe.INCOMING:return"local\u2190remote";case fe.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}}class da{static{c(this,"WorkspaceService")}notifier;local;remote;syncService;constructor(){this.notifier=re,this.local=new Ss(new Xr),this.remote=new Ss(new Zr),this.syncService=new ft(this.local,this.remote)}async push(e={}){if(this.notifier.setState(P.PUSHING),await this.refreshElements(),this.syncService.detectOutgoingChanges(),this.syncService.hasConflicts()&&!e.force)return this.notifier.setState(P.CONFLICTS);await Ur(),await this.resolveChanges({watch:e.watch})}async pull(e={}){if(this.notifier.setState(P.PULLING),await this.refreshElements(),this.syncService.detectIncomingChanges(),this.syncService.hasConflicts()&&!e.force)return this.notifier.setState(P.CONFLICTS);await Br({integrations:this.remote.cache.getElementsByType(U.Integration).map(t=>t.data),allConnectors:e.allConnectors}),await this.resolveChanges({watch:e.watch})}async resolveChanges(e={}){this.notifier.setState(P.RESOLVING),this.syncService.hasChanges()&&await this.syncService.resolveChanges(),this.updateStats(),this.notifier.setState(P.SYNCED),e.watch&&(this.notifier.setState(P.WATCHING),await this.syncService.startWatching()),e.onComplete?.()}async refreshElements(){return Promise.all([this.remote.refresh(),this.local.refresh()])}updateStats(){const e={};for(const t of this.local.cache.getAll())e[t.type]=(e[t.type]||0)+1;this.notifier.setStats(e)}}const qn=new da,Li=zt(null);function Jn({children:s,onExit:e}){const{config:t,isLoading:n}=Ze(),{data:i}=ns("/account"),[r,o]=K(P.NOT_SYNCED),[a,l]=K([]),[u,p]=K({}),[d,f]=K([]),w=i?.workspaces?.find(T=>T.key===t?.workspaceKey)||null,h=t?.workspaceKey&&t?.workspaceSecret;function y(T){if(h)try{qn.resolveChanges(T||{})}catch(N){console.error("Failed to resolve conflicts:",N),A()}}c(y,"resolveConflicts");function C(T){if(h)try{qn.pull(T||{})}catch(N){console.error("Failed to pull:",N),A()}}c(C,"pull");function v(T){if(h)try{qn.push(T||{})}catch(N){console.error("Failed to push:",N),A()}}c(v,"push");function A(){h&&e()}return c(A,"exit"),ye(()=>{const T=c(({state:E})=>o(E),"handleStateChanged"),N=c(({stats:E})=>p(E),"handleStatsChanged"),O=c(({log:E})=>f(W=>[...W,E]),"handleLogAdded"),M=c(({conflicts:E})=>l(E),"handleConflictsUpdated");return re.on(te.StateChanged,T),re.on(te.StatsChanged,N),re.on(te.LogAdded,O),re.on(te.ConflictsChanged,M),()=>{re.off(te.StateChanged,T),re.off(te.StatsChanged,N),re.off(te.LogAdded,O),re.off(te.ConflictsChanged,M)}},[]),n?null:h?m(Li.Provider,{value:{state:r,stats:u,logs:d,currentWorkspace:w,conflicts:a,resolveConflicts:y,pull:C,push:v,exit:A},children:s}):m(b,{children:m(S,{children:"No workspace selected. Please run `membrane init` to select a workspace."})})}c(Jn,"WorkspaceServiceProvider");function $e(){const s=Qt(Li);if(!s)throw new Error("useWorkspaceService must be used within WorkspaceServiceProvider");return s}c($e,"useWorkspaceService");function Wn(){const{stats:s}=$e(),e=Object.entries(s).filter(([t,n])=>n>0);return e.length===0?null:I(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])=>I(b,{children:[m(b,{width:20,children:I(S,{children:[t,":"]})}),m(S,{color:"green",children:n})]},t))})]})}c(Wn,"ElementStats");const Gn=c(s=>{switch(s){case"error":return"red";case"success":return"green";case"warning":return"yellow";default:return}},"getLogColor");function xi(s,e){return e<3?s.slice(0,Math.max(0,e)):s.length<=e?s:`${s.slice(0,e-3)}...`}c(xi,"truncateText");const Vn=5,ha=6;function pa(){const{logs:s}=$e(),[e,t]=K(0),n=Math.min(100,process.stdout.columns||100),i=Vn,r=Math.max(0,s.length-i-e),o=s.length-e,a=s.slice(r,o),l=n-ha,u=e<s.length-i,p=e>0;return xe((d,f)=>{if(s.length!==0)if(f.upArrow){const g=Math.max(0,s.length-i);t(w=>Math.min(g,w+1))}else f.downArrow?t(g=>Math.max(0,g-1)):(d==="G"||d==="g")&&t(0)}),I(b,{flexDirection:"column",paddingTop:1,children:[I(S,{color:"grey",children:["Recent Activity (",r+1,"-",o," of ",s.length,"):",s.length>Vn&&m(S,{color:"grey",children:" [arrows: scroll] [g: end]"})]}),a.map((d,f)=>m(b,{marginLeft:1,children:m(S,{color:Gn(d.type),children:xi(d.message,l)})},d.timestamp+f)),s.length>Vn&&I(b,{marginLeft:1,flexDirection:"row",children:[u&&m(S,{color:"grey",children:"\u2191 "}),p&&m(S,{color:"grey",children:"\u2193 "})]})]})}c(pa,"Logs");const Gt=[{value:"sync",label:"Continue (overwrite/delete)",key:""},{value:"exit",label:"Cancel",key:""}];function ma(){const{state:s,resolveConflicts:e,exit:t}=$e(),[n,i]=K(0),[r,o]=K(!1);return xe((a,l)=>{r||(l.upArrow?i(u=>u>0?u-1:Gt.length-1):l.downArrow?i(u=>u<Gt.length-1?u+1:0):a.toLowerCase()==="y"?i(0):a.toLowerCase()==="n"?i(1):(l.return||a===" ")&&(o(!0),Gt[n].value==="sync"?e({watch:!0}):t()))}),ye(()=>{s!==P.CONFLICTS&&r&&o(!1)},[s,r]),I(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(Hn,{})}),I(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?I(b,{flexDirection:"row",gap:1,children:[m(ht,{type:"dots"}),m(S,{color:"blue",bold:!0,children:"Syncing with remote..."})]}):m(b,{flexDirection:"column",children:Gt.map((a,l)=>m(b,{flexDirection:"column",children:I(b,{flexDirection:"row",gap:1,children:[m(S,{color:n===l?"cyan":"grey",children:n===l?"\u25B6":" "}),m(S,{color:n===l?"cyan":"grey",bold:n===l,children:a.label})]})},a.value))})})]})}c(ma,"ResolveChangesUI");const ga={[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 Hn(){const{conflicts:s}=$e(),e=Yi(()=>{const t={};return s.forEach(n=>{const i=`${n.type}-${n.direction}`;t[i]||(t[i]=[]),t[i].push(n)}),t},[s]);return m(b,{flexDirection:"column",children:Object.entries(e).map(([t,n])=>{if(n.length===0)return null;const[i,r]=t.split("-"),o=ga[i][r];return I(b,{flexDirection:"column",children:[I(b,{flexDirection:"row",gap:1,children:[I(S,{color:"yellow",children:[o.label," (",n.length,")"]}),m(S,{color:"white",children:o.description})]}),n.map(a=>m(b,{marginLeft:2,children:I(S,{color:"grey",children:["\u2022 ",a.element.id," (",a.element.relativePath,")"]})},a.element.id))]},t)})})}c(Hn,"Conflicts");function ya(){const{config:s}=Ze(),{state:e,logs:t,currentWorkspace:n,pull:i}=$e(),r=n?.name,o=r?xi(r,30):s?.workspaceKey,a=Math.min(100,process.stdout.columns||100);return ye(()=>{i({allConnectors:!1,force:!1,watch:!0})},[]),I(b,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:a,children:[m(b,{marginTop:-1,marginBottom:1,children:I(b,{flexDirection:"row",gap:1,children:[m(S,{bold:!0,children:"\u{1F504} Workspace"}),I(S,{color:ba(e),children:[" [",wa(e),"] "]})]})}),I(b,{children:[m(b,{width:12,children:m(S,{color:"grey",children:"Local:"})}),m(S,{color:"grey",children:process.cwd()})]}),I(b,{children:[m(b,{width:12,children:m(S,{color:"grey",children:"Remote:"})}),s?.workspaceKey?I(S,{color:"grey",children:[o," [o: open in console] [w: change]"]}):I(S,{children:[m(S,{color:"yellow",children:"not selected"})," [w: select]"]})]}),e===P.CONFLICTS?m(ma,{}):I(Yt,{children:[m(b,{paddingTop:1,children:m(Wn,{})}),t.length>0&&m(pa,{})]})]})}c(ya,"Workspace");function wa(s){switch(s){case P.PULLING:return"pulling";case P.PUSHING:return"pushing";case P.CONFLICTS:return"conflicts";case P.SYNCED:return"synced";case P.ERROR:return"error";case P.WATCHING:return"tracking changes";case P.RESOLVING:return"resolving";case P.NOT_SYNCED:return"not synced"}}c(wa,"getStatusDisplay");function ba(s){switch(s){case P.PULLING:return"yellow";case P.PUSHING:return"yellow";case P.CONFLICTS:return"red";case P.SYNCED:return"green";case P.ERROR:return"red";case P.WATCHING:return"green";case P.RESOLVING:return"yellow";case P.NOT_SYNCED:return"grey"}}c(ba,"getStatusColor");const Sa=c(()=>{const{isSetupComplete:s}=gs(),{config:e}=Ze();return{isSetupComplete:s,workspaceKey:e?.workspaceKey,config:e}},"useStatus");function Ca({onExit:s}){const e=fs(),{isSetupComplete:t,workspaceKey:n,config:i}=Sa(),[r,o]=K(!1),[a,l]=K(!1),[u,p]=K(!1),d=zi(!0);return xe(f=>{r||a||u||(f==="w"&&o(!0),f==="a"&&p(!0),f==="o"&&n&&i?.workspaceSecret&&(async()=>{try{const w=`https://console.integration.app/w/${await Cs(e)}`,h=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";Xi(`${h} "${w}"`)}catch(g){console.error("Failed to open workspace:",g),s()}})(),f==="s"&&l(!0))}),ye(()=>(d.current=!0,()=>{d.current=!1}),[]),r?m(ms,{onExit:c(()=>o(!1),"onExit")}):u?m(Or,{onExit:c(()=>p(!1),"onExit"),onComplete:c(()=>p(!1),"onComplete")}):a||!t?m(ys,{onComplete:c(()=>l(!1),"onComplete")},Date.now()):I(b,{flexDirection:"column",children:[m(b,{flexGrow:1,children:m(xr,{})}),m(Jn,{onExit:s,children:m(ya,{})}),m(b,{paddingLeft:2,children:m(S,{color:"grey",children:"[s: (re-)setup]"})})]})}c(Ca,"Main");const Di=Wi(process.argv.slice(2)),ka=Di.cwd?Bi(Di.cwd):process.cwd(),va=c(()=>process.exit(0),"onExit"),Ea=c(()=>m(mt,{cwd:ka,children:m(Ca,{onExit:va})}),"App");function Ta(){dt(m(Ea,{}))}c(Ta,"runAgent");function Ia(s){s.command("init").description("Run interactive setup for Membrane project").addHelpText("after",["","Examples:"," membrane init # Run interactive setup",""].join(`
|
|
141
|
+
`)).action(()=>{dt(De.createElement(mt,null,De.createElement(ys,{onComplete:c(()=>process.exit(0),"onComplete")})))})}c(Ia,"setupInitCommand");async function Pi(s,e){const t={iss:s,exp:Math.floor(Date.now()/1e3)+600,isAdmin:!0};return tn.sign(t,e)}c(Pi,"generateAdminAccessToken");async function Na(s,e){return(await nn.get(`${s}/docs-json`,{headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}})).data}c(Na,"fetchOpenApiSchema");function Mi(s,e=!0){if(!s)return e?B.string():B.string().optional();let t;switch(s.type){case"integer":t=B.coerce.number().int();break;case"number":t=B.coerce.number();break;case"boolean":t=B.coerce.boolean();break;case"string":default:t=B.string();break}return s.format==="uuid"?t=B.string().uuid():s.format==="email"?t=B.string().email():s.format==="date"?t=B.string().regex(/^\d{4}-\d{2}-\d{2}$/):s.format==="date-time"&&(t=B.string().datetime()),s.enum&&(t=B.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 ji(s){const e=s.match(/\{([^}]+)\}/g);return e?e.map(t=>t.slice(1,-1)):[]}c(ji,"extractPathParameters");function Aa(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 f of s.parameters)if(f.in==="path")u[f.name]=Mi(f.schema,!0).describe(f.description||`Path parameter: ${f.name}`);else if(f.in==="query"){const g=f.required===!0;p[f.name]=Mi(f.schema,g).describe(f.description||`Query parameter: ${f.name}`)}}Object.keys(u).length>0&&(l.params=B.object(u).describe("Path parameters")),Object.keys(p).length>0&&(l.query=B.object(p).describe("Query parameters")),s.requestBody&&s.requestBody.content&&s.requestBody.content["application/json"]&&(l.body=B.any().describe("Request body"));const d=Object.keys(l).length>0?B.object(l):B.object({});return{name:o,description:a,parameters:d,async execute(f){try{const g=ji(e);if(g.length>0){if(!f.params)throw new Error(`Missing required path parameters: ${g.join(", ")}`);const T=g.filter(N=>!(N in f.params));if(T.length>0)throw new Error(`Missing required path parameters: ${T.join(", ")}`)}let w=`${n}${e}`;if(f.params)for(const[T,N]of Object.entries(f.params)){const O=`{${T}}`;w.includes(O)&&(w=w.replace(O,String(N)))}const h=ji(w);if(h.length>0)throw new Error(`Unresolved path parameters: ${h.join(", ")}`);const y=new URLSearchParams;if(f.query)for(const[T,N]of Object.entries(f.query))N!=null&&y.append(T,String(N));y.toString()&&(w+=`?${y.toString()}`);const C=await Pi(i,r),v={method:t.toUpperCase(),headers:{Authorization:`Bearer ${C}`,"Content-Type":"application/json"}};f.body&&t.toLowerCase()!=="get"&&(v.data=f.body);const A=await nn.request({url:w,...v});return{content:[{type:"text",text:JSON.stringify(A.data,null,2)}]}}catch(g){return nn.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(Aa,"createApiTool");function Oa(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=Aa(l,r,a,e,t,n);i.push(u)}}return i}c(Oa,"convertOpenApiToTools");function $a(s){s.command("mcp").description("Launch MCP server with OpenAPI endpoints as tools (API URI is read from membrane.config.yml)").addHelpText("after",["","Examples:"," membrane mcp # Launch MCP server using API URI from membrane.config.yml",""].join(`
|
|
142
|
+
`)).action(async()=>{try{process.env.FASTMCP_SUPPRESS_WARNINGS="true";const e=Pe();e||(console.error("No membrane.config.yml found. Please run `membrane init` first."),process.exit(1)),(!e.workspaceKey||!e.workspaceSecret)&&(console.error("Missing workspace credentials"),process.exit(1));const t=e.apiUri||rn,n=await Pi(e.workspaceKey,e.workspaceSecret),i=await Na(t,n),r=Oa(i,t,e.workspaceKey,e.workspaceSecret),o=new mr({name:"Membrane API",instructions:`This MCP server lets you interact with Membrane to configure, run, and troubleshoot integrations.
|
|
144
143
|
Use it for anything related to Membrane or integrations.
|
|
145
|
-
`,version:"1.0.0"});for(const u of r){const
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
`)).action(async()=>{try{
|
|
144
|
+
`,version:"1.0.0"});for(const u of r){const p=u.execute;u.execute=async d=>($r(process.pid,process.cwd()),p(d)),o.addTool(u)}un({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(()=>{un({processId:process.pid,cwd:process.cwd(),lastActivity:new Date().toISOString()})},5e3),l=c(async()=>{clearInterval(a),et(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",()=>{et(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($a,"setupMcpCommand");const La={info:"\u{1F4DD}",success:"\u2728",warning:"\u26A0\uFE0F",error:"\u274C",debug:"\u{1F50D}"},xa={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=La[t],l=xa[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
|
+
${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 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=Pe();if(!e)throw new Error("No membrane.config.yml found. Please 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 Cs(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 Pa(s){return m(Jn,{onExit:s.onExit,children:m(Ma,{...s})})}c(Pa,"PullWrapper");function Ma(s){const{logs:e,state:t,conflicts:n,pull:i}=$e();ye(()=>{i(s)},[]);const r=t===P.CONFLICTS;return I(b,{flexDirection:"column",children:[e.slice().map((o,a)=>m(S,{color:Gn(o.type),children:o.message},o.timestamp+a)),r&&I(Yt,{children:[I(S,{color:"yellow",bold:!0,children:["Found ",n.length," conflicts with remote:"]}),m(Hn,{}),m(S,{color:"red",children:"Out of sync with remote, use --force to overwrite conflict changes"})]}),t===P.SYNCED&&m(Wn,{})]})}c(Ma,"Pull");function Ri(){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(Ri,"getWatchModeCallback");function ja(s){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(e=>{const t=c(()=>process.exit(0),"onExit"),n=e.watch?Ri():t;dt(De.createElement(mt,null,De.createElement(Pa,{force:e.force,watch:e.watch,allConnectors:e.allConnectors,onComplete:n,onExit:t})))})}c(ja,"setupPullCommand");function Ra(s){return m(Jn,{onExit:s.onExit,children:m(Ka,{...s})})}c(Ra,"PushWrapper");function Ka(s){const{logs:e,state:t,conflicts:n,push:i}=$e();ye(()=>{i(s)},[]);const r=t===P.CONFLICTS;return I(b,{flexDirection:"column",children:[e.slice().map((o,a)=>m(S,{color:Gn(o.type),children:o.message},o.timestamp+a)),r&&I(Yt,{children:[I(S,{color:"yellow",bold:!0,children:["Found ",n.length," conflicts with remote:"]}),m(Hn,{}),m(S,{color:"red",children:"Out of sync with remote, use --force to overwrite conflict changes"})]}),t===P.SYNCED&&m(Wn,{})]})}c(Ka,"Push");function _a(s){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(e=>{const t=c(()=>process.exit(0),"onExit"),n=e.watch?Ri():t;dt(De.createElement(mt,null,De.createElement(Ra,{force:e.force,watch:e.watch,onComplete:n,onExit:t})))})}c(_a,"setupPushCommand");class Fa{static{c(this,"BaseRunner")}constructor(e){if(this.options=e,this.fsPaths=on(),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 Ba="claude-sonnet-4-20250514";class Zn{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=Pe();if(!i)throw new Error("No membrane.config.yml found. Please 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 ss({token:await this.createMembraneToken(i),apiUri:i.apiUri}),o=new gr({apiKey:i.anthropicApiKey}),a={complete:c(async({prompt:l,maxTokens:u})=>{const p=await o.messages.create({model:Ba,max_tokens:u,messages:[{role:"user",content:l}]});return p.content[0].type==="text"?p.content[0].text:""},"complete")};return new Zn({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(),sn(t,n.getResult());this.writeResults(t)}async readYaml(e){const t=F.join(this.testsDir,this.testBasePath,this.connectionId,e);if(j.existsSync(t))return de.load(j.readFileSync(t,"utf8"))}async writeYaml(e,t){const n=F.join(this.testsDir,this.testBasePath,this.connectionId,e);j.mkdirSync(F.dirname(n),{recursive:!0}),j.writeFileSync(n,de.dump(t,{noRefs:!0}))}writeResults(e){const t=F.join(this.testsDir,this.testBasePath,this.connectionId);j.mkdirSync(t,{recursive:!0});const n=F.join(t,"test-results.yaml");j.writeFileSync(n,de.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 tn.sign(n,e.workspaceSecret,i)}}wr.interpolate=/{{([\s\S]+?)}}/g;function Yn(s,e){if(typeof s=="string"){const t=yr(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=>Yn(t,e)):typeof s=="object"&&s!==null?Object.fromEntries(Object.entries(s).map(([t,n])=>[t,Yn(n,e)])):s}c(Yn,"processNode");function Ua(s,e){return Yn(s,e)}c(Ua,"handleTemplate");class qa{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(),Xt(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}`)}}Xt(this.result,e.path,{error:ce(l)}),t=!0,i={error:ce(l)}}const a={...o,result:i};await this.environment.writeYaml(e.getTestCasePath(),a)}async runTestSuite(e){await e.run(),sn(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:ce(i)}),this.logMsg(`\u274C ${t}: ${i.message}`)}}logMsg(e){console.debug(`${" ".repeat(this.level*2)}${e}`)}getTestCasePath(){return`${this.path}.test.yml`}}function zn(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)||!Qn(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=zn(i,r);o!==null&&(t[n]=o)}else t[n]=r;continue}Qn(i,r)||(t[n]=r)}return Object.keys(t).length===0?null:t}c(zn,"getNotMatchingSubFields");function Qn(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(Qn,"softCompare");class Ja 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=Zt(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=is(n),a=pt(e.input.fields,o,{skipUnknownFields:!0}),l=pt(r.record.fields,o),u=zn(l,a);await this.assert(()=>!u,"Returned fields match created fields",{difference:u,sentFields:a,receivedFields:l})}const i=or(n);if(i.length>0){const r={};i.forEach(a=>{const l=ar(e.input.fields,a);typeof l<"u"&&Xt(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=Zt(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=ce(t),i=Zt(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:
|
|
149
150
|
|
|
150
151
|
${JSON.stringify(i,null,2)}
|
|
151
152
|
|
|
@@ -155,7 +156,7 @@ ${JSON.stringify(e.input?.fields,null,2)}
|
|
|
155
156
|
|
|
156
157
|
But got this error:
|
|
157
158
|
|
|
158
|
-
${JSON.stringify(
|
|
159
|
+
${JSON.stringify(n)}
|
|
159
160
|
|
|
160
161
|
${this.getExampleRecordsPrompt(r)}
|
|
161
162
|
|
|
@@ -169,7 +170,7 @@ Format your response as a JSON object with two fields:
|
|
|
169
170
|
"fields": { ... fixed fields ... }
|
|
170
171
|
}.
|
|
171
172
|
|
|
172
|
-
Only return the JSON object, no other text or wrapping (like \`\`\`json or \`\`\`).`,a=await this.environment.llm.complete({prompt:o,maxTokens:1e4}),
|
|
173
|
+
Only return the JSON object, no other text or wrapping (like \`\`\`json or \`\`\`).`,a=await this.environment.llm.complete({prompt:o,maxTokens:1e4}),l=JSON.parse(a.trim());return console.warn(k.bold.yellow("[auto-fix]"),`${this.path}:`,l.explanation),{input:{fields:l.fields}}}async generateFieldsWithLLM(e){const t=await this.getExampleRecordsForSchema(e),n=`Generate a valid JSON object that matches this JSONSchema. Return only the JSON object, no other text.
|
|
173
174
|
|
|
174
175
|
${this.getExampleRecordsPrompt(t)}
|
|
175
176
|
|
|
@@ -178,14 +179,14 @@ ${JSON.stringify(e,null,2)}.
|
|
|
178
179
|
|
|
179
180
|
Do not populate fields with null or empty strings, unless the schema explicitly requires it.
|
|
180
181
|
|
|
181
|
-
Only return the JSON object, no other text or wrapping (like \`\`\`json or \`\`\`).`,i=await this.environment.llm.complete({prompt:
|
|
182
|
+
Only return the JSON object, no other text or wrapping (like \`\`\`json or \`\`\`).`,i=await this.environment.llm.complete({prompt:n,maxTokens:1e4});return JSON.parse(i.trim())}getExampleRecordsPrompt(e){return`When a field has a "referenceCollection" property, its value should be an ID of a record from that collection. Here are some example records you can use as references:
|
|
182
183
|
|
|
183
|
-
${Object.entries(e).map(([
|
|
184
|
+
${Object.entries(e).map(([n,i])=>`Example records from collection "${n}":
|
|
184
185
|
${JSON.stringify(i,null,2)}`).join(`
|
|
185
186
|
|
|
186
187
|
`)}.
|
|
187
188
|
|
|
188
|
-
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,
|
|
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 rs(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=os(i);n[r]=await this.fetchExampleRecords(i)}return n}}class Wa 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=ce(t),i=`I'm trying to delete a record from a data collection.
|
|
189
190
|
|
|
190
191
|
I tried to delete a record with this ID:
|
|
191
192
|
|
|
@@ -193,7 +194,7 @@ ${JSON.stringify(e.input?.id,null,2)}
|
|
|
193
194
|
|
|
194
195
|
But got this error:
|
|
195
196
|
|
|
196
|
-
${JSON.stringify(
|
|
197
|
+
${JSON.stringify(n)}
|
|
197
198
|
|
|
198
199
|
Please analyze the error and provide:
|
|
199
200
|
1. A fixed ID that would work (as a string)
|
|
@@ -205,7 +206,7 @@ Format your response as a JSON object with two fields:
|
|
|
205
206
|
"id": "fixed id"
|
|
206
207
|
}.
|
|
207
208
|
|
|
208
|
-
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(
|
|
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 Ga 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=ce(t),i=`I'm trying to find a record by ID in a data collection.
|
|
209
210
|
|
|
210
211
|
I tried to find a record with this ID:
|
|
211
212
|
|
|
@@ -213,7 +214,7 @@ ${JSON.stringify(e.input?.id,null,2)}
|
|
|
213
214
|
|
|
214
215
|
But got this error:
|
|
215
216
|
|
|
216
|
-
${JSON.stringify(
|
|
217
|
+
${JSON.stringify(n)}
|
|
217
218
|
|
|
218
219
|
Please analyze the error and provide:
|
|
219
220
|
1. A fixed ID that would work (as a string)
|
|
@@ -225,7 +226,7 @@ Format your response as a JSON object with two fields:
|
|
|
225
226
|
"id": "fixed id"
|
|
226
227
|
}.
|
|
227
228
|
|
|
228
|
-
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(
|
|
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 Va 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=ce(t),i=`I'm trying to list records from a data collection.
|
|
229
230
|
|
|
230
231
|
I tried to list records with these parameters:
|
|
231
232
|
|
|
@@ -233,7 +234,7 @@ ${JSON.stringify(e.input,null,2)}
|
|
|
233
234
|
|
|
234
235
|
But got this error:
|
|
235
236
|
|
|
236
|
-
${JSON.stringify(
|
|
237
|
+
${JSON.stringify(n)}
|
|
237
238
|
|
|
238
239
|
Please analyze the error and provide:
|
|
239
240
|
1. Fixed parameters that would work (as a JSON object)
|
|
@@ -245,7 +246,7 @@ Format your response as a JSON object with two fields:
|
|
|
245
246
|
"input": { ... fixed parameters ... }
|
|
246
247
|
}.
|
|
247
248
|
|
|
248
|
-
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(
|
|
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 Ha 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(()=>Qn(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=ce(t),i=`I'm trying to match a record in a data collection.
|
|
249
250
|
|
|
250
251
|
I tried to match a record with this query:
|
|
251
252
|
|
|
@@ -253,7 +254,7 @@ ${JSON.stringify(e.input?.query,null,2)}
|
|
|
253
254
|
|
|
254
255
|
But got this error:
|
|
255
256
|
|
|
256
|
-
${JSON.stringify(
|
|
257
|
+
${JSON.stringify(n)}
|
|
257
258
|
|
|
258
259
|
Please analyze the error and provide:
|
|
259
260
|
1. Fixed query that would work (as a JSON object)
|
|
@@ -265,12 +266,12 @@ Format your response as a JSON object with two fields:
|
|
|
265
266
|
"query": { ... fixed query ... }
|
|
266
267
|
}.
|
|
267
268
|
|
|
268
|
-
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(
|
|
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 Ya 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
270
|
|
|
270
271
|
Record fields:
|
|
271
272
|
${JSON.stringify(e,null,2)}
|
|
272
273
|
|
|
273
|
-
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
|
|
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=ce(t),i=`I'm trying to search records in a data collection.
|
|
274
275
|
|
|
275
276
|
I tried to search records with these parameters:
|
|
276
277
|
|
|
@@ -278,7 +279,7 @@ ${JSON.stringify(e.input,null,2)}
|
|
|
278
279
|
|
|
279
280
|
But got this error:
|
|
280
281
|
|
|
281
|
-
${JSON.stringify(
|
|
282
|
+
${JSON.stringify(n)}
|
|
282
283
|
|
|
283
284
|
Please analyze the error and provide:
|
|
284
285
|
1. Fixed parameters that would work (as a JSON object)
|
|
@@ -290,7 +291,7 @@ Format your response as a JSON object with two fields:
|
|
|
290
291
|
"input": { ... fixed parameters ... }
|
|
291
292
|
}.
|
|
292
293
|
|
|
293
|
-
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(
|
|
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 Qa 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=en(this.dataCollection),o=is(r),a=pt(e.input.fields,o,{skipUnknownFields:!0}),l=pt(i.record.fields,o),u=zn(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=en(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=ce(t),i=en(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
295
|
|
|
295
296
|
${JSON.stringify(i,null,2)}
|
|
296
297
|
|
|
@@ -300,7 +301,7 @@ ${JSON.stringify(e.input?.fields,null,2)}
|
|
|
300
301
|
|
|
301
302
|
But got this error:
|
|
302
303
|
|
|
303
|
-
${JSON.stringify(
|
|
304
|
+
${JSON.stringify(n)}
|
|
304
305
|
|
|
305
306
|
${this.getExampleRecordsPrompt(r)}
|
|
306
307
|
|
|
@@ -314,7 +315,7 @@ Format your response as a JSON object with two fields:
|
|
|
314
315
|
"fields": { ... fixed fields ... }
|
|
315
316
|
}.
|
|
316
317
|
|
|
317
|
-
Only return the JSON object, no other text or wrapping (like \`\`\`json or \`\`\`).`,a=await this.environment.llm.complete({prompt:o,maxTokens:1e4}),
|
|
318
|
+
Only return the JSON object, no other text or wrapping (like \`\`\`json or \`\`\`).`,a=await this.environment.llm.complete({prompt:o,maxTokens:1e4}),l=JSON.parse(a.trim());return console.warn(k.bold.yellow("[auto-fix]"),`${this.path}:`,l.explanation),{input:{id:e.input.id,fields:l.fields}}}async generateFieldsWithLLM(e){const t=await this.getExampleRecordsForSchema(e),n=`Generate a valid JSON object that matches this JSONSchema. Return only the JSON object, no other text.
|
|
318
319
|
|
|
319
320
|
${this.getExampleRecordsPrompt(t)}
|
|
320
321
|
|
|
@@ -323,16 +324,16 @@ ${JSON.stringify(e,null,2)}.
|
|
|
323
324
|
|
|
324
325
|
Do not populate fields with null or empty strings, unless the schema explicitly requires it.
|
|
325
326
|
|
|
326
|
-
Only return the JSON object, no other text or wrapping (like \`\`\`json or \`\`\`).`,i=await this.environment.llm.complete({prompt:
|
|
327
|
+
Only return the JSON object, no other text or wrapping (like \`\`\`json or \`\`\`).`,i=await this.environment.llm.complete({prompt:n,maxTokens:1e4});return JSON.parse(i.trim())}getExampleRecordsPrompt(e){return`When a field has a "referenceCollection" property, its value should be an ID of a record from that collection. Here are some example records you can use as references:
|
|
327
328
|
|
|
328
|
-
${Object.entries(e).map(([
|
|
329
|
+
${Object.entries(e).map(([n,i])=>`Example records from collection "${n}":
|
|
329
330
|
${JSON.stringify(i,null,2)}`).join(`
|
|
330
331
|
|
|
331
332
|
`)}.
|
|
332
333
|
|
|
333
|
-
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,
|
|
334
|
-
`),"createExperimentalWarning");function
|
|
335
|
-
`)).action(async(t,
|
|
336
|
-
${
|
|
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 rs(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=os(i);n[r]=await this.fetchExampleRecords(i)}return n}}const Xn={spec:{testerClass:za},create:{testerClass:Ja,operationKey:"create"},"find-by-id":{testerClass:Ga,operationKey:"findById"},list:{testerClass:Va,operationKey:"list"},match:{testerClass:Ha,operationKey:"match"},search:{testerClass:Ya,operationKey:"search"},update:{testerClass:Qa,operationKey:"update"},delete:{testerClass:Wa,operationKey:"delete"}};class Xa extends qa{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=Xn[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(Xn).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(Xn).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 Za extends Fa{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 Zn.create({connectionId:l,testBasePath:u,options:{fix:n}}),g=await d.client.get(`connections/${l}/data`),w=[],h=p?p.split("/"):[];if(h.length===0||h[0]==="data"){h[0]==="data"&&h.shift();let C,v;h.length>=1&&(v=h[0],h.length>=2&&h[1].trim()!==""&&(C=h[1]));for(const A of g){if(v&&v!==A.key)continue;const T=new Xa({environment:d,dataCollectionKey:A.key,testMethod:C});w.push(T)}}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 v=C.getResult();G.debug(`Suite ${C.constructor.name} result:`,{prefix:"TestRunner"}),sn(y,v)}console.debug("[TestRunner] All results collected:",Object.keys(y)),d.writeResults(y)}catch(e){throw console.error("Error in TestRunner.run():",e),e}}}const Vt=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 ec(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",Vt()).action(async()=>{console.warn(Vt()),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"),"",Vt()].join(`
|
|
336
|
+
`)).action(async(t,n)=>{try{console.warn(Vt()),t||(G.error("Test path is required"),process.exit(1)),G.header(`Testing: ${t}`);const i=new Za({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(ec,"setupTestCommand");const tc=c(()=>{try{const s=hr(import.meta.url),e=Ui(s),t=qi(e,"..","package.json");return JSON.parse(Qi(t,"utf-8")).version}catch{return"1.0.0"}},"getPackageVersion"),Ki=tc();function nc(){const s=new pr().name("membrane").description("Command-line interface for Membrane Agent").version(Ki,"-v, --version","Output the version number");s.configureHelp({sortSubcommands:!0,subcommandTerm:c(e=>k.cyan(e.name()),"subcommandTerm"),commandUsage:c(e=>e.name()==="membrane"?`${k.cyan(e.name())} ${k.gray("[options]")} ${k.cyan("[command]")}`:e.usage(),"commandUsage"),optionTerm:c(e=>{const t=e.flags;return`${k.gray("\u25B8")} ${k.cyan(t)}`},"optionTerm"),subcommandDescription:c(e=>k.gray(e.description()),"subcommandDescription"),optionDescription:c(e=>k.gray(e.description),"optionDescription"),commandDescription:c(e=>k.gray(e.description()),"commandDescription")}),s.addHelpText("beforeAll",`
|
|
337
|
+
${k.bold.cyan("Membrane Agent CLI")} ${k.gray(`v${Ki}`)}
|
|
337
338
|
|
|
338
|
-
`),
|
|
339
|
+
`),ja(s),_a(s),ec(s),Da(s),$a(s),Ia(s),process.argv.length===2&&(s.outputHelp(),process.exit(0)),s.parse()}c(nc,"runCLI");const _i=["--cwd"];function sc(){const s=process.argv.slice(2);return s.some((e,t)=>t>0&&_i.includes(s[t-1])?!1:!_i.includes(e))}c(sc,"hasCLIArguments"),sc()?nc():Ta();
|