@membranehq/cli 1.2.1 → 1.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +78 -78
  2. package/package.json +2 -2
package/dist/index.js CHANGED
@@ -1,28 +1,28 @@
1
1
  #!/usr/bin/env node
2
- var Kc=Object.defineProperty;var c=(s,e)=>Kc(s,"name",{value:e,configurable:!0});import*as A from"node:fs";import{mkdirSync as Uc,writeFileSync as Wc,readFileSync as Jc}from"node:fs";import*as P from"node:path";import{join as Us,dirname as Hc}from"node:path";import{fileURLToPath as Vc}from"node:url";import k from"chalk";import{Command as Gc}from"commander";import{WorkspaceElementType as N,MembraneConfigLoader as zc,MembraneAxiosInstance as Yc,MembraneClient as Ti,WorkspaceElementSpecs as qe,WorkspaceSyncEventType as Xc,ConnectorFileUpdateType as Ws,getMembraneElementPath as Zc,parseMembraneElementPath as ft,compareWorkspaceExports as Qc,WorkspaceElementChangeType as ht,setValueAtLocator as Js,extractMembraneErrorData as Ee,getDataCollectionCreateFields as Hs,excludeWriteOnlyFieldsFromSchema as Ei,valueToSchema as En,getRequiredFieldsFromSchema as el,getValueAtLocator as tl,walkSchema as _i,makeDataLocationPath as Ii,getDataCollectionUpdateFields as Vs}from"@membranehq/sdk";import Gs from"lodash/camelCase.js";import zs from"lodash/upperFirst.js";import nl from"code-block-writer";import sl from"lodash/uniqBy.js";import $e,{createContext as Ys,useState as J,useEffect as Ze,useContext as Xs,useId as rl,useRef as Zs,useLayoutEffect as _n,useMemo as il}from"react";import{Box as C,Text as v,useInput as Qe,render as In,Newline as ol}from"ink";import{jsx as m,jsxs as _,Fragment as Jt}from"react/jsx-runtime";import Ai from"swr/immutable";import Oi from"os";import q from"path";import al from"conf";import Qs from"jsonwebtoken";import{AsyncLocalStorage as cl}from"async_hooks";import ll from"lodash/isEqual.js";import Se from"js-yaml";import*as ul from"node:crypto";import{createHash as dl}from"node:crypto";import fl from"chokidar";import{EventEmitter as hl}from"events";import{EventSource as pl}from"eventsource";import B from"fs";import $i from"archiver";import ml from"form-data";import Ni from"unzipper";import*as gl from"node:os";import"node:events";import xi from"ink-text-input";import{SWRConfig as yl}from"swr";import An from"ink-spinner";import{TextInput as wl,Select as bl,Spinner as Sl}from"@inkjs/ui";import{FastMCP as Cl}from"fastmcp";import Ht from"axios";import{z as W}from"zod";import Pi from"jszip";import{exec as vl}from"node:child_process";import er from"lodash/merge.js";import{faker as Vt}from"@faker-js/faker";import kl from"lodash/template.js";import Tl from"lodash/templateSettings.js";function et(s){if(s.type){if(Array.isArray(s.type))return{anyOf:s.type.map(t=>et({...s,type:t}))};if(s.type==="array"){const t={type:"array",items:s.items?et(s.items):{type:"object"}};return s.title&&(t.title=s.title),s.description&&(t.description=s.description),s.minItems!==void 0&&(t.minItems=s.minItems),s.maxItems!==void 0&&(t.maxItems=s.maxItems),s.uniqueItems!==void 0&&(t.uniqueItems=s.uniqueItems),t}}const e={};if(s.type&&!Array.isArray(s.type)&&(e.type=s.type),s.title&&(e.title=s.title),s.description&&(e.description=s.description),s.format&&(e.format=s.format),s.enum&&(e.enum=s.enum),s.default!==void 0&&(e.default=s.default),s.minimum!==void 0&&(e.minimum=s.minimum),s.maximum!==void 0&&(e.maximum=s.maximum),s.minLength!==void 0&&(e.minLength=s.minLength),s.maxLength!==void 0&&(e.maxLength=s.maxLength),s.maxItems!==void 0&&(e.maxItems=s.maxItems),s.readOnly!==void 0&&(e.readOnly=s.readOnly),s.writeOnly!==void 0&&(e.writeOnly=s.writeOnly),s.examples&&s.examples.length>0&&(e.example=s.examples[0]),s.properties){e.properties={};for(const[t,n]of Object.entries(s.properties))e.properties[t]=et(n)}return s.anyOf&&(e.anyOf=s.anyOf.map(et)),s.additionalProperties!==void 0&&(typeof s.additionalProperties=="boolean"?e.additionalProperties=s.additionalProperties:e.additionalProperties=et(s.additionalProperties)),s.required&&(e.required=s.required),e}c(et,"convertDataSchemaToOpenAPI");function El(s){const{membraneInterfaces:{actions:e}}=s,t=_l(e);return JSON.stringify({openapi:"3.0.0",info:{title:"Membrane Actions API",version:"1.0.0",description:"Generated OpenAPI specification for Membrane actions"},paths:{},components:{schemas:t}},null,2)}c(El,"generateOpenAPIContent");function _l(s){const e={};return s.forEach(t=>{const n=zs(Gs(t.key)),r={type:"object",properties:{id:{type:"string",description:"Request ID"},action:{type:"string",enum:[t.key]}},required:["id","action"]};if(t?.inputSchema){const a=et(t.inputSchema);a.properties&&(r.properties={...r.properties,...a.properties}),a.required&&(r.required=[...r.required||[],...a.required])}e[`${n}Request`]=r;const i={type:"object",properties:{id:{type:"string",description:"Response ID"},success:{type:"boolean"},data:{type:"object"}},required:["id","success"]},o=t?.customOutputSchema||t?.outputSchema;if(o){const a=et(o);i.properties={...i.properties,data:a}}e[`${n}Response`]=i}),e}c(_l,"generateOpenAPISchemas");function Il(s){const{membraneInterfaces:{actions:e}}=s,t=sl(e,"key"),n=new nl({indentNumberOfSpaces:2,newLine:`
3
- `});return n.writeLine("// Generated TypeScript definitions for Membrane actions"),n.newLine(),n.writeLine("import type {"),n.writeLine(" ActionAccessor,"),n.writeLine(" ConnectionLevelActionAccessor,"),n.writeLine('} from "@membranehq/sdk";'),n.newLine(),Al(n,t),n.toString()}c(Il,"generateTypeScriptContent");function Al(s,e){s.writeLine('declare module "@membranehq/sdk" {'),s.indent(()=>{e.forEach(t=>{const n=nr(t),r=t?.inputSchema;On(s,{interfaceName:n,properties:r?.properties,required:r?.required||[]});const i=sr(t),o=t?.customOutputSchema||t?.outputSchema;On(s,{interfaceName:i,properties:o?.properties,required:o?.required||[],fallbackContent:"result: unknown"}),s.newLine()}),On(s,{interfaceName:"MembraneClient",methods:e.map(t=>{const n=nr(t),r=sr(t);return{name:"action",parameters:`selector: "${t.key}"`,returnType:`ActionAccessor<${n}, ${r}>`}})}),s.newLine(),On(s,{interfaceName:"ConnectionAccessor",methods:e.map(t=>{const n=nr(t),r=sr(t);return{name:"action",parameters:`selector: "${t.key}"`,returnType:`ConnectionLevelActionAccessor<${n}, ${r}>`}})})}),s.writeLine("}")}c(Al,"generateModuleAugmentation");function On(s,e){const{interfaceName:t,properties:n,required:r=[],methods:i,fallbackContent:o}=e;s.writeLine(`interface ${t} {`),s.indent(()=>{n&&Object.keys(n).length>0&&Ol(s,n,r),i&&i.length>0&&(n&&Object.keys(n).length>0&&s.newLine(),i.forEach((a,l)=>{s.writeLine(`${a.name}(${a.parameters}): ${a.returnType};`),l<i.length-1&&s.newLine()})),o&&(!n||Object.keys(n).length===0)&&(!i||i.length===0)&&s.writeLine(o)}),s.writeLine("}")}c(On,"generateTypeScriptInterface");function Ol(s,e,t){Object.entries(e).forEach(([n,r])=>{const o=t.includes(n)?"":"?",a=tr(r);s.writeLine(`readonly ${n}${o}: ${a}`)})}c(Ol,"generateTypeScriptProperties");function tr(s){return s.type==="string"?s.enum?s.enum.map(e=>`'${e}'`).join(" | "):"string":s.type==="number"||s.type==="integer"?"number":s.type==="boolean"?"boolean":s.type==="array"?`${s.items?tr(s.items):"unknown"}[]`:s.type==="object"?s.properties?`{ ${Object.entries(s.properties).map(([t,n])=>{const i=(s.required||[]).includes(t)?"":"?",o=tr(n);return`readonly ${t}${i}: ${o}`}).join("; ")} }`:"Record<string, unknown>":"unknown"}c(tr,"convertJsonSchemaToTypeScript");function nr(s){return`${zs(Gs(s.key))}Input`}c(nr,"getInputTypeName");function sr(s){return`${zs(Gs(s.key))}Output`}c(sr,"getOutputTypeName");async function rr(s){const{out:e}=s;await A.promises.mkdir(e,{recursive:!0});const t=$l(s);for(const[n,r]of Object.entries(t)){const i=P.join(e,n);await A.promises.writeFile(i,r,"utf-8")}}c(rr,"generateCode");function $l(s){switch(s.target){case"openapi":return{"openapi.json":El(s)};case"typescript":return{"generated.d.ts":Il(s)};default:throw new Error(`Unsupported target: ${s.target}`)}}c($l,"generateContent");const ir=c(()=>[k.yellow("\u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510"),k.yellow("\u2502 \u26A0\uFE0F EXPERIMENTAL FEATURE WARNING \u2502"),k.yellow("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524"),k.yellow("\u2502 The codegen command is experimental and subject to rapid changes.\u2502"),k.yellow("\u2502 Features, APIs, and file structures may change without notice. \u2502"),k.yellow("\u2502 Use in production environments is not recommended. \u2502"),k.yellow("\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518"),""].join(`
4
- `),"createExperimentalWarning$2");function Nl(s,e){s.command("codegen").description("\u26A0\uFE0F EXPERIMENTAL: Generate code for easy integration within projects - This feature is experimental and will be changing rapidly. Use at your own risk.").requiredOption("--actions <actions>",'Comma-separated list of action names (e.g., "list-files,get-file-by-id")').requiredOption("--out <path>","Output directory for generated files").requiredOption("--target <type>","Target format: openapi or typescript").requiredOption("--schemasOnly","Generate only schemas without implementation").addHelpText("after",ir()).addHelpText("after",["",k.bold("Examples:"),` ${k.gray("\u25B8")} ${k.cyan("membrane codegen --actions list-files,get-file-by-id --out src/generated --target openapi --schemasOnly")}`,` ${k.gray("\u25B8")} ${k.cyan("membrane install --actions delete-file --out src/generated --target typescript --schemasOnly")}`,"",ir()].join(`
5
- `)).action(async t=>{try{console.warn(ir()),console.error(k.cyan("\u{1F527} Membrane Codegen")),console.error("Status: Loading membrane interfaces...");const n=await xl(e,t),r={out:t.out,target:t.target,schemasOnly:t.schemasOnly,membraneInterfaces:n};console.error(`Output: ${r.out}`),console.error(`Target: ${r.target}`),console.error(`Schemas Only: ${r.schemasOnly?"Yes":"No"}`),console.error(`Loaded ${n.actions.length} membrane interfaces`),console.error("Status: Generating code..."),await rr(r),console.error(k.green("\u2705 Code generation completed successfully!")),process.exit(0)}catch(n){console.error(k.red("\u274C Code generation failed:")),console.error(n instanceof Error?n.message:"Unknown error occurred"),process.exit(1)}})}c(Nl,"setupCodegenCommand");async function xl(s,e){return await s.fetchElements(),{actions:[...s.getSyncedElementsByType(N.Action).map(t=>t.data)].filter(t=>e.actions.includes(t.key||""))}}c(xl,"loadMembraneInterfaces");const Pl="membrane",Ml="membrane.config.yml",or="https://api.integration.app";function ar(){const s=process.cwd(),e=P.join(s,Pl),t=P.join(s,Ml),n=e,r=P.join(n,"workspace.yaml");return{membraneDirPath:e,configPath:t,payloadDirPath:n,workspaceDataFilePath:r}}c(ar,"getPaths");function Mi(){return ar().membraneDirPath}c(Mi,"getBasePath");const Rl={pat:{type:"string"},workspace:{type:"object"}},Ri=new al({schema:Rl,configName:"config",cwd:q.join(Oi.homedir(),".membrane")}),Ll=c(s=>{Ri.set("pat",s)},"setPat"),Li=c(()=>Ri.get("pat"),"getPat");class Di{static{c(this,"AccountApiClient")}constructor(e=or){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=Li();if(!o)throw new Error("Personal Access Token not found.");n.set("Authorization",`Bearer ${o}`)}t.body&&!n.has("Content-Type")&&n.set("Content-Type","application/json");const r=await fetch(`${this.apiBaseUrl}${e}`,{...t,headers:n});if(!r.ok){const o=await r.text();throw new Error(`API request failed: ${r.status} ${r.statusText} - ${o}`)}if(r.status===204)return{};const i=await r.text();return JSON.parse(i)}get(e){return this.request(e,{method:"GET"})}post(e,t){return this.request(e,{method:"POST",body:JSON.stringify(t)})}put(e,t){return this.request(e,{method:"PUT",body:JSON.stringify(t)})}patch(e,t){return this.request(e,{method:"PATCH",body:JSON.stringify(t)})}delete(e){return this.request(e,{method:"DELETE"})}}const Dl=c(s=>{const e=new Di(or);return t=>e.get(t)},"createAccountApiFetcher");class Bt{static{c(this,"ConfigLoader")}static instance=null;sdkLoader;constructor(){this.sdkLoader=new zc}static getInstance(){return Bt.instance||(Bt.instance=new Bt),Bt.instance}loadConfig(e){e&&e!==this.sdkLoader.getCwd()&&this.sdkLoader.setCwd(e);try{return this.sdkLoader.loadConfig({validate:!0})}catch(t){if(t.message?.includes("Failed to parse"))throw t;return null}}clearCache(){this.sdkLoader.clearCache()}updateConfig(e){return this.sdkLoader.updateConfig(e)}saveToFile(e){return this.sdkLoader.saveToFile(e)}isCacheDefined(){return this.sdkLoader.hasValidConfig()}}const tt=Bt.getInstance();function $n(s){return tt.loadConfig(s)}c($n,"readProjectConfig");const jl="membrane",Fl=["**/node_modules/**","**/.git/**","**/.DS_Store","**/Thumbs.db","**/*.tmp","**/*.swp","**/*.swo","**/*.log","**/*.lock","**/.cache/**","**/.next/**","**/.vscode/**","**/.idea/**","**/.logs/**"];function he(s){return P.join(s,jl)}c(he,"getMembraneDir");const ji=Us(he(process.cwd()),".logs");class ql{static{c(this,"WorkspaceLogger")}_logs;verboseMode=!1;notificationHandler=null;constructor(){this._logs=[]}setNotificationHandler(e){this.notificationHandler=e}setVerboseMode(e){this.verboseMode=e}getVerboseMode(){return this.verboseMode}get logs(){return[...this._logs]}get latestLogs(){return this._logs.slice(this._logs.length-5)}log(e,t="info"){const n={timestamp:new Date().toISOString(),message:e,type:t};this._logs.push(n),this._logs=this._logs.slice(0,1e3),(t!=="debug"||this.verboseMode)&&this.notificationHandler&&this.notificationHandler.addLog(n)}info(e){this.log(e,"info")}success(e){this.log(e,"success")}warning(e){this.log(e,"warning")}error(e){this.log(e,"error")}debug(e){this.log(e,"debug")}clear(){this._logs=[]}saveLogsToFile(e){if(this._logs.length===0)return null;try{const t=new Date().toISOString().replace(/[:.]/g,"_"),n=e?`-${e}`:"",r=`${t}${n}.txt`;Uc(ji,{recursive:!0});const i=Us(ji,r),o=this._logs.map(a=>`[${a.timestamp}] ${a.type?.toUpperCase()||"INFO"}: ${a.message}`).join(`
6
- `);return Wc(i,o,"utf-8"),i}catch(t){return console.error("Failed to save logs:",t),null}}}const b=new ql,Fi=new cl;class qi{static{c(this,"RequestLogger")}constructor(e=Yc){this.axiosInstance=e}interceptorsConfigured=!1;setup(){if(this.interceptorsConfigured)return;const e=c(t=>(this.logError(t),Promise.reject(t)),"errorHandler");this.axiosInstance.interceptors.request.use(t=>{const n=Fi.getStore();t.metadata={startTime:Date.now(),skipErrorLog:n};const{method:r,url:i}=this.getRequestDetails(t);return b.debug(`[Request]: ${r} ${i}`),t},e),this.axiosInstance.interceptors.response.use(t=>{const{method:n,url:r}=this.getRequestDetails(t.config),i=this.getDuration(t.config),{status:o,statusText:a}=t;return b.debug(`[Response]: ${n} ${r} - ${o} ${a} (${i}ms)`),t},e),this.interceptorsConfigured=!0}static withSkipErrorLog(e){return Fi.run(!0,e)}getRequestDetails(e){const t=e?.method?.toUpperCase()??"UNKNOWN";if(!e?.url)return{method:t,url:"unknown"};if(e.url.startsWith("http"))return{method:t,url:e.url};const r=`${e.baseURL??""}/${e.url}`.replace(/\/+/g,"/").replace(/:\//,"://");return{method:t,url:r}}getDuration(e){return Date.now()-(e?.metadata?.startTime??Date.now())}logError(e){if(e.config?.metadata?.skipErrorLog)return;const{method:t,url:n}=this.getRequestDetails(e.config),r=this.getDuration(e.config);if(e.response){const{status:i,statusText:o}=e.response;b.error(`[Response]: ${t} ${n} - ${i} ${o} (${r}ms)`),e.response.data&&b.error(`[Response Data]: ${JSON.stringify(e.response.data,null,2)}`)}}}class Bl{static{c(this,"MembraneAPIManager")}client=null;currentConfig=null;tokenExpiry=0;requestTimes=[];maxRequestsPerSecond=80;windowSizeMs=1e3;semaphore=0;maxConcurrentRequests;maxRetries;retryDelay;requestTimeout;enableJitter;semaphoreQueue=[];rateLimitMutex=Promise.resolve();requestLogger=null;constructor(e={}){this.init(e)}init(e={}){this.windowSizeMs=e.windowSizeMs??1e3,this.maxRequestsPerSecond=e.maxRequestsPerSecond??80,this.maxConcurrentRequests=e.maxConcurrentRequests??Math.max(1,Math.min(Math.floor(this.maxRequestsPerSecond/4),20)),this.maxRetries=e.maxRetries??3,this.retryDelay=e.retryDelay??1e3,this.requestTimeout=e.requestTimeout??12e4,this.enableJitter=e.enableJitter!==!1,this.requestLogger=new qi,this.requestLogger.setup()}async withClient(e,t=!0,n=process.cwd()){const r=c(async()=>{try{return await this.withRetry(async()=>{const i=await this.getClient(n);await this.acquireSemaphore();try{return await this.waitIfNeeded(),this.recordRequest(),await this.withTimeout(e(i),this.requestTimeout)}finally{this.releaseSemaphore()}},"API request")}catch(i){if(t)throw i;return}},"executeRequest");return t?r():qi.withSkipErrorLog(r)}async generateAccessToken(e,t){return Qs.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=$n(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 Ti({token:t,apiUri:e.apiUri})}async getClient(e=process.cwd()){const t=this.getCurrentConfig(e);if(!t)throw new Error("Unable to create MembraneClient: No workspace configuration found.");const n=!this.currentConfig||this.currentConfig.workspaceKey!==t.workspaceKey||this.currentConfig.workspaceSecret!==t.workspaceSecret||this.currentConfig.apiUri!==t.apiUri,r=!this.isTokenValid()||this.tokenExpiry-Date.now()<3e5;return(!this.client||n||r)&&(this.client=await this.createClient(t)),this.client}clearClient(){this.client=null,this.currentConfig=null,this.tokenExpiry=0,this.requestTimes=[],this.semaphore=0,this.semaphoreQueue=[],this.rateLimitMutex=Promise.resolve()}getCurrentConfigInfo(){return this.currentConfig}async waitIfNeeded(){this.rateLimitMutex=this.rateLimitMutex.then(async()=>{for(this.cleanOldRequests();this.requestTimes.length>=this.maxRequestsPerSecond;){const t=this.requestTimes[0]+this.windowSizeMs-Date.now()+10;if(t>0)await new Promise(n=>setTimeout(n,t)),this.cleanOldRequests();else break}}),await this.rateLimitMutex}recordRequest(){this.requestTimes.push(Date.now())}cleanOldRequests(){const e=Date.now()-this.windowSizeMs;this.requestTimes=this.requestTimes.filter(t=>t>e)}getRequestCount(){return this.cleanOldRequests(),this.requestTimes.length}async acquireSemaphore(){if(this.semaphore<this.maxConcurrentRequests){this.semaphore++;return}return new Promise(e=>{this.semaphoreQueue.push(e)})}releaseSemaphore(){if(this.semaphore--,this.semaphoreQueue.length>0){const e=this.semaphoreQueue.shift();this.semaphore++,e()}}async withRetry(e,t="operation"){let n;for(let r=0;r<=this.maxRetries;r++)try{return await e()}catch(i){if(n=i,!this.isRetryableError(i)||r===this.maxRetries)throw i;const o=new Date().toISOString(),a=r+2;b.debug(`[${o}] Retrying ${t} (attempt ${a}/${this.maxRetries+1})`);let l=this.retryDelay*Math.pow(2,r);if(this.enableJitter){const u=l*.25*(Math.random()*2-1);l=Math.max(0,l+u)}await new Promise(u=>setTimeout(u,l))}throw n||new Error("Unknown error occurred during retry attempts")}isRetryableError(e){if(!e)return!1;const t=(e.message||e.toString()||"").toLowerCase(),n=e.code;return n&&["econnrefused","enotfound","econnreset","etimedout","ehostunreach","enetunreach"].includes(n.toLowerCase())?!0:["econnrefused","connection refused","network error","timeout","socket hang up","request timeout","dns lookup failed"].some(o=>t.includes(o))}async withTimeout(e,t){let n;const r=new Promise((i,o)=>{n=setTimeout(()=>o(new Error(`Request timeout after ${t}ms`)),t)});try{const i=await Promise.race([e,r]);return n&&clearTimeout(n),i}catch(i){throw n&&clearTimeout(n),i}}}const K=new Bl;async function Bi(s){const e=await K.withClient(t=>t.get("org-workspace-id"),!0,s);if(!e)throw new Error("Failed to get workspace ID");return e.id}c(Bi,"getWorkspaceId");var U={},Nn={},Ki;function Ui(){if(Ki)return Nn;Ki=1,Object.defineProperty(Nn,"__esModule",{value:!0});function s(e){return e===void 0&&(e=""),e?String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/[^A-Za-z0-9]+/g,"$").replace(/([a-z])([A-Z])/g,function(t,n,r){return n+"$"+r}).toLowerCase().replace(/(\$)(\w)/g,function(t,n,r){return r.toUpperCase()}):""}return c(s,"toCamelCase"),Nn.default=s,Nn}c(Ui,"requireJsCamelcase");var xn={},Wi;function Ji(){if(Wi)return xn;Wi=1,Object.defineProperty(xn,"__esModule",{value:!0});function s(e){return e===void 0&&(e=""),e?String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/([a-z])([A-Z])/g,function(t,n,r){return n+"_"+r.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g,"_").toLowerCase():""}return c(s,"toSnakeCase"),xn.default=s,xn}c(Ji,"requireJsSnakecase");var Pn={},Hi;function Vi(){if(Hi)return Pn;Hi=1,Object.defineProperty(Pn,"__esModule",{value:!0});function s(e){return e===void 0&&(e=""),e?String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"$").replace(/[^A-Za-z0-9]+/g,"$").replace(/([a-z])([A-Z])/g,function(t,n,r){return n+"$"+r}).toLowerCase().replace(/(\$)(\w?)/g,function(t,n,r){return r.toUpperCase()}):""}return c(s,"toPascalCase"),Pn.default=s,Pn}c(Vi,"requireJsPascalcase");var Mn={},Gi;function Kl(){if(Gi)return Mn;Gi=1,Object.defineProperty(Mn,"__esModule",{value:!0});function s(e){return e===void 0&&(e=""),e?String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/([a-z])([A-Z])/g,function(t,n,r){return n+"_"+r.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g,".").toLowerCase():""}return c(s,"toDotCase"),Mn.default=s,Mn}c(Kl,"requireJsDotcase");var Rn={},zi;function Ul(){if(zi)return Rn;zi=1,Object.defineProperty(Rn,"__esModule",{value:!0});function s(e){return e===void 0&&(e=""),e?String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/([a-z])([A-Z])/g,function(t,n,r){return n+"_"+r.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g,"/").toLowerCase():""}return c(s,"toPathCase"),Rn.default=s,Rn}c(Ul,"requireJsPathcase");var Ln={},Yi;function Wl(){if(Yi)return Ln;Yi=1,Object.defineProperty(Ln,"__esModule",{value:!0});function s(e){return e===void 0&&(e=""),e?String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/([a-z])([A-Z])/g,function(t,n,r){return n+"_"+r.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g," ").toLowerCase():""}return c(s,"toTextCase"),Ln.default=s,Ln}c(Wl,"requireJsTextcase");var Dn={},Xi;function Jl(){if(Xi)return Dn;Xi=1,Object.defineProperty(Dn,"__esModule",{value:!0});function s(e){if(e===void 0&&(e=""),!e)return"";var t=String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/([a-z])([A-Z])/g,function(n,r,i){return r+"_"+i.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g," ").toLowerCase();return t.charAt(0).toUpperCase()+t.slice(1)}return c(s,"toSentenceCase"),Dn.default=s,Dn}c(Jl,"requireJsSentencecase");var jn={},Zi;function Hl(){if(Zi)return jn;Zi=1,Object.defineProperty(jn,"__esModule",{value:!0});function s(e){return e===void 0&&(e=""),e?String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/([a-z])([A-Z])/g,function(t,n,r){return n+"_"+r.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g," ").toLowerCase().replace(/( ?)(\w+)( ?)/g,function(t,n,r,i){return n+r.charAt(0).toUpperCase()+r.slice(1)+i}):""}return c(s,"toHeaderCase"),jn.default=s,jn}c(Hl,"requireJsHeadercase");var Fn={},Qi;function eo(){if(Qi)return Fn;Qi=1,Object.defineProperty(Fn,"__esModule",{value:!0});function s(e){return e===void 0&&(e=""),e?String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/([a-z])([A-Z])/g,function(t,n,r){return n+"_"+r.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g,"-").toLowerCase():""}return c(s,"toKebabCase"),Fn.default=s,Fn}c(eo,"requireJsKebabcase");var pt={},cr={},to;function mt(){return to||(to=1,function(s){Object.defineProperty(s,"__esModule",{value:!0}),s.belongToTypes=s.isValidObject=s.isArrayObject=s.validateOptions=s.DefaultOption=void 0,s.DefaultOption={recursive:!1,recursiveInArray:!1,keepTypesOnRecursion:[]},s.validateOptions=function(e){return e===void 0&&(e=s.DefaultOption),e.recursive==null?e=s.DefaultOption:e.recursiveInArray==null&&(e.recursiveInArray=!1),e},s.isArrayObject=function(e){return e!=null&&Array.isArray(e)},s.isValidObject=function(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)},s.belongToTypes=function(e,t){return(t||[]).some(function(n){return e instanceof n})}}(cr)),cr}c(mt,"requireUtils");var no;function Vl(){if(no)return pt;no=1;var s=pt&&pt.__spreadArrays||function(){for(var n=0,r=0,i=arguments.length;r<i;r++)n+=arguments[r].length;for(var o=Array(n),a=0,r=0;r<i;r++)for(var l=arguments[r],u=0,d=l.length;u<d;u++,a++)o[a]=l[u];return o};Object.defineProperty(pt,"__esModule",{value:!0});var e=mt();function t(n,r){if(r===void 0&&(r=e.DefaultOption),!e.isValidObject(n))return null;r=e.validateOptions(r);var i={};return Object.keys(n).forEach(function(o){var a=n[o],l=o.toLowerCase();r.recursive&&(e.isValidObject(a)?e.belongToTypes(a,r.keepTypesOnRecursion)||(a=t(a,r)):r.recursiveInArray&&e.isArrayObject(a)&&(a=s(a).map(function(u){var d=u;if(e.isValidObject(u))e.belongToTypes(d,r.keepTypesOnRecursion)||(d=t(u,r));else if(e.isArrayObject(u)){var f=t({key:u},r);d=f.key}return d}))),i[l]=a}),i}return c(t,"lowerKeys"),pt.default=t,pt}c(Vl,"requireLowercaseKeysObject");var gt={},so;function Gl(){if(so)return gt;so=1;var s=gt&&gt.__spreadArrays||function(){for(var n=0,r=0,i=arguments.length;r<i;r++)n+=arguments[r].length;for(var o=Array(n),a=0,r=0;r<i;r++)for(var l=arguments[r],u=0,d=l.length;u<d;u++,a++)o[a]=l[u];return o};Object.defineProperty(gt,"__esModule",{value:!0});var e=mt();function t(n,r){if(r===void 0&&(r=e.DefaultOption),!e.isValidObject(n))return null;r=e.validateOptions(r);var i={};return Object.keys(n).forEach(function(o){var a=n[o],l=o.toUpperCase();r.recursive&&(e.isValidObject(a)?e.belongToTypes(a,r.keepTypesOnRecursion)||(a=t(a,r)):r.recursiveInArray&&e.isArrayObject(a)&&(a=s(a).map(function(u){var d=u;if(e.isValidObject(u))e.belongToTypes(d,r.keepTypesOnRecursion)||(d=t(u,r));else if(e.isArrayObject(u)){var f=t({key:u},r);d=f.key}return d}))),i[l]=a}),i}return c(t,"upperKeys"),gt.default=t,gt}c(Gl,"requireUppercaseKeysObject");var yt={},ro;function zl(){if(ro)return yt;ro=1;var s=yt&&yt.__spreadArrays||function(){for(var r=0,i=0,o=arguments.length;i<o;i++)r+=arguments[i].length;for(var a=Array(r),l=0,i=0;i<o;i++)for(var u=arguments[i],d=0,f=u.length;d<f;d++,l++)a[l]=u[d];return a};Object.defineProperty(yt,"__esModule",{value:!0});var e=mt(),t=Ui();function n(r,i){if(i===void 0&&(i=e.DefaultOption),!e.isValidObject(r))return null;i=e.validateOptions(i);var o={};return Object.keys(r).forEach(function(a){var l=r[a],u=t.default(a);i.recursive&&(e.isValidObject(l)?e.belongToTypes(l,i.keepTypesOnRecursion)||(l=n(l,i)):i.recursiveInArray&&e.isArrayObject(l)&&(l=s(l).map(function(d){var f=d;if(e.isValidObject(d))e.belongToTypes(f,i.keepTypesOnRecursion)||(f=n(d,i));else if(e.isArrayObject(d)){var h=n({key:d},i);f=h.key}return f}))),o[u]=l}),o}return c(n,"camelKeys"),yt.default=n,yt}c(zl,"requireCamelcaseKeysObject");var wt={},io;function Yl(){if(io)return wt;io=1;var s=wt&&wt.__spreadArrays||function(){for(var r=0,i=0,o=arguments.length;i<o;i++)r+=arguments[i].length;for(var a=Array(r),l=0,i=0;i<o;i++)for(var u=arguments[i],d=0,f=u.length;d<f;d++,l++)a[l]=u[d];return a};Object.defineProperty(wt,"__esModule",{value:!0});var e=mt(),t=Ji();function n(r,i){if(i===void 0&&(i=e.DefaultOption),!e.isValidObject(r))return null;i=e.validateOptions(i);var o={};return Object.keys(r).forEach(function(a){var l=r[a],u=t.default(a);i.recursive&&(e.isValidObject(l)?e.belongToTypes(l,i.keepTypesOnRecursion)||(l=n(l,i)):i.recursiveInArray&&e.isArrayObject(l)&&(l=s(l).map(function(d){var f=d;if(e.isValidObject(d))e.belongToTypes(f,i.keepTypesOnRecursion)||(f=n(d,i));else if(e.isArrayObject(d)){var h=n({key:d},i);f=h.key}return f}))),o[u]=l}),o}return c(n,"snakeKeys"),wt.default=n,wt}c(Yl,"requireSnakecaseKeysObject");var bt={},oo;function Xl(){if(oo)return bt;oo=1;var s=bt&&bt.__spreadArrays||function(){for(var r=0,i=0,o=arguments.length;i<o;i++)r+=arguments[i].length;for(var a=Array(r),l=0,i=0;i<o;i++)for(var u=arguments[i],d=0,f=u.length;d<f;d++,l++)a[l]=u[d];return a};Object.defineProperty(bt,"__esModule",{value:!0});var e=mt(),t=Vi();function n(r,i){if(i===void 0&&(i=e.DefaultOption),!e.isValidObject(r))return null;i=e.validateOptions(i);var o={};return Object.keys(r).forEach(function(a){var l=r[a],u=t.default(a);i.recursive&&(e.isValidObject(l)?e.belongToTypes(l,i.keepTypesOnRecursion)||(l=n(l,i)):i.recursiveInArray&&e.isArrayObject(l)&&(l=s(l).map(function(d){var f=d;if(e.isValidObject(d))e.belongToTypes(f,i.keepTypesOnRecursion)||(f=n(d,i));else if(e.isArrayObject(d)){var h=n({key:d},i);f=h.key}return f}))),o[u]=l}),o}return c(n,"pascalKeys"),bt.default=n,bt}c(Xl,"requirePascalcaseKeysObject");var St={},ao;function Zl(){if(ao)return St;ao=1;var s=St&&St.__spreadArrays||function(){for(var r=0,i=0,o=arguments.length;i<o;i++)r+=arguments[i].length;for(var a=Array(r),l=0,i=0;i<o;i++)for(var u=arguments[i],d=0,f=u.length;d<f;d++,l++)a[l]=u[d];return a};Object.defineProperty(St,"__esModule",{value:!0});var e=mt(),t=eo();function n(r,i){if(i===void 0&&(i=e.DefaultOption),!e.isValidObject(r))return null;i=e.validateOptions(i);var o={};return Object.keys(r).forEach(function(a){var l=r[a],u=t.default(a);i.recursive&&(e.isValidObject(l)?e.belongToTypes(l,i.keepTypesOnRecursion)||(l=n(l,i)):i.recursiveInArray&&e.isArrayObject(l)&&(l=s(l).map(function(d){var f=d;if(e.isValidObject(d))e.belongToTypes(f,i.keepTypesOnRecursion)||(f=n(d,i));else if(e.isArrayObject(d)){var h=n({key:d},i);f=h.key}return f}))),o[u]=l}),o}return c(n,"kebabKeys"),St.default=n,St}c(Zl,"requireKebabcaseKeysObject");var co;function Ql(){if(co)return U;co=1,Object.defineProperty(U,"__esModule",{value:!0}),U.kebabKeys=U.pascalKeys=U.snakeKeys=U.camelKeys=U.upperKeys=U.lowerKeys=U.toLowerCase=U.toUpperCase=U.toKebabCase=U.toHeaderCase=U.toSentenceCase=U.toTextCase=U.toPathCase=U.toDotCase=U.toPascalCase=U.toSnakeCase=U.toCamelCase=void 0;var s=Ui();U.toCamelCase=s.default;var e=Ji();U.toSnakeCase=e.default;var t=Vi();U.toPascalCase=t.default;var n=Kl();U.toDotCase=n.default;var r=Ul();U.toPathCase=r.default;var i=Wl();U.toTextCase=i.default;var o=Jl();U.toSentenceCase=o.default;var a=Hl();U.toHeaderCase=a.default;var l=eo();U.toKebabCase=l.default;var u=Vl();U.lowerKeys=u.default;var d=Gl();U.upperKeys=d.default;var f=zl();U.camelKeys=f.default;var h=Yl();U.snakeKeys=h.default;var g=Xl();U.pascalKeys=g.default;var y=Zl();U.kebabKeys=y.default;var p=c(function(E){return String(E||"").toLowerCase()},"toLowerCase");U.toLowerCase=p;var w=c(function(E){return String(E||"").toUpperCase()},"toUpperCase");U.toUpperCase=w;var T={toCamelCase:s.default,toSnakeCase:e.default,toPascalCase:t.default,toDotCase:n.default,toPathCase:r.default,toTextCase:i.default,toSentenceCase:o.default,toHeaderCase:a.default,toKebabCase:l.default,toUpperCase:w,toLowerCase:p,lowerKeys:u.default,upperKeys:d.default,camelKeys:f.default,snakeKeys:h.default,pascalKeys:g.default,kebabKeys:y.default};return U.default=T,U}c(Ql,"requireLib");var lr,lo;function eu(){return lo||(lo=1,lr=Ql()),lr}c(eu,"requireJsConvertCase");var tu=eu();const Ne={UPDATE:"update",DELETE:"delete",CREATE:"create"},ae={INCOMING:"incoming",OUTGOING:"outgoing"},_e={[N.Integration]:{element:"integration",elements:"integrations",exportable:!1,exportCleanup:c(s=>({id:s.id,key:s.key,name:s.name,connectorId:s.connectorId,baseUri:s.baseUri,connectorVersion:s.connectorVersion}),"exportCleanup")},[N.Connector]:{element:"connector",elements:"connectors",exportable:!1},[N.Action]:{element:"action",elements:"actions",integrationSpecific:!0,exportCleanup:c(s=>(delete s.integration,s),"exportCleanup")},[N.AppDataSchema]:{element:"appDataSchema",elements:"appDataSchemas"},[N.AppEventType]:{element:"appEventType",elements:"appEventTypes"},[N.DataLinkTable]:{element:"dataLinkTable",elements:"dataLinkTables"},[N.DataSource]:{element:"dataSource",elements:"dataSources",parentKey:"universalDataSourceId",integrationSpecific:!0},[N.FieldMapping]:{element:"fieldMapping",elements:"fieldMappings",integrationSpecific:!0,parentKey:"universalFieldMappingId",exportCleanup:c(s=>(delete s.dataSourceId,s),"exportCleanup")},[N.Flow]:{element:"flow",elements:"flows",integrationSpecific:!0,parentKey:"universalFlowId"},[N.Package]:{element:"package",elements:"packages",integrationSpecific:!0}},nu=["id","workspaceId","integrationId","createdAt","updatedAt","revision","archivedAt","baseUri","state","appliedToIntegrations","dependencies"],uo=[N.Action,N.FieldMapping,N.Flow,N.DataSource,N.Package];class Z{static{c(this,"Element")}type;key;integrationKey;data;constructor(e,t,n,r){if(!r)throw new Error("Element must always contain data");if(!t)throw new Error("Element must have a key");this.type=e,this.key=t,this.data=r,this.integrationKey=n||Z.extractIntegrationKey(r)}get id(){return Z.makeId(this.type,this.key,this.integrationKey)}get dirPath(){const e=qe[this.type].apiPath;if(this.integrationKey){const t=qe[N.Integration].apiPath;return P.join(t,this.integrationKey,e,this.key)}return P.join(e,this.key)}get path(){return P.join(this.dirPath,"spec.yaml")}get relativePath(){return P.relative(he(process.cwd()),this.path)}get absolutePath(){return P.resolve(P.join(he(process.cwd()),this.path))}isEqual(e){if(this.id!==e.id)return!1;const t=this.clean(),n=e.clean();return ll(t,n)}hasParent(){if(this.data?.parentUuid)return!0;const e=this.getParentKey();return!!e&&!!this.data?.[e]}clean(){const e={...this.data};return nu.forEach(t=>{delete e[t]}),Object.keys(e).forEach(t=>{t.match(/universal.*Revision/)&&delete e[t]}),e}getParentKey(){let e="parentId";return _e?.[this.type]?.parentKey&&(e=_e?.[this.type]?.parentKey),e}static new(e,t,n,r){return new Z(e,t,n,r)}static fromData(e,t){if(!t?.key)throw new Error(`Element missing key: ${JSON.stringify(t)}`);const n=this.extractIntegrationKey(t);return new Z(e,t.key,n,t)}static fromPathAndData(e,t){const n=Z.parsePath(e);if(!t)return;const r=t?.key||n?.key;return n?Z.new(n.type,r,n.integrationKey,t):void 0}static fromElement(e){return new Z(e.type,e.key,e.integrationKey,{...e.data})}static idFromPath(e){const t=Z.parsePath(e);if(t)return Z.makeId(t.type,t.key,t.integrationKey)}static makeId(e,t,n){return e===N.Integration?`${e}:${t}`:Z.isIntegrationSpecific(e)?`${n||"universal"}:${e}:${t}`:`${e}:${t}`}static parsePath(e){const t=this.getRelativePath(e);if(!this.isElementFile(t))return;const n=Object.values(qe).map(l=>l.apiPath).join("|"),r=new RegExp(`^(?<elementType>${n})/(?<elementKey>[^/]+)/spec\\.ya?ml$`),i=t.match(r);if(i?.groups){const{elementType:l,elementKey:u}=i.groups,d=this.getElementTypeFromPath(l);if(d)return{type:d,key:u}}const o=new RegExp(`^integrations/(?<integrationKey>[^/]+)/(?<elementType>${n})/(?<elementKey>[^/]+)/spec\\.ya?ml$`),a=t.match(o);if(a?.groups){const{integrationKey:l,elementType:u,elementKey:d}=a.groups,f=this.getElementTypeFromPath(u);if(f)return{type:f,key:d,integrationKey:l}}}static extractIntegrationKey(e){return e?.integrationKey||e?.integration?.key||e?.integration_key||void 0}static isElementFile(e){return e.endsWith(".yml")||e.endsWith(".yaml")}static getElementTypeFromPath(e){return Object.values(N).find(t=>qe[t].apiPath===e)}static getRelativePath(e){return P.relative(he(process.cwd()),e)}static isIntegrationSpecific(e){return uo.includes(e)}static canBeIntegrationSpecific(e){return uo.includes(e)}}class fo{static{c(this,"BaseWorkspaceElementsRepository")}constructor(e){this.cache=e}connectorsMapping;sourceCache;setConnectorsMapping(e){this.connectorsMapping=e}setSourceCache(e){this.sourceCache=e}async getElements(){const e=[];try{const t=await this.getIntegrations();e.push(...t);const n=[N.Integration,N.Connector],r=Object.keys(_e),i=await Promise.all(r.filter(o=>!n.includes(o)).map(async o=>this.getElementsByType(o,t)));for(const o of i)e.push(...o)}catch(t){throw b.error(`Failed to get elements: ${t}`),t}return e}async putElement(e){let t=this.cache.get(e.id);return t&&!e.data.id&&t.data.id&&(e.data.id=t.data.id),!t&&e.data.id&&(t=await this.getByInternalId(e.data.id,e.type,!1)),e.data.id&&t?t=await this.updateElement(e,t,{elements:this.cache.getAll(),connectorsMapping:this.connectorsMapping,sourceElements:this.sourceCache?.getAll()}):t=await this.createElement(e,{elements:this.cache.getAll(),connectorsMapping:this.connectorsMapping,sourceElements:this.sourceCache?.getAll()}),t}async getElementsByType(e,t){return[]}async createElement(e,t){return e}async updateElement(e,t,n){return t}async getElement(e){}async getIntegrations(){return[]}async getByInternalId(e,t,n=!0){}async deleteElement(e,t){}}function ur(s,e=!0){if(A.existsSync(s))try{const t=A.readFileSync(s,"utf8");return Se.load(t)||void 0}catch(t){if(!e)return;if(t instanceof Error){const n=P.relative(process.cwd(),s);throw new Error(`Failed to parse YAML file "${n}": ${t.message}`)}throw t}}c(ur,"readYaml$1");function su(s,e,t){try{const n=Se.dump(e,t);A.writeFileSync(s,n,"utf8")}catch(n){if(n instanceof Error){const r=P.relative(process.cwd(),s);throw new Error(`Failed to write YAML file "${r}": ${n.message}`)}throw n}}c(su,"writeYaml$1");class ru extends fo{static{c(this,"LocalWorkspaceElementsRepository")}basePath;constructor(e){super(e),this.basePath=he(process.cwd())}async getElementsByType(e,t){const n=[],r=P.join(this.basePath,qe[e].apiPath),i=await this.readElementsInDir(r);n.push(...i);for(const o of t){const a=P.join(this.basePath,qe[N.Integration].apiPath,o.key,qe[e].apiPath),l=await this.readElementsInDir(a);n.push(...l)}return n.length>0&&b.debug(`[local] Fetched ${n.length} ${e}${n.length!==1?"s":""}`),n}async getElement(e){return this.readElement(e.path)}async createElement(e){return this.updateElement(e,e)}async updateElement(e,t){if(!e.data)throw new Error("Element must have data to write");const n=P.join(this.basePath,t.dirPath),r=P.join(this.basePath,t.path);return A.existsSync(n)||A.mkdirSync(n,{recursive:!0}),su(r,e.data),b.debug(`[local] Written ${t.relativePath}`),t}async deleteElement(e){const t=P.join(this.basePath,e.path),n=P.join(this.basePath,e.dirPath);A.existsSync(t)&&A.rmSync(t,{force:!0}),this.pruneEmptyDir(n),b.debug(`[local] Deleted ${e.relativePath}`)}async getIntegrations(){const e=P.join(this.basePath,qe[N.Integration].apiPath);return this.readElementsInDir(e)}async readElement(e){const t=ur(e);if(t)return Z.fromPathAndData(e,t)}async readElementsInDir(e){const t=[];if(!A.existsSync(e))return t;const n=A.readdirSync(e);if(n.length===0)return t;const r=n.map(async o=>{const a=P.join(e,o,"spec.yaml");return this.readElement(a)});return(await Promise.all(r)).filter(o=>o!=null)}pruneEmptyDir(e){try{if(!e.startsWith(this.basePath)||e===this.basePath||!A.existsSync(e)||A.readdirSync(e).length>0)return;A.rmdirSync(e),this.pruneEmptyDir(P.dirname(e))}catch(t){console.warn(`Failed to prune empty directory ${e}:`,t)}}}class iu extends fo{static{c(this,"RemoteWorkspaceElementsRepository")}async getElementsByType(e,t){const n=Z.canBeIntegrationSpecific(e),r=await this.findAll(e,n?{layer:"universal"}:{});if(!Z.canBeIntegrationSpecific(e))return r;for(const i of t){const o=i.key,a=i.data.id,l=await this.findAll(e,a?{integrationId:a}:{integrationKey:o},o);r.push(...l)}return r.length>0&&b.debug(`[remote] Fetched ${r.length} ${e}${r.length!==1?"s":""}`),r}async getElement(e){const t=await K.withClient(n=>n[_e[e.type].element](e.data.id).get());return Z.fromData(e.type,t)}async createElement(e,t){const n=e.clean();if(this.transformElementForCreate(e,n,t),e.hasParent()&&n.integrationId&&!n.isCustomized){const o=e.getParentKey(),a=new Set(["uuid","integrationId",o,"meta","integrationUuid","parentUuid"]);Object.keys(n).forEach(l=>{a.has(l)||delete n[l]})}const r=await K.withClient(o=>o[_e[e.type].elements].create(n)),i=Z.fromData(e.type,r);return b.debug(`[remote] Created ${i.id}`),i}async updateElement(e,t,n){if(!e.data.id)throw new Error("Element must have an id to update");t.data.archivedAt&&await K.withClient(a=>a[_e[e.type].element](t.data.id).restore());const r=e.clean();if(this.transformElementForUpdate(e,r,n),e.hasParent()&&r.integrationId&&!r.isCustomized)return b.debug(`[remote] Skipped update for ${t.id} (non-customized)`),t;const i=await K.withClient(a=>a[_e[e.type].element](t.data.id).put(r)),o=Z.fromData(t.type,i);return b.debug(`[remote] Updated ${t.id}`),o}async deleteElement(e){if(!e.data.id)throw new Error("Element must have an id to delete");await K.withClient(t=>t[_e[e.type].element](e.data.id).archive()),b.debug(`[remote] Deleted ${e.id}`)}async getIntegrations(){const e=await K.withClient(n=>n.integrations.findAll());if(!e)return[];const t=e.map(n=>Z.fromData(N.Integration,n));return t.length>0&&b.debug(`[remote] Fetched ${t.length} integrations`),t}async getByInternalId(e,t){let n;if(n=await K.withClient(r=>r[_e[t].element](e).get(),!1),!!n)return Z.fromData(t,n)}transformElementForCreate(e,t,n){if(e.integrationKey){const r=n.elements.find(i=>i.type===N.Integration&&i.key===e.integrationKey);if(r)t.integrationId=r.data.id;else throw new Error(`Dependency integration ${e.integrationKey} not found for ${e.id}`)}if(e.type===N.Integration){const r=n.connectorsMapping?.[t.connectorId];r&&(t.connectorId=r)}this.transformPackageDependencies(e,t,n),this.transformParentDependency(e,t,n)}transformElementForUpdate(e,t,n){if(e.type===N.Integration){const r=n.connectorsMapping?.[t.connectorId];r&&(t.connectorId=r)}if(e.integrationKey){t.integrationKey=e.integrationKey;const r=n.elements.find(i=>i.type===N.Integration&&i.key===e.integrationKey);if(r)t.integrationId=r.data.id;else throw new Error(`Dependency integration ${e.integrationKey} not found for ${e.id}`)}this.transformPackageDependencies(e,t,n),this.transformParentDependency(e,t,n)}transformPackageDependencies(e,t,n){if(e.type!==N.Package||!t.elements)return;const r=t.elements.map(i=>{const a=(n.sourceElements||n.elements).find(u=>u.data.id===i.id&&u.type===i.type);if(!a)throw new Error(`Package element ${i.type} with id ${i.id} not found in source workspace for package ${e.id}`);const l=n.elements.find(u=>u.type===i.type&&u.key===a.key&&u.integrationKey===a.integrationKey);if(!l)throw new Error(`Package element ${i.type} with key ${a.key} not found in target workspace for package ${e.id}`);return{id:l.data.id,type:i.type}});t.elements=r}transformParentDependency(e,t,n){if(!e.hasParent())return;const r=e.getParentKey();if(!r)return;const i=n.elements.find(o=>o.type===e.type&&o.key===e.key&&!o.hasParent());if(i)t[r]=i.data.id;else throw new Error(`Parent ${e.getParentKey()} not found for ${e.id}`)}async findAll(e,t={},n){const r=await K.withClient(i=>i[_e[e].elements].findAll(t));return r?r.filter(i=>i.key).map(i=>(n&&!i.integrationKey&&(i.integrationKey=n),Z.fromData(e,i))):[]}}const dr=Symbol.for("yaml.alias"),fr=Symbol.for("yaml.document"),Be=Symbol.for("yaml.map"),ho=Symbol.for("yaml.pair"),Ie=Symbol.for("yaml.scalar"),Ct=Symbol.for("yaml.seq"),pe=Symbol.for("yaml.node.type"),Ke=c(s=>!!s&&typeof s=="object"&&s[pe]===dr,"isAlias"),nt=c(s=>!!s&&typeof s=="object"&&s[pe]===fr,"isDocument"),vt=c(s=>!!s&&typeof s=="object"&&s[pe]===Be,"isMap"),G=c(s=>!!s&&typeof s=="object"&&s[pe]===ho,"isPair"),V=c(s=>!!s&&typeof s=="object"&&s[pe]===Ie,"isScalar$1"),kt=c(s=>!!s&&typeof s=="object"&&s[pe]===Ct,"isSeq");function Y(s){if(s&&typeof s=="object")switch(s[pe]){case Be:case Ct:return!0}return!1}c(Y,"isCollection$1");function X(s){if(s&&typeof s=="object")switch(s[pe]){case dr:case Be:case Ie:case Ct:return!0}return!1}c(X,"isNode");const po=c(s=>(V(s)||Y(s))&&!!s.anchor,"hasAnchor"),ce=Symbol("break visit"),mo=Symbol("skip children"),Ae=Symbol("remove node");function st(s,e){const t=go(e);nt(s)?Tt(null,s.contents,t,Object.freeze([s]))===Ae&&(s.contents=null):Tt(null,s,t,Object.freeze([]))}c(st,"visit$1"),st.BREAK=ce,st.SKIP=mo,st.REMOVE=Ae;function Tt(s,e,t,n){const r=yo(s,e,t,n);if(X(r)||G(r))return wo(s,n,r),Tt(s,r,t,n);if(typeof r!="symbol"){if(Y(e)){n=Object.freeze(n.concat(e));for(let i=0;i<e.items.length;++i){const o=Tt(i,e.items[i],t,n);if(typeof o=="number")i=o-1;else{if(o===ce)return ce;o===Ae&&(e.items.splice(i,1),i-=1)}}}else if(G(e)){n=Object.freeze(n.concat(e));const i=Tt("key",e.key,t,n);if(i===ce)return ce;i===Ae&&(e.key=null);const o=Tt("value",e.value,t,n);if(o===ce)return ce;o===Ae&&(e.value=null)}}return r}c(Tt,"visit_");async function qn(s,e){const t=go(e);nt(s)?await Et(null,s.contents,t,Object.freeze([s]))===Ae&&(s.contents=null):await Et(null,s,t,Object.freeze([]))}c(qn,"visitAsync"),qn.BREAK=ce,qn.SKIP=mo,qn.REMOVE=Ae;async function Et(s,e,t,n){const r=await yo(s,e,t,n);if(X(r)||G(r))return wo(s,n,r),Et(s,r,t,n);if(typeof r!="symbol"){if(Y(e)){n=Object.freeze(n.concat(e));for(let i=0;i<e.items.length;++i){const o=await Et(i,e.items[i],t,n);if(typeof o=="number")i=o-1;else{if(o===ce)return ce;o===Ae&&(e.items.splice(i,1),i-=1)}}}else if(G(e)){n=Object.freeze(n.concat(e));const i=await Et("key",e.key,t,n);if(i===ce)return ce;i===Ae&&(e.key=null);const o=await Et("value",e.value,t,n);if(o===ce)return ce;o===Ae&&(e.value=null)}}return r}c(Et,"visitAsync_");function go(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(go,"initVisitor");function yo(s,e,t,n){if(typeof t=="function")return t(s,e,n);if(vt(e))return t.Map?.(s,e,n);if(kt(e))return t.Seq?.(s,e,n);if(G(e))return t.Pair?.(s,e,n);if(V(e))return t.Scalar?.(s,e,n);if(Ke(e))return t.Alias?.(s,e,n)}c(yo,"callVisitor");function wo(s,e,t){const n=e[e.length-1];if(Y(n))n.items[s]=t;else if(G(n))s==="key"?n.key=t:n.value=t;else if(nt(n))n.contents=t;else{const r=Ke(n)?"alias":"scalar";throw new Error(`Cannot replace node with ${r} parent`)}}c(wo,"replaceNode");const ou={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},au=c(s=>s.replace(/[!,[\]{}]/g,e=>ou[e]),"escapeTagName");class oe{static{c(this,"Directives")}constructor(e,t){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},oe.defaultYaml,e),this.tags=Object.assign({},oe.defaultTags,t)}clone(){const e=new oe(this.yaml,this.tags);return e.docStart=this.docStart,e}atDocument(){const e=new oe(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:oe.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},oe.defaultTags);break}return e}add(e,t){this.atNextDocument&&(this.yaml={explicit:oe.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},oe.defaultTags),this.atNextDocument=!1);const n=e.trim().split(/[ \t]+/),r=n.shift();switch(r){case"%TAG":{if(n.length!==2&&(t(0,"%TAG directive should contain exactly two parts"),n.length<2))return!1;const[i,o]=n;return this.tags[i]=o,!0}case"%YAML":{if(this.yaml.explicit=!0,n.length!==1)return t(0,"%YAML directive should contain exactly one part"),!1;const[i]=n;if(i==="1.1"||i==="1.2")return this.yaml.version=i,!0;{const o=/^\d+\.\d+$/.test(i);return t(6,`Unsupported YAML version ${i}`,o),!1}}default:return t(0,`Unknown directive ${r}`,!0),!1}}tagName(e,t){if(e==="!")return"!";if(e[0]!=="!")return t(`Not a valid tag: ${e}`),null;if(e[1]==="<"){const o=e.slice(2,-1);return o==="!"||o==="!!"?(t(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==">"&&t("Verbatim tags must end with a >"),o)}const[,n,r]=e.match(/^(.*!)([^!]*)$/s);r||t(`The ${e} tag has no suffix`);const i=this.tags[n];if(i)try{return i+decodeURIComponent(r)}catch(o){return t(String(o)),null}return n==="!"?e:(t(`Could not resolve tag: ${e}`),null)}tagString(e){for(const[t,n]of Object.entries(this.tags))if(e.startsWith(n))return t+au(e.substring(n.length));return e[0]==="!"?e:`!<${e}>`}toString(e){const t=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],n=Object.entries(this.tags);let r;if(e&&n.length>0&&X(e.contents)){const i={};st(e.contents,(o,a)=>{X(a)&&a.tag&&(i[a.tag]=!0)}),r=Object.keys(i)}else r=[];for(const[i,o]of n)i==="!!"&&o==="tag:yaml.org,2002:"||(!e||r.some(a=>a.startsWith(o)))&&t.push(`%TAG ${i} ${o}`);return t.join(`
7
- `)}}oe.defaultYaml={explicit:!1,version:"1.2"},oe.defaultTags={"!!":"tag:yaml.org,2002:"};function bo(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(bo,"anchorIsValid");function So(s){const e=new Set;return st(s,{Value(t,n){n.anchor&&e.add(n.anchor)}}),e}c(So,"anchorNames");function Co(s,e){for(let t=1;;++t){const n=`${s}${t}`;if(!e.has(n))return n}}c(Co,"findNewAnchor");function cu(s,e){const t=[],n=new Map;let r=null;return{onAnchor:c(i=>{t.push(i),r??(r=So(s));const o=Co(e,r);return r.add(o),o},"onAnchor"),setAnchors:c(()=>{for(const i of t){const o=n.get(i);if(typeof o=="object"&&o.anchor&&(V(o.node)||Y(o.node)))o.node.anchor=o.anchor;else{const a=new Error("Failed to resolve repeated object (this should not happen)");throw a.source=i,a}}},"setAnchors"),sourceObjects:n}}c(cu,"createNodeAnchors");function _t(s,e,t,n){if(n&&typeof n=="object")if(Array.isArray(n))for(let r=0,i=n.length;r<i;++r){const o=n[r],a=_t(s,n,String(r),o);a===void 0?delete n[r]:a!==o&&(n[r]=a)}else if(n instanceof Map)for(const r of Array.from(n.keys())){const i=n.get(r),o=_t(s,n,r,i);o===void 0?n.delete(r):o!==i&&n.set(r,o)}else if(n instanceof Set)for(const r of Array.from(n)){const i=_t(s,n,r,r);i===void 0?n.delete(r):i!==r&&(n.delete(r),n.add(i))}else for(const[r,i]of Object.entries(n)){const o=_t(s,n,r,i);o===void 0?delete n[r]:o!==i&&(n[r]=o)}return s.call(e,t,n)}c(_t,"applyReviver");function me(s,e,t){if(Array.isArray(s))return s.map((n,r)=>me(n,String(r),t));if(s&&typeof s.toJSON=="function"){if(!t||!po(s))return s.toJSON(e,t);const n={aliasCount:0,count:1,res:void 0};t.anchors.set(s,n),t.onCreate=i=>{n.res=i,delete t.onCreate};const r=s.toJSON(e,t);return t.onCreate&&t.onCreate(r),r}return typeof s=="bigint"&&!t?.keep?Number(s):s}c(me,"toJS");class hr{static{c(this,"NodeBase")}constructor(e){Object.defineProperty(this,pe,{value:e})}clone(){const e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:t,maxAliasCount:n,onAnchor:r,reviver:i}={}){if(!nt(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=me(this,"",o);if(typeof r=="function")for(const{count:l,res:u}of o.anchors.values())r(u,l);return typeof i=="function"?_t(i,{"":a},"",a):a}}class Bn extends hr{static{c(this,"Alias")}constructor(e){super(dr),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=[],st(e,{Node:c((i,o)=>{(Ke(o)||po(o))&&n.push(o)},"Node")}),t&&(t.aliasResolveCache=n));let r;for(const i of n){if(i===this)break;i.anchor===this.source&&(r=i)}return r}toJSON(e,t){if(!t)return{source:this.source};const{anchors:n,doc:r,maxAliasCount:i}=t,o=this.resolve(r,t);if(!o){const l=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(l)}let a=n.get(o);if(a||(me(o,null,t),a=n.get(o)),!a||a.res===void 0){const l="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(l)}if(i>=0&&(a.count+=1,a.aliasCount===0&&(a.aliasCount=Kn(r,o,n)),a.count*a.aliasCount>i)){const l="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(l)}return a.res}toString(e,t,n){const r=`*${this.source}`;if(e){if(bo(this.source),e.options.verifyAliasOrder&&!e.anchors.has(this.source)){const i=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(i)}if(e.implicitKey)return`${r} `}return r}}function Kn(s,e,t){if(Ke(e)){const n=e.resolve(s),r=t&&n&&t.get(n);return r?r.count*r.aliasCount:0}else if(Y(e)){let n=0;for(const r of e.items){const i=Kn(s,r,t);i>n&&(n=i)}return n}else if(G(e)){const n=Kn(s,e.key,t),r=Kn(s,e.value,t);return Math.max(n,r)}return 1}c(Kn,"getAliasCount");const vo=c(s=>!s||typeof s!="function"&&typeof s!="object","isScalarValue");class R extends hr{static{c(this,"Scalar")}constructor(e){super(Ie),this.value=e}toJSON(e,t){return t?.keep?this.value:me(this.value,e,t)}toString(){return String(this.value)}}R.BLOCK_FOLDED="BLOCK_FOLDED",R.BLOCK_LITERAL="BLOCK_LITERAL",R.PLAIN="PLAIN",R.QUOTE_DOUBLE="QUOTE_DOUBLE",R.QUOTE_SINGLE="QUOTE_SINGLE";const lu="tag:yaml.org,2002:";function uu(s,e,t){if(e){const n=t.filter(i=>i.tag===e),r=n.find(i=>!i.format)??n[0];if(!r)throw new Error(`Tag ${e} not found`);return r}return t.find(n=>n.identify?.(s)&&!n.format)}c(uu,"findTagObject");function Gt(s,e,t){if(nt(s)&&(s=s.contents),X(s))return s;if(G(s)){const f=t.schema[Be].createNode?.(t.schema,null,t);return f.items.push(s),f}(s instanceof String||s instanceof Number||s instanceof Boolean||typeof BigInt<"u"&&s instanceof BigInt)&&(s=s.valueOf());const{aliasDuplicateObjects:n,onAnchor:r,onTagObj:i,schema:o,sourceObjects:a}=t;let l;if(n&&s&&typeof s=="object"){if(l=a.get(s),l)return l.anchor??(l.anchor=r(s)),new Bn(l.anchor);l={anchor:null,node:null},a.set(s,l)}e?.startsWith("!!")&&(e=lu+e.slice(2));let u=uu(s,e,o.tags);if(!u){if(s&&typeof s.toJSON=="function"&&(s=s.toJSON()),!s||typeof s!="object"){const f=new R(s);return l&&(l.node=f),f}u=s instanceof Map?o[Be]:Symbol.iterator in Object(s)?o[Ct]:o[Be]}i&&(i(u),delete t.onTagObj);const d=u?.createNode?u.createNode(t.schema,s,t):typeof u?.nodeClass?.from=="function"?u.nodeClass.from(t.schema,s,t):new R(s);return e?d.tag=e:u.default||(d.tag=u.tag),l&&(l.node=d),d}c(Gt,"createNode");function Un(s,e,t){let n=t;for(let r=e.length-1;r>=0;--r){const i=e[r];if(typeof i=="number"&&Number.isInteger(i)&&i>=0){const o=[];o[i]=n,n=o}else n=new Map([[i,n]])}return Gt(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(Un,"collectionFromPath");const zt=c(s=>s==null||typeof s=="object"&&!!s[Symbol.iterator]().next().done,"isEmptyPath");class ko extends hr{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=>X(n)||G(n)?n.clone(e):n),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(zt(e))this.add(t);else{const[n,...r]=e,i=this.get(n,!0);if(Y(i))i.addIn(r,t);else if(i===void 0&&this.schema)this.set(n,Un(this.schema,r,t));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${r}`)}}deleteIn(e){const[t,...n]=e;if(n.length===0)return this.delete(t);const r=this.get(t,!0);if(Y(r))return r.deleteIn(n);throw new Error(`Expected YAML collection at ${t}. Remaining path: ${n}`)}getIn(e,t){const[n,...r]=e,i=this.get(n,!0);return r.length===0?!t&&V(i)?i.value:i:Y(i)?i.getIn(r,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!G(t))return!1;const n=t.value;return n==null||e&&V(n)&&n.value==null&&!n.commentBefore&&!n.comment&&!n.tag})}hasIn(e){const[t,...n]=e;if(n.length===0)return this.has(t);const r=this.get(t,!0);return Y(r)?r.hasIn(n):!1}setIn(e,t){const[n,...r]=e;if(r.length===0)this.set(n,t);else{const i=this.get(n,!0);if(Y(i))i.setIn(r,t);else if(i===void 0&&this.schema)this.set(n,Un(this.schema,r,t));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${r}`)}}}const du=c(s=>s.replace(/^(?!$)(?: $)?/gm,"#"),"stringifyComment");function xe(s,e){return/^\n+$/.test(s)?s.substring(1):e?s.replace(/^(?! *$)/gm,e):s}c(xe,"indentComment");const rt=c((s,e,t)=>s.endsWith(`
2
+ var Uc=Object.defineProperty;var c=(s,e)=>Uc(s,"name",{value:e,configurable:!0});import*as A from"node:fs";import{mkdirSync as Wc,writeFileSync as Jc,readFileSync as Hc}from"node:fs";import*as P from"node:path";import{join as Us,dirname as Vc}from"node:path";import{fileURLToPath as Gc}from"node:url";import k from"chalk";import{Command as zc}from"commander";import{WorkspaceElementType as N,MembraneConfigLoader as Yc,MembraneAxiosInstance as Xc,MembraneClient as Ti,WorkspaceElementSpecs as qe,WorkspaceSyncEventType as Zc,ConnectorFileUpdateType as Ws,getMembraneElementPath as Qc,parseMembraneElementPath as ft,CONNECTOR_VERSION_DEVELOPMENT as Ei,compareWorkspaceExports as el,WorkspaceElementChangeType as ht,setValueAtLocator as Js,extractMembraneErrorData as Ee,getDataCollectionCreateFields as Hs,excludeWriteOnlyFieldsFromSchema as _i,valueToSchema as En,getRequiredFieldsFromSchema as tl,getValueAtLocator as nl,walkSchema as Ii,makeDataLocationPath as Ai,getDataCollectionUpdateFields as Vs}from"@membranehq/sdk";import Gs from"lodash/camelCase.js";import zs from"lodash/upperFirst.js";import sl from"code-block-writer";import rl from"lodash/uniqBy.js";import $e,{createContext as Ys,useState as J,useEffect as Ze,useContext as Xs,useId as il,useRef as Zs,useLayoutEffect as _n,useMemo as ol}from"react";import{Box as C,Text as v,useInput as Qe,render as In,Newline as al}from"ink";import{jsx as m,jsxs as _,Fragment as Jt}from"react/jsx-runtime";import Oi from"swr/immutable";import $i from"os";import q from"path";import cl from"conf";import Qs from"jsonwebtoken";import{AsyncLocalStorage as ll}from"async_hooks";import ul from"lodash/isEqual.js";import Se from"js-yaml";import*as dl from"node:crypto";import{createHash as fl}from"node:crypto";import hl from"chokidar";import{EventEmitter as pl}from"events";import{EventSource as ml}from"eventsource";import B from"fs";import Ni from"archiver";import gl from"form-data";import xi from"unzipper";import*as yl from"node:os";import"node:events";import Pi from"ink-text-input";import{SWRConfig as wl}from"swr";import An from"ink-spinner";import{TextInput as bl,Select as Sl,Spinner as Cl}from"@inkjs/ui";import{FastMCP as vl}from"fastmcp";import Ht from"axios";import{z as W}from"zod";import Mi from"jszip";import{exec as kl}from"node:child_process";import er from"lodash/merge.js";import{faker as Vt}from"@faker-js/faker";import Tl from"lodash/template.js";import El from"lodash/templateSettings.js";function et(s){if(s.type){if(Array.isArray(s.type))return{anyOf:s.type.map(t=>et({...s,type:t}))};if(s.type==="array"){const t={type:"array",items:s.items?et(s.items):{type:"object"}};return s.title&&(t.title=s.title),s.description&&(t.description=s.description),s.minItems!==void 0&&(t.minItems=s.minItems),s.maxItems!==void 0&&(t.maxItems=s.maxItems),s.uniqueItems!==void 0&&(t.uniqueItems=s.uniqueItems),t}}const e={};if(s.type&&!Array.isArray(s.type)&&(e.type=s.type),s.title&&(e.title=s.title),s.description&&(e.description=s.description),s.format&&(e.format=s.format),s.enum&&(e.enum=s.enum),s.default!==void 0&&(e.default=s.default),s.minimum!==void 0&&(e.minimum=s.minimum),s.maximum!==void 0&&(e.maximum=s.maximum),s.minLength!==void 0&&(e.minLength=s.minLength),s.maxLength!==void 0&&(e.maxLength=s.maxLength),s.maxItems!==void 0&&(e.maxItems=s.maxItems),s.readOnly!==void 0&&(e.readOnly=s.readOnly),s.writeOnly!==void 0&&(e.writeOnly=s.writeOnly),s.examples&&s.examples.length>0&&(e.example=s.examples[0]),s.properties){e.properties={};for(const[t,n]of Object.entries(s.properties))e.properties[t]=et(n)}return s.anyOf&&(e.anyOf=s.anyOf.map(et)),s.additionalProperties!==void 0&&(typeof s.additionalProperties=="boolean"?e.additionalProperties=s.additionalProperties:e.additionalProperties=et(s.additionalProperties)),s.required&&(e.required=s.required),e}c(et,"convertDataSchemaToOpenAPI");function _l(s){const{membraneInterfaces:{actions:e}}=s,t=Il(e);return JSON.stringify({openapi:"3.0.0",info:{title:"Membrane Actions API",version:"1.0.0",description:"Generated OpenAPI specification for Membrane actions"},paths:{},components:{schemas:t}},null,2)}c(_l,"generateOpenAPIContent");function Il(s){const e={};return s.forEach(t=>{const n=zs(Gs(t.key)),r={type:"object",properties:{id:{type:"string",description:"Request ID"},action:{type:"string",enum:[t.key]}},required:["id","action"]};if(t?.inputSchema){const a=et(t.inputSchema);a.properties&&(r.properties={...r.properties,...a.properties}),a.required&&(r.required=[...r.required||[],...a.required])}e[`${n}Request`]=r;const i={type:"object",properties:{id:{type:"string",description:"Response ID"},success:{type:"boolean"},data:{type:"object"}},required:["id","success"]},o=t?.customOutputSchema||t?.outputSchema;if(o){const a=et(o);i.properties={...i.properties,data:a}}e[`${n}Response`]=i}),e}c(Il,"generateOpenAPISchemas");function Al(s){const{membraneInterfaces:{actions:e}}=s,t=rl(e,"key"),n=new sl({indentNumberOfSpaces:2,newLine:`
3
+ `});return n.writeLine("// Generated TypeScript definitions for Membrane actions"),n.newLine(),n.writeLine("import type {"),n.writeLine(" ActionAccessor,"),n.writeLine(" ConnectionLevelActionAccessor,"),n.writeLine('} from "@membranehq/sdk";'),n.newLine(),Ol(n,t),n.toString()}c(Al,"generateTypeScriptContent");function Ol(s,e){s.writeLine('declare module "@membranehq/sdk" {'),s.indent(()=>{e.forEach(t=>{const n=nr(t),r=t?.inputSchema;On(s,{interfaceName:n,properties:r?.properties,required:r?.required||[]});const i=sr(t),o=t?.customOutputSchema||t?.outputSchema;On(s,{interfaceName:i,properties:o?.properties,required:o?.required||[],fallbackContent:"result: unknown"}),s.newLine()}),On(s,{interfaceName:"MembraneClient",methods:e.map(t=>{const n=nr(t),r=sr(t);return{name:"action",parameters:`selector: "${t.key}"`,returnType:`ActionAccessor<${n}, ${r}>`}})}),s.newLine(),On(s,{interfaceName:"ConnectionAccessor",methods:e.map(t=>{const n=nr(t),r=sr(t);return{name:"action",parameters:`selector: "${t.key}"`,returnType:`ConnectionLevelActionAccessor<${n}, ${r}>`}})})}),s.writeLine("}")}c(Ol,"generateModuleAugmentation");function On(s,e){const{interfaceName:t,properties:n,required:r=[],methods:i,fallbackContent:o}=e;s.writeLine(`interface ${t} {`),s.indent(()=>{n&&Object.keys(n).length>0&&$l(s,n,r),i&&i.length>0&&(n&&Object.keys(n).length>0&&s.newLine(),i.forEach((a,l)=>{s.writeLine(`${a.name}(${a.parameters}): ${a.returnType};`),l<i.length-1&&s.newLine()})),o&&(!n||Object.keys(n).length===0)&&(!i||i.length===0)&&s.writeLine(o)}),s.writeLine("}")}c(On,"generateTypeScriptInterface");function $l(s,e,t){Object.entries(e).forEach(([n,r])=>{const o=t.includes(n)?"":"?",a=tr(r);s.writeLine(`readonly ${n}${o}: ${a}`)})}c($l,"generateTypeScriptProperties");function tr(s){return s.type==="string"?s.enum?s.enum.map(e=>`'${e}'`).join(" | "):"string":s.type==="number"||s.type==="integer"?"number":s.type==="boolean"?"boolean":s.type==="array"?`${s.items?tr(s.items):"unknown"}[]`:s.type==="object"?s.properties?`{ ${Object.entries(s.properties).map(([t,n])=>{const i=(s.required||[]).includes(t)?"":"?",o=tr(n);return`readonly ${t}${i}: ${o}`}).join("; ")} }`:"Record<string, unknown>":"unknown"}c(tr,"convertJsonSchemaToTypeScript");function nr(s){return`${zs(Gs(s.key))}Input`}c(nr,"getInputTypeName");function sr(s){return`${zs(Gs(s.key))}Output`}c(sr,"getOutputTypeName");async function rr(s){const{out:e}=s;await A.promises.mkdir(e,{recursive:!0});const t=Nl(s);for(const[n,r]of Object.entries(t)){const i=P.join(e,n);await A.promises.writeFile(i,r,"utf-8")}}c(rr,"generateCode");function Nl(s){switch(s.target){case"openapi":return{"openapi.json":_l(s)};case"typescript":return{"generated.d.ts":Al(s)};default:throw new Error(`Unsupported target: ${s.target}`)}}c(Nl,"generateContent");const ir=c(()=>[k.yellow("\u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510"),k.yellow("\u2502 \u26A0\uFE0F EXPERIMENTAL FEATURE WARNING \u2502"),k.yellow("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524"),k.yellow("\u2502 The codegen command is experimental and subject to rapid changes.\u2502"),k.yellow("\u2502 Features, APIs, and file structures may change without notice. \u2502"),k.yellow("\u2502 Use in production environments is not recommended. \u2502"),k.yellow("\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518"),""].join(`
4
+ `),"createExperimentalWarning$2");function xl(s,e){s.command("codegen").description("\u26A0\uFE0F EXPERIMENTAL: Generate code for easy integration within projects - This feature is experimental and will be changing rapidly. Use at your own risk.").requiredOption("--actions <actions>",'Comma-separated list of action names (e.g., "list-files,get-file-by-id")').requiredOption("--out <path>","Output directory for generated files").requiredOption("--target <type>","Target format: openapi or typescript").requiredOption("--schemasOnly","Generate only schemas without implementation").addHelpText("after",ir()).addHelpText("after",["",k.bold("Examples:"),` ${k.gray("\u25B8")} ${k.cyan("membrane codegen --actions list-files,get-file-by-id --out src/generated --target openapi --schemasOnly")}`,` ${k.gray("\u25B8")} ${k.cyan("membrane install --actions delete-file --out src/generated --target typescript --schemasOnly")}`,"",ir()].join(`
5
+ `)).action(async t=>{try{console.warn(ir()),console.error(k.cyan("\u{1F527} Membrane Codegen")),console.error("Status: Loading membrane interfaces...");const n=await Pl(e,t),r={out:t.out,target:t.target,schemasOnly:t.schemasOnly,membraneInterfaces:n};console.error(`Output: ${r.out}`),console.error(`Target: ${r.target}`),console.error(`Schemas Only: ${r.schemasOnly?"Yes":"No"}`),console.error(`Loaded ${n.actions.length} membrane interfaces`),console.error("Status: Generating code..."),await rr(r),console.error(k.green("\u2705 Code generation completed successfully!")),process.exit(0)}catch(n){console.error(k.red("\u274C Code generation failed:")),console.error(n instanceof Error?n.message:"Unknown error occurred"),process.exit(1)}})}c(xl,"setupCodegenCommand");async function Pl(s,e){return await s.fetchElements(),{actions:[...s.getSyncedElementsByType(N.Action).map(t=>t.data)].filter(t=>e.actions.includes(t.key||""))}}c(Pl,"loadMembraneInterfaces");const Ml="membrane",Rl="membrane.config.yml",or="https://api.integration.app";function ar(){const s=process.cwd(),e=P.join(s,Ml),t=P.join(s,Rl),n=e,r=P.join(n,"workspace.yaml");return{membraneDirPath:e,configPath:t,payloadDirPath:n,workspaceDataFilePath:r}}c(ar,"getPaths");function Ri(){return ar().membraneDirPath}c(Ri,"getBasePath");const Ll={pat:{type:"string"},workspace:{type:"object"}},Li=new cl({schema:Ll,configName:"config",cwd:q.join($i.homedir(),".membrane")}),Dl=c(s=>{Li.set("pat",s)},"setPat"),Di=c(()=>Li.get("pat"),"getPat");class ji{static{c(this,"AccountApiClient")}constructor(e=or){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=Di();if(!o)throw new Error("Personal Access Token not found.");n.set("Authorization",`Bearer ${o}`)}t.body&&!n.has("Content-Type")&&n.set("Content-Type","application/json");const r=await fetch(`${this.apiBaseUrl}${e}`,{...t,headers:n});if(!r.ok){const o=await r.text();throw new Error(`API request failed: ${r.status} ${r.statusText} - ${o}`)}if(r.status===204)return{};const i=await r.text();return JSON.parse(i)}get(e){return this.request(e,{method:"GET"})}post(e,t){return this.request(e,{method:"POST",body:JSON.stringify(t)})}put(e,t){return this.request(e,{method:"PUT",body:JSON.stringify(t)})}patch(e,t){return this.request(e,{method:"PATCH",body:JSON.stringify(t)})}delete(e){return this.request(e,{method:"DELETE"})}}const jl=c(s=>{const e=new ji(or);return t=>e.get(t)},"createAccountApiFetcher");class Bt{static{c(this,"ConfigLoader")}static instance=null;sdkLoader;constructor(){this.sdkLoader=new Yc}static getInstance(){return Bt.instance||(Bt.instance=new Bt),Bt.instance}loadConfig(e){e&&e!==this.sdkLoader.getCwd()&&this.sdkLoader.setCwd(e);try{return this.sdkLoader.loadConfig({validate:!0})}catch(t){if(t.message?.includes("Failed to parse"))throw t;return null}}clearCache(){this.sdkLoader.clearCache()}updateConfig(e){return this.sdkLoader.updateConfig(e)}saveToFile(e){return this.sdkLoader.saveToFile(e)}isCacheDefined(){return this.sdkLoader.hasValidConfig()}}const tt=Bt.getInstance();function $n(s){return tt.loadConfig(s)}c($n,"readProjectConfig");const Fl="membrane",ql=["**/node_modules/**","**/.git/**","**/.DS_Store","**/Thumbs.db","**/*.tmp","**/*.swp","**/*.swo","**/*.log","**/*.lock","**/.cache/**","**/.next/**","**/.vscode/**","**/.idea/**","**/.logs/**"];function he(s){return P.join(s,Fl)}c(he,"getMembraneDir");const Fi=Us(he(process.cwd()),".logs");class Bl{static{c(this,"WorkspaceLogger")}_logs;verboseMode=!1;notificationHandler=null;constructor(){this._logs=[]}setNotificationHandler(e){this.notificationHandler=e}setVerboseMode(e){this.verboseMode=e}getVerboseMode(){return this.verboseMode}get logs(){return[...this._logs]}get latestLogs(){return this._logs.slice(this._logs.length-5)}log(e,t="info"){const n={timestamp:new Date().toISOString(),message:e,type:t};this._logs.push(n),this._logs=this._logs.slice(0,1e3),(t!=="debug"||this.verboseMode)&&this.notificationHandler&&this.notificationHandler.addLog(n)}info(e){this.log(e,"info")}success(e){this.log(e,"success")}warning(e){this.log(e,"warning")}error(e){this.log(e,"error")}debug(e){this.log(e,"debug")}clear(){this._logs=[]}saveLogsToFile(e){if(this._logs.length===0)return null;try{const t=new Date().toISOString().replace(/[:.]/g,"_"),n=e?`-${e}`:"",r=`${t}${n}.txt`;Wc(Fi,{recursive:!0});const i=Us(Fi,r),o=this._logs.map(a=>`[${a.timestamp}] ${a.type?.toUpperCase()||"INFO"}: ${a.message}`).join(`
6
+ `);return Jc(i,o,"utf-8"),i}catch(t){return console.error("Failed to save logs:",t),null}}}const b=new Bl,qi=new ll;class Bi{static{c(this,"RequestLogger")}constructor(e=Xc){this.axiosInstance=e}interceptorsConfigured=!1;setup(){if(this.interceptorsConfigured)return;const e=c(t=>(this.logError(t),Promise.reject(t)),"errorHandler");this.axiosInstance.interceptors.request.use(t=>{const n=qi.getStore();t.metadata={startTime:Date.now(),skipErrorLog:n};const{method:r,url:i}=this.getRequestDetails(t);return b.debug(`[Request]: ${r} ${i}`),t},e),this.axiosInstance.interceptors.response.use(t=>{const{method:n,url:r}=this.getRequestDetails(t.config),i=this.getDuration(t.config),{status:o,statusText:a}=t;return b.debug(`[Response]: ${n} ${r} - ${o} ${a} (${i}ms)`),t},e),this.interceptorsConfigured=!0}static withSkipErrorLog(e){return qi.run(!0,e)}getRequestDetails(e){const t=e?.method?.toUpperCase()??"UNKNOWN";if(!e?.url)return{method:t,url:"unknown"};if(e.url.startsWith("http"))return{method:t,url:e.url};const r=`${e.baseURL??""}/${e.url}`.replace(/\/+/g,"/").replace(/:\//,"://");return{method:t,url:r}}getDuration(e){return Date.now()-(e?.metadata?.startTime??Date.now())}logError(e){if(e.config?.metadata?.skipErrorLog)return;const{method:t,url:n}=this.getRequestDetails(e.config),r=this.getDuration(e.config);if(e.response){const{status:i,statusText:o}=e.response;b.error(`[Response]: ${t} ${n} - ${i} ${o} (${r}ms)`),e.response.data&&b.error(`[Response Data]: ${JSON.stringify(e.response.data,null,2)}`)}}}class Kl{static{c(this,"MembraneAPIManager")}client=null;currentConfig=null;tokenExpiry=0;requestTimes=[];maxRequestsPerSecond=80;windowSizeMs=1e3;semaphore=0;maxConcurrentRequests;maxRetries;retryDelay;requestTimeout;enableJitter;semaphoreQueue=[];rateLimitMutex=Promise.resolve();requestLogger=null;constructor(e={}){this.init(e)}init(e={}){this.windowSizeMs=e.windowSizeMs??1e3,this.maxRequestsPerSecond=e.maxRequestsPerSecond??80,this.maxConcurrentRequests=e.maxConcurrentRequests??Math.max(1,Math.min(Math.floor(this.maxRequestsPerSecond/4),20)),this.maxRetries=e.maxRetries??3,this.retryDelay=e.retryDelay??1e3,this.requestTimeout=e.requestTimeout??12e4,this.enableJitter=e.enableJitter!==!1,this.requestLogger=new Bi,this.requestLogger.setup()}async withClient(e,t=!0,n=process.cwd()){const r=c(async()=>{try{return await this.withRetry(async()=>{const i=await this.getClient(n);await this.acquireSemaphore();try{return await this.waitIfNeeded(),this.recordRequest(),await this.withTimeout(e(i),this.requestTimeout)}finally{this.releaseSemaphore()}},"API request")}catch(i){if(t)throw i;return}},"executeRequest");return t?r():Bi.withSkipErrorLog(r)}async generateAccessToken(e,t){return Qs.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=$n(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 Ti({token:t,apiUri:e.apiUri})}async getClient(e=process.cwd()){const t=this.getCurrentConfig(e);if(!t)throw new Error("Unable to create MembraneClient: No workspace configuration found.");const n=!this.currentConfig||this.currentConfig.workspaceKey!==t.workspaceKey||this.currentConfig.workspaceSecret!==t.workspaceSecret||this.currentConfig.apiUri!==t.apiUri,r=!this.isTokenValid()||this.tokenExpiry-Date.now()<3e5;return(!this.client||n||r)&&(this.client=await this.createClient(t)),this.client}clearClient(){this.client=null,this.currentConfig=null,this.tokenExpiry=0,this.requestTimes=[],this.semaphore=0,this.semaphoreQueue=[],this.rateLimitMutex=Promise.resolve()}getCurrentConfigInfo(){return this.currentConfig}async waitIfNeeded(){this.rateLimitMutex=this.rateLimitMutex.then(async()=>{for(this.cleanOldRequests();this.requestTimes.length>=this.maxRequestsPerSecond;){const t=this.requestTimes[0]+this.windowSizeMs-Date.now()+10;if(t>0)await new Promise(n=>setTimeout(n,t)),this.cleanOldRequests();else break}}),await this.rateLimitMutex}recordRequest(){this.requestTimes.push(Date.now())}cleanOldRequests(){const e=Date.now()-this.windowSizeMs;this.requestTimes=this.requestTimes.filter(t=>t>e)}getRequestCount(){return this.cleanOldRequests(),this.requestTimes.length}async acquireSemaphore(){if(this.semaphore<this.maxConcurrentRequests){this.semaphore++;return}return new Promise(e=>{this.semaphoreQueue.push(e)})}releaseSemaphore(){if(this.semaphore--,this.semaphoreQueue.length>0){const e=this.semaphoreQueue.shift();this.semaphore++,e()}}async withRetry(e,t="operation"){let n;for(let r=0;r<=this.maxRetries;r++)try{return await e()}catch(i){if(n=i,!this.isRetryableError(i)||r===this.maxRetries)throw i;const o=new Date().toISOString(),a=r+2;b.debug(`[${o}] Retrying ${t} (attempt ${a}/${this.maxRetries+1})`);let l=this.retryDelay*Math.pow(2,r);if(this.enableJitter){const u=l*.25*(Math.random()*2-1);l=Math.max(0,l+u)}await new Promise(u=>setTimeout(u,l))}throw n||new Error("Unknown error occurred during retry attempts")}isRetryableError(e){if(!e)return!1;const t=(e.message||e.toString()||"").toLowerCase(),n=e.code;return n&&["econnrefused","enotfound","econnreset","etimedout","ehostunreach","enetunreach"].includes(n.toLowerCase())?!0:["econnrefused","connection refused","network error","timeout","socket hang up","request timeout","dns lookup failed"].some(o=>t.includes(o))}async withTimeout(e,t){let n;const r=new Promise((i,o)=>{n=setTimeout(()=>o(new Error(`Request timeout after ${t}ms`)),t)});try{const i=await Promise.race([e,r]);return n&&clearTimeout(n),i}catch(i){throw n&&clearTimeout(n),i}}}const K=new Kl;async function Ki(s){const e=await K.withClient(t=>t.get("org-workspace-id"),!0,s);if(!e)throw new Error("Failed to get workspace ID");return e.id}c(Ki,"getWorkspaceId");var U={},Nn={},Ui;function Wi(){if(Ui)return Nn;Ui=1,Object.defineProperty(Nn,"__esModule",{value:!0});function s(e){return e===void 0&&(e=""),e?String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/[^A-Za-z0-9]+/g,"$").replace(/([a-z])([A-Z])/g,function(t,n,r){return n+"$"+r}).toLowerCase().replace(/(\$)(\w)/g,function(t,n,r){return r.toUpperCase()}):""}return c(s,"toCamelCase"),Nn.default=s,Nn}c(Wi,"requireJsCamelcase");var xn={},Ji;function Hi(){if(Ji)return xn;Ji=1,Object.defineProperty(xn,"__esModule",{value:!0});function s(e){return e===void 0&&(e=""),e?String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/([a-z])([A-Z])/g,function(t,n,r){return n+"_"+r.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g,"_").toLowerCase():""}return c(s,"toSnakeCase"),xn.default=s,xn}c(Hi,"requireJsSnakecase");var Pn={},Vi;function Gi(){if(Vi)return Pn;Vi=1,Object.defineProperty(Pn,"__esModule",{value:!0});function s(e){return e===void 0&&(e=""),e?String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"$").replace(/[^A-Za-z0-9]+/g,"$").replace(/([a-z])([A-Z])/g,function(t,n,r){return n+"$"+r}).toLowerCase().replace(/(\$)(\w?)/g,function(t,n,r){return r.toUpperCase()}):""}return c(s,"toPascalCase"),Pn.default=s,Pn}c(Gi,"requireJsPascalcase");var Mn={},zi;function Ul(){if(zi)return Mn;zi=1,Object.defineProperty(Mn,"__esModule",{value:!0});function s(e){return e===void 0&&(e=""),e?String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/([a-z])([A-Z])/g,function(t,n,r){return n+"_"+r.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g,".").toLowerCase():""}return c(s,"toDotCase"),Mn.default=s,Mn}c(Ul,"requireJsDotcase");var Rn={},Yi;function Wl(){if(Yi)return Rn;Yi=1,Object.defineProperty(Rn,"__esModule",{value:!0});function s(e){return e===void 0&&(e=""),e?String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/([a-z])([A-Z])/g,function(t,n,r){return n+"_"+r.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g,"/").toLowerCase():""}return c(s,"toPathCase"),Rn.default=s,Rn}c(Wl,"requireJsPathcase");var Ln={},Xi;function Jl(){if(Xi)return Ln;Xi=1,Object.defineProperty(Ln,"__esModule",{value:!0});function s(e){return e===void 0&&(e=""),e?String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/([a-z])([A-Z])/g,function(t,n,r){return n+"_"+r.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g," ").toLowerCase():""}return c(s,"toTextCase"),Ln.default=s,Ln}c(Jl,"requireJsTextcase");var Dn={},Zi;function Hl(){if(Zi)return Dn;Zi=1,Object.defineProperty(Dn,"__esModule",{value:!0});function s(e){if(e===void 0&&(e=""),!e)return"";var t=String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/([a-z])([A-Z])/g,function(n,r,i){return r+"_"+i.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g," ").toLowerCase();return t.charAt(0).toUpperCase()+t.slice(1)}return c(s,"toSentenceCase"),Dn.default=s,Dn}c(Hl,"requireJsSentencecase");var jn={},Qi;function Vl(){if(Qi)return jn;Qi=1,Object.defineProperty(jn,"__esModule",{value:!0});function s(e){return e===void 0&&(e=""),e?String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/([a-z])([A-Z])/g,function(t,n,r){return n+"_"+r.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g," ").toLowerCase().replace(/( ?)(\w+)( ?)/g,function(t,n,r,i){return n+r.charAt(0).toUpperCase()+r.slice(1)+i}):""}return c(s,"toHeaderCase"),jn.default=s,jn}c(Vl,"requireJsHeadercase");var Fn={},eo;function to(){if(eo)return Fn;eo=1,Object.defineProperty(Fn,"__esModule",{value:!0});function s(e){return e===void 0&&(e=""),e?String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/([a-z])([A-Z])/g,function(t,n,r){return n+"_"+r.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g,"-").toLowerCase():""}return c(s,"toKebabCase"),Fn.default=s,Fn}c(to,"requireJsKebabcase");var pt={},cr={},no;function mt(){return no||(no=1,function(s){Object.defineProperty(s,"__esModule",{value:!0}),s.belongToTypes=s.isValidObject=s.isArrayObject=s.validateOptions=s.DefaultOption=void 0,s.DefaultOption={recursive:!1,recursiveInArray:!1,keepTypesOnRecursion:[]},s.validateOptions=function(e){return e===void 0&&(e=s.DefaultOption),e.recursive==null?e=s.DefaultOption:e.recursiveInArray==null&&(e.recursiveInArray=!1),e},s.isArrayObject=function(e){return e!=null&&Array.isArray(e)},s.isValidObject=function(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)},s.belongToTypes=function(e,t){return(t||[]).some(function(n){return e instanceof n})}}(cr)),cr}c(mt,"requireUtils");var so;function Gl(){if(so)return pt;so=1;var s=pt&&pt.__spreadArrays||function(){for(var n=0,r=0,i=arguments.length;r<i;r++)n+=arguments[r].length;for(var o=Array(n),a=0,r=0;r<i;r++)for(var l=arguments[r],u=0,d=l.length;u<d;u++,a++)o[a]=l[u];return o};Object.defineProperty(pt,"__esModule",{value:!0});var e=mt();function t(n,r){if(r===void 0&&(r=e.DefaultOption),!e.isValidObject(n))return null;r=e.validateOptions(r);var i={};return Object.keys(n).forEach(function(o){var a=n[o],l=o.toLowerCase();r.recursive&&(e.isValidObject(a)?e.belongToTypes(a,r.keepTypesOnRecursion)||(a=t(a,r)):r.recursiveInArray&&e.isArrayObject(a)&&(a=s(a).map(function(u){var d=u;if(e.isValidObject(u))e.belongToTypes(d,r.keepTypesOnRecursion)||(d=t(u,r));else if(e.isArrayObject(u)){var f=t({key:u},r);d=f.key}return d}))),i[l]=a}),i}return c(t,"lowerKeys"),pt.default=t,pt}c(Gl,"requireLowercaseKeysObject");var gt={},ro;function zl(){if(ro)return gt;ro=1;var s=gt&&gt.__spreadArrays||function(){for(var n=0,r=0,i=arguments.length;r<i;r++)n+=arguments[r].length;for(var o=Array(n),a=0,r=0;r<i;r++)for(var l=arguments[r],u=0,d=l.length;u<d;u++,a++)o[a]=l[u];return o};Object.defineProperty(gt,"__esModule",{value:!0});var e=mt();function t(n,r){if(r===void 0&&(r=e.DefaultOption),!e.isValidObject(n))return null;r=e.validateOptions(r);var i={};return Object.keys(n).forEach(function(o){var a=n[o],l=o.toUpperCase();r.recursive&&(e.isValidObject(a)?e.belongToTypes(a,r.keepTypesOnRecursion)||(a=t(a,r)):r.recursiveInArray&&e.isArrayObject(a)&&(a=s(a).map(function(u){var d=u;if(e.isValidObject(u))e.belongToTypes(d,r.keepTypesOnRecursion)||(d=t(u,r));else if(e.isArrayObject(u)){var f=t({key:u},r);d=f.key}return d}))),i[l]=a}),i}return c(t,"upperKeys"),gt.default=t,gt}c(zl,"requireUppercaseKeysObject");var yt={},io;function Yl(){if(io)return yt;io=1;var s=yt&&yt.__spreadArrays||function(){for(var r=0,i=0,o=arguments.length;i<o;i++)r+=arguments[i].length;for(var a=Array(r),l=0,i=0;i<o;i++)for(var u=arguments[i],d=0,f=u.length;d<f;d++,l++)a[l]=u[d];return a};Object.defineProperty(yt,"__esModule",{value:!0});var e=mt(),t=Wi();function n(r,i){if(i===void 0&&(i=e.DefaultOption),!e.isValidObject(r))return null;i=e.validateOptions(i);var o={};return Object.keys(r).forEach(function(a){var l=r[a],u=t.default(a);i.recursive&&(e.isValidObject(l)?e.belongToTypes(l,i.keepTypesOnRecursion)||(l=n(l,i)):i.recursiveInArray&&e.isArrayObject(l)&&(l=s(l).map(function(d){var f=d;if(e.isValidObject(d))e.belongToTypes(f,i.keepTypesOnRecursion)||(f=n(d,i));else if(e.isArrayObject(d)){var h=n({key:d},i);f=h.key}return f}))),o[u]=l}),o}return c(n,"camelKeys"),yt.default=n,yt}c(Yl,"requireCamelcaseKeysObject");var wt={},oo;function Xl(){if(oo)return wt;oo=1;var s=wt&&wt.__spreadArrays||function(){for(var r=0,i=0,o=arguments.length;i<o;i++)r+=arguments[i].length;for(var a=Array(r),l=0,i=0;i<o;i++)for(var u=arguments[i],d=0,f=u.length;d<f;d++,l++)a[l]=u[d];return a};Object.defineProperty(wt,"__esModule",{value:!0});var e=mt(),t=Hi();function n(r,i){if(i===void 0&&(i=e.DefaultOption),!e.isValidObject(r))return null;i=e.validateOptions(i);var o={};return Object.keys(r).forEach(function(a){var l=r[a],u=t.default(a);i.recursive&&(e.isValidObject(l)?e.belongToTypes(l,i.keepTypesOnRecursion)||(l=n(l,i)):i.recursiveInArray&&e.isArrayObject(l)&&(l=s(l).map(function(d){var f=d;if(e.isValidObject(d))e.belongToTypes(f,i.keepTypesOnRecursion)||(f=n(d,i));else if(e.isArrayObject(d)){var h=n({key:d},i);f=h.key}return f}))),o[u]=l}),o}return c(n,"snakeKeys"),wt.default=n,wt}c(Xl,"requireSnakecaseKeysObject");var bt={},ao;function Zl(){if(ao)return bt;ao=1;var s=bt&&bt.__spreadArrays||function(){for(var r=0,i=0,o=arguments.length;i<o;i++)r+=arguments[i].length;for(var a=Array(r),l=0,i=0;i<o;i++)for(var u=arguments[i],d=0,f=u.length;d<f;d++,l++)a[l]=u[d];return a};Object.defineProperty(bt,"__esModule",{value:!0});var e=mt(),t=Gi();function n(r,i){if(i===void 0&&(i=e.DefaultOption),!e.isValidObject(r))return null;i=e.validateOptions(i);var o={};return Object.keys(r).forEach(function(a){var l=r[a],u=t.default(a);i.recursive&&(e.isValidObject(l)?e.belongToTypes(l,i.keepTypesOnRecursion)||(l=n(l,i)):i.recursiveInArray&&e.isArrayObject(l)&&(l=s(l).map(function(d){var f=d;if(e.isValidObject(d))e.belongToTypes(f,i.keepTypesOnRecursion)||(f=n(d,i));else if(e.isArrayObject(d)){var h=n({key:d},i);f=h.key}return f}))),o[u]=l}),o}return c(n,"pascalKeys"),bt.default=n,bt}c(Zl,"requirePascalcaseKeysObject");var St={},co;function Ql(){if(co)return St;co=1;var s=St&&St.__spreadArrays||function(){for(var r=0,i=0,o=arguments.length;i<o;i++)r+=arguments[i].length;for(var a=Array(r),l=0,i=0;i<o;i++)for(var u=arguments[i],d=0,f=u.length;d<f;d++,l++)a[l]=u[d];return a};Object.defineProperty(St,"__esModule",{value:!0});var e=mt(),t=to();function n(r,i){if(i===void 0&&(i=e.DefaultOption),!e.isValidObject(r))return null;i=e.validateOptions(i);var o={};return Object.keys(r).forEach(function(a){var l=r[a],u=t.default(a);i.recursive&&(e.isValidObject(l)?e.belongToTypes(l,i.keepTypesOnRecursion)||(l=n(l,i)):i.recursiveInArray&&e.isArrayObject(l)&&(l=s(l).map(function(d){var f=d;if(e.isValidObject(d))e.belongToTypes(f,i.keepTypesOnRecursion)||(f=n(d,i));else if(e.isArrayObject(d)){var h=n({key:d},i);f=h.key}return f}))),o[u]=l}),o}return c(n,"kebabKeys"),St.default=n,St}c(Ql,"requireKebabcaseKeysObject");var lo;function eu(){if(lo)return U;lo=1,Object.defineProperty(U,"__esModule",{value:!0}),U.kebabKeys=U.pascalKeys=U.snakeKeys=U.camelKeys=U.upperKeys=U.lowerKeys=U.toLowerCase=U.toUpperCase=U.toKebabCase=U.toHeaderCase=U.toSentenceCase=U.toTextCase=U.toPathCase=U.toDotCase=U.toPascalCase=U.toSnakeCase=U.toCamelCase=void 0;var s=Wi();U.toCamelCase=s.default;var e=Hi();U.toSnakeCase=e.default;var t=Gi();U.toPascalCase=t.default;var n=Ul();U.toDotCase=n.default;var r=Wl();U.toPathCase=r.default;var i=Jl();U.toTextCase=i.default;var o=Hl();U.toSentenceCase=o.default;var a=Vl();U.toHeaderCase=a.default;var l=to();U.toKebabCase=l.default;var u=Gl();U.lowerKeys=u.default;var d=zl();U.upperKeys=d.default;var f=Yl();U.camelKeys=f.default;var h=Xl();U.snakeKeys=h.default;var g=Zl();U.pascalKeys=g.default;var y=Ql();U.kebabKeys=y.default;var p=c(function(E){return String(E||"").toLowerCase()},"toLowerCase");U.toLowerCase=p;var w=c(function(E){return String(E||"").toUpperCase()},"toUpperCase");U.toUpperCase=w;var T={toCamelCase:s.default,toSnakeCase:e.default,toPascalCase:t.default,toDotCase:n.default,toPathCase:r.default,toTextCase:i.default,toSentenceCase:o.default,toHeaderCase:a.default,toKebabCase:l.default,toUpperCase:w,toLowerCase:p,lowerKeys:u.default,upperKeys:d.default,camelKeys:f.default,snakeKeys:h.default,pascalKeys:g.default,kebabKeys:y.default};return U.default=T,U}c(eu,"requireLib");var lr,uo;function tu(){return uo||(uo=1,lr=eu()),lr}c(tu,"requireJsConvertCase");var nu=tu();const Ne={UPDATE:"update",DELETE:"delete",CREATE:"create"},ae={INCOMING:"incoming",OUTGOING:"outgoing"},_e={[N.Integration]:{element:"integration",elements:"integrations",exportable:!1,exportCleanup:c(s=>({id:s.id,key:s.key,name:s.name,connectorId:s.connectorId,baseUri:s.baseUri,connectorVersion:s.connectorVersion}),"exportCleanup")},[N.Connector]:{element:"connector",elements:"connectors",exportable:!1},[N.Action]:{element:"action",elements:"actions",integrationSpecific:!0,exportCleanup:c(s=>(delete s.integration,s),"exportCleanup")},[N.AppDataSchema]:{element:"appDataSchema",elements:"appDataSchemas"},[N.AppEventType]:{element:"appEventType",elements:"appEventTypes"},[N.DataLinkTable]:{element:"dataLinkTable",elements:"dataLinkTables"},[N.DataSource]:{element:"dataSource",elements:"dataSources",parentKey:"universalDataSourceId",integrationSpecific:!0},[N.FieldMapping]:{element:"fieldMapping",elements:"fieldMappings",integrationSpecific:!0,parentKey:"universalFieldMappingId",exportCleanup:c(s=>(delete s.dataSourceId,s),"exportCleanup")},[N.Flow]:{element:"flow",elements:"flows",integrationSpecific:!0,parentKey:"universalFlowId"},[N.Package]:{element:"package",elements:"packages",integrationSpecific:!0}},su=["id","workspaceId","integrationId","createdAt","updatedAt","revision","archivedAt","baseUri","state","appliedToIntegrations","dependencies"],fo=[N.Action,N.FieldMapping,N.Flow,N.DataSource,N.Package];class Z{static{c(this,"Element")}type;key;integrationKey;data;constructor(e,t,n,r){if(!r)throw new Error("Element must always contain data");if(!t)throw new Error("Element must have a key");this.type=e,this.key=t,this.data=r,this.integrationKey=n||Z.extractIntegrationKey(r)}get id(){return Z.makeId(this.type,this.key,this.integrationKey)}get dirPath(){const e=qe[this.type].apiPath;if(this.integrationKey){const t=qe[N.Integration].apiPath;return P.join(t,this.integrationKey,e,this.key)}return P.join(e,this.key)}get path(){return P.join(this.dirPath,"spec.yaml")}get relativePath(){return P.relative(he(process.cwd()),this.path)}get absolutePath(){return P.resolve(P.join(he(process.cwd()),this.path))}isEqual(e){if(this.id!==e.id)return!1;const t=this.clean(),n=e.clean();return ul(t,n)}hasParent(){if(this.data?.parentUuid)return!0;const e=this.getParentKey();return!!e&&!!this.data?.[e]}clean(){const e={...this.data};return su.forEach(t=>{delete e[t]}),Object.keys(e).forEach(t=>{t.match(/universal.*Revision/)&&delete e[t]}),e}getParentKey(){let e="parentId";return _e?.[this.type]?.parentKey&&(e=_e?.[this.type]?.parentKey),e}static new(e,t,n,r){return new Z(e,t,n,r)}static fromData(e,t){if(!t?.key)throw new Error(`Element missing key: ${JSON.stringify(t)}`);const n=this.extractIntegrationKey(t);return new Z(e,t.key,n,t)}static fromPathAndData(e,t){const n=Z.parsePath(e);if(!t)return;const r=t?.key||n?.key;return n?Z.new(n.type,r,n.integrationKey,t):void 0}static fromElement(e){return new Z(e.type,e.key,e.integrationKey,{...e.data})}static idFromPath(e){const t=Z.parsePath(e);if(t)return Z.makeId(t.type,t.key,t.integrationKey)}static makeId(e,t,n){return e===N.Integration?`${e}:${t}`:Z.isIntegrationSpecific(e)?`${n||"universal"}:${e}:${t}`:`${e}:${t}`}static parsePath(e){const t=this.getRelativePath(e);if(!this.isElementFile(t))return;const n=Object.values(qe).map(l=>l.apiPath).join("|"),r=new RegExp(`^(?<elementType>${n})/(?<elementKey>[^/]+)/spec\\.ya?ml$`),i=t.match(r);if(i?.groups){const{elementType:l,elementKey:u}=i.groups,d=this.getElementTypeFromPath(l);if(d)return{type:d,key:u}}const o=new RegExp(`^integrations/(?<integrationKey>[^/]+)/(?<elementType>${n})/(?<elementKey>[^/]+)/spec\\.ya?ml$`),a=t.match(o);if(a?.groups){const{integrationKey:l,elementType:u,elementKey:d}=a.groups,f=this.getElementTypeFromPath(u);if(f)return{type:f,key:d,integrationKey:l}}}static extractIntegrationKey(e){return e?.integrationKey||e?.integration?.key||e?.integration_key||void 0}static isElementFile(e){return e.endsWith(".yml")||e.endsWith(".yaml")}static getElementTypeFromPath(e){return Object.values(N).find(t=>qe[t].apiPath===e)}static getRelativePath(e){return P.relative(he(process.cwd()),e)}static isIntegrationSpecific(e){return fo.includes(e)}static canBeIntegrationSpecific(e){return fo.includes(e)}}class ho{static{c(this,"BaseWorkspaceElementsRepository")}constructor(e){this.cache=e}connectorsMapping;sourceCache;setConnectorsMapping(e){this.connectorsMapping=e}setSourceCache(e){this.sourceCache=e}async getElements(){const e=[];try{const t=await this.getIntegrations();e.push(...t);const n=[N.Integration,N.Connector],r=Object.keys(_e),i=await Promise.all(r.filter(o=>!n.includes(o)).map(async o=>this.getElementsByType(o,t)));for(const o of i)e.push(...o)}catch(t){throw b.error(`Failed to get elements: ${t}`),t}return e}async putElement(e){let t=this.cache.get(e.id);return t&&!e.data.id&&t.data.id&&(e.data.id=t.data.id),!t&&e.data.id&&(t=await this.getByInternalId(e.data.id,e.type,!1)),e.data.id&&t?t=await this.updateElement(e,t,{elements:this.cache.getAll(),connectorsMapping:this.connectorsMapping,sourceElements:this.sourceCache?.getAll()}):t=await this.createElement(e,{elements:this.cache.getAll(),connectorsMapping:this.connectorsMapping,sourceElements:this.sourceCache?.getAll()}),t}async getElementsByType(e,t){return[]}async createElement(e,t){return e}async updateElement(e,t,n){return t}async getElement(e){}async getIntegrations(){return[]}async getByInternalId(e,t,n=!0){}async deleteElement(e,t){}}function ur(s,e=!0){if(A.existsSync(s))try{const t=A.readFileSync(s,"utf8");return Se.load(t)||void 0}catch(t){if(!e)return;if(t instanceof Error){const n=P.relative(process.cwd(),s);throw new Error(`Failed to parse YAML file "${n}": ${t.message}`)}throw t}}c(ur,"readYaml$1");function ru(s,e,t){try{const n=Se.dump(e,t);A.writeFileSync(s,n,"utf8")}catch(n){if(n instanceof Error){const r=P.relative(process.cwd(),s);throw new Error(`Failed to write YAML file "${r}": ${n.message}`)}throw n}}c(ru,"writeYaml$1");class iu extends ho{static{c(this,"LocalWorkspaceElementsRepository")}basePath;constructor(e){super(e),this.basePath=he(process.cwd())}async getElementsByType(e,t){const n=[],r=P.join(this.basePath,qe[e].apiPath),i=await this.readElementsInDir(r);n.push(...i);for(const o of t){const a=P.join(this.basePath,qe[N.Integration].apiPath,o.key,qe[e].apiPath),l=await this.readElementsInDir(a);n.push(...l)}return n.length>0&&b.debug(`[local] Fetched ${n.length} ${e}${n.length!==1?"s":""}`),n}async getElement(e){return this.readElement(e.path)}async createElement(e){return this.updateElement(e,e)}async updateElement(e,t){if(!e.data)throw new Error("Element must have data to write");const n=P.join(this.basePath,t.dirPath),r=P.join(this.basePath,t.path);return A.existsSync(n)||A.mkdirSync(n,{recursive:!0}),ru(r,e.data),b.debug(`[local] Written ${t.relativePath}`),t}async deleteElement(e){const t=P.join(this.basePath,e.path),n=P.join(this.basePath,e.dirPath);A.existsSync(t)&&A.rmSync(t,{force:!0}),this.pruneEmptyDir(n),b.debug(`[local] Deleted ${e.relativePath}`)}async getIntegrations(){const e=P.join(this.basePath,qe[N.Integration].apiPath);return this.readElementsInDir(e)}async readElement(e){const t=ur(e);if(t)return Z.fromPathAndData(e,t)}async readElementsInDir(e){const t=[];if(!A.existsSync(e))return t;const n=A.readdirSync(e);if(n.length===0)return t;const r=n.map(async o=>{const a=P.join(e,o,"spec.yaml");return this.readElement(a)});return(await Promise.all(r)).filter(o=>o!=null)}pruneEmptyDir(e){try{if(!e.startsWith(this.basePath)||e===this.basePath||!A.existsSync(e)||A.readdirSync(e).length>0)return;A.rmdirSync(e),this.pruneEmptyDir(P.dirname(e))}catch(t){console.warn(`Failed to prune empty directory ${e}:`,t)}}}class ou extends ho{static{c(this,"RemoteWorkspaceElementsRepository")}async getElementsByType(e,t){const n=Z.canBeIntegrationSpecific(e),r=await this.findAll(e,n?{layer:"universal"}:{});if(!Z.canBeIntegrationSpecific(e))return r;for(const i of t){const o=i.key,a=i.data.id,l=await this.findAll(e,a?{integrationId:a}:{integrationKey:o},o);r.push(...l)}return r.length>0&&b.debug(`[remote] Fetched ${r.length} ${e}${r.length!==1?"s":""}`),r}async getElement(e){const t=await K.withClient(n=>n[_e[e.type].element](e.data.id).get());return Z.fromData(e.type,t)}async createElement(e,t){const n=e.clean();if(this.transformElementForCreate(e,n,t),e.hasParent()&&n.integrationId&&!n.isCustomized){const o=e.getParentKey(),a=new Set(["uuid","integrationId",o,"meta","integrationUuid","parentUuid"]);Object.keys(n).forEach(l=>{a.has(l)||delete n[l]})}const r=await K.withClient(o=>o[_e[e.type].elements].create(n)),i=Z.fromData(e.type,r);return b.debug(`[remote] Created ${i.id}`),i}async updateElement(e,t,n){if(!e.data.id)throw new Error("Element must have an id to update");t.data.archivedAt&&await K.withClient(a=>a[_e[e.type].element](t.data.id).restore());const r=e.clean();if(this.transformElementForUpdate(e,r,n),e.hasParent()&&r.integrationId&&!r.isCustomized)return b.debug(`[remote] Skipped update for ${t.id} (non-customized)`),t;const i=await K.withClient(a=>a[_e[e.type].element](t.data.id).put(r)),o=Z.fromData(t.type,i);return b.debug(`[remote] Updated ${t.id}`),o}async deleteElement(e){if(!e.data.id)throw new Error("Element must have an id to delete");await K.withClient(t=>t[_e[e.type].element](e.data.id).archive()),b.debug(`[remote] Deleted ${e.id}`)}async getIntegrations(){const e=await K.withClient(n=>n.integrations.findAll());if(!e)return[];const t=e.map(n=>Z.fromData(N.Integration,n));return t.length>0&&b.debug(`[remote] Fetched ${t.length} integrations`),t}async getByInternalId(e,t){let n;if(n=await K.withClient(r=>r[_e[t].element](e).get(),!1),!!n)return Z.fromData(t,n)}transformElementForCreate(e,t,n){if(e.integrationKey){const r=n.elements.find(i=>i.type===N.Integration&&i.key===e.integrationKey);if(r)t.integrationId=r.data.id;else throw new Error(`Dependency integration ${e.integrationKey} not found for ${e.id}`)}if(e.type===N.Integration){const r=n.connectorsMapping?.[t.connectorId];r&&(t.connectorId=r)}this.transformPackageDependencies(e,t,n),this.transformParentDependency(e,t,n)}transformElementForUpdate(e,t,n){if(e.type===N.Integration){const r=n.connectorsMapping?.[t.connectorId];r&&(t.connectorId=r)}if(e.integrationKey){t.integrationKey=e.integrationKey;const r=n.elements.find(i=>i.type===N.Integration&&i.key===e.integrationKey);if(r)t.integrationId=r.data.id;else throw new Error(`Dependency integration ${e.integrationKey} not found for ${e.id}`)}this.transformPackageDependencies(e,t,n),this.transformParentDependency(e,t,n)}transformPackageDependencies(e,t,n){if(e.type!==N.Package||!t.elements)return;const r=t.elements.map(i=>{const a=(n.sourceElements||n.elements).find(u=>u.data.id===i.id&&u.type===i.type);if(!a)throw new Error(`Package element ${i.type} with id ${i.id} not found in source workspace for package ${e.id}`);const l=n.elements.find(u=>u.type===i.type&&u.key===a.key&&u.integrationKey===a.integrationKey);if(!l)throw new Error(`Package element ${i.type} with key ${a.key} not found in target workspace for package ${e.id}`);return{id:l.data.id,type:i.type}});t.elements=r}transformParentDependency(e,t,n){if(!e.hasParent())return;const r=e.getParentKey();if(!r)return;const i=n.elements.find(o=>o.type===e.type&&o.key===e.key&&!o.hasParent());if(i)t[r]=i.data.id;else throw new Error(`Parent ${e.getParentKey()} not found for ${e.id}`)}async findAll(e,t={},n){const r=await K.withClient(i=>i[_e[e].elements].findAll(t));return r?r.filter(i=>i.key).map(i=>(n&&!i.integrationKey&&(i.integrationKey=n),Z.fromData(e,i))):[]}}const dr=Symbol.for("yaml.alias"),fr=Symbol.for("yaml.document"),Be=Symbol.for("yaml.map"),po=Symbol.for("yaml.pair"),Ie=Symbol.for("yaml.scalar"),Ct=Symbol.for("yaml.seq"),pe=Symbol.for("yaml.node.type"),Ke=c(s=>!!s&&typeof s=="object"&&s[pe]===dr,"isAlias"),nt=c(s=>!!s&&typeof s=="object"&&s[pe]===fr,"isDocument"),vt=c(s=>!!s&&typeof s=="object"&&s[pe]===Be,"isMap"),G=c(s=>!!s&&typeof s=="object"&&s[pe]===po,"isPair"),V=c(s=>!!s&&typeof s=="object"&&s[pe]===Ie,"isScalar$1"),kt=c(s=>!!s&&typeof s=="object"&&s[pe]===Ct,"isSeq");function Y(s){if(s&&typeof s=="object")switch(s[pe]){case Be:case Ct:return!0}return!1}c(Y,"isCollection$1");function X(s){if(s&&typeof s=="object")switch(s[pe]){case dr:case Be:case Ie:case Ct:return!0}return!1}c(X,"isNode");const mo=c(s=>(V(s)||Y(s))&&!!s.anchor,"hasAnchor"),ce=Symbol("break visit"),go=Symbol("skip children"),Ae=Symbol("remove node");function st(s,e){const t=yo(e);nt(s)?Tt(null,s.contents,t,Object.freeze([s]))===Ae&&(s.contents=null):Tt(null,s,t,Object.freeze([]))}c(st,"visit$1"),st.BREAK=ce,st.SKIP=go,st.REMOVE=Ae;function Tt(s,e,t,n){const r=wo(s,e,t,n);if(X(r)||G(r))return bo(s,n,r),Tt(s,r,t,n);if(typeof r!="symbol"){if(Y(e)){n=Object.freeze(n.concat(e));for(let i=0;i<e.items.length;++i){const o=Tt(i,e.items[i],t,n);if(typeof o=="number")i=o-1;else{if(o===ce)return ce;o===Ae&&(e.items.splice(i,1),i-=1)}}}else if(G(e)){n=Object.freeze(n.concat(e));const i=Tt("key",e.key,t,n);if(i===ce)return ce;i===Ae&&(e.key=null);const o=Tt("value",e.value,t,n);if(o===ce)return ce;o===Ae&&(e.value=null)}}return r}c(Tt,"visit_");async function qn(s,e){const t=yo(e);nt(s)?await Et(null,s.contents,t,Object.freeze([s]))===Ae&&(s.contents=null):await Et(null,s,t,Object.freeze([]))}c(qn,"visitAsync"),qn.BREAK=ce,qn.SKIP=go,qn.REMOVE=Ae;async function Et(s,e,t,n){const r=await wo(s,e,t,n);if(X(r)||G(r))return bo(s,n,r),Et(s,r,t,n);if(typeof r!="symbol"){if(Y(e)){n=Object.freeze(n.concat(e));for(let i=0;i<e.items.length;++i){const o=await Et(i,e.items[i],t,n);if(typeof o=="number")i=o-1;else{if(o===ce)return ce;o===Ae&&(e.items.splice(i,1),i-=1)}}}else if(G(e)){n=Object.freeze(n.concat(e));const i=await Et("key",e.key,t,n);if(i===ce)return ce;i===Ae&&(e.key=null);const o=await Et("value",e.value,t,n);if(o===ce)return ce;o===Ae&&(e.value=null)}}return r}c(Et,"visitAsync_");function yo(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(yo,"initVisitor");function wo(s,e,t,n){if(typeof t=="function")return t(s,e,n);if(vt(e))return t.Map?.(s,e,n);if(kt(e))return t.Seq?.(s,e,n);if(G(e))return t.Pair?.(s,e,n);if(V(e))return t.Scalar?.(s,e,n);if(Ke(e))return t.Alias?.(s,e,n)}c(wo,"callVisitor");function bo(s,e,t){const n=e[e.length-1];if(Y(n))n.items[s]=t;else if(G(n))s==="key"?n.key=t:n.value=t;else if(nt(n))n.contents=t;else{const r=Ke(n)?"alias":"scalar";throw new Error(`Cannot replace node with ${r} parent`)}}c(bo,"replaceNode");const au={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},cu=c(s=>s.replace(/[!,[\]{}]/g,e=>au[e]),"escapeTagName");class oe{static{c(this,"Directives")}constructor(e,t){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},oe.defaultYaml,e),this.tags=Object.assign({},oe.defaultTags,t)}clone(){const e=new oe(this.yaml,this.tags);return e.docStart=this.docStart,e}atDocument(){const e=new oe(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:oe.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},oe.defaultTags);break}return e}add(e,t){this.atNextDocument&&(this.yaml={explicit:oe.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},oe.defaultTags),this.atNextDocument=!1);const n=e.trim().split(/[ \t]+/),r=n.shift();switch(r){case"%TAG":{if(n.length!==2&&(t(0,"%TAG directive should contain exactly two parts"),n.length<2))return!1;const[i,o]=n;return this.tags[i]=o,!0}case"%YAML":{if(this.yaml.explicit=!0,n.length!==1)return t(0,"%YAML directive should contain exactly one part"),!1;const[i]=n;if(i==="1.1"||i==="1.2")return this.yaml.version=i,!0;{const o=/^\d+\.\d+$/.test(i);return t(6,`Unsupported YAML version ${i}`,o),!1}}default:return t(0,`Unknown directive ${r}`,!0),!1}}tagName(e,t){if(e==="!")return"!";if(e[0]!=="!")return t(`Not a valid tag: ${e}`),null;if(e[1]==="<"){const o=e.slice(2,-1);return o==="!"||o==="!!"?(t(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==">"&&t("Verbatim tags must end with a >"),o)}const[,n,r]=e.match(/^(.*!)([^!]*)$/s);r||t(`The ${e} tag has no suffix`);const i=this.tags[n];if(i)try{return i+decodeURIComponent(r)}catch(o){return t(String(o)),null}return n==="!"?e:(t(`Could not resolve tag: ${e}`),null)}tagString(e){for(const[t,n]of Object.entries(this.tags))if(e.startsWith(n))return t+cu(e.substring(n.length));return e[0]==="!"?e:`!<${e}>`}toString(e){const t=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],n=Object.entries(this.tags);let r;if(e&&n.length>0&&X(e.contents)){const i={};st(e.contents,(o,a)=>{X(a)&&a.tag&&(i[a.tag]=!0)}),r=Object.keys(i)}else r=[];for(const[i,o]of n)i==="!!"&&o==="tag:yaml.org,2002:"||(!e||r.some(a=>a.startsWith(o)))&&t.push(`%TAG ${i} ${o}`);return t.join(`
7
+ `)}}oe.defaultYaml={explicit:!1,version:"1.2"},oe.defaultTags={"!!":"tag:yaml.org,2002:"};function So(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(So,"anchorIsValid");function Co(s){const e=new Set;return st(s,{Value(t,n){n.anchor&&e.add(n.anchor)}}),e}c(Co,"anchorNames");function vo(s,e){for(let t=1;;++t){const n=`${s}${t}`;if(!e.has(n))return n}}c(vo,"findNewAnchor");function lu(s,e){const t=[],n=new Map;let r=null;return{onAnchor:c(i=>{t.push(i),r??(r=Co(s));const o=vo(e,r);return r.add(o),o},"onAnchor"),setAnchors:c(()=>{for(const i of t){const o=n.get(i);if(typeof o=="object"&&o.anchor&&(V(o.node)||Y(o.node)))o.node.anchor=o.anchor;else{const a=new Error("Failed to resolve repeated object (this should not happen)");throw a.source=i,a}}},"setAnchors"),sourceObjects:n}}c(lu,"createNodeAnchors");function _t(s,e,t,n){if(n&&typeof n=="object")if(Array.isArray(n))for(let r=0,i=n.length;r<i;++r){const o=n[r],a=_t(s,n,String(r),o);a===void 0?delete n[r]:a!==o&&(n[r]=a)}else if(n instanceof Map)for(const r of Array.from(n.keys())){const i=n.get(r),o=_t(s,n,r,i);o===void 0?n.delete(r):o!==i&&n.set(r,o)}else if(n instanceof Set)for(const r of Array.from(n)){const i=_t(s,n,r,r);i===void 0?n.delete(r):i!==r&&(n.delete(r),n.add(i))}else for(const[r,i]of Object.entries(n)){const o=_t(s,n,r,i);o===void 0?delete n[r]:o!==i&&(n[r]=o)}return s.call(e,t,n)}c(_t,"applyReviver");function me(s,e,t){if(Array.isArray(s))return s.map((n,r)=>me(n,String(r),t));if(s&&typeof s.toJSON=="function"){if(!t||!mo(s))return s.toJSON(e,t);const n={aliasCount:0,count:1,res:void 0};t.anchors.set(s,n),t.onCreate=i=>{n.res=i,delete t.onCreate};const r=s.toJSON(e,t);return t.onCreate&&t.onCreate(r),r}return typeof s=="bigint"&&!t?.keep?Number(s):s}c(me,"toJS");class hr{static{c(this,"NodeBase")}constructor(e){Object.defineProperty(this,pe,{value:e})}clone(){const e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:t,maxAliasCount:n,onAnchor:r,reviver:i}={}){if(!nt(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=me(this,"",o);if(typeof r=="function")for(const{count:l,res:u}of o.anchors.values())r(u,l);return typeof i=="function"?_t(i,{"":a},"",a):a}}class Bn extends hr{static{c(this,"Alias")}constructor(e){super(dr),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=[],st(e,{Node:c((i,o)=>{(Ke(o)||mo(o))&&n.push(o)},"Node")}),t&&(t.aliasResolveCache=n));let r;for(const i of n){if(i===this)break;i.anchor===this.source&&(r=i)}return r}toJSON(e,t){if(!t)return{source:this.source};const{anchors:n,doc:r,maxAliasCount:i}=t,o=this.resolve(r,t);if(!o){const l=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(l)}let a=n.get(o);if(a||(me(o,null,t),a=n.get(o)),!a||a.res===void 0){const l="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(l)}if(i>=0&&(a.count+=1,a.aliasCount===0&&(a.aliasCount=Kn(r,o,n)),a.count*a.aliasCount>i)){const l="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(l)}return a.res}toString(e,t,n){const r=`*${this.source}`;if(e){if(So(this.source),e.options.verifyAliasOrder&&!e.anchors.has(this.source)){const i=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(i)}if(e.implicitKey)return`${r} `}return r}}function Kn(s,e,t){if(Ke(e)){const n=e.resolve(s),r=t&&n&&t.get(n);return r?r.count*r.aliasCount:0}else if(Y(e)){let n=0;for(const r of e.items){const i=Kn(s,r,t);i>n&&(n=i)}return n}else if(G(e)){const n=Kn(s,e.key,t),r=Kn(s,e.value,t);return Math.max(n,r)}return 1}c(Kn,"getAliasCount");const ko=c(s=>!s||typeof s!="function"&&typeof s!="object","isScalarValue");class R extends hr{static{c(this,"Scalar")}constructor(e){super(Ie),this.value=e}toJSON(e,t){return t?.keep?this.value:me(this.value,e,t)}toString(){return String(this.value)}}R.BLOCK_FOLDED="BLOCK_FOLDED",R.BLOCK_LITERAL="BLOCK_LITERAL",R.PLAIN="PLAIN",R.QUOTE_DOUBLE="QUOTE_DOUBLE",R.QUOTE_SINGLE="QUOTE_SINGLE";const uu="tag:yaml.org,2002:";function du(s,e,t){if(e){const n=t.filter(i=>i.tag===e),r=n.find(i=>!i.format)??n[0];if(!r)throw new Error(`Tag ${e} not found`);return r}return t.find(n=>n.identify?.(s)&&!n.format)}c(du,"findTagObject");function Gt(s,e,t){if(nt(s)&&(s=s.contents),X(s))return s;if(G(s)){const f=t.schema[Be].createNode?.(t.schema,null,t);return f.items.push(s),f}(s instanceof String||s instanceof Number||s instanceof Boolean||typeof BigInt<"u"&&s instanceof BigInt)&&(s=s.valueOf());const{aliasDuplicateObjects:n,onAnchor:r,onTagObj:i,schema:o,sourceObjects:a}=t;let l;if(n&&s&&typeof s=="object"){if(l=a.get(s),l)return l.anchor??(l.anchor=r(s)),new Bn(l.anchor);l={anchor:null,node:null},a.set(s,l)}e?.startsWith("!!")&&(e=uu+e.slice(2));let u=du(s,e,o.tags);if(!u){if(s&&typeof s.toJSON=="function"&&(s=s.toJSON()),!s||typeof s!="object"){const f=new R(s);return l&&(l.node=f),f}u=s instanceof Map?o[Be]:Symbol.iterator in Object(s)?o[Ct]:o[Be]}i&&(i(u),delete t.onTagObj);const d=u?.createNode?u.createNode(t.schema,s,t):typeof u?.nodeClass?.from=="function"?u.nodeClass.from(t.schema,s,t):new R(s);return e?d.tag=e:u.default||(d.tag=u.tag),l&&(l.node=d),d}c(Gt,"createNode");function Un(s,e,t){let n=t;for(let r=e.length-1;r>=0;--r){const i=e[r];if(typeof i=="number"&&Number.isInteger(i)&&i>=0){const o=[];o[i]=n,n=o}else n=new Map([[i,n]])}return Gt(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(Un,"collectionFromPath");const zt=c(s=>s==null||typeof s=="object"&&!!s[Symbol.iterator]().next().done,"isEmptyPath");class To extends hr{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=>X(n)||G(n)?n.clone(e):n),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(zt(e))this.add(t);else{const[n,...r]=e,i=this.get(n,!0);if(Y(i))i.addIn(r,t);else if(i===void 0&&this.schema)this.set(n,Un(this.schema,r,t));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${r}`)}}deleteIn(e){const[t,...n]=e;if(n.length===0)return this.delete(t);const r=this.get(t,!0);if(Y(r))return r.deleteIn(n);throw new Error(`Expected YAML collection at ${t}. Remaining path: ${n}`)}getIn(e,t){const[n,...r]=e,i=this.get(n,!0);return r.length===0?!t&&V(i)?i.value:i:Y(i)?i.getIn(r,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!G(t))return!1;const n=t.value;return n==null||e&&V(n)&&n.value==null&&!n.commentBefore&&!n.comment&&!n.tag})}hasIn(e){const[t,...n]=e;if(n.length===0)return this.has(t);const r=this.get(t,!0);return Y(r)?r.hasIn(n):!1}setIn(e,t){const[n,...r]=e;if(r.length===0)this.set(n,t);else{const i=this.get(n,!0);if(Y(i))i.setIn(r,t);else if(i===void 0&&this.schema)this.set(n,Un(this.schema,r,t));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${r}`)}}}const fu=c(s=>s.replace(/^(?!$)(?: $)?/gm,"#"),"stringifyComment");function xe(s,e){return/^\n+$/.test(s)?s.substring(1):e?s.replace(/^(?! *$)/gm,e):s}c(xe,"indentComment");const rt=c((s,e,t)=>s.endsWith(`
8
8
  `)?xe(t,e):t.includes(`
9
9
  `)?`
10
- `+xe(t,e):(s.endsWith(" ")?"":" ")+t,"lineComment"),To="flow",pr="block",Wn="quoted";function Jn(s,e,t="flow",{indentAtStart:n,lineWidth:r=80,minContentWidth:i=20,onFold:o,onOverflow:a}={}){if(!r||r<0)return s;r<i&&(i=0);const l=Math.max(1+i,1+r-e.length);if(s.length<=l)return s;const u=[],d={};let f=r-e.length;typeof n=="number"&&(n>r-Math.max(2,i)?u.push(0):f=r-n);let h,g,y=!1,p=-1,w=-1,T=-1;t===pr&&(p=Eo(s,p,e.length),p!==-1&&(f=p+l));for(let $;$=s[p+=1];){if(t===Wn&&$==="\\"){switch(w=p,s[p+1]){case"x":p+=3;break;case"u":p+=5;break;case"U":p+=9;break;default:p+=1}T=p}if($===`
11
- `)t===pr&&(p=Eo(s,p,e.length)),f=p+e.length+l,h=void 0;else{if($===" "&&g&&g!==" "&&g!==`
10
+ `+xe(t,e):(s.endsWith(" ")?"":" ")+t,"lineComment"),Eo="flow",pr="block",Wn="quoted";function Jn(s,e,t="flow",{indentAtStart:n,lineWidth:r=80,minContentWidth:i=20,onFold:o,onOverflow:a}={}){if(!r||r<0)return s;r<i&&(i=0);const l=Math.max(1+i,1+r-e.length);if(s.length<=l)return s;const u=[],d={};let f=r-e.length;typeof n=="number"&&(n>r-Math.max(2,i)?u.push(0):f=r-n);let h,g,y=!1,p=-1,w=-1,T=-1;t===pr&&(p=_o(s,p,e.length),p!==-1&&(f=p+l));for(let $;$=s[p+=1];){if(t===Wn&&$==="\\"){switch(w=p,s[p+1]){case"x":p+=3;break;case"u":p+=5;break;case"U":p+=9;break;default:p+=1}T=p}if($===`
11
+ `)t===pr&&(p=_o(s,p,e.length)),f=p+e.length+l,h=void 0;else{if($===" "&&g&&g!==" "&&g!==`
12
12
  `&&g!==" "){const I=s[p+1];I&&I!==" "&&I!==`
13
13
  `&&I!==" "&&(h=p)}if(p>=f)if(h)u.push(h),f=h+l,h=void 0;else if(t===Wn){for(;g===" "||g===" ";)g=$,$=s[p+=1],y=!0;const I=p>T+1?p-2:w-1;if(d[I])return s;u.push(I),d[I]=!0,f=I+l,h=void 0}else y=!0}g=$}if(y&&a&&a(),u.length===0)return s;o&&o();let E=s.slice(0,u[0]);for(let $=0;$<u.length;++$){const I=u[$],x=u[$+1]||s.length;I===0?E=`
14
14
  ${e}${s.slice(0,x)}`:(t===Wn&&d[I]&&(E+=`${s[I]}\\`),E+=`
15
- ${e}${s.slice(I+1,x)}`)}return E}c(Jn,"foldFlowLines");function Eo(s,e,t){let n=e,r=e+1,i=s[r];for(;i===" "||i===" ";)if(e<r+t)i=s[++e];else{do i=s[++e];while(i&&i!==`
16
- `);n=e,r=e+1,i=s[r]}return n}c(Eo,"consumeMoreIndentedLines");const Hn=c((s,e)=>({indentAtStart:e?s.indent.length:s.indentAtStart,lineWidth:s.options.lineWidth,minContentWidth:s.options.minContentWidth}),"getFoldOptions"),Vn=c(s=>/^(%|---|\.\.\.)/m.test(s),"containsDocumentMarker");function fu(s,e,t){if(!e||e<0)return!1;const n=e-t,r=s.length;if(r<=n)return!1;for(let i=0,o=0;i<r;++i)if(s[i]===`
17
- `){if(i-o>n)return!0;if(o=i+1,r-o<=n)return!1}return!0}c(fu,"lineLengthOverLimit");function Yt(s,e){const t=JSON.stringify(s);if(e.options.doubleQuotedAsJSON)return t;const{implicitKey:n}=e,r=e.options.doubleQuotedMinMultiLineLength,i=e.indent||(Vn(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 d=t.substr(l+2,4);switch(d){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:d.substr(0,2)==="00"?o+="\\x"+d.substr(2):o+=t.substr(l,6)}l+=5,a=l+1}break;case"n":if(n||t[l+2]==='"'||t.length<r)l+=1;else{for(o+=t.slice(a,l)+`
15
+ ${e}${s.slice(I+1,x)}`)}return E}c(Jn,"foldFlowLines");function _o(s,e,t){let n=e,r=e+1,i=s[r];for(;i===" "||i===" ";)if(e<r+t)i=s[++e];else{do i=s[++e];while(i&&i!==`
16
+ `);n=e,r=e+1,i=s[r]}return n}c(_o,"consumeMoreIndentedLines");const Hn=c((s,e)=>({indentAtStart:e?s.indent.length:s.indentAtStart,lineWidth:s.options.lineWidth,minContentWidth:s.options.minContentWidth}),"getFoldOptions"),Vn=c(s=>/^(%|---|\.\.\.)/m.test(s),"containsDocumentMarker");function hu(s,e,t){if(!e||e<0)return!1;const n=e-t,r=s.length;if(r<=n)return!1;for(let i=0,o=0;i<r;++i)if(s[i]===`
17
+ `){if(i-o>n)return!0;if(o=i+1,r-o<=n)return!1}return!0}c(hu,"lineLengthOverLimit");function Yt(s,e){const t=JSON.stringify(s);if(e.options.doubleQuotedAsJSON)return t;const{implicitKey:n}=e,r=e.options.doubleQuotedMinMultiLineLength,i=e.indent||(Vn(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 d=t.substr(l+2,4);switch(d){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:d.substr(0,2)==="00"?o+="\\x"+d.substr(2):o+=t.substr(l,6)}l+=5,a=l+1}break;case"n":if(n||t[l+2]==='"'||t.length<r)l+=1;else{for(o+=t.slice(a,l)+`
18
18
 
19
19
  `;t[l+2]==="\\"&&t[l+3]==="n"&&t[l+4]!=='"';)o+=`
20
20
  `,l+=2;o+=i,t[l+2]===" "&&(o+="\\"),l+=1,a=l+1}break;default:l+=1}return o=a?o+t.slice(a):t,n?o:Jn(o,i,Wn,Hn(e,!1))}c(Yt,"doubleQuotedString");function mr(s,e){if(e.options.singleQuote===!1||e.implicitKey&&s.includes(`
21
21
  `)||/[ \t]\n|\n[ \t]/.test(s))return Yt(s,e);const t=e.indent||(Vn(s)?" ":""),n="'"+s.replace(/'/g,"''").replace(/\n+/g,`$&
22
- ${t}`)+"'";return e.implicitKey?n:Jn(n,t,To,Hn(e,!1))}c(mr,"singleQuotedString");function It(s,e){const{singleQuote:t}=e.options;let n;if(t===!1)n=Yt;else{const r=s.includes('"'),i=s.includes("'");r&&!i?n=mr:i&&!r?n=Yt:n=t?mr:Yt}return n(s,e)}c(It,"quotedString");let gr;try{gr=new RegExp(`(^|(?<!
22
+ ${t}`)+"'";return e.implicitKey?n:Jn(n,t,Eo,Hn(e,!1))}c(mr,"singleQuotedString");function It(s,e){const{singleQuote:t}=e.options;let n;if(t===!1)n=Yt;else{const r=s.includes('"'),i=s.includes("'");r&&!i?n=mr:i&&!r?n=Yt:n=t?mr:Yt}return n(s,e)}c(It,"quotedString");let gr;try{gr=new RegExp(`(^|(?<!
23
23
  ))
24
24
  +(?!
25
- |$)`,"g")}catch{gr=/\n+(?!\n|$)/g}function Gn({comment:s,type:e,value:t},n,r,i){const{blockQuote:o,commentString:a,lineWidth:l}=n.options;if(!o||/\n[\t ]+$/.test(t)||/^\s*$/.test(t))return It(t,n);const u=n.indent||(n.forceBlockIndent||Vn(t)?" ":""),d=o==="literal"?!0:o==="folded"||e===R.BLOCK_FOLDED?!1:e===R.BLOCK_LITERAL?!0:!fu(t,l,u.length);if(!t)return d?`|
25
+ |$)`,"g")}catch{gr=/\n+(?!\n|$)/g}function Gn({comment:s,type:e,value:t},n,r,i){const{blockQuote:o,commentString:a,lineWidth:l}=n.options;if(!o||/\n[\t ]+$/.test(t)||/^\s*$/.test(t))return It(t,n);const u=n.indent||(n.forceBlockIndent||Vn(t)?" ":""),d=o==="literal"?!0:o==="folded"||e===R.BLOCK_FOLDED?!1:e===R.BLOCK_LITERAL?!0:!hu(t,l,u.length);if(!t)return d?`|
26
26
  `:`>
27
27
  `;let f,h;for(h=t.length;h>0;--h){const x=t[h-1];if(x!==`
28
28
  `&&x!==" "&&x!==" ")break}let g=t.substring(h);const y=g.indexOf(`
@@ -31,12 +31,12 @@ ${t}`)+"'";return e.implicitKey?n:Jn(n,t,To,Hn(e,!1))}c(mr,"singleQuotedString")
31
31
  `)T=w;else break}let E=t.substring(0,T<w?T+1:w);E&&(t=t.substring(E.length),E=E.replace(/\n+/g,`$&${u}`));let I=(p?u?"2":"1":"")+f;if(s&&(I+=" "+a(s.replace(/ ?[\r\n]+/g," ")),r&&r()),!d){const x=t.replace(/\n+/g,`
32
32
  $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${u}`);let M=!1;const j=Hn(n,!0);o!=="folded"&&e!==R.BLOCK_FOLDED&&(j.onOverflow=()=>{M=!0});const O=Jn(`${E}${x}${g}`,u,pr,j);if(!M)return`>${I}
33
33
  ${u}${O}`}return t=t.replace(/\n+/g,`$&${u}`),`|${I}
34
- ${u}${E}${t}${g}`}c(Gn,"blockString");function hu(s,e,t,n){const{type:r,value:i}=s,{actualString:o,implicitKey:a,indent:l,indentStep:u,inFlow:d}=e;if(a&&i.includes(`
34
+ ${u}${E}${t}${g}`}c(Gn,"blockString");function pu(s,e,t,n){const{type:r,value:i}=s,{actualString:o,implicitKey:a,indent:l,indentStep:u,inFlow:d}=e;if(a&&i.includes(`
35
35
  `)||d&&/[[\]{},]/.test(i))return It(i,e);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(i))return a||d||!i.includes(`
36
36
  `)?It(i,e):Gn(s,e,t,n);if(!a&&!d&&r!==R.PLAIN&&i.includes(`
37
37
  `))return Gn(s,e,t,n);if(Vn(i)){if(l==="")return e.forceBlockIndent=!0,Gn(s,e,t,n);if(a&&l===u)return It(i,e)}const f=i.replace(/\n+/g,`$&
38
- ${l}`);if(o){const h=c(p=>p.default&&p.tag!=="tag:yaml.org,2002:str"&&p.test?.test(f),"test"),{compat:g,tags:y}=e.doc.schema;if(y.some(h)||g?.some(h))return It(i,e)}return a?f:Jn(f,l,To,Hn(e,!1))}c(hu,"plainString");function Xt(s,e,t,n){const{implicitKey:r,inFlow:i}=e,o=typeof s.value=="string"?s:Object.assign({},s,{value:String(s.value)});let{type:a}=s;a!==R.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(a=R.QUOTE_DOUBLE);const l=c(d=>{switch(d){case R.BLOCK_FOLDED:case R.BLOCK_LITERAL:return r||i?It(o.value,e):Gn(o,e,t,n);case R.QUOTE_DOUBLE:return Yt(o.value,e);case R.QUOTE_SINGLE:return mr(o.value,e);case R.PLAIN:return hu(o,e,t,n);default:return null}},"_stringify");let u=l(a);if(u===null){const{defaultKeyType:d,defaultStringType:f}=e.options,h=r&&d||f;if(u=l(h),u===null)throw new Error(`Unsupported default string type ${h}`)}return u}c(Xt,"stringifyString");function _o(s,e){const t=Object.assign({blockQuote:!0,commentString:du,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(_o,"createStringifyContext");function pu(s,e){if(e.tag){const r=s.filter(i=>i.tag===e.tag);if(r.length>0)return r.find(i=>i.format===e.format)??r[0]}let t,n;if(V(e)){n=e.value;let r=s.filter(i=>i.identify?.(n));if(r.length>1){const i=r.filter(o=>o.test);i.length>0&&(r=i)}t=r.find(i=>i.format===e.format)??r.find(i=>!i.format)}else n=e,t=s.find(r=>r.nodeClass&&n instanceof r.nodeClass);if(!t){const r=n?.constructor?.name??(n===null?"null":typeof n);throw new Error(`Tag not resolved for ${r} value`)}return t}c(pu,"getTagObject");function mu(s,e,{anchors:t,doc:n}){if(!n.directives)return"";const r=[],i=(V(s)||Y(s))&&s.anchor;i&&bo(i)&&(t.add(i),r.push(`&${i}`));const o=s.tag??(e.default?null:e.tag);return o&&r.push(n.directives.tagString(o)),r.join(" ")}c(mu,"stringifyProps");function At(s,e,t,n){if(G(s))return s.toString(e,t,n);if(Ke(s)){if(e.doc.directives)return s.toString(e);if(e.resolvedAliases?.has(s))throw new TypeError("Cannot stringify circular structure without alias nodes");e.resolvedAliases?e.resolvedAliases.add(s):e.resolvedAliases=new Set([s]),s=s.resolve(e.doc)}let r;const i=X(s)?s:e.doc.createNode(s,{onTagObj:c(l=>r=l,"onTagObj")});r??(r=pu(e.doc.schema.tags,i));const o=mu(i,r,e);o.length>0&&(e.indentAtStart=(e.indentAtStart??0)+o.length+1);const a=typeof r.stringify=="function"?r.stringify(i,e,t,n):V(i)?Xt(i,e,t,n):i.toString(e,t,n);return o?V(i)||a[0]==="{"||a[0]==="["?`${o} ${a}`:`${o}
39
- ${e.indent}${a}`:a}c(At,"stringify$2");function gu({key:s,value:e},t,n,r){const{allNullValues:i,doc:o,indent:a,indentStep:l,options:{commentString:u,indentSeq:d,simpleKeys:f}}=t;let h=X(s)&&s.comment||null;if(f){if(h)throw new Error("With simple keys, key nodes cannot have comments");if(Y(s)||!X(s)&&typeof s=="object"){const j="With simple keys, collection cannot be used as a key value";throw new Error(j)}}let g=!f&&(!s||h&&e==null&&!t.inFlow||Y(s)||(V(s)?s.type===R.BLOCK_FOLDED||s.type===R.BLOCK_LITERAL:typeof s=="object"));t=Object.assign({},t,{allNullValues:!1,implicitKey:!g&&(f||!i),indent:a+l});let y=!1,p=!1,w=At(s,t,()=>y=!0,()=>p=!0);if(!g&&!t.inFlow&&w.length>1024){if(f)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");g=!0}if(t.inFlow){if(i||e==null)return y&&n&&n(),w===""?"?":g?`? ${w}`:w}else if(i&&!f||e==null&&g)return w=`? ${w}`,h&&!y?w+=rt(w,t.indent,u(h)):p&&r&&r(),w;y&&(h=null),g?(h&&(w+=rt(w,t.indent,u(h))),w=`? ${w}
38
+ ${l}`);if(o){const h=c(p=>p.default&&p.tag!=="tag:yaml.org,2002:str"&&p.test?.test(f),"test"),{compat:g,tags:y}=e.doc.schema;if(y.some(h)||g?.some(h))return It(i,e)}return a?f:Jn(f,l,Eo,Hn(e,!1))}c(pu,"plainString");function Xt(s,e,t,n){const{implicitKey:r,inFlow:i}=e,o=typeof s.value=="string"?s:Object.assign({},s,{value:String(s.value)});let{type:a}=s;a!==R.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(a=R.QUOTE_DOUBLE);const l=c(d=>{switch(d){case R.BLOCK_FOLDED:case R.BLOCK_LITERAL:return r||i?It(o.value,e):Gn(o,e,t,n);case R.QUOTE_DOUBLE:return Yt(o.value,e);case R.QUOTE_SINGLE:return mr(o.value,e);case R.PLAIN:return pu(o,e,t,n);default:return null}},"_stringify");let u=l(a);if(u===null){const{defaultKeyType:d,defaultStringType:f}=e.options,h=r&&d||f;if(u=l(h),u===null)throw new Error(`Unsupported default string type ${h}`)}return u}c(Xt,"stringifyString");function Io(s,e){const t=Object.assign({blockQuote:!0,commentString:fu,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(Io,"createStringifyContext");function mu(s,e){if(e.tag){const r=s.filter(i=>i.tag===e.tag);if(r.length>0)return r.find(i=>i.format===e.format)??r[0]}let t,n;if(V(e)){n=e.value;let r=s.filter(i=>i.identify?.(n));if(r.length>1){const i=r.filter(o=>o.test);i.length>0&&(r=i)}t=r.find(i=>i.format===e.format)??r.find(i=>!i.format)}else n=e,t=s.find(r=>r.nodeClass&&n instanceof r.nodeClass);if(!t){const r=n?.constructor?.name??(n===null?"null":typeof n);throw new Error(`Tag not resolved for ${r} value`)}return t}c(mu,"getTagObject");function gu(s,e,{anchors:t,doc:n}){if(!n.directives)return"";const r=[],i=(V(s)||Y(s))&&s.anchor;i&&So(i)&&(t.add(i),r.push(`&${i}`));const o=s.tag??(e.default?null:e.tag);return o&&r.push(n.directives.tagString(o)),r.join(" ")}c(gu,"stringifyProps");function At(s,e,t,n){if(G(s))return s.toString(e,t,n);if(Ke(s)){if(e.doc.directives)return s.toString(e);if(e.resolvedAliases?.has(s))throw new TypeError("Cannot stringify circular structure without alias nodes");e.resolvedAliases?e.resolvedAliases.add(s):e.resolvedAliases=new Set([s]),s=s.resolve(e.doc)}let r;const i=X(s)?s:e.doc.createNode(s,{onTagObj:c(l=>r=l,"onTagObj")});r??(r=mu(e.doc.schema.tags,i));const o=gu(i,r,e);o.length>0&&(e.indentAtStart=(e.indentAtStart??0)+o.length+1);const a=typeof r.stringify=="function"?r.stringify(i,e,t,n):V(i)?Xt(i,e,t,n):i.toString(e,t,n);return o?V(i)||a[0]==="{"||a[0]==="["?`${o} ${a}`:`${o}
39
+ ${e.indent}${a}`:a}c(At,"stringify$2");function yu({key:s,value:e},t,n,r){const{allNullValues:i,doc:o,indent:a,indentStep:l,options:{commentString:u,indentSeq:d,simpleKeys:f}}=t;let h=X(s)&&s.comment||null;if(f){if(h)throw new Error("With simple keys, key nodes cannot have comments");if(Y(s)||!X(s)&&typeof s=="object"){const j="With simple keys, collection cannot be used as a key value";throw new Error(j)}}let g=!f&&(!s||h&&e==null&&!t.inFlow||Y(s)||(V(s)?s.type===R.BLOCK_FOLDED||s.type===R.BLOCK_LITERAL:typeof s=="object"));t=Object.assign({},t,{allNullValues:!1,implicitKey:!g&&(f||!i),indent:a+l});let y=!1,p=!1,w=At(s,t,()=>y=!0,()=>p=!0);if(!g&&!t.inFlow&&w.length>1024){if(f)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");g=!0}if(t.inFlow){if(i||e==null)return y&&n&&n(),w===""?"?":g?`? ${w}`:w}else if(i&&!f||e==null&&g)return w=`? ${w}`,h&&!y?w+=rt(w,t.indent,u(h)):p&&r&&r(),w;y&&(h=null),g?(h&&(w+=rt(w,t.indent,u(h))),w=`? ${w}
40
40
  ${a}:`):(w=`${w}:`,h&&(w+=rt(w,t.indent,u(h))));let T,E,$;X(e)?(T=!!e.spaceBefore,E=e.commentBefore,$=e.comment):(T=!1,E=null,$=null,e&&typeof e=="object"&&(e=o.createNode(e))),t.implicitKey=!1,!g&&!h&&V(e)&&(t.indentAtStart=w.length+1),p=!1,!d&&l.length>=2&&!t.inFlow&&!g&&kt(e)&&!e.flow&&!e.tag&&!e.anchor&&(t.indent=t.indent.substring(2));let I=!1;const x=At(e,t,()=>I=!0,()=>p=!0);let M=" ";if(h||T||E){if(M=T?`
41
41
  `:"",E){const j=u(E);M+=`
42
42
  ${xe(j,t.indent)}`}x===""&&!t.inFlow?M===`
@@ -46,32 +46,32 @@ ${xe(j,t.indent)}`}x===""&&!t.inFlow?M===`
46
46
  ${t.indent}`}else if(!g&&Y(e)){const j=x[0],O=x.indexOf(`
47
47
  `),te=O!==-1,Fe=t.inFlow??e.flow??e.items.length===0;if(te||!Fe){let dt=!1;if(te&&(j==="&"||j==="!")){let ne=x.indexOf(" ");j==="&"&&ne!==-1&&ne<O&&x[ne+1]==="!"&&(ne=x.indexOf(" ",ne+1)),(ne===-1||O<ne)&&(dt=!0)}dt||(M=`
48
48
  ${t.indent}`)}}else(x===""||x[0]===`
49
- `)&&(M="");return w+=M+x,t.inFlow?I&&n&&n():$&&!I?w+=rt(w,t.indent,u($)):p&&r&&r(),w}c(gu,"stringifyPair");function Io(s,e){(s==="debug"||s==="warn")&&console.warn(e)}c(Io,"warn");const zn="<<",Pe={identify:c(s=>s===zn||typeof s=="symbol"&&s.description===zn,"identify"),default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:c(()=>Object.assign(new R(Symbol(zn)),{addToJSMap:Ao}),"resolve"),stringify:c(()=>zn,"stringify")},yu=c((s,e)=>(Pe.identify(e)||V(e)&&(!e.type||e.type===R.PLAIN)&&Pe.identify(e.value))&&s?.doc.schema.tags.some(t=>t.tag===Pe.tag&&t.default),"isMergeKey");function Ao(s,e,t){if(t=s&&Ke(t)?t.resolve(s.doc):t,kt(t))for(const n of t.items)yr(s,e,n);else if(Array.isArray(t))for(const n of t)yr(s,e,n);else yr(s,e,t)}c(Ao,"addMergeToJSMap");function yr(s,e,t){const n=s&&Ke(t)?t.resolve(s.doc):t;if(!vt(n))throw new Error("Merge sources must be maps or map aliases");const r=n.toJSON(null,s,Map);for(const[i,o]of r)e instanceof Map?e.has(i)||e.set(i,o):e instanceof Set?e.add(i):Object.prototype.hasOwnProperty.call(e,i)||Object.defineProperty(e,i,{value:o,writable:!0,enumerable:!0,configurable:!0});return e}c(yr,"mergeValue");function Oo(s,e,{key:t,value:n}){if(X(t)&&t.addToJSMap)t.addToJSMap(s,e,n);else if(yu(s,t))Ao(s,e,n);else{const r=me(t,"",s);if(e instanceof Map)e.set(r,me(n,r,s));else if(e instanceof Set)e.add(r);else{const i=wu(t,r,s),o=me(n,i,s);i in e?Object.defineProperty(e,i,{value:o,writable:!0,enumerable:!0,configurable:!0}):e[i]=o}}return e}c(Oo,"addPairToJSMap");function wu(s,e,t){if(e===null)return"";if(typeof e!="object")return String(e);if(X(s)&&t?.doc){const n=_o(t.doc,{});n.anchors=new Set;for(const i of t.anchors.keys())n.anchors.add(i.anchor);n.inFlow=!0,n.inStringifyKey=!0;const r=s.toString(n);if(!t.mapKeyWarned){let i=JSON.stringify(r);i.length>40&&(i=i.substring(0,36)+'..."'),Io(t.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${i}. Set mapAsMap: true to use object keys.`),t.mapKeyWarned=!0}return r}return JSON.stringify(e)}c(wu,"stringifyKey");function wr(s,e,t){const n=Gt(s,void 0,t),r=Gt(e,void 0,t);return new se(n,r)}c(wr,"createPair");class se{static{c(this,"Pair")}constructor(e,t=null){Object.defineProperty(this,pe,{value:ho}),this.key=e,this.value=t}clone(e){let{key:t,value:n}=this;return X(t)&&(t=t.clone(e)),X(n)&&(n=n.clone(e)),new se(t,n)}toJSON(e,t){const n=t?.mapAsMap?new Map:{};return Oo(t,n,this)}toString(e,t,n){return e?.doc?gu(this,e,t,n):JSON.stringify(this)}}function $o(s,e,t){return(e.inFlow??s.flow?Su:bu)(s,e,t)}c($o,"stringifyCollection");function bu({comment:s,items:e},t,{blockItemPrefix:n,flowChars:r,itemIndent:i,onChompKeep:o,onComment:a}){const{indent:l,options:{commentString:u}}=t,d=Object.assign({},t,{indent:i,type:null});let f=!1;const h=[];for(let y=0;y<e.length;++y){const p=e[y];let w=null;if(X(p))!f&&p.spaceBefore&&h.push(""),Yn(t,h,p.commentBefore,f),p.comment&&(w=p.comment);else if(G(p)){const E=X(p.key)?p.key:null;E&&(!f&&E.spaceBefore&&h.push(""),Yn(t,h,E.commentBefore,f))}f=!1;let T=At(p,d,()=>w=null,()=>f=!0);w&&(T+=rt(T,i,u(w))),f&&w&&(f=!1),h.push(n+T)}let g;if(h.length===0)g=r.start+r.end;else{g=h[0];for(let y=1;y<h.length;++y){const p=h[y];g+=p?`
49
+ `)&&(M="");return w+=M+x,t.inFlow?I&&n&&n():$&&!I?w+=rt(w,t.indent,u($)):p&&r&&r(),w}c(yu,"stringifyPair");function Ao(s,e){(s==="debug"||s==="warn")&&console.warn(e)}c(Ao,"warn");const zn="<<",Pe={identify:c(s=>s===zn||typeof s=="symbol"&&s.description===zn,"identify"),default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:c(()=>Object.assign(new R(Symbol(zn)),{addToJSMap:Oo}),"resolve"),stringify:c(()=>zn,"stringify")},wu=c((s,e)=>(Pe.identify(e)||V(e)&&(!e.type||e.type===R.PLAIN)&&Pe.identify(e.value))&&s?.doc.schema.tags.some(t=>t.tag===Pe.tag&&t.default),"isMergeKey");function Oo(s,e,t){if(t=s&&Ke(t)?t.resolve(s.doc):t,kt(t))for(const n of t.items)yr(s,e,n);else if(Array.isArray(t))for(const n of t)yr(s,e,n);else yr(s,e,t)}c(Oo,"addMergeToJSMap");function yr(s,e,t){const n=s&&Ke(t)?t.resolve(s.doc):t;if(!vt(n))throw new Error("Merge sources must be maps or map aliases");const r=n.toJSON(null,s,Map);for(const[i,o]of r)e instanceof Map?e.has(i)||e.set(i,o):e instanceof Set?e.add(i):Object.prototype.hasOwnProperty.call(e,i)||Object.defineProperty(e,i,{value:o,writable:!0,enumerable:!0,configurable:!0});return e}c(yr,"mergeValue");function $o(s,e,{key:t,value:n}){if(X(t)&&t.addToJSMap)t.addToJSMap(s,e,n);else if(wu(s,t))Oo(s,e,n);else{const r=me(t,"",s);if(e instanceof Map)e.set(r,me(n,r,s));else if(e instanceof Set)e.add(r);else{const i=bu(t,r,s),o=me(n,i,s);i in e?Object.defineProperty(e,i,{value:o,writable:!0,enumerable:!0,configurable:!0}):e[i]=o}}return e}c($o,"addPairToJSMap");function bu(s,e,t){if(e===null)return"";if(typeof e!="object")return String(e);if(X(s)&&t?.doc){const n=Io(t.doc,{});n.anchors=new Set;for(const i of t.anchors.keys())n.anchors.add(i.anchor);n.inFlow=!0,n.inStringifyKey=!0;const r=s.toString(n);if(!t.mapKeyWarned){let i=JSON.stringify(r);i.length>40&&(i=i.substring(0,36)+'..."'),Ao(t.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${i}. Set mapAsMap: true to use object keys.`),t.mapKeyWarned=!0}return r}return JSON.stringify(e)}c(bu,"stringifyKey");function wr(s,e,t){const n=Gt(s,void 0,t),r=Gt(e,void 0,t);return new se(n,r)}c(wr,"createPair");class se{static{c(this,"Pair")}constructor(e,t=null){Object.defineProperty(this,pe,{value:po}),this.key=e,this.value=t}clone(e){let{key:t,value:n}=this;return X(t)&&(t=t.clone(e)),X(n)&&(n=n.clone(e)),new se(t,n)}toJSON(e,t){const n=t?.mapAsMap?new Map:{};return $o(t,n,this)}toString(e,t,n){return e?.doc?yu(this,e,t,n):JSON.stringify(this)}}function No(s,e,t){return(e.inFlow??s.flow?Cu:Su)(s,e,t)}c(No,"stringifyCollection");function Su({comment:s,items:e},t,{blockItemPrefix:n,flowChars:r,itemIndent:i,onChompKeep:o,onComment:a}){const{indent:l,options:{commentString:u}}=t,d=Object.assign({},t,{indent:i,type:null});let f=!1;const h=[];for(let y=0;y<e.length;++y){const p=e[y];let w=null;if(X(p))!f&&p.spaceBefore&&h.push(""),Yn(t,h,p.commentBefore,f),p.comment&&(w=p.comment);else if(G(p)){const E=X(p.key)?p.key:null;E&&(!f&&E.spaceBefore&&h.push(""),Yn(t,h,E.commentBefore,f))}f=!1;let T=At(p,d,()=>w=null,()=>f=!0);w&&(T+=rt(T,i,u(w))),f&&w&&(f=!1),h.push(n+T)}let g;if(h.length===0)g=r.start+r.end;else{g=h[0];for(let y=1;y<h.length;++y){const p=h[y];g+=p?`
50
50
  ${l}${p}`:`
51
51
  `}}return s?(g+=`
52
- `+xe(u(s),l),a&&a()):f&&o&&o(),g}c(bu,"stringifyBlockCollection");function Su({items:s},e,{flowChars:t,itemIndent:n}){const{indent:r,indentStep:i,flowCollectionPadding:o,options:{commentString:a}}=e;n+=i;const l=Object.assign({},e,{indent:n,inFlow:!0,type:null});let u=!1,d=0;const f=[];for(let y=0;y<s.length;++y){const p=s[y];let w=null;if(X(p))p.spaceBefore&&f.push(""),Yn(e,f,p.commentBefore,!1),p.comment&&(w=p.comment);else if(G(p)){const E=X(p.key)?p.key:null;E&&(E.spaceBefore&&f.push(""),Yn(e,f,E.commentBefore,!1),E.comment&&(u=!0));const $=X(p.value)?p.value:null;$?($.comment&&(w=$.comment),$.commentBefore&&(u=!0)):p.value==null&&E?.comment&&(w=E.comment)}w&&(u=!0);let T=At(p,l,()=>w=null);y<s.length-1&&(T+=","),w&&(T+=rt(T,n,a(w))),!u&&(f.length>d||T.includes(`
52
+ `+xe(u(s),l),a&&a()):f&&o&&o(),g}c(Su,"stringifyBlockCollection");function Cu({items:s},e,{flowChars:t,itemIndent:n}){const{indent:r,indentStep:i,flowCollectionPadding:o,options:{commentString:a}}=e;n+=i;const l=Object.assign({},e,{indent:n,inFlow:!0,type:null});let u=!1,d=0;const f=[];for(let y=0;y<s.length;++y){const p=s[y];let w=null;if(X(p))p.spaceBefore&&f.push(""),Yn(e,f,p.commentBefore,!1),p.comment&&(w=p.comment);else if(G(p)){const E=X(p.key)?p.key:null;E&&(E.spaceBefore&&f.push(""),Yn(e,f,E.commentBefore,!1),E.comment&&(u=!0));const $=X(p.value)?p.value:null;$?($.comment&&(w=$.comment),$.commentBefore&&(u=!0)):p.value==null&&E?.comment&&(w=E.comment)}w&&(u=!0);let T=At(p,l,()=>w=null);y<s.length-1&&(T+=","),w&&(T+=rt(T,n,a(w))),!u&&(f.length>d||T.includes(`
53
53
  `))&&(u=!0),f.push(T),d=f.length}const{start:h,end:g}=t;if(f.length===0)return h+g;if(!u){const y=f.reduce((p,w)=>p+w.length+2,2);u=e.options.lineWidth>0&&y>e.options.lineWidth}if(u){let y=h;for(const p of f)y+=p?`
54
54
  ${i}${r}${p}`:`
55
55
  `;return`${y}
56
- ${r}${g}`}else return`${h}${o}${f.join(" ")}${o}${g}`}c(Su,"stringifyFlowCollection");function Yn({indent:s,options:{commentString:e}},t,n,r){if(n&&r&&(n=n.replace(/^\n+/,"")),n){const i=xe(e(n),s);t.push(i.trimStart())}}c(Yn,"addCommentBefore");function it(s,e){const t=V(e)?e.value:e;for(const n of s)if(G(n)&&(n.key===e||n.key===t||V(n.key)&&n.key.value===t))return n}c(it,"findPair");class le extends ko{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:r,replacer:i}=n,o=new this(e),a=c((l,u)=>{if(typeof i=="function")u=i.call(t,l,u);else if(Array.isArray(i)&&!i.includes(l))return;(u!==void 0||r)&&o.items.push(wr(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;G(e)?n=e:!e||typeof e!="object"||!("key"in e)?n=new se(e,e?.value):n=new se(e.key,e.value);const r=it(this.items,n.key),i=this.schema?.sortMapEntries;if(r){if(!t)throw new Error(`Key ${n.key} already set`);V(r.value)&&vo(n.value)?r.value.value=n.value:r.value=n.value}else if(i){const o=this.items.findIndex(a=>i(n,a)<0);o===-1?this.items.push(n):this.items.splice(o,0,n)}else this.items.push(n)}delete(e){const t=it(this.items,e);return t?this.items.splice(this.items.indexOf(t),1).length>0:!1}get(e,t){const r=it(this.items,e)?.value;return(!t&&V(r)?r.value:r)??void 0}has(e){return!!it(this.items,e)}set(e,t){this.add(new se(e,t),!0)}toJSON(e,t,n){const r=n?new n:t?.mapAsMap?new Map:{};t?.onCreate&&t.onCreate(r);for(const i of this.items)Oo(t,r,i);return r}toString(e,t,n){if(!e)return JSON.stringify(this);for(const r of this.items)if(!G(r))throw new Error(`Map items must all be pairs; found ${JSON.stringify(r)} instead`);return!e.allNullValues&&this.hasAllNullValues(!1)&&(e=Object.assign({},e,{allNullValues:!0})),$o(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:n,onComment:t})}}const Ot={collection:"map",default:!0,nodeClass:le,tag:"tag:yaml.org,2002:map",resolve(s,e){return vt(s)||e("Expected a mapping for this tag"),s},createNode:c((s,e,t)=>le.from(s,e,t),"createNode")};class Ue extends ko{static{c(this,"YAMLSeq")}static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(Ct,e),this.items=[]}add(e){this.items.push(e)}delete(e){const t=Xn(e);return typeof t!="number"?!1:this.items.splice(t,1).length>0}get(e,t){const n=Xn(e);if(typeof n!="number")return;const r=this.items[n];return!t&&V(r)?r.value:r}has(e){const t=Xn(e);return typeof t=="number"&&t<this.items.length}set(e,t){const n=Xn(e);if(typeof n!="number")throw new Error(`Expected a valid index, not ${e}.`);const r=this.items[n];V(r)&&vo(t)?r.value=t:this.items[n]=t}toJSON(e,t){const n=[];t?.onCreate&&t.onCreate(n);let r=0;for(const i of this.items)n.push(me(i,String(r++),t));return n}toString(e,t,n){return e?$o(this,e,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(e.indent||"")+" ",onChompKeep:n,onComment:t}):JSON.stringify(this)}static from(e,t,n){const{replacer:r}=n,i=new this(e);if(t&&Symbol.iterator in Object(t)){let o=0;for(let a of t){if(typeof r=="function"){const l=t instanceof Set?a:String(o++);a=r.call(t,l,a)}i.items.push(Gt(a,void 0,n))}}return i}}function Xn(s){let e=V(s)?s.value:s;return e&&typeof e=="string"&&(e=Number(e)),typeof e=="number"&&Number.isInteger(e)&&e>=0?e:null}c(Xn,"asItemIndex");const $t={collection:"seq",default:!0,nodeClass:Ue,tag:"tag:yaml.org,2002:seq",resolve(s,e){return kt(s)||e("Expected a sequence for this tag"),s},createNode:c((s,e,t)=>Ue.from(s,e,t),"createNode")},Zn={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),Xt(s,e,t,n)}},Qn={identify:c(s=>s==null,"identify"),createNode:c(()=>new R(null),"createNode"),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:c(()=>new R(null),"resolve"),stringify:c(({source:s},e)=>typeof s=="string"&&Qn.test.test(s)?s:e.options.nullStr,"stringify")},br={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 R(s[0]==="t"||s[0]==="T"),"resolve"),stringify({source:s,value:e},t){if(s&&br.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 Ce({format:s,minFractionDigits:e,tag:t,value:n}){if(typeof n=="bigint")return String(n);const r=typeof n=="number"?n:Number(n);if(!isFinite(r))return isNaN(r)?".nan":r<0?"-.inf":".inf";let i=JSON.stringify(n);if(!s&&e&&(!t||t==="tag:yaml.org,2002:float")&&/^\d/.test(i)){let o=i.indexOf(".");o<0&&(o=i.length,i+=".");let a=e-(i.length-o-1);for(;a-- >0;)i+="0"}return i}c(Ce,"stringifyNumber");const No={identify:c(s=>typeof s=="number","identify"),default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:c(s=>s.slice(-3).toLowerCase()==="nan"?NaN:s[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,"resolve"),stringify:Ce},xo={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():Ce(s)}},Po={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 R(parseFloat(s)),t=s.indexOf(".");return t!==-1&&s[s.length-1]==="0"&&(e.minFractionDigits=s.length-t-1),e},stringify:Ce},es=c(s=>typeof s=="bigint"||Number.isInteger(s),"intIdentify$2"),Sr=c((s,e,t,{intAsBigInt:n})=>n?BigInt(s):parseInt(s.substring(e),t),"intResolve$1");function Mo(s,e,t){const{value:n}=s;return es(n)&&n>=0?t+n.toString(e):Ce(s)}c(Mo,"intStringify$1");const Ro={identify:c(s=>es(s)&&s>=0,"identify"),default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:c((s,e,t)=>Sr(s,2,8,t),"resolve"),stringify:c(s=>Mo(s,8,"0o"),"stringify")},Lo={identify:es,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:c((s,e,t)=>Sr(s,0,10,t),"resolve"),stringify:Ce},Do={identify:c(s=>es(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)=>Sr(s,2,16,t),"resolve"),stringify:c(s=>Mo(s,16,"0x"),"stringify")},Cu=[Ot,$t,Zn,Qn,br,Ro,Lo,Do,No,xo,Po];function jo(s){return typeof s=="bigint"||Number.isInteger(s)}c(jo,"intIdentify$1");const ts=c(({value:s})=>JSON.stringify(s),"stringifyJSON"),vu=[{identify:c(s=>typeof s=="string","identify"),default:!0,tag:"tag:yaml.org,2002:str",resolve:c(s=>s,"resolve"),stringify:ts},{identify:c(s=>s==null,"identify"),createNode:c(()=>new R(null),"createNode"),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:c(()=>null,"resolve"),stringify:ts},{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:ts},{identify:jo,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})=>jo(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:ts}],ku={default:!0,tag:"",test:/^/,resolve(s,e){return e(`Unresolved plain scalar ${JSON.stringify(s)}`),s}},Tu=[Ot,$t].concat(vu,ku),Cr={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 r=0;r<t.length;++r)n[r]=t.charCodeAt(r);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,r,i){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=R.BLOCK_LITERAL),e!==R.QUOTE_DOUBLE){const l=Math.max(n.options.lineWidth-n.indent.length,n.options.minContentWidth),u=Math.ceil(a.length/l),d=new Array(u);for(let f=0,h=0;f<u;++f,h+=l)d[f]=a.substr(h,l);a=d.join(e===R.BLOCK_LITERAL?`
57
- `:" ")}return Xt({comment:s,type:e,value:a},n,r,i)}};function Fo(s,e){if(kt(s))for(let t=0;t<s.items.length;++t){let n=s.items[t];if(!G(n)){if(vt(n)){n.items.length>1&&e("Each pair must have its own sequence indicator");const r=n.items[0]||new se(new R(null));if(n.commentBefore&&(r.key.commentBefore=r.key.commentBefore?`${n.commentBefore}
56
+ ${r}${g}`}else return`${h}${o}${f.join(" ")}${o}${g}`}c(Cu,"stringifyFlowCollection");function Yn({indent:s,options:{commentString:e}},t,n,r){if(n&&r&&(n=n.replace(/^\n+/,"")),n){const i=xe(e(n),s);t.push(i.trimStart())}}c(Yn,"addCommentBefore");function it(s,e){const t=V(e)?e.value:e;for(const n of s)if(G(n)&&(n.key===e||n.key===t||V(n.key)&&n.key.value===t))return n}c(it,"findPair");class le extends To{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:r,replacer:i}=n,o=new this(e),a=c((l,u)=>{if(typeof i=="function")u=i.call(t,l,u);else if(Array.isArray(i)&&!i.includes(l))return;(u!==void 0||r)&&o.items.push(wr(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;G(e)?n=e:!e||typeof e!="object"||!("key"in e)?n=new se(e,e?.value):n=new se(e.key,e.value);const r=it(this.items,n.key),i=this.schema?.sortMapEntries;if(r){if(!t)throw new Error(`Key ${n.key} already set`);V(r.value)&&ko(n.value)?r.value.value=n.value:r.value=n.value}else if(i){const o=this.items.findIndex(a=>i(n,a)<0);o===-1?this.items.push(n):this.items.splice(o,0,n)}else this.items.push(n)}delete(e){const t=it(this.items,e);return t?this.items.splice(this.items.indexOf(t),1).length>0:!1}get(e,t){const r=it(this.items,e)?.value;return(!t&&V(r)?r.value:r)??void 0}has(e){return!!it(this.items,e)}set(e,t){this.add(new se(e,t),!0)}toJSON(e,t,n){const r=n?new n:t?.mapAsMap?new Map:{};t?.onCreate&&t.onCreate(r);for(const i of this.items)$o(t,r,i);return r}toString(e,t,n){if(!e)return JSON.stringify(this);for(const r of this.items)if(!G(r))throw new Error(`Map items must all be pairs; found ${JSON.stringify(r)} instead`);return!e.allNullValues&&this.hasAllNullValues(!1)&&(e=Object.assign({},e,{allNullValues:!0})),No(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:n,onComment:t})}}const Ot={collection:"map",default:!0,nodeClass:le,tag:"tag:yaml.org,2002:map",resolve(s,e){return vt(s)||e("Expected a mapping for this tag"),s},createNode:c((s,e,t)=>le.from(s,e,t),"createNode")};class Ue extends To{static{c(this,"YAMLSeq")}static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(Ct,e),this.items=[]}add(e){this.items.push(e)}delete(e){const t=Xn(e);return typeof t!="number"?!1:this.items.splice(t,1).length>0}get(e,t){const n=Xn(e);if(typeof n!="number")return;const r=this.items[n];return!t&&V(r)?r.value:r}has(e){const t=Xn(e);return typeof t=="number"&&t<this.items.length}set(e,t){const n=Xn(e);if(typeof n!="number")throw new Error(`Expected a valid index, not ${e}.`);const r=this.items[n];V(r)&&ko(t)?r.value=t:this.items[n]=t}toJSON(e,t){const n=[];t?.onCreate&&t.onCreate(n);let r=0;for(const i of this.items)n.push(me(i,String(r++),t));return n}toString(e,t,n){return e?No(this,e,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(e.indent||"")+" ",onChompKeep:n,onComment:t}):JSON.stringify(this)}static from(e,t,n){const{replacer:r}=n,i=new this(e);if(t&&Symbol.iterator in Object(t)){let o=0;for(let a of t){if(typeof r=="function"){const l=t instanceof Set?a:String(o++);a=r.call(t,l,a)}i.items.push(Gt(a,void 0,n))}}return i}}function Xn(s){let e=V(s)?s.value:s;return e&&typeof e=="string"&&(e=Number(e)),typeof e=="number"&&Number.isInteger(e)&&e>=0?e:null}c(Xn,"asItemIndex");const $t={collection:"seq",default:!0,nodeClass:Ue,tag:"tag:yaml.org,2002:seq",resolve(s,e){return kt(s)||e("Expected a sequence for this tag"),s},createNode:c((s,e,t)=>Ue.from(s,e,t),"createNode")},Zn={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),Xt(s,e,t,n)}},Qn={identify:c(s=>s==null,"identify"),createNode:c(()=>new R(null),"createNode"),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:c(()=>new R(null),"resolve"),stringify:c(({source:s},e)=>typeof s=="string"&&Qn.test.test(s)?s:e.options.nullStr,"stringify")},br={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 R(s[0]==="t"||s[0]==="T"),"resolve"),stringify({source:s,value:e},t){if(s&&br.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 Ce({format:s,minFractionDigits:e,tag:t,value:n}){if(typeof n=="bigint")return String(n);const r=typeof n=="number"?n:Number(n);if(!isFinite(r))return isNaN(r)?".nan":r<0?"-.inf":".inf";let i=JSON.stringify(n);if(!s&&e&&(!t||t==="tag:yaml.org,2002:float")&&/^\d/.test(i)){let o=i.indexOf(".");o<0&&(o=i.length,i+=".");let a=e-(i.length-o-1);for(;a-- >0;)i+="0"}return i}c(Ce,"stringifyNumber");const xo={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:Ce},Po={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():Ce(s)}},Mo={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 R(parseFloat(s)),t=s.indexOf(".");return t!==-1&&s[s.length-1]==="0"&&(e.minFractionDigits=s.length-t-1),e},stringify:Ce},es=c(s=>typeof s=="bigint"||Number.isInteger(s),"intIdentify$2"),Sr=c((s,e,t,{intAsBigInt:n})=>n?BigInt(s):parseInt(s.substring(e),t),"intResolve$1");function Ro(s,e,t){const{value:n}=s;return es(n)&&n>=0?t+n.toString(e):Ce(s)}c(Ro,"intStringify$1");const Lo={identify:c(s=>es(s)&&s>=0,"identify"),default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:c((s,e,t)=>Sr(s,2,8,t),"resolve"),stringify:c(s=>Ro(s,8,"0o"),"stringify")},Do={identify:es,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:c((s,e,t)=>Sr(s,0,10,t),"resolve"),stringify:Ce},jo={identify:c(s=>es(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)=>Sr(s,2,16,t),"resolve"),stringify:c(s=>Ro(s,16,"0x"),"stringify")},vu=[Ot,$t,Zn,Qn,br,Lo,Do,jo,xo,Po,Mo];function Fo(s){return typeof s=="bigint"||Number.isInteger(s)}c(Fo,"intIdentify$1");const ts=c(({value:s})=>JSON.stringify(s),"stringifyJSON"),ku=[{identify:c(s=>typeof s=="string","identify"),default:!0,tag:"tag:yaml.org,2002:str",resolve:c(s=>s,"resolve"),stringify:ts},{identify:c(s=>s==null,"identify"),createNode:c(()=>new R(null),"createNode"),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:c(()=>null,"resolve"),stringify:ts},{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:ts},{identify:Fo,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})=>Fo(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:ts}],Tu={default:!0,tag:"",test:/^/,resolve(s,e){return e(`Unresolved plain scalar ${JSON.stringify(s)}`),s}},Eu=[Ot,$t].concat(ku,Tu),Cr={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 r=0;r<t.length;++r)n[r]=t.charCodeAt(r);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,r,i){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=R.BLOCK_LITERAL),e!==R.QUOTE_DOUBLE){const l=Math.max(n.options.lineWidth-n.indent.length,n.options.minContentWidth),u=Math.ceil(a.length/l),d=new Array(u);for(let f=0,h=0;f<u;++f,h+=l)d[f]=a.substr(h,l);a=d.join(e===R.BLOCK_LITERAL?`
57
+ `:" ")}return Xt({comment:s,type:e,value:a},n,r,i)}};function qo(s,e){if(kt(s))for(let t=0;t<s.items.length;++t){let n=s.items[t];if(!G(n)){if(vt(n)){n.items.length>1&&e("Each pair must have its own sequence indicator");const r=n.items[0]||new se(new R(null));if(n.commentBefore&&(r.key.commentBefore=r.key.commentBefore?`${n.commentBefore}
58
58
  ${r.key.commentBefore}`:n.commentBefore),n.comment){const i=r.value??r.key;i.comment=i.comment?`${n.comment}
59
- ${i.comment}`:n.comment}n=r}s.items[t]=G(n)?n:new se(n)}}else e("Expected a sequence for this tag");return s}c(Fo,"resolvePairs");function qo(s,e,t){const{replacer:n}=t,r=new Ue(s);r.tag="tag:yaml.org,2002:pairs";let i=0;if(e&&Symbol.iterator in Object(e))for(let o of e){typeof n=="function"&&(o=n.call(e,String(i++),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;r.items.push(wr(a,l,t))}return r}c(qo,"createPairs");const vr={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:Fo,createNode:qo};class Kt extends Ue{static{c(this,"YAMLOMap")}constructor(){super(),this.add=le.prototype.add.bind(this),this.delete=le.prototype.delete.bind(this),this.get=le.prototype.get.bind(this),this.has=le.prototype.has.bind(this),this.set=le.prototype.set.bind(this),this.tag=Kt.tag}toJSON(e,t){if(!t)return super.toJSON(e);const n=new Map;t?.onCreate&&t.onCreate(n);for(const r of this.items){let i,o;if(G(r)?(i=me(r.key,"",t),o=me(r.value,i,t)):i=me(r,"",t),n.has(i))throw new Error("Ordered maps must not include duplicate keys");n.set(i,o)}return n}static from(e,t,n){const r=qo(e,t,n),i=new this;return i.items=r.items,i}}Kt.tag="tag:yaml.org,2002:omap";const kr={collection:"seq",identify:c(s=>s instanceof Map,"identify"),nodeClass:Kt,default:!1,tag:"tag:yaml.org,2002:omap",resolve(s,e){const t=Fo(s,e),n=[];for(const{key:r}of t.items)V(r)&&(n.includes(r.value)?e(`Ordered maps must not include duplicate keys: ${r.value}`):n.push(r.value));return Object.assign(new Kt,t)},createNode:c((s,e,t)=>Kt.from(s,e,t),"createNode")};function Bo({value:s,source:e},t){return e&&(s?Ko:Uo).test.test(e)?e:s?t.options.trueStr:t.options.falseStr}c(Bo,"boolStringify");const Ko={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 R(!0),"resolve"),stringify:Bo},Uo={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 R(!1),"resolve"),stringify:Bo},Eu={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:Ce},_u={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():Ce(s)}},Iu={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 R(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:Ce},Zt=c(s=>typeof s=="bigint"||Number.isInteger(s),"intIdentify");function ns(s,e,t,{intAsBigInt:n}){const r=s[0];if((r==="-"||r==="+")&&(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 r==="-"?BigInt(-1)*o:o}const i=parseInt(s,t);return r==="-"?-1*i:i}c(ns,"intResolve");function Tr(s,e,t){const{value:n}=s;if(Zt(n)){const r=n.toString(e);return n<0?"-"+t+r.substr(1):t+r}return Ce(s)}c(Tr,"intStringify");const Au={identify:Zt,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:c((s,e,t)=>ns(s,2,2,t),"resolve"),stringify:c(s=>Tr(s,2,"0b"),"stringify")},Ou={identify:Zt,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:c((s,e,t)=>ns(s,1,8,t),"resolve"),stringify:c(s=>Tr(s,8,"0"),"stringify")},$u={identify:Zt,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:c((s,e,t)=>ns(s,0,10,t),"resolve"),stringify:Ce},Nu={identify:Zt,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:c((s,e,t)=>ns(s,2,16,t),"resolve"),stringify:c(s=>Tr(s,16,"0x"),"stringify")};class Ut extends le{static{c(this,"YAMLSet")}constructor(e){super(e),this.tag=Ut.tag}add(e){let t;G(e)?t=e:e&&typeof e=="object"&&"key"in e&&"value"in e&&e.value===null?t=new se(e.key,null):t=new se(e,null),it(this.items,t.key)||this.items.push(t)}get(e,t){const n=it(this.items,e);return!t&&G(n)?V(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=it(this.items,e);n&&!t?this.items.splice(this.items.indexOf(n),1):!n&&t&&this.items.push(new se(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:r}=n,i=new this(e);if(t&&Symbol.iterator in Object(t))for(let o of t)typeof r=="function"&&(o=r.call(t,o,o)),i.items.push(wr(o,null,n));return i}}Ut.tag="tag:yaml.org,2002:set";const Er={collection:"map",identify:c(s=>s instanceof Set,"identify"),nodeClass:Ut,default:!1,tag:"tag:yaml.org,2002:set",createNode:c((s,e,t)=>Ut.from(s,e,t),"createNode"),resolve(s,e){if(vt(s)){if(s.hasAllNullValues(!0))return Object.assign(new Ut,s);e("Set items must all have null values")}else e("Expected a mapping for this tag");return s}};function _r(s,e){const t=s[0],n=t==="-"||t==="+"?s.substring(1):s,r=c(o=>e?BigInt(o):Number(o),"num"),i=n.replace(/_/g,"").split(":").reduce((o,a)=>o*r(60)+r(a),r(0));return t==="-"?r(-1)*i:i}c(_r,"parseSexagesimal");function Wo(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 Ce(s);let n="";e<0&&(n="-",e*=t(-1));const r=t(60),i=[e%r];return e<60?i.unshift(0):(e=(e-i[0])/r,i.unshift(e%r),e>=60&&(e=(e-i[0])/r,i.unshift(e))),n+i.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}c(Wo,"stringifySexagesimal");const Jo={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})=>_r(s,t),"resolve"),stringify:Wo},Ho={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=>_r(s,!1),"resolve"),stringify:Wo},ss={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(ss.test);if(!e)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");const[,t,n,r,i,o,a]=e.map(Number),l=e[7]?Number((e[7]+"00").substr(1,3)):0;let u=Date.UTC(t,n-1,r,i||0,o||0,a||0,l);const d=e[8];if(d&&d!=="Z"){let f=_r(d,!1);Math.abs(f)<30&&(f*=60),u-=6e4*f}return new Date(u)},stringify:c(({value:s})=>s?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??"","stringify")},Vo=[Ot,$t,Zn,Qn,Ko,Uo,Au,Ou,$u,Nu,Eu,_u,Iu,Cr,Pe,kr,vr,Er,Jo,Ho,ss],Go=new Map([["core",Cu],["failsafe",[Ot,$t,Zn]],["json",Tu],["yaml11",Vo],["yaml-1.1",Vo]]),zo={binary:Cr,bool:br,float:Po,floatExp:xo,floatNaN:No,floatTime:Ho,int:Lo,intHex:Do,intOct:Ro,intTime:Jo,map:Ot,merge:Pe,null:Qn,omap:kr,pairs:vr,seq:$t,set:Er,timestamp:ss},xu={"tag:yaml.org,2002:binary":Cr,"tag:yaml.org,2002:merge":Pe,"tag:yaml.org,2002:omap":kr,"tag:yaml.org,2002:pairs":vr,"tag:yaml.org,2002:set":Er,"tag:yaml.org,2002:timestamp":ss};function Ir(s,e,t){const n=Go.get(e);if(n&&!s)return t&&!n.includes(Pe)?n.concat(Pe):n.slice();let r=n;if(!r)if(Array.isArray(s))r=[];else{const i=Array.from(Go.keys()).filter(o=>o!=="yaml11").map(o=>JSON.stringify(o)).join(", ");throw new Error(`Unknown schema "${e}"; use one of ${i} or define customTags array`)}if(Array.isArray(s))for(const i of s)r=r.concat(i);else typeof s=="function"&&(r=s(r.slice()));return t&&(r=r.concat(Pe)),r.reduce((i,o)=>{const a=typeof o=="string"?zo[o]:o;if(!a){const l=JSON.stringify(o),u=Object.keys(zo).map(d=>JSON.stringify(d)).join(", ");throw new Error(`Unknown custom tag ${l}; use one of ${u}`)}return i.includes(a)||i.push(a),i},[])}c(Ir,"getTags");const Pu=c((s,e)=>s.key<e.key?-1:s.key>e.key?1:0,"sortMapEntriesByKey");class js{static{c(this,"Schema")}constructor({compat:e,customTags:t,merge:n,resolveKnownTags:r,schema:i,sortMapEntries:o,toStringDefaults:a}){this.compat=Array.isArray(e)?Ir(e,"compat"):e?Ir(null,e):null,this.name=typeof i=="string"&&i||"core",this.knownTags=r?xu:{},this.tags=Ir(t,this.name,n),this.toStringOptions=a??null,Object.defineProperty(this,Be,{value:Ot}),Object.defineProperty(this,Ie,{value:Zn}),Object.defineProperty(this,Ct,{value:$t}),this.sortMapEntries=typeof o=="function"?o:o===!0?Pu:null}clone(){const e=Object.create(js.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}}function Mu(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 r=_o(s,e),{commentString:i}=r.options;if(s.commentBefore){t.length!==1&&t.unshift("");const l=i(s.commentBefore);t.unshift(xe(l,""))}let o=!1,a=null;if(s.contents){if(X(s.contents)){if(s.contents.spaceBefore&&n&&t.push(""),s.contents.commentBefore){const d=i(s.contents.commentBefore);t.push(xe(d,""))}r.forceBlockIndent=!!s.comment,a=s.contents.comment}const l=a?void 0:()=>o=!0;let u=At(s.contents,r,()=>a=null,l);a&&(u+=rt(u,"",i(a))),(u[0]==="|"||u[0]===">")&&t[t.length-1]==="---"?t[t.length-1]=`--- ${u}`:t.push(u)}else t.push(At(s.contents,r));if(s.directives?.docEnd)if(s.comment){const l=i(s.comment);l.includes(`
59
+ ${i.comment}`:n.comment}n=r}s.items[t]=G(n)?n:new se(n)}}else e("Expected a sequence for this tag");return s}c(qo,"resolvePairs");function Bo(s,e,t){const{replacer:n}=t,r=new Ue(s);r.tag="tag:yaml.org,2002:pairs";let i=0;if(e&&Symbol.iterator in Object(e))for(let o of e){typeof n=="function"&&(o=n.call(e,String(i++),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;r.items.push(wr(a,l,t))}return r}c(Bo,"createPairs");const vr={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:qo,createNode:Bo};class Kt extends Ue{static{c(this,"YAMLOMap")}constructor(){super(),this.add=le.prototype.add.bind(this),this.delete=le.prototype.delete.bind(this),this.get=le.prototype.get.bind(this),this.has=le.prototype.has.bind(this),this.set=le.prototype.set.bind(this),this.tag=Kt.tag}toJSON(e,t){if(!t)return super.toJSON(e);const n=new Map;t?.onCreate&&t.onCreate(n);for(const r of this.items){let i,o;if(G(r)?(i=me(r.key,"",t),o=me(r.value,i,t)):i=me(r,"",t),n.has(i))throw new Error("Ordered maps must not include duplicate keys");n.set(i,o)}return n}static from(e,t,n){const r=Bo(e,t,n),i=new this;return i.items=r.items,i}}Kt.tag="tag:yaml.org,2002:omap";const kr={collection:"seq",identify:c(s=>s instanceof Map,"identify"),nodeClass:Kt,default:!1,tag:"tag:yaml.org,2002:omap",resolve(s,e){const t=qo(s,e),n=[];for(const{key:r}of t.items)V(r)&&(n.includes(r.value)?e(`Ordered maps must not include duplicate keys: ${r.value}`):n.push(r.value));return Object.assign(new Kt,t)},createNode:c((s,e,t)=>Kt.from(s,e,t),"createNode")};function Ko({value:s,source:e},t){return e&&(s?Uo:Wo).test.test(e)?e:s?t.options.trueStr:t.options.falseStr}c(Ko,"boolStringify");const Uo={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 R(!0),"resolve"),stringify:Ko},Wo={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 R(!1),"resolve"),stringify:Ko},_u={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:Ce},Iu={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():Ce(s)}},Au={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 R(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:Ce},Zt=c(s=>typeof s=="bigint"||Number.isInteger(s),"intIdentify");function ns(s,e,t,{intAsBigInt:n}){const r=s[0];if((r==="-"||r==="+")&&(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 r==="-"?BigInt(-1)*o:o}const i=parseInt(s,t);return r==="-"?-1*i:i}c(ns,"intResolve");function Tr(s,e,t){const{value:n}=s;if(Zt(n)){const r=n.toString(e);return n<0?"-"+t+r.substr(1):t+r}return Ce(s)}c(Tr,"intStringify");const Ou={identify:Zt,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:c((s,e,t)=>ns(s,2,2,t),"resolve"),stringify:c(s=>Tr(s,2,"0b"),"stringify")},$u={identify:Zt,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:c((s,e,t)=>ns(s,1,8,t),"resolve"),stringify:c(s=>Tr(s,8,"0"),"stringify")},Nu={identify:Zt,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:c((s,e,t)=>ns(s,0,10,t),"resolve"),stringify:Ce},xu={identify:Zt,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:c((s,e,t)=>ns(s,2,16,t),"resolve"),stringify:c(s=>Tr(s,16,"0x"),"stringify")};class Ut extends le{static{c(this,"YAMLSet")}constructor(e){super(e),this.tag=Ut.tag}add(e){let t;G(e)?t=e:e&&typeof e=="object"&&"key"in e&&"value"in e&&e.value===null?t=new se(e.key,null):t=new se(e,null),it(this.items,t.key)||this.items.push(t)}get(e,t){const n=it(this.items,e);return!t&&G(n)?V(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=it(this.items,e);n&&!t?this.items.splice(this.items.indexOf(n),1):!n&&t&&this.items.push(new se(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:r}=n,i=new this(e);if(t&&Symbol.iterator in Object(t))for(let o of t)typeof r=="function"&&(o=r.call(t,o,o)),i.items.push(wr(o,null,n));return i}}Ut.tag="tag:yaml.org,2002:set";const Er={collection:"map",identify:c(s=>s instanceof Set,"identify"),nodeClass:Ut,default:!1,tag:"tag:yaml.org,2002:set",createNode:c((s,e,t)=>Ut.from(s,e,t),"createNode"),resolve(s,e){if(vt(s)){if(s.hasAllNullValues(!0))return Object.assign(new Ut,s);e("Set items must all have null values")}else e("Expected a mapping for this tag");return s}};function _r(s,e){const t=s[0],n=t==="-"||t==="+"?s.substring(1):s,r=c(o=>e?BigInt(o):Number(o),"num"),i=n.replace(/_/g,"").split(":").reduce((o,a)=>o*r(60)+r(a),r(0));return t==="-"?r(-1)*i:i}c(_r,"parseSexagesimal");function Jo(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 Ce(s);let n="";e<0&&(n="-",e*=t(-1));const r=t(60),i=[e%r];return e<60?i.unshift(0):(e=(e-i[0])/r,i.unshift(e%r),e>=60&&(e=(e-i[0])/r,i.unshift(e))),n+i.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}c(Jo,"stringifySexagesimal");const Ho={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})=>_r(s,t),"resolve"),stringify:Jo},Vo={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=>_r(s,!1),"resolve"),stringify:Jo},ss={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(ss.test);if(!e)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");const[,t,n,r,i,o,a]=e.map(Number),l=e[7]?Number((e[7]+"00").substr(1,3)):0;let u=Date.UTC(t,n-1,r,i||0,o||0,a||0,l);const d=e[8];if(d&&d!=="Z"){let f=_r(d,!1);Math.abs(f)<30&&(f*=60),u-=6e4*f}return new Date(u)},stringify:c(({value:s})=>s?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??"","stringify")},Go=[Ot,$t,Zn,Qn,Uo,Wo,Ou,$u,Nu,xu,_u,Iu,Au,Cr,Pe,kr,vr,Er,Ho,Vo,ss],zo=new Map([["core",vu],["failsafe",[Ot,$t,Zn]],["json",Eu],["yaml11",Go],["yaml-1.1",Go]]),Yo={binary:Cr,bool:br,float:Mo,floatExp:Po,floatNaN:xo,floatTime:Vo,int:Do,intHex:jo,intOct:Lo,intTime:Ho,map:Ot,merge:Pe,null:Qn,omap:kr,pairs:vr,seq:$t,set:Er,timestamp:ss},Pu={"tag:yaml.org,2002:binary":Cr,"tag:yaml.org,2002:merge":Pe,"tag:yaml.org,2002:omap":kr,"tag:yaml.org,2002:pairs":vr,"tag:yaml.org,2002:set":Er,"tag:yaml.org,2002:timestamp":ss};function Ir(s,e,t){const n=zo.get(e);if(n&&!s)return t&&!n.includes(Pe)?n.concat(Pe):n.slice();let r=n;if(!r)if(Array.isArray(s))r=[];else{const i=Array.from(zo.keys()).filter(o=>o!=="yaml11").map(o=>JSON.stringify(o)).join(", ");throw new Error(`Unknown schema "${e}"; use one of ${i} or define customTags array`)}if(Array.isArray(s))for(const i of s)r=r.concat(i);else typeof s=="function"&&(r=s(r.slice()));return t&&(r=r.concat(Pe)),r.reduce((i,o)=>{const a=typeof o=="string"?Yo[o]:o;if(!a){const l=JSON.stringify(o),u=Object.keys(Yo).map(d=>JSON.stringify(d)).join(", ");throw new Error(`Unknown custom tag ${l}; use one of ${u}`)}return i.includes(a)||i.push(a),i},[])}c(Ir,"getTags");const Mu=c((s,e)=>s.key<e.key?-1:s.key>e.key?1:0,"sortMapEntriesByKey");class js{static{c(this,"Schema")}constructor({compat:e,customTags:t,merge:n,resolveKnownTags:r,schema:i,sortMapEntries:o,toStringDefaults:a}){this.compat=Array.isArray(e)?Ir(e,"compat"):e?Ir(null,e):null,this.name=typeof i=="string"&&i||"core",this.knownTags=r?Pu:{},this.tags=Ir(t,this.name,n),this.toStringOptions=a??null,Object.defineProperty(this,Be,{value:Ot}),Object.defineProperty(this,Ie,{value:Zn}),Object.defineProperty(this,Ct,{value:$t}),this.sortMapEntries=typeof o=="function"?o:o===!0?Mu:null}clone(){const e=Object.create(js.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}}function Ru(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 r=Io(s,e),{commentString:i}=r.options;if(s.commentBefore){t.length!==1&&t.unshift("");const l=i(s.commentBefore);t.unshift(xe(l,""))}let o=!1,a=null;if(s.contents){if(X(s.contents)){if(s.contents.spaceBefore&&n&&t.push(""),s.contents.commentBefore){const d=i(s.contents.commentBefore);t.push(xe(d,""))}r.forceBlockIndent=!!s.comment,a=s.contents.comment}const l=a?void 0:()=>o=!0;let u=At(s.contents,r,()=>a=null,l);a&&(u+=rt(u,"",i(a))),(u[0]==="|"||u[0]===">")&&t[t.length-1]==="---"?t[t.length-1]=`--- ${u}`:t.push(u)}else t.push(At(s.contents,r));if(s.directives?.docEnd)if(s.comment){const l=i(s.comment);l.includes(`
60
60
  `)?(t.push("..."),t.push(xe(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(xe(i(l),"")))}return t.join(`
61
61
  `)+`
62
- `}c(Mu,"stringifyDocument");class Wt{static{c(this,"Document")}constructor(e,t,n){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,pe,{value:fr});let r=null;typeof t=="function"||Array.isArray(t)?r=t:n===void 0&&t&&(n=t,t=void 0);const i=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},n);this.options=i;let{version:o}=i;n?._directives?(this.directives=n._directives.atDocument(),this.directives.yaml.explicit&&(o=this.directives.yaml.version)):this.directives=new oe({version:o}),this.setSchema(o,n),this.contents=e===void 0?null:this.createNode(e,r,n)}clone(){const e=Object.create(Wt.prototype,{[pe]:{value:fr}});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=X(this.contents)?this.contents.clone(e.schema):this.contents,this.range&&(e.range=this.range.slice()),e}add(e){Nt(this.contents)&&this.contents.add(e)}addIn(e,t){Nt(this.contents)&&this.contents.addIn(e,t)}createAlias(e,t){if(!e.anchor){const n=So(this);e.anchor=!t||n.has(t)?Co(t||"a",n):t}return new Bn(e.anchor)}createNode(e,t,n){let r;if(typeof t=="function")e=t.call({"":e},"",e),r=t;else if(Array.isArray(t)){const w=c(E=>typeof E=="number"||E instanceof String||E instanceof Number,"keyToStr"),T=t.filter(w).map(String);T.length>0&&(t=t.concat(T)),r=t}else n===void 0&&t&&(n=t,t=void 0);const{aliasDuplicateObjects:i,anchorPrefix:o,flow:a,keepUndefined:l,onTagObj:u,tag:d}=n??{},{onAnchor:f,setAnchors:h,sourceObjects:g}=cu(this,o||"a"),y={aliasDuplicateObjects:i??!0,keepUndefined:l??!1,onAnchor:f,onTagObj:u,replacer:r,schema:this.schema,sourceObjects:g},p=Gt(e,d,y);return a&&Y(p)&&(p.flow=!0),h(),p}createPair(e,t,n={}){const r=this.createNode(e,null,n),i=this.createNode(t,null,n);return new se(r,i)}delete(e){return Nt(this.contents)?this.contents.delete(e):!1}deleteIn(e){return zt(e)?this.contents==null?!1:(this.contents=null,!0):Nt(this.contents)?this.contents.deleteIn(e):!1}get(e,t){return Y(this.contents)?this.contents.get(e,t):void 0}getIn(e,t){return zt(e)?!t&&V(this.contents)?this.contents.value:this.contents:Y(this.contents)?this.contents.getIn(e,t):void 0}has(e){return Y(this.contents)?this.contents.has(e):!1}hasIn(e){return zt(e)?this.contents!==void 0:Y(this.contents)?this.contents.hasIn(e):!1}set(e,t){this.contents==null?this.contents=Un(this.schema,[e],t):Nt(this.contents)&&this.contents.set(e,t)}setIn(e,t){zt(e)?this.contents=t:this.contents==null?this.contents=Un(this.schema,Array.from(e),t):Nt(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 oe({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 oe({version:e}),n={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,n=null;break;default:{const r=JSON.stringify(e);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${r}`)}}if(t.schema instanceof Object)this.schema=t.schema;else if(n)this.schema=new js(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:r,onAnchor:i,reviver:o}={}){const a={anchors:new Map,doc:this,keep:!e,mapAsMap:n===!0,mapKeyWarned:!1,maxAliasCount:typeof r=="number"?r:100},l=me(this.contents,t??"",a);if(typeof i=="function")for(const{count:u,res:d}of a.anchors.values())i(d,u);return typeof o=="function"?_t(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 Mu(this,e)}}function Nt(s){if(Y(s))return!0;throw new Error("Expected a YAML collection as document contents")}c(Nt,"assertCollection");class Ar extends Error{static{c(this,"YAMLError")}constructor(e,t,n,r){super(),this.name=e,this.code=n,this.message=r,this.pos=t}}class ot extends Ar{static{c(this,"YAMLParseError")}constructor(e,t,n){super("YAMLParseError",e,t,n)}}class Yo extends Ar{static{c(this,"YAMLWarning")}constructor(e,t,n){super("YAMLWarning",e,t,n)}}const rs=c((s,e)=>t=>{if(t.pos[0]===-1)return;t.linePos=t.pos.map(a=>e.linePos(a));const{line:n,col:r}=t.linePos[0];t.message+=` at line ${n}, column ${r}`;let i=r-1,o=s.substring(e.lineStarts[n-1],e.lineStarts[n]).replace(/[\n\r]+$/,"");if(i>=60&&o.length>80){const a=Math.min(i-39,o.length-79);o="\u2026"+o.substring(a),i-=a-1}if(o.length>80&&(o=o.substring(0,79)+"\u2026"),n>1&&/^ *$/.test(o.substring(0,i))){let a=s.substring(e.lineStarts[n-2],e.lineStarts[n-1]);a.length>80&&(a=a.substring(0,79)+`\u2026
62
+ `}c(Ru,"stringifyDocument");class Wt{static{c(this,"Document")}constructor(e,t,n){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,pe,{value:fr});let r=null;typeof t=="function"||Array.isArray(t)?r=t:n===void 0&&t&&(n=t,t=void 0);const i=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},n);this.options=i;let{version:o}=i;n?._directives?(this.directives=n._directives.atDocument(),this.directives.yaml.explicit&&(o=this.directives.yaml.version)):this.directives=new oe({version:o}),this.setSchema(o,n),this.contents=e===void 0?null:this.createNode(e,r,n)}clone(){const e=Object.create(Wt.prototype,{[pe]:{value:fr}});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=X(this.contents)?this.contents.clone(e.schema):this.contents,this.range&&(e.range=this.range.slice()),e}add(e){Nt(this.contents)&&this.contents.add(e)}addIn(e,t){Nt(this.contents)&&this.contents.addIn(e,t)}createAlias(e,t){if(!e.anchor){const n=Co(this);e.anchor=!t||n.has(t)?vo(t||"a",n):t}return new Bn(e.anchor)}createNode(e,t,n){let r;if(typeof t=="function")e=t.call({"":e},"",e),r=t;else if(Array.isArray(t)){const w=c(E=>typeof E=="number"||E instanceof String||E instanceof Number,"keyToStr"),T=t.filter(w).map(String);T.length>0&&(t=t.concat(T)),r=t}else n===void 0&&t&&(n=t,t=void 0);const{aliasDuplicateObjects:i,anchorPrefix:o,flow:a,keepUndefined:l,onTagObj:u,tag:d}=n??{},{onAnchor:f,setAnchors:h,sourceObjects:g}=lu(this,o||"a"),y={aliasDuplicateObjects:i??!0,keepUndefined:l??!1,onAnchor:f,onTagObj:u,replacer:r,schema:this.schema,sourceObjects:g},p=Gt(e,d,y);return a&&Y(p)&&(p.flow=!0),h(),p}createPair(e,t,n={}){const r=this.createNode(e,null,n),i=this.createNode(t,null,n);return new se(r,i)}delete(e){return Nt(this.contents)?this.contents.delete(e):!1}deleteIn(e){return zt(e)?this.contents==null?!1:(this.contents=null,!0):Nt(this.contents)?this.contents.deleteIn(e):!1}get(e,t){return Y(this.contents)?this.contents.get(e,t):void 0}getIn(e,t){return zt(e)?!t&&V(this.contents)?this.contents.value:this.contents:Y(this.contents)?this.contents.getIn(e,t):void 0}has(e){return Y(this.contents)?this.contents.has(e):!1}hasIn(e){return zt(e)?this.contents!==void 0:Y(this.contents)?this.contents.hasIn(e):!1}set(e,t){this.contents==null?this.contents=Un(this.schema,[e],t):Nt(this.contents)&&this.contents.set(e,t)}setIn(e,t){zt(e)?this.contents=t:this.contents==null?this.contents=Un(this.schema,Array.from(e),t):Nt(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 oe({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 oe({version:e}),n={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,n=null;break;default:{const r=JSON.stringify(e);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${r}`)}}if(t.schema instanceof Object)this.schema=t.schema;else if(n)this.schema=new js(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:r,onAnchor:i,reviver:o}={}){const a={anchors:new Map,doc:this,keep:!e,mapAsMap:n===!0,mapKeyWarned:!1,maxAliasCount:typeof r=="number"?r:100},l=me(this.contents,t??"",a);if(typeof i=="function")for(const{count:u,res:d}of a.anchors.values())i(d,u);return typeof o=="function"?_t(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 Ru(this,e)}}function Nt(s){if(Y(s))return!0;throw new Error("Expected a YAML collection as document contents")}c(Nt,"assertCollection");class Ar extends Error{static{c(this,"YAMLError")}constructor(e,t,n,r){super(),this.name=e,this.code=n,this.message=r,this.pos=t}}class ot extends Ar{static{c(this,"YAMLParseError")}constructor(e,t,n){super("YAMLParseError",e,t,n)}}class Xo extends Ar{static{c(this,"YAMLWarning")}constructor(e,t,n){super("YAMLWarning",e,t,n)}}const rs=c((s,e)=>t=>{if(t.pos[0]===-1)return;t.linePos=t.pos.map(a=>e.linePos(a));const{line:n,col:r}=t.linePos[0];t.message+=` at line ${n}, column ${r}`;let i=r-1,o=s.substring(e.lineStarts[n-1],e.lineStarts[n]).replace(/[\n\r]+$/,"");if(i>=60&&o.length>80){const a=Math.min(i-39,o.length-79);o="\u2026"+o.substring(a),i-=a-1}if(o.length>80&&(o=o.substring(0,79)+"\u2026"),n>1&&/^ *$/.test(o.substring(0,i))){let a=s.substring(e.lineStarts[n-2],e.lineStarts[n-1]);a.length>80&&(a=a.substring(0,79)+`\u2026
63
63
  `),o=a+o}if(/[^ ]/.test(o)){let a=1;const l=t.linePos[1];l&&l.line===n&&l.col>r&&(a=Math.max(1,Math.min(l.col-r,80-i)));const u=" ".repeat(i)+"^".repeat(a);t.message+=`:
64
64
 
65
65
  ${o}
66
66
  ${u}
67
67
  `}},"prettifyError");function xt(s,{flow:e,indicator:t,next:n,offset:r,onError:i,parentIndent:o,startOnNewline:a}){let l=!1,u=a,d=a,f="",h="",g=!1,y=!1,p=null,w=null,T=null,E=null,$=null,I=null,x=null;for(const O of s)switch(y&&(O.type!=="space"&&O.type!=="newline"&&O.type!=="comma"&&i(O.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),y=!1),p&&(u&&O.type!=="comment"&&O.type!=="newline"&&i(p,"TAB_AS_INDENT","Tabs are not allowed as indentation"),p=null),O.type){case"space":!e&&(t!=="doc-start"||n?.type!=="flow-collection")&&O.source.includes(" ")&&(p=O),d=!0;break;case"comment":{d||i(O,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");const te=O.source.substring(1)||" ";f?f+=h+te:f=te,h="",u=!1;break}case"newline":u?f?f+=O.source:(!I||t!=="seq-item-ind")&&(l=!0):h+=O.source,u=!0,g=!0,(w||T)&&(E=O),d=!0;break;case"anchor":w&&i(O,"MULTIPLE_ANCHORS","A node can have at most one anchor"),O.source.endsWith(":")&&i(O.offset+O.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),w=O,x??(x=O.offset),u=!1,d=!1,y=!0;break;case"tag":{T&&i(O,"MULTIPLE_TAGS","A node can have at most one tag"),T=O,x??(x=O.offset),u=!1,d=!1,y=!0;break}case t:(w||T)&&i(O,"BAD_PROP_ORDER",`Anchors and tags must be after the ${O.source} indicator`),I&&i(O,"UNEXPECTED_TOKEN",`Unexpected ${O.source} in ${e??"collection"}`),I=O,u=t==="seq-item-ind"||t==="explicit-key-ind",d=!1;break;case"comma":if(e){$&&i(O,"UNEXPECTED_TOKEN",`Unexpected , in ${e}`),$=O,u=!1,d=!1;break}default:i(O,"UNEXPECTED_TOKEN",`Unexpected ${O.type} token`),u=!1,d=!1}const M=s[s.length-1],j=M?M.offset+M.source.length:r;return y&&n&&n.type!=="space"&&n.type!=="newline"&&n.type!=="comma"&&(n.type!=="scalar"||n.source!=="")&&i(n.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),p&&(u&&p.indent<=o||n?.type==="block-map"||n?.type==="block-seq")&&i(p,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:$,found:I,spaceBefore:l,comment:f,hasNewline:g,anchor:w,tag:T,newlineAfterProp:E,end:j,start:x??j}}c(xt,"resolveProps");function Qt(s){if(!s)return null;switch(s.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(s.source.includes(`
68
- `))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(Qt(e.key)||Qt(e.value))return!0}return!1;default:return!0}}c(Qt,"containsNewline");function Or(s,e,t){if(e?.type==="flow-collection"){const n=e.end[0];n.indent===s&&(n.source==="]"||n.source==="}")&&Qt(e)&&t(n,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}c(Or,"flowIndentCheck");function Xo(s,e,t){const{uniqueKeys:n}=s.options;if(n===!1)return!1;const r=typeof n=="function"?n:(i,o)=>i===o||V(i)&&V(o)&&i.value===o.value;return e.some(i=>r(i.key,t))}c(Xo,"mapIncludes");const Zo="All mapping items must start at the same column";function Ru({composeNode:s,composeEmptyNode:e},t,n,r,i){const o=i?.nodeClass??le,a=new o(t.schema);t.atRoot&&(t.atRoot=!1);let l=n.offset,u=null;for(const d of n.items){const{start:f,key:h,sep:g,value:y}=d,p=xt(f,{indicator:"explicit-key-ind",next:h??g?.[0],offset:l,onError:r,parentIndent:n.indent,startOnNewline:!0}),w=!p.found;if(w){if(h&&(h.type==="block-seq"?r(l,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in h&&h.indent!==n.indent&&r(l,"BAD_INDENT",Zo)),!p.anchor&&!p.tag&&!g){u=p.end,p.comment&&(a.comment?a.comment+=`
69
- `+p.comment:a.comment=p.comment);continue}(p.newlineAfterProp||Qt(h))&&r(h??f[f.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else p.found?.indent!==n.indent&&r(l,"BAD_INDENT",Zo);t.atKey=!0;const T=p.end,E=h?s(t,h,p,r):e(t,T,f,null,p,r);t.schema.compat&&Or(n.indent,h,r),t.atKey=!1,Xo(t,a.items,E)&&r(T,"DUPLICATE_KEY","Map keys must be unique");const $=xt(g??[],{indicator:"map-value-ind",next:y,offset:E.range[2],onError:r,parentIndent:n.indent,startOnNewline:!h||h.type==="block-scalar"});if(l=$.end,$.found){w&&(y?.type==="block-map"&&!$.hasNewline&&r(l,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),t.options.strict&&p.start<$.found.offset-1024&&r(E.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));const I=y?s(t,y,$,r):e(t,l,g,null,$,r);t.schema.compat&&Or(n.indent,y,r),l=I.range[2];const x=new se(E,I);t.options.keepSourceTokens&&(x.srcToken=d),a.items.push(x)}else{w&&r(E.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),$.comment&&(E.comment?E.comment+=`
70
- `+$.comment:E.comment=$.comment);const I=new se(E);t.options.keepSourceTokens&&(I.srcToken=d),a.items.push(I)}}return u&&u<l&&r(u,"IMPOSSIBLE","Map comment with trailing content"),a.range=[n.offset,l,u??l],a}c(Ru,"resolveBlockMap");function Lu({composeNode:s,composeEmptyNode:e},t,n,r,i){const o=i?.nodeClass??Ue,a=new o(t.schema);t.atRoot&&(t.atRoot=!1),t.atKey&&(t.atKey=!1);let l=n.offset,u=null;for(const{start:d,value:f}of n.items){const h=xt(d,{indicator:"seq-item-ind",next:f,offset:l,onError:r,parentIndent:n.indent,startOnNewline:!0});if(!h.found)if(h.anchor||h.tag||f)f&&f.type==="block-seq"?r(h.end,"BAD_INDENT","All sequence items must start at the same column"):r(l,"MISSING_CHAR","Sequence item without - indicator");else{u=h.end,h.comment&&(a.comment=h.comment);continue}const g=f?s(t,f,h,r):e(t,h.end,d,null,h,r);t.schema.compat&&Or(n.indent,f,r),l=g.range[2],a.items.push(g)}return a.range=[n.offset,l,u??l],a}c(Lu,"resolveBlockSeq");function en(s,e,t,n){let r="";if(s){let i=!1,o="";for(const a of s){const{source:l,type:u}=a;switch(u){case"space":i=!0;break;case"comment":{t&&!i&&n(a,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");const d=l.substring(1)||" ";r?r+=o+d:r=d,o="";break}case"newline":r&&(o+=l),i=!0;break;default:n(a,"UNEXPECTED_TOKEN",`Unexpected ${u} at node end`)}e+=l.length}}return{comment:r,offset:e}}c(en,"resolveEnd");const $r="Block collections are not allowed within flow collections",Nr=c(s=>s&&(s.type==="block-map"||s.type==="block-seq"),"isBlock");function Du({composeNode:s,composeEmptyNode:e},t,n,r,i){const o=n.start.source==="{",a=o?"flow map":"flow sequence",l=i?.nodeClass??(o?le:Ue),u=new l(t.schema);u.flow=!0;const d=t.atRoot;d&&(t.atRoot=!1),t.atKey&&(t.atKey=!1);let f=n.offset+n.start.source.length;for(let w=0;w<n.items.length;++w){const T=n.items[w],{start:E,key:$,sep:I,value:x}=T,M=xt(E,{flow:a,indicator:"explicit-key-ind",next:$??I?.[0],offset:f,onError:r,parentIndent:n.indent,startOnNewline:!1});if(!M.found){if(!M.anchor&&!M.tag&&!I&&!x){w===0&&M.comma?r(M.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`):w<n.items.length-1&&r(M.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${a}`),M.comment&&(u.comment?u.comment+=`
68
+ `))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(Qt(e.key)||Qt(e.value))return!0}return!1;default:return!0}}c(Qt,"containsNewline");function Or(s,e,t){if(e?.type==="flow-collection"){const n=e.end[0];n.indent===s&&(n.source==="]"||n.source==="}")&&Qt(e)&&t(n,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}c(Or,"flowIndentCheck");function Zo(s,e,t){const{uniqueKeys:n}=s.options;if(n===!1)return!1;const r=typeof n=="function"?n:(i,o)=>i===o||V(i)&&V(o)&&i.value===o.value;return e.some(i=>r(i.key,t))}c(Zo,"mapIncludes");const Qo="All mapping items must start at the same column";function Lu({composeNode:s,composeEmptyNode:e},t,n,r,i){const o=i?.nodeClass??le,a=new o(t.schema);t.atRoot&&(t.atRoot=!1);let l=n.offset,u=null;for(const d of n.items){const{start:f,key:h,sep:g,value:y}=d,p=xt(f,{indicator:"explicit-key-ind",next:h??g?.[0],offset:l,onError:r,parentIndent:n.indent,startOnNewline:!0}),w=!p.found;if(w){if(h&&(h.type==="block-seq"?r(l,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in h&&h.indent!==n.indent&&r(l,"BAD_INDENT",Qo)),!p.anchor&&!p.tag&&!g){u=p.end,p.comment&&(a.comment?a.comment+=`
69
+ `+p.comment:a.comment=p.comment);continue}(p.newlineAfterProp||Qt(h))&&r(h??f[f.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else p.found?.indent!==n.indent&&r(l,"BAD_INDENT",Qo);t.atKey=!0;const T=p.end,E=h?s(t,h,p,r):e(t,T,f,null,p,r);t.schema.compat&&Or(n.indent,h,r),t.atKey=!1,Zo(t,a.items,E)&&r(T,"DUPLICATE_KEY","Map keys must be unique");const $=xt(g??[],{indicator:"map-value-ind",next:y,offset:E.range[2],onError:r,parentIndent:n.indent,startOnNewline:!h||h.type==="block-scalar"});if(l=$.end,$.found){w&&(y?.type==="block-map"&&!$.hasNewline&&r(l,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),t.options.strict&&p.start<$.found.offset-1024&&r(E.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));const I=y?s(t,y,$,r):e(t,l,g,null,$,r);t.schema.compat&&Or(n.indent,y,r),l=I.range[2];const x=new se(E,I);t.options.keepSourceTokens&&(x.srcToken=d),a.items.push(x)}else{w&&r(E.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),$.comment&&(E.comment?E.comment+=`
70
+ `+$.comment:E.comment=$.comment);const I=new se(E);t.options.keepSourceTokens&&(I.srcToken=d),a.items.push(I)}}return u&&u<l&&r(u,"IMPOSSIBLE","Map comment with trailing content"),a.range=[n.offset,l,u??l],a}c(Lu,"resolveBlockMap");function Du({composeNode:s,composeEmptyNode:e},t,n,r,i){const o=i?.nodeClass??Ue,a=new o(t.schema);t.atRoot&&(t.atRoot=!1),t.atKey&&(t.atKey=!1);let l=n.offset,u=null;for(const{start:d,value:f}of n.items){const h=xt(d,{indicator:"seq-item-ind",next:f,offset:l,onError:r,parentIndent:n.indent,startOnNewline:!0});if(!h.found)if(h.anchor||h.tag||f)f&&f.type==="block-seq"?r(h.end,"BAD_INDENT","All sequence items must start at the same column"):r(l,"MISSING_CHAR","Sequence item without - indicator");else{u=h.end,h.comment&&(a.comment=h.comment);continue}const g=f?s(t,f,h,r):e(t,h.end,d,null,h,r);t.schema.compat&&Or(n.indent,f,r),l=g.range[2],a.items.push(g)}return a.range=[n.offset,l,u??l],a}c(Du,"resolveBlockSeq");function en(s,e,t,n){let r="";if(s){let i=!1,o="";for(const a of s){const{source:l,type:u}=a;switch(u){case"space":i=!0;break;case"comment":{t&&!i&&n(a,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");const d=l.substring(1)||" ";r?r+=o+d:r=d,o="";break}case"newline":r&&(o+=l),i=!0;break;default:n(a,"UNEXPECTED_TOKEN",`Unexpected ${u} at node end`)}e+=l.length}}return{comment:r,offset:e}}c(en,"resolveEnd");const $r="Block collections are not allowed within flow collections",Nr=c(s=>s&&(s.type==="block-map"||s.type==="block-seq"),"isBlock");function ju({composeNode:s,composeEmptyNode:e},t,n,r,i){const o=n.start.source==="{",a=o?"flow map":"flow sequence",l=i?.nodeClass??(o?le:Ue),u=new l(t.schema);u.flow=!0;const d=t.atRoot;d&&(t.atRoot=!1),t.atKey&&(t.atKey=!1);let f=n.offset+n.start.source.length;for(let w=0;w<n.items.length;++w){const T=n.items[w],{start:E,key:$,sep:I,value:x}=T,M=xt(E,{flow:a,indicator:"explicit-key-ind",next:$??I?.[0],offset:f,onError:r,parentIndent:n.indent,startOnNewline:!1});if(!M.found){if(!M.anchor&&!M.tag&&!I&&!x){w===0&&M.comma?r(M.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`):w<n.items.length-1&&r(M.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${a}`),M.comment&&(u.comment?u.comment+=`
71
71
  `+M.comment:u.comment=M.comment),f=M.end;continue}!o&&t.options.strict&&Qt($)&&r($,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(w===0)M.comma&&r(M.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`);else if(M.comma||r(M.start,"MISSING_CHAR",`Missing , between ${a} items`),M.comment){let j="";e:for(const O of E)switch(O.type){case"comma":case"space":break;case"comment":j=O.source.substring(1);break e;default:break e}if(j){let O=u.items[u.items.length-1];G(O)&&(O=O.value??O.key),O.comment?O.comment+=`
72
72
  `+j:O.comment=j,M.comment=M.comment.substring(j.length+1)}}if(!o&&!I&&!M.found){const j=x?s(t,x,M,r):e(t,M.end,I,null,M,r);u.items.push(j),f=j.range[2],Nr(x)&&r(j.range,"BLOCK_IN_FLOW",$r)}else{t.atKey=!0;const j=M.end,O=$?s(t,$,M,r):e(t,j,E,null,M,r);Nr($)&&r(O.range,"BLOCK_IN_FLOW",$r),t.atKey=!1;const te=xt(I??[],{flow:a,indicator:"map-value-ind",next:x,offset:O.range[2],onError:r,parentIndent:n.indent,startOnNewline:!1});if(te.found){if(!o&&!M.found&&t.options.strict){if(I)for(const ne of I){if(ne===te.found)break;if(ne.type==="newline"){r(ne,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}M.start<te.found.offset-1024&&r(te.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else x&&("source"in x&&x.source&&x.source[0]===":"?r(x,"MISSING_CHAR",`Missing space after : in ${a}`):r(te.start,"MISSING_CHAR",`Missing , or : between ${a} items`));const Fe=x?s(t,x,te,r):te.found?e(t,te.end,I,null,te,r):null;Fe?Nr(x)&&r(Fe.range,"BLOCK_IN_FLOW",$r):te.comment&&(O.comment?O.comment+=`
73
- `+te.comment:O.comment=te.comment);const dt=new se(O,Fe);if(t.options.keepSourceTokens&&(dt.srcToken=T),o){const ne=u;Xo(t,ne.items,O)&&r(j,"DUPLICATE_KEY","Map keys must be unique"),ne.items.push(dt)}else{const ne=new le(t.schema);ne.flow=!0,ne.items.push(dt);const ki=(Fe??O).range;ne.range=[O.range[0],ki[1],ki[2]],u.items.push(ne)}f=Fe?Fe.range[2]:te.end}}const h=o?"}":"]",[g,...y]=n.end;let p=f;if(g&&g.source===h)p=g.offset+g.source.length;else{const w=a[0].toUpperCase()+a.substring(1),T=d?`${w} must end with a ${h}`:`${w} in block collection must be sufficiently indented and end with a ${h}`;r(f,d?"MISSING_CHAR":"BAD_INDENT",T),g&&g.source.length!==1&&y.unshift(g)}if(y.length>0){const w=en(y,p,t.options.strict,r);w.comment&&(u.comment?u.comment+=`
74
- `+w.comment:u.comment=w.comment),u.range=[n.offset,p,w.offset]}else u.range=[n.offset,p,p];return u}c(Du,"resolveFlowCollection");function xr(s,e,t,n,r,i){const o=t.type==="block-map"?Ru(s,e,t,n,i):t.type==="block-seq"?Lu(s,e,t,n,i):Du(s,e,t,n,i),a=o.constructor;return r==="!"||r===a.tagName?(o.tag=a.tagName,o):(r&&(o.tag=r),o)}c(xr,"resolveCollection");function ju(s,e,t,n,r){const i=n.tag,o=i?e.directives.tagName(i.source,h=>r(i,"TAG_RESOLVE_FAILED",h)):null;if(t.type==="block-seq"){const{anchor:h,newlineAfterProp:g}=n,y=h&&i?h.offset>i.offset?h:i:h??i;y&&(!g||g.offset<y.offset)&&r(y,"MISSING_CHAR","Missing newline after block sequence props")}const a=t.type==="block-map"?"map":t.type==="block-seq"?"seq":t.start.source==="{"?"map":"seq";if(!i||!o||o==="!"||o===le.tagName&&a==="map"||o===Ue.tagName&&a==="seq")return xr(s,e,t,r,o);let l=e.schema.tags.find(h=>h.tag===o&&h.collection===a);if(!l){const h=e.schema.knownTags[o];if(h&&h.collection===a)e.schema.tags.push(Object.assign({},h,{default:!1})),l=h;else return h?r(i,"BAD_COLLECTION_TYPE",`${h.tag} used for ${a} collection, but expects ${h.collection??"scalar"}`,!0):r(i,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),xr(s,e,t,r,o)}const u=xr(s,e,t,r,o,l),d=l.resolve?.(u,h=>r(i,"TAG_RESOLVE_FAILED",h),e.options)??u,f=X(d)?d:new R(d);return f.range=u.range,f.tag=o,l?.format&&(f.format=l.format),f}c(ju,"composeCollection");function Qo(s,e,t){const n=e.offset,r=Fu(e,s.options.strict,t);if(!r)return{value:"",type:null,comment:"",range:[n,n,n]};const i=r.mode===">"?R.BLOCK_FOLDED:R.BLOCK_LITERAL,o=e.source?qu(e.source):[];let a=o.length;for(let p=o.length-1;p>=0;--p){const w=o[p][1];if(w===""||w==="\r")a=p;else break}if(a===0){const p=r.chomp==="+"&&o.length>0?`
73
+ `+te.comment:O.comment=te.comment);const dt=new se(O,Fe);if(t.options.keepSourceTokens&&(dt.srcToken=T),o){const ne=u;Zo(t,ne.items,O)&&r(j,"DUPLICATE_KEY","Map keys must be unique"),ne.items.push(dt)}else{const ne=new le(t.schema);ne.flow=!0,ne.items.push(dt);const ki=(Fe??O).range;ne.range=[O.range[0],ki[1],ki[2]],u.items.push(ne)}f=Fe?Fe.range[2]:te.end}}const h=o?"}":"]",[g,...y]=n.end;let p=f;if(g&&g.source===h)p=g.offset+g.source.length;else{const w=a[0].toUpperCase()+a.substring(1),T=d?`${w} must end with a ${h}`:`${w} in block collection must be sufficiently indented and end with a ${h}`;r(f,d?"MISSING_CHAR":"BAD_INDENT",T),g&&g.source.length!==1&&y.unshift(g)}if(y.length>0){const w=en(y,p,t.options.strict,r);w.comment&&(u.comment?u.comment+=`
74
+ `+w.comment:u.comment=w.comment),u.range=[n.offset,p,w.offset]}else u.range=[n.offset,p,p];return u}c(ju,"resolveFlowCollection");function xr(s,e,t,n,r,i){const o=t.type==="block-map"?Lu(s,e,t,n,i):t.type==="block-seq"?Du(s,e,t,n,i):ju(s,e,t,n,i),a=o.constructor;return r==="!"||r===a.tagName?(o.tag=a.tagName,o):(r&&(o.tag=r),o)}c(xr,"resolveCollection");function Fu(s,e,t,n,r){const i=n.tag,o=i?e.directives.tagName(i.source,h=>r(i,"TAG_RESOLVE_FAILED",h)):null;if(t.type==="block-seq"){const{anchor:h,newlineAfterProp:g}=n,y=h&&i?h.offset>i.offset?h:i:h??i;y&&(!g||g.offset<y.offset)&&r(y,"MISSING_CHAR","Missing newline after block sequence props")}const a=t.type==="block-map"?"map":t.type==="block-seq"?"seq":t.start.source==="{"?"map":"seq";if(!i||!o||o==="!"||o===le.tagName&&a==="map"||o===Ue.tagName&&a==="seq")return xr(s,e,t,r,o);let l=e.schema.tags.find(h=>h.tag===o&&h.collection===a);if(!l){const h=e.schema.knownTags[o];if(h&&h.collection===a)e.schema.tags.push(Object.assign({},h,{default:!1})),l=h;else return h?r(i,"BAD_COLLECTION_TYPE",`${h.tag} used for ${a} collection, but expects ${h.collection??"scalar"}`,!0):r(i,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),xr(s,e,t,r,o)}const u=xr(s,e,t,r,o,l),d=l.resolve?.(u,h=>r(i,"TAG_RESOLVE_FAILED",h),e.options)??u,f=X(d)?d:new R(d);return f.range=u.range,f.tag=o,l?.format&&(f.format=l.format),f}c(Fu,"composeCollection");function ea(s,e,t){const n=e.offset,r=qu(e,s.options.strict,t);if(!r)return{value:"",type:null,comment:"",range:[n,n,n]};const i=r.mode===">"?R.BLOCK_FOLDED:R.BLOCK_LITERAL,o=e.source?Bu(e.source):[];let a=o.length;for(let p=o.length-1;p>=0;--p){const w=o[p][1];if(w===""||w==="\r")a=p;else break}if(a===0){const p=r.chomp==="+"&&o.length>0?`
75
75
  `.repeat(Math.max(1,o.length-1)):"";let w=n+r.length;return e.source&&(w+=e.source.length),{value:p,type:i,comment:r.comment,range:[n,w,w]}}let l=e.indent+r.indent,u=e.offset+r.length,d=0;for(let p=0;p<a;++p){const[w,T]=o[p];if(T===""||T==="\r")r.indent===0&&w.length>l&&(l=w.length);else{w.length<l&&t(u+w.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator"),r.indent===0&&(l=w.length),d=p,l===0&&!s.atRoot&&t(u,"BAD_INDENT","Block scalar values in collections must be indented");break}u+=w.length+T.length+1}for(let p=o.length-1;p>=a;--p)o[p][0].length>l&&(a=p+1);let f="",h="",g=!1;for(let p=0;p<d;++p)f+=o[p][0].slice(l)+`
76
76
  `;for(let p=d;p<a;++p){let[w,T]=o[p];u+=w.length+T.length+1;const E=T[T.length-1]==="\r";if(E&&(T=T.slice(0,-1)),T&&w.length<l){const I=`Block scalar lines must not be less indented than their ${r.indent?"explicit indentation indicator":"first line"}`;t(u-T.length-(E?2:1),"BAD_INDENT",I),w=""}i===R.BLOCK_LITERAL?(f+=h+w.slice(l)+T,h=`
77
77
  `):w.length>l||T[0]===" "?(h===" "?h=`
@@ -86,41 +86,41 @@ ${u}
86
86
  `+o[p][0].slice(l);f[f.length-1]!==`
87
87
  `&&(f+=`
88
88
  `);break;default:f+=`
89
- `}const y=n+r.length+e.source.length;return{value:f,type:i,comment:r.comment,range:[n,y,y]}}c(Qo,"resolveBlockScalar");function Fu({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:r}=e[0],i=r[0];let o=0,a="",l=-1;for(let h=1;h<r.length;++h){const g=r[h];if(!a&&(g==="-"||g==="+"))a=g;else{const y=Number(g);!o&&y?o=y:l===-1&&(l=s+h)}}l!==-1&&n(l,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${r}`);let u=!1,d="",f=r.length;for(let h=1;h<e.length;++h){const g=e[h];switch(g.type){case"space":u=!0;case"newline":f+=g.source.length;break;case"comment":t&&!u&&n(g,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),f+=g.source.length,d=g.source.substring(1);break;case"error":n(g,"UNEXPECTED_TOKEN",g.message),f+=g.source.length;break;default:{const y=`Unexpected token in block scalar header: ${g.type}`;n(g,"UNEXPECTED_TOKEN",y);const p=g.source;p&&typeof p=="string"&&(f+=p.length)}}}return{mode:i,indent:o,chomp:a,comment:d,length:f}}c(Fu,"parseBlockScalarHeader");function qu(s){const e=s.split(/\n( *)/),t=e[0],n=t.match(/^( *)/),i=[n?.[1]?[n[1],t.slice(n[1].length)]:["",t]];for(let o=1;o<e.length;o+=2)i.push([e[o],e[o+1]]);return i}c(qu,"splitLines");function ea(s,e,t){const{offset:n,type:r,source:i,end:o}=s;let a,l;const u=c((h,g,y)=>t(n+h,g,y),"_onError");switch(r){case"scalar":a=R.PLAIN,l=Bu(i,u);break;case"single-quoted-scalar":a=R.QUOTE_SINGLE,l=Ku(i,u);break;case"double-quoted-scalar":a=R.QUOTE_DOUBLE,l=Uu(i,u);break;default:return t(s,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${r}`),{value:"",type:null,comment:"",range:[n,n+i.length,n+i.length]}}const d=n+i.length,f=en(o,d,e,t);return{value:l,type:a,comment:f.comment,range:[n,d,f.offset]}}c(ea,"resolveFlowScalar");function Bu(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}`),ta(s)}c(Bu,"plainValue");function Ku(s,e){return(s[s.length-1]!=="'"||s.length===1)&&e(s.length,"MISSING_CHAR","Missing closing 'quote"),ta(s.slice(1,-1)).replace(/''/g,"'")}c(Ku,"singleQuotedValue");function ta(s){let e,t;try{e=new RegExp(`(.*?)(?<![ ])[ ]*\r?
89
+ `}const y=n+r.length+e.source.length;return{value:f,type:i,comment:r.comment,range:[n,y,y]}}c(ea,"resolveBlockScalar");function qu({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:r}=e[0],i=r[0];let o=0,a="",l=-1;for(let h=1;h<r.length;++h){const g=r[h];if(!a&&(g==="-"||g==="+"))a=g;else{const y=Number(g);!o&&y?o=y:l===-1&&(l=s+h)}}l!==-1&&n(l,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${r}`);let u=!1,d="",f=r.length;for(let h=1;h<e.length;++h){const g=e[h];switch(g.type){case"space":u=!0;case"newline":f+=g.source.length;break;case"comment":t&&!u&&n(g,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),f+=g.source.length,d=g.source.substring(1);break;case"error":n(g,"UNEXPECTED_TOKEN",g.message),f+=g.source.length;break;default:{const y=`Unexpected token in block scalar header: ${g.type}`;n(g,"UNEXPECTED_TOKEN",y);const p=g.source;p&&typeof p=="string"&&(f+=p.length)}}}return{mode:i,indent:o,chomp:a,comment:d,length:f}}c(qu,"parseBlockScalarHeader");function Bu(s){const e=s.split(/\n( *)/),t=e[0],n=t.match(/^( *)/),i=[n?.[1]?[n[1],t.slice(n[1].length)]:["",t]];for(let o=1;o<e.length;o+=2)i.push([e[o],e[o+1]]);return i}c(Bu,"splitLines");function ta(s,e,t){const{offset:n,type:r,source:i,end:o}=s;let a,l;const u=c((h,g,y)=>t(n+h,g,y),"_onError");switch(r){case"scalar":a=R.PLAIN,l=Ku(i,u);break;case"single-quoted-scalar":a=R.QUOTE_SINGLE,l=Uu(i,u);break;case"double-quoted-scalar":a=R.QUOTE_DOUBLE,l=Wu(i,u);break;default:return t(s,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${r}`),{value:"",type:null,comment:"",range:[n,n+i.length,n+i.length]}}const d=n+i.length,f=en(o,d,e,t);return{value:l,type:a,comment:f.comment,range:[n,d,f.offset]}}c(ta,"resolveFlowScalar");function Ku(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}`),na(s)}c(Ku,"plainValue");function Uu(s,e){return(s[s.length-1]!=="'"||s.length===1)&&e(s.length,"MISSING_CHAR","Missing closing 'quote"),na(s.slice(1,-1)).replace(/''/g,"'")}c(Uu,"singleQuotedValue");function na(s){let e,t;try{e=new RegExp(`(.*?)(?<![ ])[ ]*\r?
90
90
  `,"sy"),t=new RegExp(`[ ]*(.*?)(?:(?<![ ])[ ]*)?\r?
91
91
  `,"sy")}catch{e=/(.*?)[ \t]*\r?\n/sy,t=/[ \t]*(.*?)[ \t]*\r?\n/sy}let n=e.exec(s);if(!n)return s;let r=n[1],i=" ",o=e.lastIndex;for(t.lastIndex=o;n=t.exec(s);)n[1]===""?i===`
92
92
  `?r+=i:i=`
93
- `:(r+=i+n[1],i=" "),o=t.lastIndex;const a=/[ \t]*(.*)/sy;return a.lastIndex=o,n=a.exec(s),r+i+(n?.[1]??"")}c(ta,"foldLines");function Uu(s,e){let t="";for(let n=1;n<s.length-1;++n){const r=s[n];if(!(r==="\r"&&s[n+1]===`
93
+ `:(r+=i+n[1],i=" "),o=t.lastIndex;const a=/[ \t]*(.*)/sy;return a.lastIndex=o,n=a.exec(s),r+i+(n?.[1]??"")}c(na,"foldLines");function Wu(s,e){let t="";for(let n=1;n<s.length-1;++n){const r=s[n];if(!(r==="\r"&&s[n+1]===`
94
94
  `))if(r===`
95
- `){const{fold:i,offset:o}=Wu(s,n);t+=i,n=o}else if(r==="\\"){let i=s[++n];const o=Ju[i];if(o)t+=o;else if(i===`
95
+ `){const{fold:i,offset:o}=Ju(s,n);t+=i,n=o}else if(r==="\\"){let i=s[++n];const o=Hu[i];if(o)t+=o;else if(i===`
96
96
  `)for(i=s[n+1];i===" "||i===" ";)i=s[++n+1];else if(i==="\r"&&s[n+1]===`
97
- `)for(i=s[++n+1];i===" "||i===" ";)i=s[++n+1];else if(i==="x"||i==="u"||i==="U"){const a={x:2,u:4,U:8}[i];t+=Hu(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(r===" "||r===" "){const i=n;let o=s[n+1];for(;o===" "||o===" ";)o=s[++n+1];o!==`
97
+ `)for(i=s[++n+1];i===" "||i===" ";)i=s[++n+1];else if(i==="x"||i==="u"||i==="U"){const a={x:2,u:4,U:8}[i];t+=Vu(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(r===" "||r===" "){const i=n;let o=s[n+1];for(;o===" "||o===" ";)o=s[++n+1];o!==`
98
98
  `&&!(o==="\r"&&s[n+2]===`
99
- `)&&(t+=n>i?s.slice(i,n+1):r)}else t+=r}return(s[s.length-1]!=='"'||s.length===1)&&e(s.length,"MISSING_CHAR",'Missing closing "quote'),t}c(Uu,"doubleQuotedValue");function Wu(s,e){let t="",n=s[e+1];for(;(n===" "||n===" "||n===`
99
+ `)&&(t+=n>i?s.slice(i,n+1):r)}else t+=r}return(s[s.length-1]!=='"'||s.length===1)&&e(s.length,"MISSING_CHAR",'Missing closing "quote'),t}c(Wu,"doubleQuotedValue");function Ju(s,e){let t="",n=s[e+1];for(;(n===" "||n===" "||n===`
100
100
  `||n==="\r")&&!(n==="\r"&&s[e+2]!==`
101
101
  `);)n===`
102
102
  `&&(t+=`
103
- `),e+=1,n=s[e+1];return t||(t=" "),{fold:t,offset:e}}c(Wu,"foldNewline");const Ju={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
104
- `,r:"\r",t:" ",v:"\v",N:"\x85",_:"\xA0",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function Hu(s,e,t,n){const r=s.substr(e,t),o=r.length===t&&/^[0-9a-fA-F]+$/.test(r)?parseInt(r,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(Hu,"parseCharCode");function na(s,e,t,n){const{value:r,type:i,comment:o,range:a}=e.type==="block-scalar"?Qo(s,e,n):ea(e,s.options.strict,n),l=t?s.directives.tagName(t.source,f=>n(t,"TAG_RESOLVE_FAILED",f)):null;let u;s.options.stringKeys&&s.atKey?u=s.schema[Ie]:l?u=Vu(s.schema,r,l,t,n):e.type==="scalar"?u=Gu(s,r,e,n):u=s.schema[Ie];let d;try{const f=u.resolve(r,h=>n(t??e,"TAG_RESOLVE_FAILED",h),s.options);d=V(f)?f:new R(f)}catch(f){const h=f instanceof Error?f.message:String(f);n(t??e,"TAG_RESOLVE_FAILED",h),d=new R(r)}return d.range=a,d.source=r,i&&(d.type=i),l&&(d.tag=l),u.format&&(d.format=u.format),o&&(d.comment=o),d}c(na,"composeScalar");function Vu(s,e,t,n,r){if(t==="!")return s[Ie];const i=[];for(const a of s.tags)if(!a.collection&&a.tag===t)if(a.default&&a.test)i.push(a);else return a;for(const a of i)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):(r(n,"TAG_RESOLVE_FAILED",`Unresolved tag: ${t}`,t!=="tag:yaml.org,2002:str"),s[Ie])}c(Vu,"findScalarTagByName");function Gu({atKey:s,directives:e,schema:t},n,r,i){const o=t.tags.find(a=>(a.default===!0||s&&a.default==="key")&&a.test?.test(n))||t[Ie];if(t.compat){const a=t.compat.find(l=>l.default&&l.test?.test(n))??t[Ie];if(o.tag!==a.tag){const l=e.tagString(o.tag),u=e.tagString(a.tag),d=`Value may be parsed as either ${l} or ${u}`;i(r,"TAG_RESOLVE_FAILED",d,!0)}}return o}c(Gu,"findScalarTagByTest");function zu(s,e,t){if(e){t??(t=e.length);for(let n=t-1;n>=0;--n){let r=e[n];switch(r.type){case"space":case"comment":case"newline":s-=r.source.length;continue}for(r=e[++n];r?.type==="space";)s+=r.source.length,r=e[++n];break}}return s}c(zu,"emptyScalarPosition");const Yu={composeNode:sa,composeEmptyNode:Pr};function sa(s,e,t,n){const r=s.atKey,{spaceBefore:i,comment:o,anchor:a,tag:l}=t;let u,d=!0;switch(e.type){case"alias":u=Xu(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=na(s,e,l,n),a&&(u.anchor=a.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":u=ju(Yu,s,e,t,n),a&&(u.anchor=a.source.substring(1));break;default:{const f=e.type==="error"?e.message:`Unsupported token (type: ${e.type})`;n(e,"UNEXPECTED_TOKEN",f),u=Pr(s,e.offset,void 0,null,t,n),d=!1}}return a&&u.anchor===""&&n(a,"BAD_ALIAS","Anchor cannot be an empty string"),r&&s.options.stringKeys&&(!V(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"),i&&(u.spaceBefore=!0),o&&(e.type==="scalar"&&e.source===""?u.comment=o:u.commentBefore=o),s.options.keepSourceTokens&&d&&(u.srcToken=e),u}c(sa,"composeNode");function Pr(s,e,t,n,{spaceBefore:r,comment:i,anchor:o,tag:a,end:l},u){const d={type:"scalar",offset:zu(e,t,n),indent:-1,source:""},f=na(s,d,a,u);return o&&(f.anchor=o.source.substring(1),f.anchor===""&&u(o,"BAD_ALIAS","Anchor cannot be an empty string")),r&&(f.spaceBefore=!0),i&&(f.comment=i,f.range[2]=l),f}c(Pr,"composeEmptyNode");function Xu({options:s},{offset:e,source:t,end:n},r){const i=new Bn(t.substring(1));i.source===""&&r(e,"BAD_ALIAS","Alias cannot be an empty string"),i.source.endsWith(":")&&r(e+t.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);const o=e+t.length,a=en(n,o,s.strict,r);return i.range=[e,o,a.offset],a.comment&&(i.comment=a.comment),i}c(Xu,"composeAlias");function Zu(s,e,{offset:t,start:n,value:r,end:i},o){const a=Object.assign({_directives:e},s),l=new Wt(void 0,a),u={atKey:!1,atRoot:!0,directives:l.directives,options:l.options,schema:l.schema},d=xt(n,{indicator:"doc-start",next:r??i?.[0],offset:t,onError:o,parentIndent:0,startOnNewline:!0});d.found&&(l.directives.docStart=!0,r&&(r.type==="block-map"||r.type==="block-seq")&&!d.hasNewline&&o(d.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),l.contents=r?sa(u,r,d,o):Pr(u,d.end,n,null,d,o);const f=l.contents.range[2],h=en(i,f,!1,o);return h.comment&&(l.comment=h.comment),l.range=[t,f,h.offset],l}c(Zu,"composeDoc");function tn(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(tn,"getErrorPos");function ra(s){let e="",t=!1,n=!1;for(let r=0;r<s.length;++r){const i=s[r];switch(i[0]){case"#":e+=(e===""?"":n?`
103
+ `),e+=1,n=s[e+1];return t||(t=" "),{fold:t,offset:e}}c(Ju,"foldNewline");const Hu={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
104
+ `,r:"\r",t:" ",v:"\v",N:"\x85",_:"\xA0",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function Vu(s,e,t,n){const r=s.substr(e,t),o=r.length===t&&/^[0-9a-fA-F]+$/.test(r)?parseInt(r,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(Vu,"parseCharCode");function sa(s,e,t,n){const{value:r,type:i,comment:o,range:a}=e.type==="block-scalar"?ea(s,e,n):ta(e,s.options.strict,n),l=t?s.directives.tagName(t.source,f=>n(t,"TAG_RESOLVE_FAILED",f)):null;let u;s.options.stringKeys&&s.atKey?u=s.schema[Ie]:l?u=Gu(s.schema,r,l,t,n):e.type==="scalar"?u=zu(s,r,e,n):u=s.schema[Ie];let d;try{const f=u.resolve(r,h=>n(t??e,"TAG_RESOLVE_FAILED",h),s.options);d=V(f)?f:new R(f)}catch(f){const h=f instanceof Error?f.message:String(f);n(t??e,"TAG_RESOLVE_FAILED",h),d=new R(r)}return d.range=a,d.source=r,i&&(d.type=i),l&&(d.tag=l),u.format&&(d.format=u.format),o&&(d.comment=o),d}c(sa,"composeScalar");function Gu(s,e,t,n,r){if(t==="!")return s[Ie];const i=[];for(const a of s.tags)if(!a.collection&&a.tag===t)if(a.default&&a.test)i.push(a);else return a;for(const a of i)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):(r(n,"TAG_RESOLVE_FAILED",`Unresolved tag: ${t}`,t!=="tag:yaml.org,2002:str"),s[Ie])}c(Gu,"findScalarTagByName");function zu({atKey:s,directives:e,schema:t},n,r,i){const o=t.tags.find(a=>(a.default===!0||s&&a.default==="key")&&a.test?.test(n))||t[Ie];if(t.compat){const a=t.compat.find(l=>l.default&&l.test?.test(n))??t[Ie];if(o.tag!==a.tag){const l=e.tagString(o.tag),u=e.tagString(a.tag),d=`Value may be parsed as either ${l} or ${u}`;i(r,"TAG_RESOLVE_FAILED",d,!0)}}return o}c(zu,"findScalarTagByTest");function Yu(s,e,t){if(e){t??(t=e.length);for(let n=t-1;n>=0;--n){let r=e[n];switch(r.type){case"space":case"comment":case"newline":s-=r.source.length;continue}for(r=e[++n];r?.type==="space";)s+=r.source.length,r=e[++n];break}}return s}c(Yu,"emptyScalarPosition");const Xu={composeNode:ra,composeEmptyNode:Pr};function ra(s,e,t,n){const r=s.atKey,{spaceBefore:i,comment:o,anchor:a,tag:l}=t;let u,d=!0;switch(e.type){case"alias":u=Zu(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=sa(s,e,l,n),a&&(u.anchor=a.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":u=Fu(Xu,s,e,t,n),a&&(u.anchor=a.source.substring(1));break;default:{const f=e.type==="error"?e.message:`Unsupported token (type: ${e.type})`;n(e,"UNEXPECTED_TOKEN",f),u=Pr(s,e.offset,void 0,null,t,n),d=!1}}return a&&u.anchor===""&&n(a,"BAD_ALIAS","Anchor cannot be an empty string"),r&&s.options.stringKeys&&(!V(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"),i&&(u.spaceBefore=!0),o&&(e.type==="scalar"&&e.source===""?u.comment=o:u.commentBefore=o),s.options.keepSourceTokens&&d&&(u.srcToken=e),u}c(ra,"composeNode");function Pr(s,e,t,n,{spaceBefore:r,comment:i,anchor:o,tag:a,end:l},u){const d={type:"scalar",offset:Yu(e,t,n),indent:-1,source:""},f=sa(s,d,a,u);return o&&(f.anchor=o.source.substring(1),f.anchor===""&&u(o,"BAD_ALIAS","Anchor cannot be an empty string")),r&&(f.spaceBefore=!0),i&&(f.comment=i,f.range[2]=l),f}c(Pr,"composeEmptyNode");function Zu({options:s},{offset:e,source:t,end:n},r){const i=new Bn(t.substring(1));i.source===""&&r(e,"BAD_ALIAS","Alias cannot be an empty string"),i.source.endsWith(":")&&r(e+t.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);const o=e+t.length,a=en(n,o,s.strict,r);return i.range=[e,o,a.offset],a.comment&&(i.comment=a.comment),i}c(Zu,"composeAlias");function Qu(s,e,{offset:t,start:n,value:r,end:i},o){const a=Object.assign({_directives:e},s),l=new Wt(void 0,a),u={atKey:!1,atRoot:!0,directives:l.directives,options:l.options,schema:l.schema},d=xt(n,{indicator:"doc-start",next:r??i?.[0],offset:t,onError:o,parentIndent:0,startOnNewline:!0});d.found&&(l.directives.docStart=!0,r&&(r.type==="block-map"||r.type==="block-seq")&&!d.hasNewline&&o(d.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),l.contents=r?ra(u,r,d,o):Pr(u,d.end,n,null,d,o);const f=l.contents.range[2],h=en(i,f,!1,o);return h.comment&&(l.comment=h.comment),l.range=[t,f,h.offset],l}c(Qu,"composeDoc");function tn(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(tn,"getErrorPos");function ia(s){let e="",t=!1,n=!1;for(let r=0;r<s.length;++r){const i=s[r];switch(i[0]){case"#":e+=(e===""?"":n?`
105
105
 
106
106
  `:`
107
- `)+(i.substring(1)||" "),t=!0,n=!1;break;case"%":s[r+1]?.[0]!=="#"&&(r+=1),t=!1;break;default:t||(n=!0),t=!1}}return{comment:e,afterEmptyLine:n}}c(ra,"parsePrelude");class Mr{static{c(this,"Composer")}constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(t,n,r,i)=>{const o=tn(t);i?this.warnings.push(new Yo(o,n,r)):this.errors.push(new ot(o,n,r))},this.directives=new oe({version:e.version||"1.2"}),this.options=e}decorate(e,t){const{comment:n,afterEmptyLine:r}=ra(this.prelude);if(n){const i=e.contents;if(t)e.comment=e.comment?`${e.comment}
107
+ `)+(i.substring(1)||" "),t=!0,n=!1;break;case"%":s[r+1]?.[0]!=="#"&&(r+=1),t=!1;break;default:t||(n=!0),t=!1}}return{comment:e,afterEmptyLine:n}}c(ia,"parsePrelude");class Mr{static{c(this,"Composer")}constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(t,n,r,i)=>{const o=tn(t);i?this.warnings.push(new Xo(o,n,r)):this.errors.push(new ot(o,n,r))},this.directives=new oe({version:e.version||"1.2"}),this.options=e}decorate(e,t){const{comment:n,afterEmptyLine:r}=ia(this.prelude);if(n){const i=e.contents;if(t)e.comment=e.comment?`${e.comment}
108
108
  ${n}`:n;else if(r||e.directives.docStart||!i)e.commentBefore=n;else if(Y(i)&&!i.flow&&i.items.length>0){let o=i.items[0];G(o)&&(o=o.key);const a=o.commentBefore;o.commentBefore=a?`${n}
109
109
  ${a}`:n}else{const o=i.commentBefore;i.commentBefore=o?`${n}
110
- ${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:ra(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(e,t=!1,n=-1){for(const r of e)yield*this.next(r);yield*this.end(t,n)}*next(e){switch(e.type){case"directive":this.directives.add(e.source,(t,n,r)=>{const i=tn(e);i[0]+=t,this.onError(i,"BAD_DIRECTIVE",n,r)}),this.prelude.push(e.source),this.atDirectives=!0;break;case"document":{const t=Zu(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 ot(tn(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 ot(tn(e),"UNEXPECTED_TOKEN",n));break}this.doc.directives.docEnd=!0;const t=en(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}
111
- ${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.push(new ot(tn(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),r=new Wt(void 0,n);this.atDirectives&&this.onError(t,"MISSING_CHAR","Missing directives-end indicator line"),r.range=[0,t,t],this.decorate(r,!1),yield r}}}function Qu(s,e=!0,t){if(s){const n=c((r,i,o)=>{const a=typeof r=="number"?r:Array.isArray(r)?r[0]:r.offset;if(t)t(a,i,o);else throw new ot([a,a+1],i,o)},"_onError");switch(s.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return ea(s,e,n);case"block-scalar":return Qo({options:{strict:e}},s,n)}}return null}c(Qu,"resolveAsScalar");function ed(s,e){const{implicitKey:t=!1,indent:n,inFlow:r=!1,offset:i=-1,type:o="PLAIN"}=e,a=Xt({type:o,value:s},{implicitKey:t,indent:n>0?" ".repeat(n):"",inFlow:r,options:{blockQuote:!0,lineWidth:-1}}),l=e.end??[{type:"newline",offset:-1,indent:n,source:`
110
+ ${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:ia(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(e,t=!1,n=-1){for(const r of e)yield*this.next(r);yield*this.end(t,n)}*next(e){switch(e.type){case"directive":this.directives.add(e.source,(t,n,r)=>{const i=tn(e);i[0]+=t,this.onError(i,"BAD_DIRECTIVE",n,r)}),this.prelude.push(e.source),this.atDirectives=!0;break;case"document":{const t=Qu(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 ot(tn(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 ot(tn(e),"UNEXPECTED_TOKEN",n));break}this.doc.directives.docEnd=!0;const t=en(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}
111
+ ${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.push(new ot(tn(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),r=new Wt(void 0,n);this.atDirectives&&this.onError(t,"MISSING_CHAR","Missing directives-end indicator line"),r.range=[0,t,t],this.decorate(r,!1),yield r}}}function ed(s,e=!0,t){if(s){const n=c((r,i,o)=>{const a=typeof r=="number"?r:Array.isArray(r)?r[0]:r.offset;if(t)t(a,i,o);else throw new ot([a,a+1],i,o)},"_onError");switch(s.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return ta(s,e,n);case"block-scalar":return ea({options:{strict:e}},s,n)}}return null}c(ed,"resolveAsScalar");function td(s,e){const{implicitKey:t=!1,indent:n,inFlow:r=!1,offset:i=-1,type:o="PLAIN"}=e,a=Xt({type:o,value:s},{implicitKey:t,indent:n>0?" ".repeat(n):"",inFlow:r,options:{blockQuote:!0,lineWidth:-1}}),l=e.end??[{type:"newline",offset:-1,indent:n,source:`
112
112
  `}];switch(a[0]){case"|":case">":{const u=a.indexOf(`
113
113
  `),d=a.substring(0,u),f=a.substring(u+1)+`
114
- `,h=[{type:"block-scalar-header",offset:i,indent:n,source:d}];return ia(h,l)||h.push({type:"newline",offset:-1,indent:n,source:`
115
- `}),{type:"block-scalar",offset:i,indent:n,props:h,source:f}}case'"':return{type:"double-quoted-scalar",offset:i,indent:n,source:a,end:l};case"'":return{type:"single-quoted-scalar",offset:i,indent:n,source:a,end:l};default:return{type:"scalar",offset:i,indent:n,source:a,end:l}}}c(ed,"createScalarToken");function td(s,e,t={}){let{afterKey:n=!1,implicitKey:r=!1,inFlow:i=!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=Xt({type:o,value:e},{implicitKey:r||a===null,indent:a!==null&&a>0?" ".repeat(a):"",inFlow:i,options:{blockQuote:!0,lineWidth:-1}});switch(l[0]){case"|":case">":nd(s,l);break;case'"':Rr(s,l,"double-quoted-scalar");break;case"'":Rr(s,l,"single-quoted-scalar");break;default:Rr(s,l,"scalar")}}c(td,"setScalarValue");function nd(s,e){const t=e.indexOf(`
114
+ `,h=[{type:"block-scalar-header",offset:i,indent:n,source:d}];return oa(h,l)||h.push({type:"newline",offset:-1,indent:n,source:`
115
+ `}),{type:"block-scalar",offset:i,indent:n,props:h,source:f}}case'"':return{type:"double-quoted-scalar",offset:i,indent:n,source:a,end:l};case"'":return{type:"single-quoted-scalar",offset:i,indent:n,source:a,end:l};default:return{type:"scalar",offset:i,indent:n,source:a,end:l}}}c(td,"createScalarToken");function nd(s,e,t={}){let{afterKey:n=!1,implicitKey:r=!1,inFlow:i=!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=Xt({type:o,value:e},{implicitKey:r||a===null,indent:a!==null&&a>0?" ".repeat(a):"",inFlow:i,options:{blockQuote:!0,lineWidth:-1}});switch(l[0]){case"|":case">":sd(s,l);break;case'"':Rr(s,l,"double-quoted-scalar");break;case"'":Rr(s,l,"single-quoted-scalar");break;default:Rr(s,l,"scalar")}}c(nd,"setScalarValue");function sd(s,e){const t=e.indexOf(`
116
116
  `),n=e.substring(0,t),r=e.substring(t+1)+`
117
- `;if(s.type==="block-scalar"){const i=s.props[0];if(i.type!=="block-scalar-header")throw new Error("Invalid block scalar header");i.source=n,s.source=r}else{const{offset:i}=s,o="indent"in s?s.indent:-1,a=[{type:"block-scalar-header",offset:i,indent:o,source:n}];ia(a,"end"in s?s.end:void 0)||a.push({type:"newline",offset:-1,indent:o,source:`
118
- `});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:r})}}c(nd,"setBlockScalarValue");function ia(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(ia,"addEndtoBlockProps");function Rr(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 r=e.length;s.props[0].type==="block-scalar-header"&&(r-=s.props[0].source.length);for(const i of n)i.offset+=r;delete s.props,Object.assign(s,{type:t,source:e,end:n});break}case"block-map":case"block-seq":{const r={type:"newline",offset:s.offset+e.length,indent:s.indent,source:`
119
- `};delete s.items,Object.assign(s,{type:t,source:e,end:[r]});break}default:{const n="indent"in s?s.indent:-1,r="end"in s&&Array.isArray(s.end)?s.end.filter(i=>i.type==="space"||i.type==="comment"||i.type==="newline"):[];for(const i of Object.keys(s))i!=="type"&&i!=="offset"&&delete s[i];Object.assign(s,{type:t,indent:n,source:e,end:r})}}}c(Rr,"setFlowScalarValue");const sd=c(s=>"type"in s?is(s):os(s),"stringify$1");function is(s){switch(s.type){case"block-scalar":{let e="";for(const t of s.props)e+=is(t);return e+s.source}case"block-map":case"block-seq":{let e="";for(const t of s.items)e+=os(t);return e}case"flow-collection":{let e=s.start.source;for(const t of s.items)e+=os(t);for(const t of s.end)e+=t.source;return e}case"document":{let e=os(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(is,"stringifyToken");function os({start:s,key:e,sep:t,value:n}){let r="";for(const i of s)r+=i.source;if(e&&(r+=is(e)),t)for(const i of t)r+=i.source;return n&&(r+=is(n)),r}c(os,"stringifyItem");const Lr=Symbol("break visit"),rd=Symbol("skip children"),oa=Symbol("remove item");function at(s,e){"type"in s&&s.type==="document"&&(s={start:s.start,value:s.value}),aa(Object.freeze([]),s,e)}c(at,"visit"),at.BREAK=Lr,at.SKIP=rd,at.REMOVE=oa,at.itemAtPath=(s,e)=>{let t=s;for(const[n,r]of e){const i=t?.[n];if(i&&"items"in i)t=i.items[r];else return}return t},at.parentCollection=(s,e)=>{const t=at.itemAtPath(s,e.slice(0,-1)),n=e[e.length-1][0],r=t?.[n];if(r&&"items"in r)return r;throw new Error("Parent collection not found")};function aa(s,e,t){let n=t(e,s);if(typeof n=="symbol")return n;for(const r of["key","value"]){const i=e[r];if(i&&"items"in i){for(let o=0;o<i.items.length;++o){const a=aa(Object.freeze(s.concat([[r,o]])),i.items[o],t);if(typeof a=="number")o=a-1;else{if(a===Lr)return Lr;a===oa&&(i.items.splice(o,1),o-=1)}}typeof n=="function"&&r==="key"&&(n=n(e,s))}}return typeof n=="function"?n(e,s):n}c(aa,"_visit");const as="\uFEFF",cs="",ls="",nn="",id=c(s=>!!s&&"items"in s,"isCollection"),od=c(s=>!!s&&(s.type==="scalar"||s.type==="single-quoted-scalar"||s.type==="double-quoted-scalar"||s.type==="block-scalar"),"isScalar");function ad(s){switch(s){case as:return"<BOM>";case cs:return"<DOC>";case ls:return"<FLOW_END>";case nn:return"<SCALAR>";default:return JSON.stringify(s)}}c(ad,"prettyToken");function ca(s){switch(s){case as:return"byte-order-mark";case cs:return"doc-mode";case ls:return"flow-error-end";case nn:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case`
117
+ `;if(s.type==="block-scalar"){const i=s.props[0];if(i.type!=="block-scalar-header")throw new Error("Invalid block scalar header");i.source=n,s.source=r}else{const{offset:i}=s,o="indent"in s?s.indent:-1,a=[{type:"block-scalar-header",offset:i,indent:o,source:n}];oa(a,"end"in s?s.end:void 0)||a.push({type:"newline",offset:-1,indent:o,source:`
118
+ `});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:r})}}c(sd,"setBlockScalarValue");function oa(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(oa,"addEndtoBlockProps");function Rr(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 r=e.length;s.props[0].type==="block-scalar-header"&&(r-=s.props[0].source.length);for(const i of n)i.offset+=r;delete s.props,Object.assign(s,{type:t,source:e,end:n});break}case"block-map":case"block-seq":{const r={type:"newline",offset:s.offset+e.length,indent:s.indent,source:`
119
+ `};delete s.items,Object.assign(s,{type:t,source:e,end:[r]});break}default:{const n="indent"in s?s.indent:-1,r="end"in s&&Array.isArray(s.end)?s.end.filter(i=>i.type==="space"||i.type==="comment"||i.type==="newline"):[];for(const i of Object.keys(s))i!=="type"&&i!=="offset"&&delete s[i];Object.assign(s,{type:t,indent:n,source:e,end:r})}}}c(Rr,"setFlowScalarValue");const rd=c(s=>"type"in s?is(s):os(s),"stringify$1");function is(s){switch(s.type){case"block-scalar":{let e="";for(const t of s.props)e+=is(t);return e+s.source}case"block-map":case"block-seq":{let e="";for(const t of s.items)e+=os(t);return e}case"flow-collection":{let e=s.start.source;for(const t of s.items)e+=os(t);for(const t of s.end)e+=t.source;return e}case"document":{let e=os(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(is,"stringifyToken");function os({start:s,key:e,sep:t,value:n}){let r="";for(const i of s)r+=i.source;if(e&&(r+=is(e)),t)for(const i of t)r+=i.source;return n&&(r+=is(n)),r}c(os,"stringifyItem");const Lr=Symbol("break visit"),id=Symbol("skip children"),aa=Symbol("remove item");function at(s,e){"type"in s&&s.type==="document"&&(s={start:s.start,value:s.value}),ca(Object.freeze([]),s,e)}c(at,"visit"),at.BREAK=Lr,at.SKIP=id,at.REMOVE=aa,at.itemAtPath=(s,e)=>{let t=s;for(const[n,r]of e){const i=t?.[n];if(i&&"items"in i)t=i.items[r];else return}return t},at.parentCollection=(s,e)=>{const t=at.itemAtPath(s,e.slice(0,-1)),n=e[e.length-1][0],r=t?.[n];if(r&&"items"in r)return r;throw new Error("Parent collection not found")};function ca(s,e,t){let n=t(e,s);if(typeof n=="symbol")return n;for(const r of["key","value"]){const i=e[r];if(i&&"items"in i){for(let o=0;o<i.items.length;++o){const a=ca(Object.freeze(s.concat([[r,o]])),i.items[o],t);if(typeof a=="number")o=a-1;else{if(a===Lr)return Lr;a===aa&&(i.items.splice(o,1),o-=1)}}typeof n=="function"&&r==="key"&&(n=n(e,s))}}return typeof n=="function"?n(e,s):n}c(ca,"_visit");const as="\uFEFF",cs="",ls="",nn="",od=c(s=>!!s&&"items"in s,"isCollection"),ad=c(s=>!!s&&(s.type==="scalar"||s.type==="single-quoted-scalar"||s.type==="double-quoted-scalar"||s.type==="block-scalar"),"isScalar");function cd(s){switch(s){case as:return"<BOM>";case cs:return"<DOC>";case ls:return"<FLOW_END>";case nn:return"<SCALAR>";default:return JSON.stringify(s)}}c(cd,"prettyToken");function la(s){switch(s){case as:return"byte-order-mark";case cs:return"doc-mode";case ls:return"flow-error-end";case nn:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case`
120
120
  `:case`\r
121
- `: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(ca,"tokenType");var cd=Object.freeze({__proto__:null,BOM:as,DOCUMENT:cs,FLOW_END:ls,SCALAR:nn,createScalarToken:ed,isCollection:id,isScalar:od,prettyToken:ad,resolveAsScalar:Qu,setScalarValue:td,stringify:sd,tokenType:ca,visit:at});function ve(s){switch(s){case void 0:case" ":case`
122
- `:case"\r":case" ":return!0;default:return!1}}c(ve,"isEmpty");const la=new Set("0123456789ABCDEFabcdef"),ld=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),us=new Set(",[]{}"),ud=new Set(` ,[]{}
123
- \r `),Dr=c(s=>!s||ud.has(s),"isNotAnchorChar");class ua{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===`
121
+ `: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(la,"tokenType");var ld=Object.freeze({__proto__:null,BOM:as,DOCUMENT:cs,FLOW_END:ls,SCALAR:nn,createScalarToken:td,isCollection:od,isScalar:ad,prettyToken:cd,resolveAsScalar:ed,setScalarValue:nd,stringify:rd,tokenType:la,visit:at});function ve(s){switch(s){case void 0:case" ":case`
122
+ `:case"\r":case" ":return!0;default:return!1}}c(ve,"isEmpty");const ua=new Set("0123456789ABCDEFabcdef"),ud=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),us=new Set(",[]{}"),dd=new Set(` ,[]{}
123
+ \r `),Dr=c(s=>!s||dd.has(s),"isNotAnchorChar");class da{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===`
124
124
  `?!0:t==="\r"?this.buffer[e+1]===`
125
125
  `:!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 r=this.buffer[n+e+1];if(r===`
126
126
  `||!r&&!this.atEnd)return e+n+1}return t===`
@@ -135,43 +135,43 @@ ${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.pus
135
135
  `&&i>=this.pos&&i+1+t>a)e=i;else break}while(!0);return yield nn,yield*this.pushToIndex(e+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){const e=this.flowLevel>0;let t=this.pos-1,n=this.pos-1,r;for(;r=this.buffer[++n];)if(r===":"){const i=this.buffer[n+1];if(ve(i)||e&&us.has(i))break;t=n}else if(ve(r)){let i=this.buffer[n+1];if(r==="\r"&&(i===`
136
136
  `?(n+=1,r=`
137
137
  `,i=this.buffer[n+1]):t=n),i==="#"||e&&us.has(i))break;if(r===`
138
- `){const o=this.continueScalar(n+1);if(o===-1)break;n=Math.max(n,o-2)}}else{if(e&&us.has(r))break;t=n}return!r&&!this.atEnd?this.setNext("plain-scalar"):(yield nn,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(Dr))+(yield*this.pushSpaces(!0))+(yield*this.pushIndicators());case"-":case"?":case":":{const e=this.flowLevel>0,t=this.charAt(1);if(ve(t)||e&&us.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(;!ve(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(ld.has(t))t=this.buffer[++e];else if(t==="%"&&la.has(this.buffer[e+1])&&la.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===`
138
+ `){const o=this.continueScalar(n+1);if(o===-1)break;n=Math.max(n,o-2)}}else{if(e&&us.has(r))break;t=n}return!r&&!this.atEnd?this.setNext("plain-scalar"):(yield nn,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(Dr))+(yield*this.pushSpaces(!0))+(yield*this.pushIndicators());case"-":case"?":case":":{const e=this.flowLevel>0,t=this.charAt(1);if(ve(t)||e&&us.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(;!ve(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(ud.has(t))t=this.buffer[++e];else if(t==="%"&&ua.has(this.buffer[e+1])&&ua.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===`
139
139
  `?yield*this.pushCount(1):e==="\r"&&this.charAt(1)===`
140
- `?yield*this.pushCount(2):0}*pushSpaces(e){let t=this.pos-1,n;do n=this.buffer[++t];while(n===" "||e&&n===" ");const r=t-this.pos;return r>0&&(yield this.buffer.substr(this.pos,r),this.pos=t),r}*pushUntil(e){let t=this.pos,n=this.buffer[t];for(;!e(n);)n=this.buffer[++t];return yield*this.pushToIndex(t,!1)}}class da{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 i=t+n>>1;this.lineStarts[i]<e?t=i+1:n=i}if(this.lineStarts[t]===e)return{line:t+1,col:1};if(t===0)return{line:0,col:e};const r=this.lineStarts[t-1];return{line:t,col:e-r+1}}}}function We(s,e){for(let t=0;t<s.length;++t)if(s[t].type===e)return!0;return!1}c(We,"includesToken");function fa(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(fa,"findNonEmptyIndex");function ha(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(ha,"isFlowToken");function ds(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(ds,"getPrevProps");function Pt(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(Pt,"getFirstKeyStartProps");function pa(s){if(s.start.type==="flow-seq-start")for(const e of s.items)e.sep&&!e.value&&!We(e.start,"explicit-key-ind")&&!We(e.sep,"map-value-ind")&&(e.key&&(e.value=e.key),delete e.key,ha(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(pa,"fixFlowSeqItems");class jr{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 ua,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=ca(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"&&pa(t),n.type){case"document":n.value=t;break;case"block-scalar":n.props.push(t);break;case"block-map":{const r=n.items[n.items.length-1];if(r.value){n.items.push({start:[],key:t,sep:[]}),this.onKeyLine=!0;return}else if(r.sep)r.value=t;else{Object.assign(r,{key:t,sep:[]}),this.onKeyLine=!r.explicitKey;return}break}case"block-seq":{const r=n.items[n.items.length-1];r.value?n.items.push({start:[],value:t}):r.value=t;break}case"flow-collection":{const r=n.items[n.items.length-1];!r||r.value?n.items.push({start:[],key:t,sep:[]}):r.sep?r.value=t:Object.assign(r,{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 r=t.items[t.items.length-1];r&&!r.sep&&!r.value&&r.start.length>0&&fa(r.start)===-1&&(t.indent===0||r.start.every(i=>i.type!=="comment"||i.indent<t.indent))&&(n.type==="document"?n.end=r.start:n.items.push({start:r.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":{fa(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=ds(this.peek(2)),n=Pt(t);let r;e.end?(r=e.end,r.push(this.sourceToken),delete e.end):r=[this.sourceToken];const i={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:n,key:e,sep:r}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=i}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(`
140
+ `?yield*this.pushCount(2):0}*pushSpaces(e){let t=this.pos-1,n;do n=this.buffer[++t];while(n===" "||e&&n===" ");const r=t-this.pos;return r>0&&(yield this.buffer.substr(this.pos,r),this.pos=t),r}*pushUntil(e){let t=this.pos,n=this.buffer[t];for(;!e(n);)n=this.buffer[++t];return yield*this.pushToIndex(t,!1)}}class fa{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 i=t+n>>1;this.lineStarts[i]<e?t=i+1:n=i}if(this.lineStarts[t]===e)return{line:t+1,col:1};if(t===0)return{line:0,col:e};const r=this.lineStarts[t-1];return{line:t,col:e-r+1}}}}function We(s,e){for(let t=0;t<s.length;++t)if(s[t].type===e)return!0;return!1}c(We,"includesToken");function ha(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(ha,"findNonEmptyIndex");function pa(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(pa,"isFlowToken");function ds(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(ds,"getPrevProps");function Pt(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(Pt,"getFirstKeyStartProps");function ma(s){if(s.start.type==="flow-seq-start")for(const e of s.items)e.sep&&!e.value&&!We(e.start,"explicit-key-ind")&&!We(e.sep,"map-value-ind")&&(e.key&&(e.value=e.key),delete e.key,pa(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(ma,"fixFlowSeqItems");class jr{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 da,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=la(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"&&ma(t),n.type){case"document":n.value=t;break;case"block-scalar":n.props.push(t);break;case"block-map":{const r=n.items[n.items.length-1];if(r.value){n.items.push({start:[],key:t,sep:[]}),this.onKeyLine=!0;return}else if(r.sep)r.value=t;else{Object.assign(r,{key:t,sep:[]}),this.onKeyLine=!r.explicitKey;return}break}case"block-seq":{const r=n.items[n.items.length-1];r.value?n.items.push({start:[],value:t}):r.value=t;break}case"flow-collection":{const r=n.items[n.items.length-1];!r||r.value?n.items.push({start:[],key:t,sep:[]}):r.sep?r.value=t:Object.assign(r,{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 r=t.items[t.items.length-1];r&&!r.sep&&!r.value&&r.start.length>0&&ha(r.start)===-1&&(t.indent===0||r.start.every(i=>i.type!=="comment"||i.indent<t.indent))&&(n.type==="document"?n.end=r.start:n.items.push({start:r.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":{ha(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=ds(this.peek(2)),n=Pt(t);let r;e.end?(r=e.end,r.push(this.sourceToken),delete e.end):r=[this.sourceToken];const i={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:n,key:e,sep:r}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=i}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(`
141
141
  `)+1;for(;t!==0;)this.onNewLine(this.offset+t),t=this.source.indexOf(`
142
- `,t)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(e){const t=e.items[e.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,t.value){const n="end"in t.value?t.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type==="comment"?n?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"space":case"comment":if(t.value)e.items.push({start:[this.sourceToken]});else if(t.sep)t.sep.push(this.sourceToken);else{if(this.atIndentedComment(t.start,e.indent)){const r=e.items[e.items.length-2]?.value?.end;if(Array.isArray(r)){Array.prototype.push.apply(r,t.start),r.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return}if(this.indent>=e.indent){const n=!this.onKeyLine&&this.indent===e.indent,r=n&&(t.sep||t.explicitKey)&&this.type!=="seq-item-ind";let i=[];if(r&&t.sep&&!t.value){const o=[];for(let a=0;a<t.sep.length;++a){const l=t.sep[a];switch(l.type){case"newline":o.push(a);break;case"space":break;case"comment":l.indent>e.indent&&(o.length=0);break;default:o.length=0}}o.length>=2&&(i=t.sep.splice(o[1]))}switch(this.type){case"anchor":case"tag":r||t.value?(i.push(this.sourceToken),e.items.push({start:i}),this.onKeyLine=!0):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"explicit-key-ind":!t.sep&&!t.explicitKey?(t.start.push(this.sourceToken),t.explicitKey=!0):r||t.value?(i.push(this.sourceToken),e.items.push({start:i,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(t.explicitKey)if(t.sep)if(t.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(We(t.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,key:null,sep:[this.sourceToken]}]});else if(ha(t.key)&&!We(t.sep,"newline")){const o=Pt(t.start),a=t.key,l=t.sep;l.push(this.sourceToken),delete t.key,delete t.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:a,sep:l}]})}else i.length>0?t.sep=t.sep.concat(i,this.sourceToken):t.sep.push(this.sourceToken);else if(We(t.start,"newline"))Object.assign(t,{key:null,sep:[this.sourceToken]});else{const o=Pt(t.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:null,sep:[this.sourceToken]}]})}else t.sep?t.value||r?e.items.push({start:i,key:null,sep:[this.sourceToken]}):We(t.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{const o=this.flowScalar(this.type);r||t.value?(e.items.push({start:i,key:o,sep:[]}),this.onKeyLine=!0):t.sep?this.stack.push(o):(Object.assign(t,{key:o,sep:[]}),this.onKeyLine=!0);return}default:{const o=this.startBlockValue(e);if(o){if(o.type==="block-seq"){if(!t.explicitKey&&t.sep&&!We(t.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else n&&e.items.push({start:i});this.stack.push(o);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(e){const t=e.items[e.items.length-1];switch(this.type){case"newline":if(t.value){const n="end"in t.value?t.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type==="comment"?n?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.start.push(this.sourceToken);return;case"space":case"comment":if(t.value)e.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(t.start,e.indent)){const r=e.items[e.items.length-2]?.value?.end;if(Array.isArray(r)){Array.prototype.push.apply(r,t.start),r.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return;case"anchor":case"tag":if(t.value||this.indent<=e.indent)break;t.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==e.indent)break;t.value||We(t.start,"seq-item-ind")?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return}if(this.indent>e.indent){const n=this.startBlockValue(e);if(n){this.stack.push(n);return}}yield*this.pop(),yield*this.step()}*flowCollection(e){const t=e.items[e.items.length-1];if(this.type==="flow-error-end"){let n;do yield*this.pop(),n=this.peek(1);while(n&&n.type==="flow-collection")}else if(e.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!t||t.sep?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return;case"map-value-ind":!t||t.value?e.items.push({start:[],key:null,sep:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!t||t.value?e.items.push({start:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{const r=this.flowScalar(this.type);!t||t.value?e.items.push({start:[],key:r,sep:[]}):t.sep?this.stack.push(r):Object.assign(t,{key:r,sep:[]});return}case"flow-map-end":case"flow-seq-end":e.end.push(this.sourceToken);return}const n=this.startBlockValue(e);n?this.stack.push(n):(yield*this.pop(),yield*this.step())}else{const n=this.peek(2);if(n.type==="block-map"&&(this.type==="map-value-ind"&&n.indent===e.indent||this.type==="newline"&&!n.items[n.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&n.type!=="flow-collection"){const r=ds(n),i=Pt(r);pa(e);const o=e.end.splice(1,e.end.length);o.push(this.sourceToken);const a={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:i,key:e,sep:o}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=a}else yield*this.lineEnd(e)}}flowScalar(e){if(this.onNewLine){let t=this.source.indexOf(`
142
+ `,t)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(e){const t=e.items[e.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,t.value){const n="end"in t.value?t.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type==="comment"?n?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"space":case"comment":if(t.value)e.items.push({start:[this.sourceToken]});else if(t.sep)t.sep.push(this.sourceToken);else{if(this.atIndentedComment(t.start,e.indent)){const r=e.items[e.items.length-2]?.value?.end;if(Array.isArray(r)){Array.prototype.push.apply(r,t.start),r.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return}if(this.indent>=e.indent){const n=!this.onKeyLine&&this.indent===e.indent,r=n&&(t.sep||t.explicitKey)&&this.type!=="seq-item-ind";let i=[];if(r&&t.sep&&!t.value){const o=[];for(let a=0;a<t.sep.length;++a){const l=t.sep[a];switch(l.type){case"newline":o.push(a);break;case"space":break;case"comment":l.indent>e.indent&&(o.length=0);break;default:o.length=0}}o.length>=2&&(i=t.sep.splice(o[1]))}switch(this.type){case"anchor":case"tag":r||t.value?(i.push(this.sourceToken),e.items.push({start:i}),this.onKeyLine=!0):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"explicit-key-ind":!t.sep&&!t.explicitKey?(t.start.push(this.sourceToken),t.explicitKey=!0):r||t.value?(i.push(this.sourceToken),e.items.push({start:i,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(t.explicitKey)if(t.sep)if(t.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(We(t.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,key:null,sep:[this.sourceToken]}]});else if(pa(t.key)&&!We(t.sep,"newline")){const o=Pt(t.start),a=t.key,l=t.sep;l.push(this.sourceToken),delete t.key,delete t.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:a,sep:l}]})}else i.length>0?t.sep=t.sep.concat(i,this.sourceToken):t.sep.push(this.sourceToken);else if(We(t.start,"newline"))Object.assign(t,{key:null,sep:[this.sourceToken]});else{const o=Pt(t.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:null,sep:[this.sourceToken]}]})}else t.sep?t.value||r?e.items.push({start:i,key:null,sep:[this.sourceToken]}):We(t.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{const o=this.flowScalar(this.type);r||t.value?(e.items.push({start:i,key:o,sep:[]}),this.onKeyLine=!0):t.sep?this.stack.push(o):(Object.assign(t,{key:o,sep:[]}),this.onKeyLine=!0);return}default:{const o=this.startBlockValue(e);if(o){if(o.type==="block-seq"){if(!t.explicitKey&&t.sep&&!We(t.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else n&&e.items.push({start:i});this.stack.push(o);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(e){const t=e.items[e.items.length-1];switch(this.type){case"newline":if(t.value){const n="end"in t.value?t.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type==="comment"?n?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.start.push(this.sourceToken);return;case"space":case"comment":if(t.value)e.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(t.start,e.indent)){const r=e.items[e.items.length-2]?.value?.end;if(Array.isArray(r)){Array.prototype.push.apply(r,t.start),r.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return;case"anchor":case"tag":if(t.value||this.indent<=e.indent)break;t.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==e.indent)break;t.value||We(t.start,"seq-item-ind")?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return}if(this.indent>e.indent){const n=this.startBlockValue(e);if(n){this.stack.push(n);return}}yield*this.pop(),yield*this.step()}*flowCollection(e){const t=e.items[e.items.length-1];if(this.type==="flow-error-end"){let n;do yield*this.pop(),n=this.peek(1);while(n&&n.type==="flow-collection")}else if(e.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!t||t.sep?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return;case"map-value-ind":!t||t.value?e.items.push({start:[],key:null,sep:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!t||t.value?e.items.push({start:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{const r=this.flowScalar(this.type);!t||t.value?e.items.push({start:[],key:r,sep:[]}):t.sep?this.stack.push(r):Object.assign(t,{key:r,sep:[]});return}case"flow-map-end":case"flow-seq-end":e.end.push(this.sourceToken);return}const n=this.startBlockValue(e);n?this.stack.push(n):(yield*this.pop(),yield*this.step())}else{const n=this.peek(2);if(n.type==="block-map"&&(this.type==="map-value-ind"&&n.indent===e.indent||this.type==="newline"&&!n.items[n.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&n.type!=="flow-collection"){const r=ds(n),i=Pt(r);ma(e);const o=e.end.splice(1,e.end.length);o.push(this.sourceToken);const a={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:i,key:e,sep:o}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=a}else yield*this.lineEnd(e)}}flowScalar(e){if(this.onNewLine){let t=this.source.indexOf(`
143
143
  `)+1;for(;t!==0;)this.onNewLine(this.offset+t),t=this.source.indexOf(`
144
- `,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=ds(e),n=Pt(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=ds(e),n=Pt(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 ma(s){const e=s.prettyErrors!==!1;return{lineCounter:s.lineCounter||e&&new da||null,prettyErrors:e}}c(ma,"parseOptions");function dd(s,e={}){const{lineCounter:t,prettyErrors:n}=ma(e),r=new jr(t?.addNewLine),i=new Mr(e),o=Array.from(i.compose(r.parse(s)));if(n&&t)for(const a of o)a.errors.forEach(rs(s,t)),a.warnings.forEach(rs(s,t));return o.length>0?o:Object.assign([],{empty:!0},i.streamInfo())}c(dd,"parseAllDocuments");function ga(s,e={}){const{lineCounter:t,prettyErrors:n}=ma(e),r=new jr(t?.addNewLine),i=new Mr(e);let o=null;for(const a of i.compose(r.parse(s),!0,s.length))if(!o)o=a;else if(o.options.logLevel!=="silent"){o.errors.push(new ot(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return n&&t&&(o.errors.forEach(rs(s,t)),o.warnings.forEach(rs(s,t))),o}c(ga,"parseDocument");function fd(s,e,t){let n;typeof e=="function"?n=e:t===void 0&&e&&typeof e=="object"&&(t=e);const r=ga(s,t);if(!r)return null;if(r.warnings.forEach(i=>Io(r.options.logLevel,i)),r.errors.length>0){if(r.options.logLevel!=="silent")throw r.errors[0];r.errors=[]}return r.toJS(Object.assign({reviver:n},t))}c(fd,"parse");function hd(s,e,t){let n=null;if(typeof e=="function"||Array.isArray(e)?n=e:t===void 0&&e&&(t=e),typeof t=="string"&&(t=t.length),typeof t=="number"){const r=Math.round(t);t=r<1?void 0:r>8?{indent:8}:{indent:r}}if(s===void 0){const{keepUndefined:r}=t??e??{};if(!r)return}return nt(s)&&!n?s.toString(t):new Wt(s,n,t).toString(t)}c(hd,"stringify");var pd=Object.freeze({__proto__:null,Alias:Bn,CST:cd,Composer:Mr,Document:Wt,Lexer:ua,LineCounter:da,Pair:se,Parser:jr,Scalar:R,Schema:js,YAMLError:Ar,YAMLMap:le,YAMLParseError:ot,YAMLSeq:Ue,YAMLWarning:Yo,isAlias:Ke,isCollection:Y,isDocument:nt,isMap:vt,isNode:X,isPair:G,isScalar:V,isSeq:kt,parse:fd,parseAllDocuments:dd,parseDocument:ga,stringify:hd,visit:st,visitAsync:qn});class Fr extends hl{static{c(this,"TypedEventEmitter")}on(e,t){return super.on(e,t)}emit(e,...t){return super.emit(e,...t)}off(e,t){return super.off(e,t)}once(e,t){return super.once(e,t)}}const ue={Updated:"updated",Deleted:"deleted",Stopped:"stopped"},md={ignored:Fl,persistent:!0,ignoreInitial:!0,followSymlinks:!1,depth:20,awaitWriteFinish:{stabilityThreshold:500,pollInterval:100},ignorePermissionErrors:!0,atomic:!0,usePolling:!1,alwaysStat:!1,interval:1e3,binaryInterval:300};class gd extends Fr{static{c(this,"LocalElementWatcher")}constructor(e){super(),this.options=e,this.membraneDir=he(this.options.cwd),this.lockTimeoutMs=this.options.lockTimeoutMs??1e3}isWatching=!1;watcher;membraneDir;contentCache={};ignoredPaths=new Set;lockTimeoutMs;async start(){this.isWatching||(A.existsSync(this.membraneDir)||A.mkdirSync(this.membraneDir,{recursive:!0}),this.initializeContentCache(),this.watcher=fl.watch(this.membraneDir,md),this.watcher.on("add",e=>this.handleFileSystemEvent(ue.Updated,e)).on("change",e=>this.handleFileSystemEvent(ue.Updated,e)).on("unlink",e=>this.handleFileSystemEvent(ue.Deleted,e)).on("ready",()=>this.isWatching=!0))}async stop(){!this.isWatching||!this.watcher||(await this.watcher.close(),this.isWatching=!1,this.watcher=void 0,this.clearCache(),this.clearAllLocks(),this.emit(ue.Stopped))}getCwd(){return this.options.cwd}async executeWithPathLock(e,t){const n=P.resolve(e);this.ignoredPaths.add(n);try{await t()}finally{setTimeout(()=>{this.ignoredPaths.delete(n)},this.lockTimeoutMs)}}isPathLocked(e){const t=P.resolve(e);if(this.ignoredPaths.has(t))return!0;for(const n of this.ignoredPaths)if(t.startsWith(n+P.sep))return!0;return!1}clearAllLocks(){this.ignoredPaths.clear()}handleFileSystemEvent(e,t){const n=P.relative(this.membraneDir,t);if(this.isPathLocked(t))return;if(e===ue.Deleted){this.removeFromCache(n);const a={filePath:t,relativePath:n,data:void 0};b.info(`[local] ${e}: ${a.relativePath}`),this.emit(e,a);return}const r=this.readFileContent(t);if(!this.hasContentChanged(n,r))return;const o=this.processFileEvent(t,r);this.updateCache(n,r),o&&(b.info(`[local] ${e}: ${o.relativePath}`),this.emit(e,o))}readFileContent(e){return A.readFileSync(e,"utf8")}processFileEvent(e,t){const n=P.relative(this.membraneDir,e);let r;try{r=t?pd.parse(t):void 0}catch{r=void 0}return{filePath:e,relativePath:n,data:r}}hasContentChanged(e,t){if(!t)return this.contentCache[e]!==void 0;const n=this.getContentHash(t);return this.contentCache[e]!==n}getContentHash(e){return ul.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(){A.existsSync(this.membraneDir)&&this.scanDirectoryForCache(this.membraneDir)}scanDirectoryForCache(e){const t=A.readdirSync(e,{withFileTypes:!0});for(const n of t){const r=P.join(e,n.name);if(n.isDirectory())this.scanDirectoryForCache(r);else if(n.isFile())try{const i=A.readFileSync(r,"utf8"),o=P.relative(this.membraneDir,r);this.updateCache(o,i)}catch{}}}}var qr=(s=>(s.Updated="updated",s.ConnectorFileUpdated="connector-file-updated",s.Connected="connected",s.Disconnected="disconnected",s.Error="error",s))(qr||{});const yd={debounceMs:2e3,reconnectIntervalMs:5e3,maxReconnectAttempts:1/0,maxBackoffMs:6e4,connectionTimeoutMs:3e5};class wd extends Fr{static{c(this,"RemoteElementWatcher")}constructor(e=yd){super(),this.config=e}eventSource;debounceTimeouts=new Map;reconnectAttempts=0;reconnectTimeout;connectionTimeout;isStarted=!1;isConnected=!1;async start(){this.isStarted||(this.isStarted=!0,await this.connect())}async stop(){this.isStarted&&(this.isStarted=!1,this.isConnected=!1,this.clearReconnectTimeout(),this.clearConnectionTimeout(),this.clearAllDebounceTimeouts(),this.eventSource&&(this.eventSource.close(),this.eventSource=void 0))}async connect(){try{b.debug("[remote-events] Connecting to server"),this.eventSource&&(this.eventSource.close(),this.eventSource=void 0);const e=await K.getClient(process.cwd()),t=await e.getToken();if(!t)throw new Error("No auth token available");const n=`${e.apiUri}/sse/workspace?token=${encodeURIComponent(t)}`;b.debug("[remote-events] Subscribing to workspace events"),this.eventSource=new pl(n),this.setupEventSourceHandlers()}catch(e){b.debug(`[remote-events] Failed to connect: ${e}`),this.emit("error",{error:e}),this.scheduleReconnect()}}setupEventSourceHandlers(){this.eventSource&&(this.eventSource.onopen=()=>{b.debug("[remote-events] Connected to server"),this.reconnectAttempts=0,this.isConnected=!0,this.resetConnectionTimeout(),this.emit("connected",{})},this.eventSource.onmessage=e=>{try{this.resetConnectionTimeout();const t=JSON.parse(e.data);this.handleElementUpdate(t)}catch(t){b.debug(`[remote-events] Failed to parse workspace event: ${t}`)}},this.eventSource.onerror=e=>{b.debug(`[remote-events] Connection error: ${JSON.stringify(e,null,2)}`),this.isConnected=!1,this.clearConnectionTimeout(),this.eventSource&&(this.eventSource.close(),this.eventSource=void 0),this.emit("disconnected",{}),this.isStarted&&this.scheduleReconnect()})}handleElementUpdate(e){if(e.type!==Xc.ElementUpdate)return;const{elementId:t,elementType:n,data:r={}}=e;if(!(!t||!n)){if(n===N.Connector){const{filePath:i,eventType:o,newPath:a}=r;return b.debug(`[remote-watcher] Received connector event - elementId: ${t}, filePath: ${i}, eventType: ${o}`),this.scheduleConnectorFileUpdate(t,i,o,a)}return this.scheduleElementUpdate(t,n)}}scheduleElementUpdate(e,t){const n=this.debounceTimeouts.get(e);n&&clearTimeout(n);const r=setTimeout(()=>{this.debounceTimeouts.delete(e),this.emit("updated",{elementId:e,elementType:t})},this.config.debounceMs);this.debounceTimeouts.set(e,r)}scheduleConnectorFileUpdate(e,t,n,r){const i=JSON.stringify({connectorId:e,filePath:t}),o=this.debounceTimeouts.get(i);o&&clearTimeout(o);const a=setTimeout(()=>{this.debounceTimeouts.delete(i),this.emit("connector-file-updated",{connectorId:e,filePath:t,eventType:n,newPath:r})},this.config.debounceMs);this.debounceTimeouts.set(i,a)}scheduleReconnect(){if(!this.isStarted||this.reconnectAttempts>=this.config.maxReconnectAttempts){this.reconnectAttempts>=this.config.maxReconnectAttempts&&(b.error("[remote-events] Max reconnection attempts reached. Connection will not be retried."),this.emit("error",{error:new Error("Max reconnection attempts reached")}));return}this.reconnectTimeout&&clearTimeout(this.reconnectTimeout),this.reconnectAttempts++;const e=this.config.reconnectIntervalMs*Math.pow(2,this.reconnectAttempts-1),t=Math.random()*.3*e,n=Math.min(e+t,this.config.maxBackoffMs);b.debug(`[remote-events] Reconnecting in ${Math.round(n)}ms (attempt ${this.reconnectAttempts})`),this.reconnectTimeout=setTimeout(()=>{this.connect()},n)}clearReconnectTimeout(){this.reconnectTimeout&&(clearTimeout(this.reconnectTimeout),this.reconnectTimeout=void 0)}resetConnectionTimeout(){this.clearConnectionTimeout(),this.connectionTimeout=setTimeout(()=>{this.isConnected&&this.isStarted&&(b.debug("[remote-events] Connection timeout detected, reconnecting..."),this.isConnected=!1,this.eventSource&&(this.eventSource.close(),this.eventSource=void 0),this.scheduleReconnect())},this.config.connectionTimeoutMs)}clearConnectionTimeout(){this.connectionTimeout&&(clearTimeout(this.connectionTimeout),this.connectionTimeout=void 0)}clearAllDebounceTimeouts(){this.debounceTimeouts.forEach(e=>clearTimeout(e)),this.debounceTimeouts.clear()}}class ya{static{c(this,"ElementsCache")}elements=new Map;typeIndex=new Map;internalIdIndex=new Map;constructor(e){e&&this.addAll(e)}add(e){const t=e.id;this.elements.set(t,e),this.typeIndex.has(e.type)||this.typeIndex.set(e.type,new Set),this.typeIndex.get(e.type).add(t),e.data?.id&&this.internalIdIndex.set(e.data.id,t)}remove(e){const t=e.id,n=this.elements.delete(t);if(n){const r=this.typeIndex.get(e.type);r&&(r.delete(t),r.size===0&&this.typeIndex.delete(e.type)),e.data?.id&&this.internalIdIndex.delete(e.data.id)}return n}put(e){this.elements.has(e.id)&&this.remove(e),this.add(e)}get(e){return this.elements.get(e)}getByInternalId(e){const t=this.internalIdIndex.get(e);if(t)return this.elements.get(t)}getElementsByType(e){const t=this.typeIndex.get(e);return t?Array.from(t).map(n=>this.elements.get(n)).filter(n=>n!==void 0):[]}getAll(){return Array.from(this.elements.values())??[]}getTypes(){return Array.from(this.typeIndex.keys())}addAll(e){for(const t of e)t&&this.add(t)}removeAll(e){for(const t of e)this.remove(t)}getElementIdsByType(e){return this.typeIndex.get(e)}clear(){this.elements.clear(),this.typeIndex.clear(),this.internalIdIndex.clear()}getAllIds(){return new Set(this.elements.keys())}}const Mt="connectors",Me="development",Br={};async function bd(){const e=(await K.withClient(o=>o.get("org-workspace-id"))).id,t={};b.info("[connectors] Loading custom connectors"),await K.withClient(o=>o.get(`/connectors?workspaceId=${e}`)),b.info("[connectors] Loading public connectors");const n=Je(),i=(B.existsSync(n)?B.readdirSync(n):[]).filter(o=>{if(o.startsWith("."))return!1;const a=q.join(n,o);try{return B.statSync(a).isDirectory()}catch{return!1}});for(const o of i){b.info(`[connectors] Loading connector from: ${o}`);const a=B.readdirSync(q.join(n,o)),l=await Kr(o);if(!l)continue;"baseUri"in l&&delete l.baseUri;let u;if(l.uuid&&(u=await K.withClient(f=>f.get(`/connectors/${l.uuid}`),!1)),u)t[l.id]=u.id,b.info(`[connectors] Matched ${l.name} uuid: ${l.uuid}`),u.archivedAt&&(b.info(`[connectors] Restoring archived connector ${l.name}`),await K.withClient(f=>f.post(`connectors/${u.id}/restore`))),b.info(`[connectors] Updating connector ${l.name}`),await K.withClient(f=>f.patch(`connectors/${u.id}`,{...l,workspaceId:e}));else if(!t[l.id]){let f=!1;try{const h=await Ur({connectorId:l.id});h&&h.isPublic&&(f=!0)}catch{}if(!f){b.info(`[connectors] Creating custom connector ${l.name} (${l.key})`);const h=await K.withClient(g=>g.post("connectors",{...l,workspaceId:e}));t[l.id]=h.id}}const d=a.filter(f=>B.statSync(q.join(n,o,f)).isDirectory());for(const f of d)await vd({connector:l,version:f,connectorId:t[l.id]})}return t}c(bd,"pushConnectors");async function wa({connectorId:s,connectorVersion:e,allConnectors:t,pulledConnectors:n,pulledConnectorVersions:r}){if(!s||r[s]?.has(e))return;const i=Mi(),o=await Ur({connectorId:s});if(!o.isPublic||t){if(!o?.key){console.error(`[connectors] Connector ${s} has no key. Skipping..`),b.error(`[connectors] Connector ${s} has no key. Skipping..`);return}n.has(s)||(await kd({basePath:i,connector:o}),n.add(s)),r[s]||(r[s]=new Set),r[s].has(e)||(await Td({connector:o,connectorVersion:e,basePath:i}),r[s].add(e))}}c(wa,"pullRemoteConnector");function Je(){const s=ar();return q.join(s.membraneDirPath,Mt)}c(Je,"getConnectorsPath");async function Kr(s){const e=q.join(Je(),s,`${s}.yml`);return ur(e,!1)}c(Kr,"readConnector");async function Sd(s,e){return b.info(`[connectors] Zipping ${s} into ${e}`),new Promise((t,n)=>{const r=B.createWriteStream(e),i=$i("zip",{zlib:{level:9}});r.on("close",()=>{b.success(`[connectors] Successfully created ${e}`),t()}),r.on("end",()=>{b.info("[connectors] Data has been drained")}),i.on("warning",a=>{a.code==="ENOENT"?console.warn(a):n(a)}),i.on("error",a=>{n(a)}),i.pipe(r);const o=B.readdirSync(s);for(const a of o){const l=q.join(s,a),u=B.statSync(l);u.isFile()?i.file(l,{name:a}):u.isDirectory()&&i.directory(l,a)}i.finalize()})}c(Sd,"createZipArchive");async function Cd(s,e){return b.info(`[connectors] Unzipping into ${e}`),new Promise((t,n)=>{const r=Ni.Parse();r.on("entry",i=>{const o=i.path;if(i.type==="Directory"){const l=q.join(e,o);B.mkdirSync(l,{recursive:!0}),i.autodrain()}else{const l=q.join(e,o),u=q.dirname(l);B.mkdirSync(u,{recursive:!0});const d=B.createWriteStream(l);i.pipe(d),d.on("finish",()=>{})}}),r.on("end",()=>{b.success(`[connectors] Successfully extracted to ${e}`),t()}),r.on("error",i=>{n(i)}),r.write(s),r.end()})}c(Cd,"extractZipArchive");async function vd({connector:s,version:e,connectorId:t}){const n=q.join(Je(),Re(s),ba(e)),r=q.join(n,"src"),i=q.join(n,"src.zip"),o=B.existsSync(i);if(B.existsSync(r)&&(b.info(`[connectors] Archiving source code for ${s.name} version ${e}`),await Sd(r,i)),!B.existsSync(i)){b.warning(`[connectors] No source code found for ${s.name} version ${e}`);return}try{const a=new ml;if(a.append("file",B.createReadStream(i),"file.zip"),b.info(`[connectors] Pushing connector version ${e} for ${s.name}`),e==Me)b.info(`[connectors] Uploading connector ${t}`),await K.withClient(l=>l.post(`connectors/${t}/upload`,a,{headers:{...a.getHeaders()}}));else{if(a.append("version",e),a.append("changelog","Imported Version"),(await K.withClient(u=>u.get(`/connectors/${t}/versions`))).find(u=>u.version==e)){b.info(`[connectors] Version ${e} already published`);return}b.info(`[connectors] Publishing version ${e} of connector ${t}`),await K.withClient(u=>u.post(`connectors/${t}/publish-version`,a,{headers:{...a.getHeaders()}}))}b.success(`Successfully pushed connector version ${e} for ${s.name}`)}catch(a){b.error(`Error pushing connector version ${e} for ${s.name}: ${a}`),console.error(`[connectors] Error pushing connector version ${e} for ${s.name}: ${a}`)}finally{!o&&B.existsSync(i)&&(b.info(`[connectors] Cleaning up temporary zip file for ${s.name} version ${e}`),B.unlinkSync(i))}}c(vd,"pushConnectorVersion");async function Ur({connectorId:s}){if(s){if(Br[s])return Br[s];try{const e=await K.withClient(t=>t.get(`connectors/${s}`),!1);return Br[s]=e,e}catch(e){return b.error(`[connectors] Failed to get connector ${s}: ${e}`),console.error(`[connectors] Failed to get connector ${s}: ${e}`),null}}}c(Ur,"getConnector");async function kd({basePath:s,connector:e}){const t=Re(e),n=q.join(s,Mt,t);B.mkdirSync(n,{recursive:!0});const r=q.join(n,`${Re(e)}.yml`);B.writeFileSync(r,Se.dump(e)),b.info(`[connectors] Pulled connector ${e.name}`)}c(kd,"pullConnector$1");async function Td({connector:s,connectorVersion:e,basePath:t}){const n=Re(s),r=ba(e),i=q.join(t,"connectors",n,r),o=await K.withClient(l=>l.get(`connectors/${s.id}/download`,{version:e},{responseType:"arraybuffer",headers:{Accept:"application/zip"},timeout:1e6}));B.mkdirSync(i,{recursive:!0});const a=q.join(i,"src.zip");if(B.writeFileSync(a,o),!e){const l=q.join(i,"src");B.mkdirSync(l,{recursive:!0}),await Cd(o,l)}b.info(`[connectors] Pulled connector version: ${s.name} (${r})`)}c(Td,"pullConnectorVersion");function Re(s){return s.key}c(Re,"getConnectorDirName");function ba(s){return s??Me}c(ba,"getConnectorVersionDirName");function Ed(s){const e=Mi(),t=Re(s);return q.join(e,Mt,t)}c(Ed,"getConnectorDirPath");function _d(s){return s.match(`${Mt}/[^/]+/${Me}/src/.*`)!==null}c(_d,"isConnectorSourceFile");async function Id(s){const e=s.match(`${Mt}/([^/]+)/${Me}/src/(.*)`);if(!e)return;const t=e[1],n=e[2],r=await Kr(t);if(!r){b.warning(`[connectors] Connector ${t} not found. Ignoring file change`);return}const i=r.id,o=B.readFileSync(s,"utf-8");await K.withClient(a=>a.put(`connectors/${i}/files/${n}`,o,{headers:{"Content-Type":"text/plain"}})),b.info(`[connectors] Pushed file ${n} for connector ${r.name}`)}c(Id,"putConnectorFile");async function Ad(s){const e=s.match(`${Mt}/([^/]+)/${Me}/src/(.*)`);if(!e)return;const t=e[1],n=e[2],r=await Kr(t);if(!r){b.warning(`[connectors] Connector ${t} not found. Ignoring file change`);return}const i=r.id;await K.withClient(o=>o.delete(`connectors/${i}/files/${n}`)),b.info(`[connectors] Deleted file ${n} for connector ${r.name}`)}c(Ad,"deleteConnectorFile");async function Od(s,e){try{const t=await K.withClient(o=>o.get(`connectors/${s}`));if(!t){b.warning(`[connectors] Connector ${s} not found`);return}const n=await K.withClient(o=>o.get(`connectors/${s}/files/${e}`)),r=Re(t),i=q.join(Je(),r,Me,"src",e);B.mkdirSync(q.dirname(i),{recursive:!0}),n!=null?(B.writeFileSync(i,n),b.info(`[connectors] Pulled file ${e} for connector ${t.name}`)):B.existsSync(i)&&(B.unlinkSync(i),b.info(`[connectors] Deleted file ${e} for connector ${t.name}`))}catch(t){b.error(`[connectors] Failed to pull connector file ${e} for connector ${s}: ${t}`),console.error(`[connectors] Failed to pull connector file ${e} for connector ${s}: ${t}`)}}c(Od,"pullConnectorFile");async function $d(s,e){const t=await K.withClient(i=>i.get(`connectors/${s}`),!1);if(!t){b.warning(`[connectors] Connector ${s} not found`);return}const n=Re(t),r=q.join(Je(),n,Me,"src",e);B.existsSync(r)&&(B.unlinkSync(r),b.info(`[connectors] Deleted file ${e} for connector ${n}`))}c($d,"deleteLocalConnectorFile");async function Nd(s,e,t){if(t&&e!==t)try{const n=await K.withClient(l=>l.get(`connectors/${s}`),!1);if(!n){b.warning(`[connectors] Connector ${s} not found`);return}const r=Re(n),i=q.join(Je(),r,Me,"src"),o=q.join(i,e),a=q.join(i,t);B.existsSync(o)&&(B.mkdirSync(q.dirname(a),{recursive:!0}),B.renameSync(o,a),b.info(`[connectors] Renamed directory from ${e} to ${t} for connector ${r}`))}catch(n){b.error(`[connectors] Failed to rename directory ${e} to ${t} for connector ${s}: ${n}`)}}c(Nd,"renameLocalConnectorDirectory");async function xd(s,e){try{const t=await K.withClient(i=>i.get(`connectors/${s}`),!1);if(!t){b.warning(`[connectors] Connector ${s} not found`);return}const n=Re(t),r=q.join(Je(),n,Me,"src",e);if(B.existsSync(r)){const i=q.resolve(Je());if(!q.resolve(r).startsWith(i))return;B.rmSync(r,{recursive:!0,force:!0}),b.info(`[connectors] Deleted directory ${e} for connector ${n}`)}}catch(t){b.error(`[connectors] Failed to delete directory ${e} for connector ${s}: ${t}`)}}c(xd,"deleteLocalConnectorDirectory");const Q={LogAdded:"logAdded",StateChanged:"stateChanged",StatsChanged:"statsChanged",ConflictsChanged:"conflictsChanged",McpStatusChanged:"mcpStatusChanged",McpServersChanged:"mcpServersChanged",ConfigChanged:"configChanged"};class Pd extends Fr{static{c(this,"WorkspaceNotifications")}constructor(e){super(),this.config=e,b.setNotificationHandler(this)}clientId;heartbeatInterval;isCleaningUp=!1;async connectToRemote(){await this.registerWithRemoteServer(),await this.startHeartbeatLoop()}async setState(e){this.emit(Q.StateChanged,{state:e}),await this.emitRemote({status:e})}setConflicts(e){this.emit(Q.ConflictsChanged,{conflicts:e})}setConfig(e){this.emit(Q.ConfigChanged,{config:e})}setStats(e){this.emit(Q.StatsChanged,{stats:e})}addLog(e){this.emit(Q.LogAdded,{log:e})}setMcpStatus(e){this.emit(Q.McpStatusChanged,{status:e})}async setMcpServers(e){this.emit(Q.McpServersChanged,{servers:e}),await this.emitRemote({mcpServers:e.map(t=>({name:t.agentName,totalRequests:t.totalRequests}))})}async cleanup(){!this.clientId||this.isCleaningUp||(this.isCleaningUp=!0,this.heartbeatInterval&&(clearInterval(this.heartbeatInterval),this.heartbeatInterval=void 0),await this.withErrorHandling(async()=>{await K.withClient(e=>e.delete(`/local-clients/${this.clientId}`))}),this.clientId=void 0)}async registerWithRemoteServer(){if(this.clientId)return;const e=await this.withErrorHandling(async()=>await K.withClient(t=>t.post("/local-clients",{hostname:Oi.hostname(),workingDirectory:process.cwd()})));e?.id?this.clientId=e.id:this.addLog({timestamp:new Date().toISOString(),message:"Failed to register with remote server",type:"error"})}async startHeartbeatLoop(){this.heartbeatInterval=setInterval(async()=>{this.clientId&&await this.sendHeartbeat()},this.config.heartbeatIntervalMs)}async sendHeartbeat(){this.clientId&&await this.withErrorHandling(async()=>{await K.withClient(e=>e.post(`/local-clients/${this.clientId}/keep-alive`,{}))})}async emitRemote(e){this.clientId&&await this.withErrorHandling(async()=>{await K.withClient(t=>t.patch(`/local-clients/${this.clientId}`,e))})}async withErrorHandling(e){try{return await e()}catch(t){const n=t instanceof Error?t.message:String(t);return this.addLog({timestamp:new Date().toISOString(),message:`Failed to connect to remote: ${n}`,type:"error"}),null}}}const He=new Pd({heartbeatIntervalMs:15e3}),Sa=[N.AppDataSchema,N.AppEventType,N.DataLinkTable,N.DataSource,N.FieldMapping,N.Action,N.Flow,N.Package];class Tn{static{c(this,"ElementSyncService")}localWatcher=void 0;remoteWatcher=void 0;notifier;changes=[];localCache;remoteCache;localRepo;remoteRepo;pulledConnectors=new Set;pulledConnectorVersions={};constructor(){this.notifier=He,this.localCache=new ya,this.remoteCache=new ya,this.localRepo=new ru(this.localCache),this.remoteRepo=new iu(this.remoteCache)}clear(){this.changes=[]}needsForcedSync(){return this.changes.some(e=>e.isConflict)}needsSync(){return this.changes.length>0}async getStats(){const e=this.localCache.getAll(),t={};return e.forEach(n=>{t[n.type]=(t[n.type]||0)+1}),t}async fetchElements(){const e=await this.localRepo.getElements(),t=await this.remoteRepo.getElements();this.localCache.addAll(e),this.remoteCache.addAll(t)}async updateElement(e,t){const n=this.getHandler(t),r=this.getCache(t);try{const i=await n.putElement(e);r.put(i)}catch(i){throw b.error(`Failed to update element ${e.id}: ${i}`),i}}async deleteElement(e,t){const n=this.getHandler(t),r=this.getCache(t);try{await n.deleteElement(e,{elements:n.cache.getAll(),connectorsMapping:n.connectorsMapping}),r.remove(e)}catch(i){throw b.error(`Failed to delete element ${e.id}: ${i}`),i}}async pullConnectors(e=!1){const t=this.remoteCache.getElementsByType(N.Integration).map(n=>n.data);for(const n of t){const r=n.connectorId,i=n.connectorVersion;r&&await wa({connectorId:r,connectorVersion:i,allConnectors:e,pulledConnectors:this.pulledConnectors,pulledConnectorVersions:this.pulledConnectorVersions})}}async pushConnectors(){const e=await bd();this.remoteRepo.setConnectorsMapping(e)}getHandler(e){return e===ae.INCOMING?this.localRepo:(this.remoteRepo.setSourceCache(this.localCache),this.remoteRepo)}getCache(e){return e===ae.INCOMING?this.localCache:this.remoteCache}async startWatching(){this.localWatcher=new gd({cwd:process.cwd(),lockTimeoutMs:1e3}),this.localWatcher.on(ue.Updated,e=>this.handleLocalEvent(e,ue.Updated)),this.localWatcher.on(ue.Deleted,e=>this.handleLocalEvent(e,ue.Deleted)),await this.localWatcher.start(),b.success("[local] Tracking changes.."),this.remoteWatcher=new wd,this.remoteWatcher.on(qr.Updated,({elementId:e,elementType:t})=>this.handleRemoteElementEvent(e,t)),this.remoteWatcher.on(qr.ConnectorFileUpdated,({connectorId:e,filePath:t,eventType:n,newPath:r})=>this.handleRemoteConnectorFileEvent(e,t,n,r)),await this.remoteWatcher.start(),b.success("[remote] Tracking changes..")}async stopWatching(){this.localWatcher&&(await this.localWatcher.stop(),this.localWatcher=void 0),this.remoteWatcher&&(await this.remoteWatcher.stop(),this.remoteWatcher=void 0)}async handleRemoteElementEvent(e,t){try{const n=await this.remoteRepo.getByInternalId(e,t),r=!!n?.data.archivedAt||!!n?.data.isDeactivated;if(!n||r){const o=n||this.remoteCache.getByInternalId(e);return o?(b.info(`[${this.getDirectionLabel(ae.INCOMING)}] Deleted: ${o.id}`),this.localWatcher?.executeWithPathLock(o.absolutePath,()=>this.deleteElement(o,ae.INCOMING))):void 0}if(b.info(`[${this.getDirectionLabel(ae.INCOMING)}] Updated: ${n.id}`),await this.localWatcher?.executeWithPathLock(n.absolutePath,async()=>this.updateElement(n,ae.INCOMING)),t===N.Integration){const o=n.data.connectorId,a=n.data.connectorVersion,l=await Ur({connectorId:o});if(!l?.key)return;const u=Ed(l);await this.localWatcher?.executeWithPathLock(u,async()=>wa({connectorId:o,connectorVersion:a,allConnectors:!1,pulledConnectors:this.pulledConnectors,pulledConnectorVersions:this.pulledConnectorVersions}))}}catch(n){b.error(`[sync] Error handling remote event: ${n}`)}}async handleRemoteConnectorFileEvent(e,t,n,r){try{switch(n){case Ws.ConnectorFileDeleted:await $d(e,t);break;case Ws.ConnectorDirectoryRenamed:await Nd(e,t,r);break;case Ws.ConnectorDirectoryDeleted:await xd(e,t);break;default:await Od(e,t);break}}catch(i){b.error(`[sync] Error handling remote connector file event: ${i}`)}}async handleLocalEvent(e,t){try{if(_d(e.filePath))switch(t){case ue.Updated:await Id(e.filePath);break;case ue.Deleted:await Ad(e.filePath);break}else{let n=Z.fromPathAndData(e.filePath,e.data);if(!n){const r=Z.idFromPath(e.filePath);if(!r||(n=this.remoteCache.get(r),!n))return}switch(b.info(`[${this.getDirectionLabel(ae.OUTGOING)}] ${tu.toSentenceCase(t)}: ${n.id}`),t){case ue.Updated:await this.updateElement(n,ae.OUTGOING);break;case ue.Deleted:await this.deleteElement(n,ae.OUTGOING);break}}}catch(n){b.error(`[sync] Error handling local event: ${n}`)}}detectIncomingChanges(){this.clearChanges();const e=Tn.getChanges(ae.INCOMING,this.remoteCache,this.localCache);return this.updateChanges(e),e}detectOutgoingChanges(){this.clearChanges();const e=Tn.getChanges(ae.OUTGOING,this.localCache,this.remoteCache);return this.updateChanges(e),e}async resolveChanges(){if(!this.needsSync())return;b.info("[resolver] Resolving changes.."),b.info("[resolver] Resolving integration elements");const e=this.changes.filter(r=>r.element.type===N.Integration);await Promise.all(e.map(async r=>this.resolveChange(r))),e.length>0&&(await this.fetchElements(),this.changes=this.changes.length>0&&this.changes[0]?.direction===ae.INCOMING?this.detectIncomingChanges():this.detectOutgoingChanges(),this.changes=this.changes.filter(r=>r.element.type!==N.Integration)),b.info("[resolver] Resolving universal elements");const t=this.changes.filter(r=>!r.element.hasParent());for(const r of Sa){const i=t.filter(o=>o.element.type===r);b.info(`[resolver] Resolving ${r} elements`),await Promise.all(i.map(async o=>this.resolveChange(o)))}b.info("[resolver] Resolving integration level elements");const n=this.changes.filter(r=>r.element.hasParent());for(const r of Sa){const i=n.filter(o=>o.element.type===r);b.info(`[resolver] Resolving ${r} elements`),await Promise.all(i.map(async o=>this.resolveChange(o)))}b.success("[resolver] Resolved changes")}async resolveChange(e){switch(e.type){case Ne.DELETE:return this.deleteElement(e.element,e.direction);case Ne.CREATE:return this.updateElement(e.element,e.direction);case Ne.UPDATE:return this.updateElement(e.element,e.direction)}}static getChanges(e,t,n){const r=t.getAllIds(),i=n.getAllIds(),o=new Set([...r,...i]),a=[];for(const l of o){const u=t.get(l),d=n.get(l),f=Tn.detectChangeForElement(u,d,e);f&&a.push(f)}return a}updateChanges(e){if(this.changes=e,this.needsForcedSync()){const t=e.filter(n=>n.isConflict);b.warning("[resolver] Conflicts detected"),this.notifier.setConflicts(t)}}clearChanges(){this.changes=[]}getDirectionLabel(e){switch(e){case ae.INCOMING:return"local\u2190remote";case ae.OUTGOING:return"local\u2192remote"}}static detectChangeForElement(e,t,n){return e&&!t?{type:Ne.CREATE,element:e,direction:n,isConflict:!1}:!e&&t?{type:Ne.DELETE,element:t,direction:n,isConflict:!0}:e&&t&&!e.isEqual(t)?{type:Ne.UPDATE,element:e,direction:n,isConflict:!1}:null}}const Ve=P.join(gl.tmpdir(),"membrane-mcp-status"),Ca=3e4;class Md{static{c(this,"McpStatusService")}constructor(e=2e3){this.pollIntervalMs=e}isRunning=!1;pollInterval;async start(){this.isRunning||(this.isRunning=!0,this.pollInterval=setInterval(async()=>await this.checkStatus(),this.pollIntervalMs),await this.checkStatus())}async stop(){this.pollInterval&&(clearInterval(this.pollInterval),this.pollInterval=void 0,this.isRunning=!1)}async checkStatus(){try{const e=process.cwd(),t=fs(void 0,e),n=va(e);t&&He.setMcpStatus(t),await He.setMcpServers(n)}catch{b.error("Failed to check MCP status")}}}function fs(s,e){try{const t=e||process.cwd();if(!s){const r=va(t);return r.length===0?null:r[0]}const n=Hr(s,t);if(A.existsSync(n)){const r=A.statSync(n),i=new Date;if(i.getTime()-r.mtime.getTime()>Ca)return sn(s,t),null;const a=A.readFileSync(n,"utf8"),l=JSON.parse(a);if(l.isRunning){const u=new Date(l.lastActivity).getTime();if(i.getTime()-u>Ca)return sn(s,t),null}return l}}catch{s&&e&&sn(s,e)}return null}c(fs,"getMcpStatus");function va(s){try{const e=s||process.cwd(),t=Jr(e);if(!A.existsSync(Ve))return[];const n=A.readdirSync(Ve),r=[];for(const i of n){const o=i.match(new RegExp(`^mcp-${t}-(\\d+)\\.json$`));if(o){const a=parseInt(o[1],10),l=fs(a,e);l&&r.push(l)}}return r.sort((i,o)=>new Date(o.startTime).getTime()-new Date(i.startTime).getTime())}catch{return[]}}c(va,"getAllMcpStatusFiles");function Wr(s){try{const t={...fs(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};A.existsSync(Ve)||A.mkdirSync(Ve,{recursive:!0});const n=Hr(s.processId,s.cwd);A.writeFileSync(n,JSON.stringify(t,null,2))}catch{}}c(Wr,"updateMcpStatus");function sn(s,e){try{const t=e||process.cwd();if(s){const n=Hr(s,t);A.existsSync(n)&&A.unlinkSync(n)}else{const n=Jr(t);if(A.existsSync(Ve)){const r=A.readdirSync(Ve);for(const i of r)i.match(new RegExp(`^mcp-${n}-\\d+\\.json$`))&&A.unlinkSync(P.join(Ve,i))}}}catch{}}c(sn,"clearMcpStatus");function Rd(s,e){const t=fs(s,e);t&&Wr({processId:s,cwd:e,totalRequests:t.totalRequests+1,lastRequestTime:new Date().toISOString(),lastActivity:new Date().toISOString()})}c(Rd,"trackToolExecution");function Jr(s){return dl("md5").update(s).digest("hex").slice(0,8)}c(Jr,"getCwdHash");function Hr(s,e){const t=Jr(e);return P.join(Ve,`mcp-${t}-${s}.json`)}c(Hr,"getStatusFilePath");const hs={Agent:"agent",Cli:"cli"},D={NOT_INITIALIZED:"not_initialized",SETTING_UP:"setting_up",INITIALIZED:"initialized",NOT_SYNCED:"not_synced",PULLING:"pulling",PUSHING:"pushing",RESOLVING:"resolving",CONFLICTS:"conflicts",SYNCED:"synced",WATCHING:"watching",ERROR:"error"};class Ld{static{c(this,"MembraneCLIService")}constructor(e,t,n=()=>process.exit(0)){this.mode=e,this.cwd=t,this.onShutdown=n,this.notifier=He,this.mcpStatusService=new Md,this.syncService=new Tn,this.setupProcessCleanup()}initialized=!1;notifier;mcpStatusService;syncService;isShuttingDown=!1;currentConfig=null;get config(){return this.currentConfig}getSyncedElements(){return this.syncService.localCache.getAll()}getSyncedElementsByType(e){return this.syncService.localCache.getElementsByType(e)}async fetchElements(){await this.syncService.fetchElements()}async pullWorkspace(e={}){let t=!1;try{if(b.setVerboseMode(!!e.verbose),e.rps!==void 0&&K.init({maxRequestsPerSecond:e.rps}),await this.notifier.setState(D.PULLING),await this.syncService.fetchElements(),this.syncService.detectIncomingChanges(),this.syncService.needsForcedSync()&&!e.force){await this.notifier.setState(D.CONFLICTS),e.watch||(t=!0);return}await this.syncService.pullConnectors(e.allConnectors),await this.syncWorkspaces(e)}catch(n){t=!0,b.error(`Failed to pull workspace: ${n}`),await this.notifier.setState(D.ERROR),b.saveLogsToFile("error")}finally{if(e.saveLogs&&b.saveLogsToFile(),t)process.exit(1);else return e?.onComplete?.()}}async pushWorkspace(e={}){let t=!1;try{if(b.setVerboseMode(!!e.verbose),e.rps!==void 0&&K.init({maxRequestsPerSecond:e.rps}),await this.notifier.setState(D.PUSHING),await this.syncService.fetchElements(),this.syncService.detectOutgoingChanges(),this.syncService.needsForcedSync()&&!e.force){await this.notifier.setState(D.CONFLICTS),e.watch||(t=!0);return}await this.syncService.pushConnectors(),await this.syncWorkspaces(e)}catch(n){t=!0,b.error(`Failed to push workspace: ${n}`),await this.notifier.setState(D.ERROR),b.saveLogsToFile("error")}finally{if(e.saveLogs&&b.saveLogsToFile(),t)process.exit(1);else return e?.onComplete?.()}}async syncWorkspaces(e={}){try{e.verbose!==void 0&&b.setVerboseMode(!!e.verbose),await this.notifier.setState(D.RESOLVING),this.syncService.needsSync()&&await this.syncService.resolveChanges();const t=await this.syncService.getStats();this.notifier.setStats(t),await this.notifier.setState(D.SYNCED),e.watch&&(await this.notifier.setState(D.WATCHING),await this.syncService.startWatching())}catch(t){b.error(`Failed to sync local and remote workspaces: ${t}`),await this.notifier.setState(D.ERROR),b.saveLogsToFile("error")}}async init({force:e=!1}={}){if(!(this.initialized&&!e)){await this.notifier.setState(D.NOT_INITIALIZED);try{await this.loadConfig(),tt.isCacheDefined()?(await this.initServices(),this.initialized=!0,await this.notifier.setState(D.INITIALIZED)):(this.initialized=!1,await this.notifier.setState(D.SETTING_UP))}catch(t){b.error(`Failed to initialize services: ${t}`),await this.notifier.setState(D.ERROR),b.saveLogsToFile("error"),this.onShutdown()}}}async loadConfig(){this.currentConfig=tt.loadConfig(this.cwd),this.notifier.setConfig(this.currentConfig)}async updateConfig(e){const t={...this.currentConfig,...e};if(!(JSON.stringify(t)!==JSON.stringify(this.currentConfig)))return;await this.stopServices();const r=tt.updateConfig(t);this.currentConfig=r,await this.init({force:!0})}async shutdown(){!this.initialized||this.isShuttingDown||(this.isShuttingDown=!0,this.mode===hs.Agent&&(await this.notifier.cleanup(),await this.mcpStatusService.stop()),this.initialized=!1,this.onShutdown())}async initServices(){this.mode===hs.Agent&&(await this.notifier.connectToRemote(),await this.mcpStatusService.start()),this.syncService.clear()}async stopServices(){this.mode===hs.Agent&&(await this.notifier.cleanup(),await this.mcpStatusService.stop())}setupProcessCleanup(){["SIGINT","SIGTERM","uncaughtException","unhandledRejection"].forEach(t=>process.on(t,()=>this.shutdown())),process.on("beforeExit",t=>{t===0&&this.shutdown()})}}const ka=Ys(null);function Dd({children:s,membraneCLIService:e}){const{data:t}=Ai("/account"),[n,r]=J(D.NOT_INITIALIZED),[i,o]=J([]),[a,l]=J({}),[u,d]=J([]),[f,h]=J(null),y=t?.workspaces?.find(p=>p.workspaceKey===f?.workspaceKey)||null;return Ze(()=>{const p=c(({state:I})=>r(I),"handleStateChanged"),w=c(({stats:I})=>l(I),"handleStatsChanged"),T=c(({log:I})=>d(x=>[...x,I]),"handleLogAdded"),E=c(({conflicts:I})=>o(I),"handleConflictsUpdated"),$=c(({config:I})=>h(I),"handleConfigChanged");return e.notifier.on(Q.StateChanged,p),e.notifier.on(Q.StatsChanged,w),e.notifier.on(Q.LogAdded,T),e.notifier.on(Q.ConflictsChanged,E),e.notifier.on(Q.ConfigChanged,$),e.init(),()=>{e.notifier.off(Q.StateChanged,p),e.notifier.off(Q.StatsChanged,w),e.notifier.off(Q.LogAdded,T),e.notifier.off(Q.ConflictsChanged,E),e.notifier.off(Q.ConfigChanged,$)}},[]),m(ka.Provider,{value:{state:n,stats:a,logs:u,currentWorkspace:y,conflicts:i,config:f,updateConfig:c(p=>e.updateConfig(p),"updateConfig"),resolveConflicts:c(p=>e.syncWorkspaces(p),"resolveConflicts"),pull:c(p=>e.pullWorkspace(p),"pull"),push:c(p=>e.pushWorkspace(p),"push"),exit:c(()=>e.shutdown(),"exit"),fetchElements:c(()=>e.fetchElements(),"fetchElements"),getSyncedElementsByType:c(p=>e.getSyncedElementsByType(p),"getSyncedElementsByType")},children:s})}c(Dd,"MembraneCLIServiceProvider");function ge(){const s=Xs(ka);if(!s)throw new Error("useMembraneCLIService must be used within MembraneCLIServiceProvider");return s}c(ge,"useMembraneCLIService");const Vr=Ys(null),Ta=c(()=>{const s=Xs(Vr);if(!s)throw new Error("useTree must be used within TreeView");return s},"useTree"),jd=c(s=>$e.Children.count(s)>0,"hasChildren");function Fd(s){const e=Ta(),{label:t,value:n,isInitiallyExpanded:r}=s,i=rl(),o=Zs(e.registerChildItem(t)).current,a=e.isActiveByRef(o),[l,u]=J(r??!1),d={props:s,ref:o,id:i,active:a,expanded:l,setExpanded:u,label:t,value:n,isInitiallyExpanded:r,isParent:!1},{children:f}=s,h=typeof f=="function"?f(d):f;return{...d,props:{...s,children:h},isParent:jd(h)}}c(Fd,"useTreeItem");function Rt(s){const e=Ta(),t=Fd(s),{expanded:n,isParent:r,props:{children:i},setExpanded:o}=t,{renderValue:a=Bd}=s,l=t.ref;_n(()=>{function h(g){return s.onInput?.(g)?!0:g.active&&g.key.rightArrow&&!n?(o(!0),!0):g.active&&g.key.leftArrow&&n?(o(!1),!0):!1}c(h,"onInput"),l.onInput=h},[l,s.onInput,n,o]),l.firstChild??={parent:l,index:0};let u=l.firstChild;function d(h){const g=u;return g.nextSibling||(g.nextSibling={parent:l,prevSibling:g,index:g.index+1}),u=g.nextSibling,g.label=h,g}c(d,"registerChildItem");function f(){l.lastRenderedChild=u.prevSibling}return c(f,"commitChildren"),_n(()=>{f()}),_(Jt,{children:[_(C,{marginLeft:e.depth*2,children:[m(C,{width:2,children:r&&m(v,{children:n?"\u25BC":"\u25B6"})}),qd(t),a(t)]}),n&&m(Vr.Provider,{value:{...e,depth:e.depth+1,registerChildItem:d},children:i})]})}c(Rt,"TreeItem");function qd({active:s,label:e}){return m(C,{width:32,children:m(v,{inverse:s,children:e})})}c(qd,"defaultRenderLabel");function Bd(s){return m(v,{})}c(Bd,"defaultRenderValue");const ct=c(({label:s,onPress:e,hotkey:t})=>m(Rt,{label:s,onInput:c(({input:n,key:r,active:i})=>i&&r.return||t&&t in r&&r[t]||n===t?(e(),!0):!1,"onInput"),renderValue:c(()=>m(C,{children:m(v,{children:`${t?` (${t})`:""}`})}),"renderValue")}),"ActionTreeItem"),Ea=c(({label:s,value:e,onChange:t,disabled:n=!1,mask:r,...i})=>{const[o,a]=J(e),[l,u]=J(!1);return _n(()=>{l||a(e)},[l,e]),m(Rt,{label:s,value:e,onInput:c(({key:d,active:f})=>n?!1:l?(d.escape&&u(!1),d.return&&(t(o),u(!1)),!0):f&&d.return?(u(!0),a(e),!0):!1,"onInput"),renderValue:c(()=>{const d=o,f=r?r.repeat(d.length):d;return m(C,{children:n||!l?m(v,{dimColor:!0,children:f}):_(Jt,{children:[m(C,{width:f.length+1,children:m(xi,{...i,focus:l,value:d,onChange:a})}),m(v,{dimColor:!0,children:" \u241B cancel"})]})})},"renderValue")})},"TreeTextField"),Kd=c(s=>m(Ea,{...s,mask:"*"}),"SecretField"),ye=c(({children:s,showHelp:e=!1})=>{const t=Zs({parent:void 0,label:"<<ROOT>>",index:0}),[n,r]=J(t.current),i={depth:0,isActiveByRef:c(a=>n===a,"isActiveByRef"),registerChildItem:c(()=>t.current,"registerChildItem"),activeItemRef:n};_n(()=>{r(a=>a.parent?a.parent.lastRenderedChild&&a.index>a.parent.lastRenderedChild.index?a.parent.lastRenderedChild:a:t.current.firstChild??t.current)});function*o(a){a&&(yield a,yield*o(a.firstChild),a.nextSibling&&a!==a.parent?.lastRenderedChild&&(yield*o(a.nextSibling)))}return c(o,"walkTree"),Qe((a,l)=>{if(n.onInput?.({input:a,key:l,active:!0}))return;let u,d;for(const f of o(t.current))if(f.label!=null){if(u===n&&(d=f),f&&f.onInput?.({input:a,key:l,active:f===n}))return;u=f}l.upArrow?r(f=>f.prevSibling?.lastRenderedChild??f.prevSibling??f.parent??t.current):l.downArrow?r(f=>d??f):l.pageUp?r(()=>t.current.firstChild??t.current):l.pageDown?r(()=>t.current.lastRenderedChild??t.current):l.tab?console.log({label:n.label,nextSibling:n.nextSibling?.label,prevSibling:n.prevSibling?.label,parent:n.parent?.label,firstChild:n.firstChild?.label,lastRenderedChild:n.lastRenderedChild?.label}):l.leftArrow?r(f=>f.parent??t.current):l.rightArrow&&r(f=>f.lastRenderedChild?f.firstChild:f)}),m(Vr.Provider,{value:i,children:_(C,{flexDirection:"column",children:[m(Rt,{isInitiallyExpanded:!0,label:"rootItem",children:s}),e&&m(C,{marginTop:1,flexDirection:"column",children:m(v,{dimColor:!0,children:"\u2191/\u2193 move \u2022 \u2190 collapse \u2022 \u2192 expand \u2022 Enter/Space select/edit \u2022 Esc exit"})})]})})},"TreeView");ye.Item=Rt,ye.TextField=Ea;function lt({label:s,elementType:e,isActionExcluded:t,toggleAction:n,generateCode:r}){const[i,o]=J([]),{fetchElements:a,getSyncedElementsByType:l}=ge();return Ze(()=>{c(async()=>{try{await a();const d=l(e);o(d.map(f=>f.data))}catch(d){console.error(String(d))}},"loadElements")()},[e,a,l,o]),m(Rt,{label:s,children:i.map(u=>m(Rt,{label:u.name,children:e===N.Action&&_(Jt,{children:[t&&n&&m(ct,{label:`Toggle ${t(u)?"":"(excluded)"}`,onPress:c(()=>{n(u)},"onPress")}),r&&m(ct,{label:"Generate code",onPress:c(()=>{r?.(u)},"onPress")})]})},u.id))})}c(lt,"WorkspaceElementsTreeItem");function Ud({onComplete:s}){const{config:e,updateConfig:t,fetchElements:n,getSyncedElementsByType:r}=ge(),[i,o]=J(""),a=e,l=c(h=>{o(h),setTimeout(()=>o(""),2e3)},"setFlash"),u=c(async(h,g)=>{try{await t({[h]:g}),l("\u2705 Configuration updated!")}catch{l("\u274C Error updating configuration")}},"updateField"),d=c(async()=>{try{if(e){const h=tt.saveToFile(e);l(h?"\u2705 Configuration saved successfully!":"\u274C Failed to save configuration"),await n();const g=r(N.Action);await rr({out:a?.outputDir??"",target:a?.projectType??"typescript",schemasOnly:!1,membraneInterfaces:{actions:g.filter(y=>!a?.excludedActionKeys?.includes(y.key)).map(y=>y.data)}}),l("\u2705 Code generated successfully!")}}catch{l("\u274C Error saving configuration")}},"handleSaveConfig"),f=c(async()=>{try{const h=tt.loadConfig();h?(await t(h),l("\u2705 Configuration reloaded successfully!")):l("\u274C No configuration found to reload")}catch{l("\u274C Error reloading configuration")}},"handleReloadConfig");return _(C,{flexDirection:"column",gap:1,children:[m(v,{bold:!0,color:"cyan",children:"\u2699\uFE0F Membrane Configuration Manager"}),m(C,{paddingX:2,children:_(ye,{showHelp:!0,children:[_(ye.Item,{label:"Configuration",isInitiallyExpanded:!0,children:[_(ye.Item,{label:"Project",children:[m(ye.TextField,{label:"Workspace Key",value:a?.workspaceKey??"",onChange:c(h=>u("workspaceKey",h),"onChange"),disabled:!0}),m(Kd,{label:"Workspace Secret",value:a?.workspaceSecret??"",onChange:c(h=>u("workspaceSecret",h),"onChange"),disabled:!0}),m(ye.TextField,{label:"API URI",value:a?.apiUri??"",onChange:c(h=>u("apiUri",h),"onChange")}),m(ye.TextField,{label:"Test Customer ID",value:a?.testCustomerId??"",onChange:c(h=>u("testCustomerId",h),"onChange")})]}),_(ye.Item,{label:"Code Generation",isInitiallyExpanded:!0,children:[_(ye.Item,{label:"Project Type",isInitiallyExpanded:!0,value:a?.projectType,renderValue:c(({value:h})=>m(v,{children:h==="typescript"?"TypeScript":h==="openapi"?"OpenAPI":"(Not set)"}),"renderValue"),children:[m(ct,{label:"Update to TypeScript",onPress:c(()=>u("projectType","typescript"),"onPress")}),m(ct,{label:"Update to OpenAPI",onPress:c(()=>u("projectType","openapi"),"onPress")})]}),m(ye.TextField,{label:"Project dir",value:a?.outputDir??"",onChange:c(h=>u("outputDir",h),"onChange")})]}),_(ye.Item,{label:"Workspace Elements",children:[m(lt,{label:"Actions",elementType:N.Action,isActionExcluded:c(h=>a?.excludedActionKeys?.includes(h.key)??!1,"isActionExcluded"),toggleAction:c(h=>u("excludedActionKeys",[...a?.excludedActionKeys??[],h.key]),"toggleAction"),generateCode:c(h=>{(async()=>{try{await rr({out:a?.outputDir??"",target:a?.projectType??"typescript",schemasOnly:!1,membraneInterfaces:{actions:[h]}}),l("\u2705 Code generated successfully!")}catch{l("\u274C Error generating code")}})()},"generateCode")}),m(lt,{label:"Flows",elementType:N.Flow}),m(lt,{label:"Data Sources",elementType:N.DataSource}),m(lt,{label:"Field Mappings",elementType:N.FieldMapping}),m(lt,{label:"Packages",elementType:N.Package}),m(lt,{label:"App Data Schemas",elementType:N.AppDataSchema}),m(lt,{label:"App Event Types",elementType:N.AppEventType})]})]}),m(ct,{label:"Save Configuration",onPress:d,hotkey:"s"}),m(ct,{label:"Reload Configuration",onPress:f,hotkey:"r"}),m(ct,{label:"Exit",onPress:c(()=>s?.(),"onPress"),hotkey:"escape"})]})}),i&&m(C,{paddingX:2,children:m(v,{color:i.includes("\u2705")?"green":"red",children:i})})]})}c(Ud,"ConfigManager");const _a=Ys(process.cwd());function Wd({cwd:s,children:e}){return m(_a.Provider,{value:s,children:e})}c(Wd,"CwdProvider");function Jd(){return Xs(_a)}c(Jd,"useCwd");function ps({cwd:s,children:e,membraneCLIService:t}){const n=s||process.cwd();return m(Wd,{cwd:n,children:m(yl,{value:{fetcher:Dl()},children:m(Dd,{membraneCLIService:t,children:e})})})}c(ps,"Layout");function Hd(s,e){s.command("config").alias("install").description("\u26A0\uFE0F EXPERIMENTAL: Manage local membrane configuration with interactive UI").addHelpText("after",["","Examples:"," membrane config # Open interactive config manager",""].join(`
145
- `)).action(()=>{In($e.createElement(ps,{membraneCLIService:e,children:$e.createElement(Ud,{onComplete:c(()=>process.exit(0),"onComplete")})}))})}c(Hd,"setupConfigCommand");function Vd({currentPat:s,onSubmit:e}){const[t,n]=J(""),[r,i]=J(!1),[o,a]=J(null);return _(C,{flexDirection:"column",borderStyle:"round",borderTop:!0,width:70,paddingX:1,children:[m(C,{marginTop:-1,marginBottom:1,children:m(v,{bold:!0,children:"\u{1F511} Enter your Personal Access Token"})}),m(v,{children:"Please provide your Personal Access Token. You can find it here:"}),m(C,{marginTop:1,marginBottom:1,children:m(v,{color:"yellow",children:"https://console.integration.app/w/0/manage-account/api-token"})}),s&&m(v,{dimColor:!0,children:"Press Enter to keep your current token or type a new one."}),m(xi,{mask:"*",placeholder:`${s?"******":"Enter your token here..."}`,value:t,onChange:n,onSubmit:c(async u=>{a(null),i(!0);try{await e(u),n("")}catch{a("Invalid token. Please try again.")}finally{i(!1)}},"handleSubmit")}),r&&m(C,{marginTop:1,children:_(v,{children:[m(An,{type:"dots"})," Validating token..."]})}),o&&m(v,{color:"red",children:o})]})}c(Vd,"PersonalAccessTokenInput");function Ia({onExit:s,showEscOption:e=!0}){const[t,n]=J(""),{data:r,error:i,isLoading:o}=Ai("/account"),{updateConfig:a}=ge(),l=r?.workspaces,u=o;if(Qe((p,w)=>{w.escape&&s?.()}),u)return _(C,{children:[m(An,{}),m(v,{children:" Fetching workspaces..."})]});if(i)return _(C,{flexDirection:"column",children:[_(v,{color:"red",children:["Error: ",i.message]}),m(C,{marginTop:1,children:m(v,{color:"grey",children:"Press ESC to go back"})})]});const d=l?.filter(p=>p.name.toLowerCase().includes(t.toLowerCase()))??[],f=d.map(p=>({label:p.name,value:p.id})),h=f.length,g=l?.length??0;async function y(p){const w=d.find($=>$.id===p);if(!w)return;const{key:T,secret:E}=w;!T||!E||(await a({workspaceKey:T,workspaceSecret:E}),s?.())}return c(y,"handleSelect"),_(C,{flexDirection:"column",borderStyle:"round",borderTop:!0,width:70,paddingX:1,children:[m(C,{marginTop:-1,children:m(v,{bold:!0,children:"\u{1F4C1} Select your workspace"})}),_(C,{marginTop:1,children:[m(v,{children:"Search: "}),m(wl,{placeholder:"Enter a search query...",onChange:n})]}),g>5&&_(v,{children:["Showing ",h," of ",g," workspaces."]}),m(C,{marginTop:1,children:m(bl,{options:f,onChange:c(p=>{p&&y(p)},"onChange")})}),e&&m(C,{marginTop:1,children:m(v,{color:"grey",children:"Press ESC to go back"})})]})}c(Ia,"SelectWorkspace");var rn=(s=>(s[s.Authenticate=0]="Authenticate",s[s.ConnectWorkspace=1]="ConnectWorkspace",s))(rn||{});const Gd={0:"Authenticate in Membrane",1:"Connect a Membrane Workspace"},Gr=[rn.Authenticate,rn.ConnectWorkspace];function Aa({onComplete:s}){const{config:e}=ge(),[t,n]=J(!1),[r,i]=J(0),o=!!(e?.workspaceKey&&e?.workspaceSecret),a=Li(),l=Gr[r],u=r+1,d=Gr.length,f=Gr.map((y,p)=>{let w="pending";return p<r?w="done":p===r&&(w="current"),{id:y,label:Gd[y],status:w}});async function h(y){const p=a&&y===""?a:y,w=new Di;try{await w.request("/account",{headers:{Authorization:`Bearer ${p}`}}),Ll(p),i(T=>T+1)}catch(T){console.error(T)}}c(h,"handlePatSubmit");function g(){n(!0),s&&s()}return c(g,"handleWorkspaceSelected"),Qe((y,p)=>{o&&p.escape&&s&&s()}),t?m(C,{children:m(v,{children:"\u2705 Setup complete. You are ready to go!"})}):_(C,{flexDirection:"column",alignSelf:"flex-start",gap:1,children:[_(C,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:70,children:[m(C,{marginTop:-1,marginBottom:1,children:_(v,{bold:!0,children:["\u{1F6E0}\uFE0F Setup \u2014"," ",_(v,{color:"cyan",children:["Step ",u," of ",d]}),o&&m(v,{color:"grey",children:" [esc: go back]"})]})}),m(C,{flexDirection:"column",paddingLeft:2,children:f.map(y=>m(zd,{status:y.status,label:y.label},y.id))})]}),l===rn.Authenticate&&m(Vd,{currentPat:a,onSubmit:h}),l===rn.ConnectWorkspace&&m(Ia,{onExit:g,showEscOption:!1})]})}c(Aa,"Setup");function zd({status:s,label:e}){return _(C,{children:[_(C,{width:2,children:[s==="current"&&m(An,{type:"dots"}),s==="done"&&m(v,{children:"\u2705"})]}),m(v,{dimColor:s!=="current",children:e})]})}c(zd,"StepDisplay");function Yd(s,e){s.command("init").description("Run interactive setup for Membrane project").option("--key <key>","Workspace key for non-interactive setup").option("--secret <secret>","Workspace secret for non-interactive setup").addHelpText("after",["","Examples:"," membrane init # Run interactive setup"," membrane init --key KEY --secret SEC # Non-interactive setup with key and secret",""].join(`
146
- `)).action(t=>{t.key&&t.secret?tt.saveToFile({workspaceKey:t.key,workspaceSecret:t.secret})?(console.error("\u2705 Configuration saved to membrane.config.yml"),process.exit(0)):(console.error("Error writing configuration file"),process.exit(1)):t.key||t.secret?(console.error("Error: Both --key and --secret must be provided for non-interactive mode"),process.exit(1)):In($e.createElement(ps,{membraneCLIService:e,children:$e.createElement(Aa,{onComplete:c(()=>process.exit(0),"onComplete")})}))})}c(Yd,"setupInitCommand");async function Oa(s,e,t){const n={iss:s,exp:Math.floor(Date.now()/1e3)+600,isAdmin:!0};return t&&(n.id=t),Qs.sign(n,e)}c(Oa,"generateMcpAccessToken");async function Xd(s,e){return(await Ht.get(`${s}/docs-json`,{headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}})).data}c(Xd,"fetchOpenApiSchema");function Ge(s,e=!0,t,n=new Set){if(!s)return e?W.string():W.string().optional();if(Object.keys(s).length===0)return e?W.any():W.any().optional();if(s.$ref){const i=s.$ref.replace("#/components/schemas/","");if(n.has(i))return W.any();if(n.add(i),t?.schemas?.[i]){const o=t.schemas[i];return Ge(o,e,t,n)}return W.any()}let r;if(s.type==="object"||s.properties){const i={};if(s.properties)for(const[o,a]of Object.entries(s.properties)){const l=s.required?.includes(o)??!1;i[o]=Ge(a,l,t,n)}if(Object.keys(i).length>0){if(r=W.object(i),s.additionalProperties)if(typeof s.additionalProperties=="object"){const o=Ge(s.additionalProperties,!1,t,n);r=r.catchall(o)}else s.additionalProperties===!0&&(r=r.passthrough())}else if(s.additionalProperties&&typeof s.additionalProperties=="object"){const o=Ge(s.additionalProperties,!1,t,n);r=W.record(W.string(),o)}else r=W.record(W.string(),W.any())}else if(s.type==="array"){const i=s.items?Ge(s.items,!0,t,n):W.any();r=W.array(i)}else if(s.anyOf)r=W.any();else{switch(s.type){case"integer":r=W.coerce.number().int();break;case"number":r=W.coerce.number();break;case"boolean":r=W.coerce.boolean();break;case"string":default:r=W.string();break}s.format==="uuid"?r=W.string().uuid():s.format==="email"?r=W.string().email():s.format==="date"?r=W.string().regex(/^\d{4}-\d{2}-\d{2}$/):s.format==="date-time"&&(r=W.string().datetime()),s.enum&&(r=W.enum(s.enum)),(s.type==="integer"||s.type==="number")&&(s.minimum!==void 0&&(r=r.min(s.minimum)),s.maximum!==void 0&&(r=r.max(s.maximum))),s.type==="string"&&(s.minLength!==void 0&&(r=r.min(s.minLength)),s.maxLength!==void 0&&(r=r.max(s.maxLength)))}return e?r:r.optional()}c(Ge,"convertOpenApiSchemaToZod");function $a(s){const e=s.match(/\{([^}]+)\}/g);return e?e.map(t=>t.slice(1,-1)):[]}c($a,"extractPathParameters");function Zd(s,e,t,n,r,i,o,a){const l=s.operationId||`${t}_${e.replace(/[^a-zA-Z0-9]/g,"_")}`,u=s.description||s.summary||`${t.toUpperCase()} ${e}`,d={},f={},h={};if(s.parameters){for(const y of s.parameters)if(y.in==="path")f[y.name]=Ge(y.schema,!0,o).describe(y.description||`Path parameter: ${y.name}`);else if(y.in==="query"){const p=y.required===!0;h[y.name]=Ge(y.schema,p,o).describe(y.description||`Query parameter: ${y.name}`)}}if(Object.keys(f).length>0&&(d.params=W.object(f).describe("Path parameters")),Object.keys(h).length>0&&(d.query=W.object(h).describe("Query parameters")),s.requestBody&&s.requestBody.content){const y=s.requestBody.required===!0;if(s.requestBody.content["application/json"]){const p=s.requestBody.content["application/json"].schema;p?d.body=Ge(p,y,o).describe("Request body (JSON)"):d.body=W.any().describe("Request body (JSON)")}else s.requestBody.content["application/octet-stream"]||s.requestBody.content["text/plain"]?d.body=y?W.string().describe("Request body (binary/text)"):W.string().optional().describe("Request body (binary/text)"):d.body=W.any().describe("Request body")}const g=Object.keys(d).length>0?W.object(d):W.object({});return{name:l,description:u,parameters:g,async execute(y){try{const p=$a(e);if(p.length>0){if(!y.params)throw new Error(`Missing required path parameters: ${p.join(", ")}`);const M=p.filter(j=>!(j in y.params));if(M.length>0)throw new Error(`Missing required path parameters: ${M.join(", ")}`)}let w=`${n}${e}`;if(y.params)for(const[M,j]of Object.entries(y.params)){const O=`{${M}}`;w.includes(O)&&(w=w.replace(O,String(j)))}const T=$a(w);if(T.length>0)throw new Error(`Unresolved path parameters: ${T.join(", ")}`);const E=new URLSearchParams;if(y.query)for(const[M,j]of Object.entries(y.query))j!=null&&E.append(M,String(j));E.toString()&&(w+=`?${E.toString()}`);const $=await Oa(r,i,a),I={method:t.toUpperCase(),headers:{Authorization:`Bearer ${$}`}};y.body&&t.toLowerCase()!=="get"&&(s.requestBody?.content?.["application/json"]?(I.headers["Content-Type"]="application/json",I.data=y.body):s.requestBody?.content?.["application/octet-stream"]?(I.headers["Content-Type"]="application/octet-stream",I.data=y.body):s.requestBody?.content?.["text/plain"]?(I.headers["Content-Type"]="text/plain",I.data=y.body):(I.headers["Content-Type"]="application/json",I.data=y.body));const x=await Ht.request({url:w,...I});return{content:[{type:"text",text:x.data===""?"":JSON.stringify(x.data,null,2)}]}}catch(p){return Ht.isAxiosError(p)?{content:[{type:"text",text:`Error: ${p.response?.data?`HTTP ${p.response.status}: ${p.response.statusText} - ${JSON.stringify(p.response.data)}`:`HTTP ${p.response?.status||"unknown"}: ${p.message}`}`}],isError:!0}:p instanceof Error?{content:[{type:"text",text:`Error: API call failed: ${p.message}`}],isError:!0}:{content:[{type:"text",text:"Error: API call failed with unknown error"}],isError:!0}}}}}c(Zd,"createApiTool");function Qd(s,e,t,n,r){const i=[];if(!s.paths)return i;const o=s.components||{};for(const[a,l]of Object.entries(s.paths))if(typeof l=="object"&&l!==null){for(const[u,d]of Object.entries(l))if(["get","post","put","delete","patch"].includes(u)&&d&&typeof d=="object"){const f=Zd(d,a,u,e,t,n,o,r);i.push(f)}}return i}c(Qd,"convertOpenApiToTools");function ef(s){s.command("mcp").description("Launch MCP server with OpenAPI endpoints as tools (API URI is read from environment variables or membrane.config.yml)").addHelpText("after",["","Examples:"," membrane mcp # Launch MCP server using API URI from env vars or membrane.config.yml",""].join(`
147
- `)).action(async()=>{try{process.env.FASTMCP_SUPPRESS_WARNINGS="true";const e=$n();e||(console.error("No configuration found. Please set MEMBRANE_WORKSPACE_KEY and MEMBRANE_WORKSPACE_SECRET environment variables, or run `membrane init` first."),process.exit(1)),(!e.workspaceKey||!e.workspaceSecret)&&(console.error("Missing workspace credentials. Please provide them in the configuration file, command line, or environment variables."),process.exit(1));const t=e.apiUri||or,n=await Oa(e.workspaceKey,e.workspaceSecret,e.testCustomerId),r=await Xd(t,n),i=Qd(r,t,e.workspaceKey,e.workspaceSecret,e.testCustomerId),o=new Cl({name:"Membrane API",instructions:`This MCP server lets you interact with Membrane to configure, run, and troubleshoot integrations.
144
+ `,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=ds(e),n=Pt(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=ds(e),n=Pt(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 ga(s){const e=s.prettyErrors!==!1;return{lineCounter:s.lineCounter||e&&new fa||null,prettyErrors:e}}c(ga,"parseOptions");function fd(s,e={}){const{lineCounter:t,prettyErrors:n}=ga(e),r=new jr(t?.addNewLine),i=new Mr(e),o=Array.from(i.compose(r.parse(s)));if(n&&t)for(const a of o)a.errors.forEach(rs(s,t)),a.warnings.forEach(rs(s,t));return o.length>0?o:Object.assign([],{empty:!0},i.streamInfo())}c(fd,"parseAllDocuments");function ya(s,e={}){const{lineCounter:t,prettyErrors:n}=ga(e),r=new jr(t?.addNewLine),i=new Mr(e);let o=null;for(const a of i.compose(r.parse(s),!0,s.length))if(!o)o=a;else if(o.options.logLevel!=="silent"){o.errors.push(new ot(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return n&&t&&(o.errors.forEach(rs(s,t)),o.warnings.forEach(rs(s,t))),o}c(ya,"parseDocument");function hd(s,e,t){let n;typeof e=="function"?n=e:t===void 0&&e&&typeof e=="object"&&(t=e);const r=ya(s,t);if(!r)return null;if(r.warnings.forEach(i=>Ao(r.options.logLevel,i)),r.errors.length>0){if(r.options.logLevel!=="silent")throw r.errors[0];r.errors=[]}return r.toJS(Object.assign({reviver:n},t))}c(hd,"parse");function pd(s,e,t){let n=null;if(typeof e=="function"||Array.isArray(e)?n=e:t===void 0&&e&&(t=e),typeof t=="string"&&(t=t.length),typeof t=="number"){const r=Math.round(t);t=r<1?void 0:r>8?{indent:8}:{indent:r}}if(s===void 0){const{keepUndefined:r}=t??e??{};if(!r)return}return nt(s)&&!n?s.toString(t):new Wt(s,n,t).toString(t)}c(pd,"stringify");var md=Object.freeze({__proto__:null,Alias:Bn,CST:ld,Composer:Mr,Document:Wt,Lexer:da,LineCounter:fa,Pair:se,Parser:jr,Scalar:R,Schema:js,YAMLError:Ar,YAMLMap:le,YAMLParseError:ot,YAMLSeq:Ue,YAMLWarning:Xo,isAlias:Ke,isCollection:Y,isDocument:nt,isMap:vt,isNode:X,isPair:G,isScalar:V,isSeq:kt,parse:hd,parseAllDocuments:fd,parseDocument:ya,stringify:pd,visit:st,visitAsync:qn});class Fr extends pl{static{c(this,"TypedEventEmitter")}on(e,t){return super.on(e,t)}emit(e,...t){return super.emit(e,...t)}off(e,t){return super.off(e,t)}once(e,t){return super.once(e,t)}}const ue={Updated:"updated",Deleted:"deleted",Stopped:"stopped"},gd={ignored:ql,persistent:!0,ignoreInitial:!0,followSymlinks:!1,depth:20,awaitWriteFinish:{stabilityThreshold:500,pollInterval:100},ignorePermissionErrors:!0,atomic:!0,usePolling:!1,alwaysStat:!1,interval:1e3,binaryInterval:300};class yd extends Fr{static{c(this,"LocalElementWatcher")}constructor(e){super(),this.options=e,this.membraneDir=he(this.options.cwd),this.lockTimeoutMs=this.options.lockTimeoutMs??1e3}isWatching=!1;watcher;membraneDir;contentCache={};ignoredPaths=new Set;lockTimeoutMs;async start(){this.isWatching||(A.existsSync(this.membraneDir)||A.mkdirSync(this.membraneDir,{recursive:!0}),this.initializeContentCache(),this.watcher=hl.watch(this.membraneDir,gd),this.watcher.on("add",e=>this.handleFileSystemEvent(ue.Updated,e)).on("change",e=>this.handleFileSystemEvent(ue.Updated,e)).on("unlink",e=>this.handleFileSystemEvent(ue.Deleted,e)).on("ready",()=>this.isWatching=!0))}async stop(){!this.isWatching||!this.watcher||(await this.watcher.close(),this.isWatching=!1,this.watcher=void 0,this.clearCache(),this.clearAllLocks(),this.emit(ue.Stopped))}getCwd(){return this.options.cwd}async executeWithPathLock(e,t){const n=P.resolve(e);this.ignoredPaths.add(n);try{await t()}finally{setTimeout(()=>{this.ignoredPaths.delete(n)},this.lockTimeoutMs)}}isPathLocked(e){const t=P.resolve(e);if(this.ignoredPaths.has(t))return!0;for(const n of this.ignoredPaths)if(t.startsWith(n+P.sep))return!0;return!1}clearAllLocks(){this.ignoredPaths.clear()}handleFileSystemEvent(e,t){const n=P.relative(this.membraneDir,t);if(this.isPathLocked(t))return;if(e===ue.Deleted){this.removeFromCache(n);const a={filePath:t,relativePath:n,data:void 0};b.info(`[local] ${e}: ${a.relativePath}`),this.emit(e,a);return}const r=this.readFileContent(t);if(!this.hasContentChanged(n,r))return;const o=this.processFileEvent(t,r);this.updateCache(n,r),o&&(b.info(`[local] ${e}: ${o.relativePath}`),this.emit(e,o))}readFileContent(e){return A.readFileSync(e,"utf8")}processFileEvent(e,t){const n=P.relative(this.membraneDir,e);let r;try{r=t?md.parse(t):void 0}catch{r=void 0}return{filePath:e,relativePath:n,data:r}}hasContentChanged(e,t){if(!t)return this.contentCache[e]!==void 0;const n=this.getContentHash(t);return this.contentCache[e]!==n}getContentHash(e){return dl.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(){A.existsSync(this.membraneDir)&&this.scanDirectoryForCache(this.membraneDir)}scanDirectoryForCache(e){const t=A.readdirSync(e,{withFileTypes:!0});for(const n of t){const r=P.join(e,n.name);if(n.isDirectory())this.scanDirectoryForCache(r);else if(n.isFile())try{const i=A.readFileSync(r,"utf8"),o=P.relative(this.membraneDir,r);this.updateCache(o,i)}catch{}}}}var qr=(s=>(s.Updated="updated",s.ConnectorFileUpdated="connector-file-updated",s.Connected="connected",s.Disconnected="disconnected",s.Error="error",s))(qr||{});const wd={debounceMs:2e3,reconnectIntervalMs:5e3,maxReconnectAttempts:1/0,maxBackoffMs:6e4,connectionTimeoutMs:3e5};class bd extends Fr{static{c(this,"RemoteElementWatcher")}constructor(e=wd){super(),this.config=e}eventSource;debounceTimeouts=new Map;reconnectAttempts=0;reconnectTimeout;connectionTimeout;isStarted=!1;isConnected=!1;async start(){this.isStarted||(this.isStarted=!0,await this.connect())}async stop(){this.isStarted&&(this.isStarted=!1,this.isConnected=!1,this.clearReconnectTimeout(),this.clearConnectionTimeout(),this.clearAllDebounceTimeouts(),this.eventSource&&(this.eventSource.close(),this.eventSource=void 0))}async connect(){try{b.debug("[remote-events] Connecting to server"),this.eventSource&&(this.eventSource.close(),this.eventSource=void 0);const e=await K.getClient(process.cwd()),t=await e.getToken();if(!t)throw new Error("No auth token available");const n=`${e.apiUri}/sse/workspace?token=${encodeURIComponent(t)}`;b.debug("[remote-events] Subscribing to workspace events"),this.eventSource=new ml(n),this.setupEventSourceHandlers()}catch(e){b.debug(`[remote-events] Failed to connect: ${e}`),this.emit("error",{error:e}),this.scheduleReconnect()}}setupEventSourceHandlers(){this.eventSource&&(this.eventSource.onopen=()=>{b.debug("[remote-events] Connected to server"),this.reconnectAttempts=0,this.isConnected=!0,this.resetConnectionTimeout(),this.emit("connected",{})},this.eventSource.onmessage=e=>{try{this.resetConnectionTimeout();const t=JSON.parse(e.data);this.handleElementUpdate(t)}catch(t){b.debug(`[remote-events] Failed to parse workspace event: ${t}`)}},this.eventSource.onerror=e=>{b.debug(`[remote-events] Connection error: ${JSON.stringify(e,null,2)}`),this.isConnected=!1,this.clearConnectionTimeout(),this.eventSource&&(this.eventSource.close(),this.eventSource=void 0),this.emit("disconnected",{}),this.isStarted&&this.scheduleReconnect()})}handleElementUpdate(e){if(e.type!==Zc.ElementUpdate)return;const{elementId:t,elementType:n,data:r={}}=e;if(!(!t||!n)){if(n===N.Connector){const{filePath:i,eventType:o,newPath:a}=r;return b.debug(`[remote-watcher] Received connector event - elementId: ${t}, filePath: ${i}, eventType: ${o}`),this.scheduleConnectorFileUpdate(t,i,o,a)}return this.scheduleElementUpdate(t,n)}}scheduleElementUpdate(e,t){const n=this.debounceTimeouts.get(e);n&&clearTimeout(n);const r=setTimeout(()=>{this.debounceTimeouts.delete(e),this.emit("updated",{elementId:e,elementType:t})},this.config.debounceMs);this.debounceTimeouts.set(e,r)}scheduleConnectorFileUpdate(e,t,n,r){const i=JSON.stringify({connectorId:e,filePath:t}),o=this.debounceTimeouts.get(i);o&&clearTimeout(o);const a=setTimeout(()=>{this.debounceTimeouts.delete(i),this.emit("connector-file-updated",{connectorId:e,filePath:t,eventType:n,newPath:r})},this.config.debounceMs);this.debounceTimeouts.set(i,a)}scheduleReconnect(){if(!this.isStarted||this.reconnectAttempts>=this.config.maxReconnectAttempts){this.reconnectAttempts>=this.config.maxReconnectAttempts&&(b.error("[remote-events] Max reconnection attempts reached. Connection will not be retried."),this.emit("error",{error:new Error("Max reconnection attempts reached")}));return}this.reconnectTimeout&&clearTimeout(this.reconnectTimeout),this.reconnectAttempts++;const e=this.config.reconnectIntervalMs*Math.pow(2,this.reconnectAttempts-1),t=Math.random()*.3*e,n=Math.min(e+t,this.config.maxBackoffMs);b.debug(`[remote-events] Reconnecting in ${Math.round(n)}ms (attempt ${this.reconnectAttempts})`),this.reconnectTimeout=setTimeout(()=>{this.connect()},n)}clearReconnectTimeout(){this.reconnectTimeout&&(clearTimeout(this.reconnectTimeout),this.reconnectTimeout=void 0)}resetConnectionTimeout(){this.clearConnectionTimeout(),this.connectionTimeout=setTimeout(()=>{this.isConnected&&this.isStarted&&(b.debug("[remote-events] Connection timeout detected, reconnecting..."),this.isConnected=!1,this.eventSource&&(this.eventSource.close(),this.eventSource=void 0),this.scheduleReconnect())},this.config.connectionTimeoutMs)}clearConnectionTimeout(){this.connectionTimeout&&(clearTimeout(this.connectionTimeout),this.connectionTimeout=void 0)}clearAllDebounceTimeouts(){this.debounceTimeouts.forEach(e=>clearTimeout(e)),this.debounceTimeouts.clear()}}class wa{static{c(this,"ElementsCache")}elements=new Map;typeIndex=new Map;internalIdIndex=new Map;constructor(e){e&&this.addAll(e)}add(e){const t=e.id;this.elements.set(t,e),this.typeIndex.has(e.type)||this.typeIndex.set(e.type,new Set),this.typeIndex.get(e.type).add(t),e.data?.id&&this.internalIdIndex.set(e.data.id,t)}remove(e){const t=e.id,n=this.elements.delete(t);if(n){const r=this.typeIndex.get(e.type);r&&(r.delete(t),r.size===0&&this.typeIndex.delete(e.type)),e.data?.id&&this.internalIdIndex.delete(e.data.id)}return n}put(e){this.elements.has(e.id)&&this.remove(e),this.add(e)}get(e){return this.elements.get(e)}getByInternalId(e){const t=this.internalIdIndex.get(e);if(t)return this.elements.get(t)}getElementsByType(e){const t=this.typeIndex.get(e);return t?Array.from(t).map(n=>this.elements.get(n)).filter(n=>n!==void 0):[]}getAll(){return Array.from(this.elements.values())??[]}getTypes(){return Array.from(this.typeIndex.keys())}addAll(e){for(const t of e)t&&this.add(t)}removeAll(e){for(const t of e)this.remove(t)}getElementIdsByType(e){return this.typeIndex.get(e)}clear(){this.elements.clear(),this.typeIndex.clear(),this.internalIdIndex.clear()}getAllIds(){return new Set(this.elements.keys())}}const Mt="connectors",Me="development",Br={};async function Sd(){const e=(await K.withClient(o=>o.get("org-workspace-id"))).id,t={};b.info("[connectors] Loading custom connectors"),await K.withClient(o=>o.get(`/connectors?workspaceId=${e}`)),b.info("[connectors] Loading public connectors");const n=Je(),i=(B.existsSync(n)?B.readdirSync(n):[]).filter(o=>{if(o.startsWith("."))return!1;const a=q.join(n,o);try{return B.statSync(a).isDirectory()}catch{return!1}});for(const o of i){b.info(`[connectors] Loading connector from: ${o}`);const a=B.readdirSync(q.join(n,o)),l=await Kr(o);if(!l)continue;"baseUri"in l&&delete l.baseUri;let u;if(l.uuid&&(u=await K.withClient(f=>f.get(`/connectors/${l.uuid}`),!1)),u)t[l.id]=u.id,b.info(`[connectors] Matched ${l.name} uuid: ${l.uuid}`),u.archivedAt&&(b.info(`[connectors] Restoring archived connector ${l.name}`),await K.withClient(f=>f.post(`connectors/${u.id}/restore`))),b.info(`[connectors] Updating connector ${l.name}`),await K.withClient(f=>f.patch(`connectors/${u.id}`,{...l,workspaceId:e}));else if(!t[l.id]){let f=!1;try{const h=await Ur({connectorId:l.id});h&&h.isPublic&&(f=!0)}catch{}if(!f){b.info(`[connectors] Creating custom connector ${l.name} (${l.key})`);const h=await K.withClient(g=>g.post("connectors",{...l,workspaceId:e}));t[l.id]=h.id}}const d=a.filter(f=>B.statSync(q.join(n,o,f)).isDirectory());for(const f of d)await kd({connector:l,version:f,connectorId:t[l.id]})}return t}c(Sd,"pushConnectors");async function ba({connectorId:s,connectorVersion:e,allConnectors:t,pulledConnectors:n,pulledConnectorVersions:r}){if(!s||r[s]?.has(e))return;const i=Ri(),o=await Ur({connectorId:s});if(!o.isPublic||t){if(!o?.key){console.error(`[connectors] Connector ${s} has no key. Skipping..`),b.error(`[connectors] Connector ${s} has no key. Skipping..`);return}n.has(s)||(await Td({basePath:i,connector:o}),n.add(s)),r[s]||(r[s]=new Set),r[s].has(e)||(await Ed({connector:o,connectorVersion:e,basePath:i}),r[s].add(e))}}c(ba,"pullRemoteConnector");function Je(){const s=ar();return q.join(s.membraneDirPath,Mt)}c(Je,"getConnectorsPath");async function Kr(s){const e=q.join(Je(),s,`${s}.yml`);return ur(e,!1)}c(Kr,"readConnector");async function Cd(s,e){return b.info(`[connectors] Zipping ${s} into ${e}`),new Promise((t,n)=>{const r=B.createWriteStream(e),i=Ni("zip",{zlib:{level:9}});r.on("close",()=>{b.success(`[connectors] Successfully created ${e}`),t()}),r.on("end",()=>{b.info("[connectors] Data has been drained")}),i.on("warning",a=>{a.code==="ENOENT"?console.warn(a):n(a)}),i.on("error",a=>{n(a)}),i.pipe(r);const o=B.readdirSync(s);for(const a of o){const l=q.join(s,a),u=B.statSync(l);u.isFile()?i.file(l,{name:a}):u.isDirectory()&&i.directory(l,a)}i.finalize()})}c(Cd,"createZipArchive");async function vd(s,e){return b.info(`[connectors] Unzipping into ${e}`),new Promise((t,n)=>{const r=xi.Parse();r.on("entry",i=>{const o=i.path;if(i.type==="Directory"){const l=q.join(e,o);B.mkdirSync(l,{recursive:!0}),i.autodrain()}else{const l=q.join(e,o),u=q.dirname(l);B.mkdirSync(u,{recursive:!0});const d=B.createWriteStream(l);i.pipe(d),d.on("finish",()=>{})}}),r.on("end",()=>{b.success(`[connectors] Successfully extracted to ${e}`),t()}),r.on("error",i=>{n(i)}),r.write(s),r.end()})}c(vd,"extractZipArchive");async function kd({connector:s,version:e,connectorId:t}){const n=q.join(Je(),Re(s),Sa(e)),r=q.join(n,"src"),i=q.join(n,"src.zip"),o=B.existsSync(i);if(B.existsSync(r)&&(b.info(`[connectors] Archiving source code for ${s.name} version ${e}`),await Cd(r,i)),!B.existsSync(i)){b.warning(`[connectors] No source code found for ${s.name} version ${e}`);return}try{const a=new gl;if(a.append("file",B.createReadStream(i),"file.zip"),b.info(`[connectors] Pushing connector version ${e} for ${s.name}`),e==Me)b.info(`[connectors] Uploading connector ${t}`),await K.withClient(l=>l.post(`connectors/${t}/upload`,a,{headers:{...a.getHeaders()}}));else{if(a.append("version",e),a.append("changelog","Imported Version"),(await K.withClient(u=>u.get(`/connectors/${t}/versions`))).find(u=>u.version==e)){b.info(`[connectors] Version ${e} already published`);return}b.info(`[connectors] Publishing version ${e} of connector ${t}`),await K.withClient(u=>u.post(`connectors/${t}/publish-version`,a,{headers:{...a.getHeaders()}}))}b.success(`Successfully pushed connector version ${e} for ${s.name}`)}catch(a){b.error(`Error pushing connector version ${e} for ${s.name}: ${a}`),console.error(`[connectors] Error pushing connector version ${e} for ${s.name}: ${a}`)}finally{!o&&B.existsSync(i)&&(b.info(`[connectors] Cleaning up temporary zip file for ${s.name} version ${e}`),B.unlinkSync(i))}}c(kd,"pushConnectorVersion");async function Ur({connectorId:s}){if(s){if(Br[s])return Br[s];try{const e=await K.withClient(t=>t.get(`connectors/${s}`),!1);return Br[s]=e,e}catch(e){return b.error(`[connectors] Failed to get connector ${s}: ${e}`),console.error(`[connectors] Failed to get connector ${s}: ${e}`),null}}}c(Ur,"getConnector");async function Td({basePath:s,connector:e}){const t=Re(e),n=q.join(s,Mt,t);B.mkdirSync(n,{recursive:!0});const r=q.join(n,`${Re(e)}.yml`);B.writeFileSync(r,Se.dump(e)),b.info(`[connectors] Pulled connector ${e.name}`)}c(Td,"pullConnector$1");async function Ed({connector:s,connectorVersion:e,basePath:t}){const n=Re(s),r=Sa(e),i=q.join(t,"connectors",n,r),o=await K.withClient(l=>l.get(`connectors/${s.id}/download`,{version:e},{responseType:"arraybuffer",headers:{Accept:"application/zip"},timeout:1e6}));B.mkdirSync(i,{recursive:!0});const a=q.join(i,"src.zip");if(B.writeFileSync(a,o),!e){const l=q.join(i,"src");B.mkdirSync(l,{recursive:!0}),await vd(o,l)}b.info(`[connectors] Pulled connector version: ${s.name} (${r})`)}c(Ed,"pullConnectorVersion");function Re(s){return s.key}c(Re,"getConnectorDirName");function Sa(s){return s??Me}c(Sa,"getConnectorVersionDirName");function _d(s){const e=Ri(),t=Re(s);return q.join(e,Mt,t)}c(_d,"getConnectorDirPath");function Id(s){return s.match(`${Mt}/[^/]+/${Me}/src/.*`)!==null}c(Id,"isConnectorSourceFile");async function Ad(s){const e=s.match(`${Mt}/([^/]+)/${Me}/src/(.*)`);if(!e)return;const t=e[1],n=e[2],r=await Kr(t);if(!r){b.warning(`[connectors] Connector ${t} not found. Ignoring file change`);return}const i=r.id,o=B.readFileSync(s,"utf-8");await K.withClient(a=>a.put(`connectors/${i}/files/${n}`,o,{headers:{"Content-Type":"text/plain"}})),b.info(`[connectors] Pushed file ${n} for connector ${r.name}`)}c(Ad,"putConnectorFile");async function Od(s){const e=s.match(`${Mt}/([^/]+)/${Me}/src/(.*)`);if(!e)return;const t=e[1],n=e[2],r=await Kr(t);if(!r){b.warning(`[connectors] Connector ${t} not found. Ignoring file change`);return}const i=r.id;await K.withClient(o=>o.delete(`connectors/${i}/files/${n}`)),b.info(`[connectors] Deleted file ${n} for connector ${r.name}`)}c(Od,"deleteConnectorFile");async function $d(s,e){try{const t=await K.withClient(o=>o.get(`connectors/${s}`));if(!t){b.warning(`[connectors] Connector ${s} not found`);return}const n=await K.withClient(o=>o.get(`connectors/${s}/files/${e}`)),r=Re(t),i=q.join(Je(),r,Me,"src",e);B.mkdirSync(q.dirname(i),{recursive:!0}),n!=null?(B.writeFileSync(i,n),b.info(`[connectors] Pulled file ${e} for connector ${t.name}`)):B.existsSync(i)&&(B.unlinkSync(i),b.info(`[connectors] Deleted file ${e} for connector ${t.name}`))}catch(t){b.error(`[connectors] Failed to pull connector file ${e} for connector ${s}: ${t}`),console.error(`[connectors] Failed to pull connector file ${e} for connector ${s}: ${t}`)}}c($d,"pullConnectorFile");async function Nd(s,e){const t=await K.withClient(i=>i.get(`connectors/${s}`),!1);if(!t){b.warning(`[connectors] Connector ${s} not found`);return}const n=Re(t),r=q.join(Je(),n,Me,"src",e);B.existsSync(r)&&(B.unlinkSync(r),b.info(`[connectors] Deleted file ${e} for connector ${n}`))}c(Nd,"deleteLocalConnectorFile");async function xd(s,e,t){if(t&&e!==t)try{const n=await K.withClient(l=>l.get(`connectors/${s}`),!1);if(!n){b.warning(`[connectors] Connector ${s} not found`);return}const r=Re(n),i=q.join(Je(),r,Me,"src"),o=q.join(i,e),a=q.join(i,t);B.existsSync(o)&&(B.mkdirSync(q.dirname(a),{recursive:!0}),B.renameSync(o,a),b.info(`[connectors] Renamed directory from ${e} to ${t} for connector ${r}`))}catch(n){b.error(`[connectors] Failed to rename directory ${e} to ${t} for connector ${s}: ${n}`)}}c(xd,"renameLocalConnectorDirectory");async function Pd(s,e){try{const t=await K.withClient(i=>i.get(`connectors/${s}`),!1);if(!t){b.warning(`[connectors] Connector ${s} not found`);return}const n=Re(t),r=q.join(Je(),n,Me,"src",e);if(B.existsSync(r)){const i=q.resolve(Je());if(!q.resolve(r).startsWith(i))return;B.rmSync(r,{recursive:!0,force:!0}),b.info(`[connectors] Deleted directory ${e} for connector ${n}`)}}catch(t){b.error(`[connectors] Failed to delete directory ${e} for connector ${s}: ${t}`)}}c(Pd,"deleteLocalConnectorDirectory");const Q={LogAdded:"logAdded",StateChanged:"stateChanged",StatsChanged:"statsChanged",ConflictsChanged:"conflictsChanged",McpStatusChanged:"mcpStatusChanged",McpServersChanged:"mcpServersChanged",ConfigChanged:"configChanged"};class Md extends Fr{static{c(this,"WorkspaceNotifications")}constructor(e){super(),this.config=e,b.setNotificationHandler(this)}clientId;heartbeatInterval;isCleaningUp=!1;async connectToRemote(){await this.registerWithRemoteServer(),await this.startHeartbeatLoop()}async setState(e){this.emit(Q.StateChanged,{state:e}),await this.emitRemote({status:e})}setConflicts(e){this.emit(Q.ConflictsChanged,{conflicts:e})}setConfig(e){this.emit(Q.ConfigChanged,{config:e})}setStats(e){this.emit(Q.StatsChanged,{stats:e})}addLog(e){this.emit(Q.LogAdded,{log:e})}setMcpStatus(e){this.emit(Q.McpStatusChanged,{status:e})}async setMcpServers(e){this.emit(Q.McpServersChanged,{servers:e}),await this.emitRemote({mcpServers:e.map(t=>({name:t.agentName,totalRequests:t.totalRequests}))})}async cleanup(){!this.clientId||this.isCleaningUp||(this.isCleaningUp=!0,this.heartbeatInterval&&(clearInterval(this.heartbeatInterval),this.heartbeatInterval=void 0),await this.withErrorHandling(async()=>{await K.withClient(e=>e.delete(`/local-clients/${this.clientId}`))}),this.clientId=void 0)}async registerWithRemoteServer(){if(this.clientId)return;const e=await this.withErrorHandling(async()=>await K.withClient(t=>t.post("/local-clients",{hostname:$i.hostname(),workingDirectory:process.cwd()})));e?.id?this.clientId=e.id:this.addLog({timestamp:new Date().toISOString(),message:"Failed to register with remote server",type:"error"})}async startHeartbeatLoop(){this.heartbeatInterval=setInterval(async()=>{this.clientId&&await this.sendHeartbeat()},this.config.heartbeatIntervalMs)}async sendHeartbeat(){this.clientId&&await this.withErrorHandling(async()=>{await K.withClient(e=>e.post(`/local-clients/${this.clientId}/keep-alive`,{}))})}async emitRemote(e){this.clientId&&await this.withErrorHandling(async()=>{await K.withClient(t=>t.patch(`/local-clients/${this.clientId}`,e))})}async withErrorHandling(e){try{return await e()}catch(t){const n=t instanceof Error?t.message:String(t);return this.addLog({timestamp:new Date().toISOString(),message:`Failed to connect to remote: ${n}`,type:"error"}),null}}}const He=new Md({heartbeatIntervalMs:15e3}),Ca=[N.AppDataSchema,N.AppEventType,N.DataLinkTable,N.DataSource,N.FieldMapping,N.Action,N.Flow,N.Package];class Tn{static{c(this,"ElementSyncService")}localWatcher=void 0;remoteWatcher=void 0;notifier;changes=[];localCache;remoteCache;localRepo;remoteRepo;pulledConnectors=new Set;pulledConnectorVersions={};constructor(){this.notifier=He,this.localCache=new wa,this.remoteCache=new wa,this.localRepo=new iu(this.localCache),this.remoteRepo=new ou(this.remoteCache)}clear(){this.changes=[]}needsForcedSync(){return this.changes.some(e=>e.isConflict)}needsSync(){return this.changes.length>0}async getStats(){const e=this.localCache.getAll(),t={};return e.forEach(n=>{t[n.type]=(t[n.type]||0)+1}),t}async fetchElements(){const e=await this.localRepo.getElements(),t=await this.remoteRepo.getElements();this.localCache.addAll(e),this.remoteCache.addAll(t)}async updateElement(e,t){const n=this.getHandler(t),r=this.getCache(t);try{const i=await n.putElement(e);r.put(i)}catch(i){throw b.error(`Failed to update element ${e.id}: ${i}`),i}}async deleteElement(e,t){const n=this.getHandler(t),r=this.getCache(t);try{await n.deleteElement(e,{elements:n.cache.getAll(),connectorsMapping:n.connectorsMapping}),r.remove(e)}catch(i){throw b.error(`Failed to delete element ${e.id}: ${i}`),i}}async pullConnectors(e=!1){const t=this.remoteCache.getElementsByType(N.Integration).map(n=>n.data);for(const n of t){const r=n.connectorId,i=n.connectorVersion;r&&await ba({connectorId:r,connectorVersion:i,allConnectors:e,pulledConnectors:this.pulledConnectors,pulledConnectorVersions:this.pulledConnectorVersions})}}async pushConnectors(){const e=await Sd();this.remoteRepo.setConnectorsMapping(e)}getHandler(e){return e===ae.INCOMING?this.localRepo:(this.remoteRepo.setSourceCache(this.localCache),this.remoteRepo)}getCache(e){return e===ae.INCOMING?this.localCache:this.remoteCache}async startWatching(){this.localWatcher=new yd({cwd:process.cwd(),lockTimeoutMs:1e3}),this.localWatcher.on(ue.Updated,e=>this.handleLocalEvent(e,ue.Updated)),this.localWatcher.on(ue.Deleted,e=>this.handleLocalEvent(e,ue.Deleted)),await this.localWatcher.start(),b.success("[local] Tracking changes.."),this.remoteWatcher=new bd,this.remoteWatcher.on(qr.Updated,({elementId:e,elementType:t})=>this.handleRemoteElementEvent(e,t)),this.remoteWatcher.on(qr.ConnectorFileUpdated,({connectorId:e,filePath:t,eventType:n,newPath:r})=>this.handleRemoteConnectorFileEvent(e,t,n,r)),await this.remoteWatcher.start(),b.success("[remote] Tracking changes..")}async stopWatching(){this.localWatcher&&(await this.localWatcher.stop(),this.localWatcher=void 0),this.remoteWatcher&&(await this.remoteWatcher.stop(),this.remoteWatcher=void 0)}async handleRemoteElementEvent(e,t){try{const n=await this.remoteRepo.getByInternalId(e,t),r=!!n?.data.archivedAt||!!n?.data.isDeactivated;if(!n||r){const o=n||this.remoteCache.getByInternalId(e);return o?(b.info(`[${this.getDirectionLabel(ae.INCOMING)}] Deleted: ${o.id}`),this.localWatcher?.executeWithPathLock(o.absolutePath,()=>this.deleteElement(o,ae.INCOMING))):void 0}if(b.info(`[${this.getDirectionLabel(ae.INCOMING)}] Updated: ${n.id}`),await this.localWatcher?.executeWithPathLock(n.absolutePath,async()=>this.updateElement(n,ae.INCOMING)),t===N.Integration){const o=n.data.connectorId,a=n.data.connectorVersion,l=await Ur({connectorId:o});if(!l?.key)return;const u=_d(l);await this.localWatcher?.executeWithPathLock(u,async()=>ba({connectorId:o,connectorVersion:a,allConnectors:!1,pulledConnectors:this.pulledConnectors,pulledConnectorVersions:this.pulledConnectorVersions}))}}catch(n){b.error(`[sync] Error handling remote event: ${n}`)}}async handleRemoteConnectorFileEvent(e,t,n,r){try{switch(n){case Ws.ConnectorFileDeleted:await Nd(e,t);break;case Ws.ConnectorDirectoryRenamed:await xd(e,t,r);break;case Ws.ConnectorDirectoryDeleted:await Pd(e,t);break;default:await $d(e,t);break}}catch(i){b.error(`[sync] Error handling remote connector file event: ${i}`)}}async handleLocalEvent(e,t){try{if(Id(e.filePath))switch(t){case ue.Updated:await Ad(e.filePath);break;case ue.Deleted:await Od(e.filePath);break}else{let n=Z.fromPathAndData(e.filePath,e.data);if(!n){const r=Z.idFromPath(e.filePath);if(!r||(n=this.remoteCache.get(r),!n))return}switch(b.info(`[${this.getDirectionLabel(ae.OUTGOING)}] ${nu.toSentenceCase(t)}: ${n.id}`),t){case ue.Updated:await this.updateElement(n,ae.OUTGOING);break;case ue.Deleted:await this.deleteElement(n,ae.OUTGOING);break}}}catch(n){b.error(`[sync] Error handling local event: ${n}`)}}detectIncomingChanges(){this.clearChanges();const e=Tn.getChanges(ae.INCOMING,this.remoteCache,this.localCache);return this.updateChanges(e),e}detectOutgoingChanges(){this.clearChanges();const e=Tn.getChanges(ae.OUTGOING,this.localCache,this.remoteCache);return this.updateChanges(e),e}async resolveChanges(){if(!this.needsSync())return;b.info("[resolver] Resolving changes.."),b.info("[resolver] Resolving integration elements");const e=this.changes.filter(r=>r.element.type===N.Integration);await Promise.all(e.map(async r=>this.resolveChange(r))),e.length>0&&(await this.fetchElements(),this.changes=this.changes.length>0&&this.changes[0]?.direction===ae.INCOMING?this.detectIncomingChanges():this.detectOutgoingChanges(),this.changes=this.changes.filter(r=>r.element.type!==N.Integration)),b.info("[resolver] Resolving universal elements");const t=this.changes.filter(r=>!r.element.hasParent());for(const r of Ca){const i=t.filter(o=>o.element.type===r);b.info(`[resolver] Resolving ${r} elements`),await Promise.all(i.map(async o=>this.resolveChange(o)))}b.info("[resolver] Resolving integration level elements");const n=this.changes.filter(r=>r.element.hasParent());for(const r of Ca){const i=n.filter(o=>o.element.type===r);b.info(`[resolver] Resolving ${r} elements`),await Promise.all(i.map(async o=>this.resolveChange(o)))}b.success("[resolver] Resolved changes")}async resolveChange(e){switch(e.type){case Ne.DELETE:return this.deleteElement(e.element,e.direction);case Ne.CREATE:return this.updateElement(e.element,e.direction);case Ne.UPDATE:return this.updateElement(e.element,e.direction)}}static getChanges(e,t,n){const r=t.getAllIds(),i=n.getAllIds(),o=new Set([...r,...i]),a=[];for(const l of o){const u=t.get(l),d=n.get(l),f=Tn.detectChangeForElement(u,d,e);f&&a.push(f)}return a}updateChanges(e){if(this.changes=e,this.needsForcedSync()){const t=e.filter(n=>n.isConflict);b.warning("[resolver] Conflicts detected"),this.notifier.setConflicts(t)}}clearChanges(){this.changes=[]}getDirectionLabel(e){switch(e){case ae.INCOMING:return"local\u2190remote";case ae.OUTGOING:return"local\u2192remote"}}static detectChangeForElement(e,t,n){return e&&!t?{type:Ne.CREATE,element:e,direction:n,isConflict:!1}:!e&&t?{type:Ne.DELETE,element:t,direction:n,isConflict:!0}:e&&t&&!e.isEqual(t)?{type:Ne.UPDATE,element:e,direction:n,isConflict:!1}:null}}const Ve=P.join(yl.tmpdir(),"membrane-mcp-status"),va=3e4;class Rd{static{c(this,"McpStatusService")}constructor(e=2e3){this.pollIntervalMs=e}isRunning=!1;pollInterval;async start(){this.isRunning||(this.isRunning=!0,this.pollInterval=setInterval(async()=>await this.checkStatus(),this.pollIntervalMs),await this.checkStatus())}async stop(){this.pollInterval&&(clearInterval(this.pollInterval),this.pollInterval=void 0,this.isRunning=!1)}async checkStatus(){try{const e=process.cwd(),t=fs(void 0,e),n=ka(e);t&&He.setMcpStatus(t),await He.setMcpServers(n)}catch{b.error("Failed to check MCP status")}}}function fs(s,e){try{const t=e||process.cwd();if(!s){const r=ka(t);return r.length===0?null:r[0]}const n=Hr(s,t);if(A.existsSync(n)){const r=A.statSync(n),i=new Date;if(i.getTime()-r.mtime.getTime()>va)return sn(s,t),null;const a=A.readFileSync(n,"utf8"),l=JSON.parse(a);if(l.isRunning){const u=new Date(l.lastActivity).getTime();if(i.getTime()-u>va)return sn(s,t),null}return l}}catch{s&&e&&sn(s,e)}return null}c(fs,"getMcpStatus");function ka(s){try{const e=s||process.cwd(),t=Jr(e);if(!A.existsSync(Ve))return[];const n=A.readdirSync(Ve),r=[];for(const i of n){const o=i.match(new RegExp(`^mcp-${t}-(\\d+)\\.json$`));if(o){const a=parseInt(o[1],10),l=fs(a,e);l&&r.push(l)}}return r.sort((i,o)=>new Date(o.startTime).getTime()-new Date(i.startTime).getTime())}catch{return[]}}c(ka,"getAllMcpStatusFiles");function Wr(s){try{const t={...fs(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};A.existsSync(Ve)||A.mkdirSync(Ve,{recursive:!0});const n=Hr(s.processId,s.cwd);A.writeFileSync(n,JSON.stringify(t,null,2))}catch{}}c(Wr,"updateMcpStatus");function sn(s,e){try{const t=e||process.cwd();if(s){const n=Hr(s,t);A.existsSync(n)&&A.unlinkSync(n)}else{const n=Jr(t);if(A.existsSync(Ve)){const r=A.readdirSync(Ve);for(const i of r)i.match(new RegExp(`^mcp-${n}-\\d+\\.json$`))&&A.unlinkSync(P.join(Ve,i))}}}catch{}}c(sn,"clearMcpStatus");function Ld(s,e){const t=fs(s,e);t&&Wr({processId:s,cwd:e,totalRequests:t.totalRequests+1,lastRequestTime:new Date().toISOString(),lastActivity:new Date().toISOString()})}c(Ld,"trackToolExecution");function Jr(s){return fl("md5").update(s).digest("hex").slice(0,8)}c(Jr,"getCwdHash");function Hr(s,e){const t=Jr(e);return P.join(Ve,`mcp-${t}-${s}.json`)}c(Hr,"getStatusFilePath");const hs={Agent:"agent",Cli:"cli"},D={NOT_INITIALIZED:"not_initialized",SETTING_UP:"setting_up",INITIALIZED:"initialized",NOT_SYNCED:"not_synced",PULLING:"pulling",PUSHING:"pushing",RESOLVING:"resolving",CONFLICTS:"conflicts",SYNCED:"synced",WATCHING:"watching",ERROR:"error"};class Dd{static{c(this,"MembraneCLIService")}constructor(e,t,n=()=>process.exit(0)){this.mode=e,this.cwd=t,this.onShutdown=n,this.notifier=He,this.mcpStatusService=new Rd,this.syncService=new Tn,this.setupProcessCleanup()}initialized=!1;notifier;mcpStatusService;syncService;isShuttingDown=!1;currentConfig=null;get config(){return this.currentConfig}getSyncedElements(){return this.syncService.localCache.getAll()}getSyncedElementsByType(e){return this.syncService.localCache.getElementsByType(e)}async fetchElements(){await this.syncService.fetchElements()}async pullWorkspace(e={}){let t=!1;try{if(b.setVerboseMode(!!e.verbose),e.rps!==void 0&&K.init({maxRequestsPerSecond:e.rps}),await this.notifier.setState(D.PULLING),await this.syncService.fetchElements(),this.syncService.detectIncomingChanges(),this.syncService.needsForcedSync()&&!e.force){await this.notifier.setState(D.CONFLICTS),e.watch||(t=!0);return}await this.syncService.pullConnectors(e.allConnectors),await this.syncWorkspaces(e)}catch(n){t=!0,b.error(`Failed to pull workspace: ${n}`),await this.notifier.setState(D.ERROR),b.saveLogsToFile("error")}finally{if(e.saveLogs&&b.saveLogsToFile(),t)process.exit(1);else return e?.onComplete?.()}}async pushWorkspace(e={}){let t=!1;try{if(b.setVerboseMode(!!e.verbose),e.rps!==void 0&&K.init({maxRequestsPerSecond:e.rps}),await this.notifier.setState(D.PUSHING),await this.syncService.fetchElements(),this.syncService.detectOutgoingChanges(),this.syncService.needsForcedSync()&&!e.force){await this.notifier.setState(D.CONFLICTS),e.watch||(t=!0);return}await this.syncService.pushConnectors(),await this.syncWorkspaces(e)}catch(n){t=!0,b.error(`Failed to push workspace: ${n}`),await this.notifier.setState(D.ERROR),b.saveLogsToFile("error")}finally{if(e.saveLogs&&b.saveLogsToFile(),t)process.exit(1);else return e?.onComplete?.()}}async syncWorkspaces(e={}){try{e.verbose!==void 0&&b.setVerboseMode(!!e.verbose),await this.notifier.setState(D.RESOLVING),this.syncService.needsSync()&&await this.syncService.resolveChanges();const t=await this.syncService.getStats();this.notifier.setStats(t),await this.notifier.setState(D.SYNCED),e.watch&&(await this.notifier.setState(D.WATCHING),await this.syncService.startWatching())}catch(t){b.error(`Failed to sync local and remote workspaces: ${t}`),await this.notifier.setState(D.ERROR),b.saveLogsToFile("error")}}async init({force:e=!1}={}){if(!(this.initialized&&!e)){await this.notifier.setState(D.NOT_INITIALIZED);try{await this.loadConfig(),tt.isCacheDefined()?(await this.initServices(),this.initialized=!0,await this.notifier.setState(D.INITIALIZED)):(this.initialized=!1,await this.notifier.setState(D.SETTING_UP))}catch(t){b.error(`Failed to initialize services: ${t}`),await this.notifier.setState(D.ERROR),b.saveLogsToFile("error"),this.onShutdown()}}}async loadConfig(){this.currentConfig=tt.loadConfig(this.cwd),this.notifier.setConfig(this.currentConfig)}async updateConfig(e){const t={...this.currentConfig,...e};if(!(JSON.stringify(t)!==JSON.stringify(this.currentConfig)))return;await this.stopServices();const r=tt.updateConfig(t);this.currentConfig=r,await this.init({force:!0})}async shutdown(){!this.initialized||this.isShuttingDown||(this.isShuttingDown=!0,this.mode===hs.Agent&&(await this.notifier.cleanup(),await this.mcpStatusService.stop()),this.initialized=!1,this.onShutdown())}async initServices(){this.mode===hs.Agent&&(await this.notifier.connectToRemote(),await this.mcpStatusService.start()),this.syncService.clear()}async stopServices(){this.mode===hs.Agent&&(await this.notifier.cleanup(),await this.mcpStatusService.stop())}setupProcessCleanup(){["SIGINT","SIGTERM","uncaughtException","unhandledRejection"].forEach(t=>process.on(t,()=>this.shutdown())),process.on("beforeExit",t=>{t===0&&this.shutdown()})}}const Ta=Ys(null);function jd({children:s,membraneCLIService:e}){const{data:t}=Oi("/account"),[n,r]=J(D.NOT_INITIALIZED),[i,o]=J([]),[a,l]=J({}),[u,d]=J([]),[f,h]=J(null),y=t?.workspaces?.find(p=>p.workspaceKey===f?.workspaceKey)||null;return Ze(()=>{const p=c(({state:I})=>r(I),"handleStateChanged"),w=c(({stats:I})=>l(I),"handleStatsChanged"),T=c(({log:I})=>d(x=>[...x,I]),"handleLogAdded"),E=c(({conflicts:I})=>o(I),"handleConflictsUpdated"),$=c(({config:I})=>h(I),"handleConfigChanged");return e.notifier.on(Q.StateChanged,p),e.notifier.on(Q.StatsChanged,w),e.notifier.on(Q.LogAdded,T),e.notifier.on(Q.ConflictsChanged,E),e.notifier.on(Q.ConfigChanged,$),e.init(),()=>{e.notifier.off(Q.StateChanged,p),e.notifier.off(Q.StatsChanged,w),e.notifier.off(Q.LogAdded,T),e.notifier.off(Q.ConflictsChanged,E),e.notifier.off(Q.ConfigChanged,$)}},[]),m(Ta.Provider,{value:{state:n,stats:a,logs:u,currentWorkspace:y,conflicts:i,config:f,updateConfig:c(p=>e.updateConfig(p),"updateConfig"),resolveConflicts:c(p=>e.syncWorkspaces(p),"resolveConflicts"),pull:c(p=>e.pullWorkspace(p),"pull"),push:c(p=>e.pushWorkspace(p),"push"),exit:c(()=>e.shutdown(),"exit"),fetchElements:c(()=>e.fetchElements(),"fetchElements"),getSyncedElementsByType:c(p=>e.getSyncedElementsByType(p),"getSyncedElementsByType")},children:s})}c(jd,"MembraneCLIServiceProvider");function ge(){const s=Xs(Ta);if(!s)throw new Error("useMembraneCLIService must be used within MembraneCLIServiceProvider");return s}c(ge,"useMembraneCLIService");const Vr=Ys(null),Ea=c(()=>{const s=Xs(Vr);if(!s)throw new Error("useTree must be used within TreeView");return s},"useTree"),Fd=c(s=>$e.Children.count(s)>0,"hasChildren");function qd(s){const e=Ea(),{label:t,value:n,isInitiallyExpanded:r}=s,i=il(),o=Zs(e.registerChildItem(t)).current,a=e.isActiveByRef(o),[l,u]=J(r??!1),d={props:s,ref:o,id:i,active:a,expanded:l,setExpanded:u,label:t,value:n,isInitiallyExpanded:r,isParent:!1},{children:f}=s,h=typeof f=="function"?f(d):f;return{...d,props:{...s,children:h},isParent:Fd(h)}}c(qd,"useTreeItem");function Rt(s){const e=Ea(),t=qd(s),{expanded:n,isParent:r,props:{children:i},setExpanded:o}=t,{renderValue:a=Kd}=s,l=t.ref;_n(()=>{function h(g){return s.onInput?.(g)?!0:g.active&&g.key.rightArrow&&!n?(o(!0),!0):g.active&&g.key.leftArrow&&n?(o(!1),!0):!1}c(h,"onInput"),l.onInput=h},[l,s.onInput,n,o]),l.firstChild??={parent:l,index:0};let u=l.firstChild;function d(h){const g=u;return g.nextSibling||(g.nextSibling={parent:l,prevSibling:g,index:g.index+1}),u=g.nextSibling,g.label=h,g}c(d,"registerChildItem");function f(){l.lastRenderedChild=u.prevSibling}return c(f,"commitChildren"),_n(()=>{f()}),_(Jt,{children:[_(C,{marginLeft:e.depth*2,children:[m(C,{width:2,children:r&&m(v,{children:n?"\u25BC":"\u25B6"})}),Bd(t),a(t)]}),n&&m(Vr.Provider,{value:{...e,depth:e.depth+1,registerChildItem:d},children:i})]})}c(Rt,"TreeItem");function Bd({active:s,label:e}){return m(C,{width:32,children:m(v,{inverse:s,children:e})})}c(Bd,"defaultRenderLabel");function Kd(s){return m(v,{})}c(Kd,"defaultRenderValue");const ct=c(({label:s,onPress:e,hotkey:t})=>m(Rt,{label:s,onInput:c(({input:n,key:r,active:i})=>i&&r.return||t&&t in r&&r[t]||n===t?(e(),!0):!1,"onInput"),renderValue:c(()=>m(C,{children:m(v,{children:`${t?` (${t})`:""}`})}),"renderValue")}),"ActionTreeItem"),_a=c(({label:s,value:e,onChange:t,disabled:n=!1,mask:r,...i})=>{const[o,a]=J(e),[l,u]=J(!1);return _n(()=>{l||a(e)},[l,e]),m(Rt,{label:s,value:e,onInput:c(({key:d,active:f})=>n?!1:l?(d.escape&&u(!1),d.return&&(t(o),u(!1)),!0):f&&d.return?(u(!0),a(e),!0):!1,"onInput"),renderValue:c(()=>{const d=o,f=r?r.repeat(d.length):d;return m(C,{children:n||!l?m(v,{dimColor:!0,children:f}):_(Jt,{children:[m(C,{width:f.length+1,children:m(Pi,{...i,focus:l,value:d,onChange:a})}),m(v,{dimColor:!0,children:" \u241B cancel"})]})})},"renderValue")})},"TreeTextField"),Ud=c(s=>m(_a,{...s,mask:"*"}),"SecretField"),ye=c(({children:s,showHelp:e=!1})=>{const t=Zs({parent:void 0,label:"<<ROOT>>",index:0}),[n,r]=J(t.current),i={depth:0,isActiveByRef:c(a=>n===a,"isActiveByRef"),registerChildItem:c(()=>t.current,"registerChildItem"),activeItemRef:n};_n(()=>{r(a=>a.parent?a.parent.lastRenderedChild&&a.index>a.parent.lastRenderedChild.index?a.parent.lastRenderedChild:a:t.current.firstChild??t.current)});function*o(a){a&&(yield a,yield*o(a.firstChild),a.nextSibling&&a!==a.parent?.lastRenderedChild&&(yield*o(a.nextSibling)))}return c(o,"walkTree"),Qe((a,l)=>{if(n.onInput?.({input:a,key:l,active:!0}))return;let u,d;for(const f of o(t.current))if(f.label!=null){if(u===n&&(d=f),f&&f.onInput?.({input:a,key:l,active:f===n}))return;u=f}l.upArrow?r(f=>f.prevSibling?.lastRenderedChild??f.prevSibling??f.parent??t.current):l.downArrow?r(f=>d??f):l.pageUp?r(()=>t.current.firstChild??t.current):l.pageDown?r(()=>t.current.lastRenderedChild??t.current):l.tab?console.log({label:n.label,nextSibling:n.nextSibling?.label,prevSibling:n.prevSibling?.label,parent:n.parent?.label,firstChild:n.firstChild?.label,lastRenderedChild:n.lastRenderedChild?.label}):l.leftArrow?r(f=>f.parent??t.current):l.rightArrow&&r(f=>f.lastRenderedChild?f.firstChild:f)}),m(Vr.Provider,{value:i,children:_(C,{flexDirection:"column",children:[m(Rt,{isInitiallyExpanded:!0,label:"rootItem",children:s}),e&&m(C,{marginTop:1,flexDirection:"column",children:m(v,{dimColor:!0,children:"\u2191/\u2193 move \u2022 \u2190 collapse \u2022 \u2192 expand \u2022 Enter/Space select/edit \u2022 Esc exit"})})]})})},"TreeView");ye.Item=Rt,ye.TextField=_a;function lt({label:s,elementType:e,isActionExcluded:t,toggleAction:n,generateCode:r}){const[i,o]=J([]),{fetchElements:a,getSyncedElementsByType:l}=ge();return Ze(()=>{c(async()=>{try{await a();const d=l(e);o(d.map(f=>f.data))}catch(d){console.error(String(d))}},"loadElements")()},[e,a,l,o]),m(Rt,{label:s,children:i.map(u=>m(Rt,{label:u.name,children:e===N.Action&&_(Jt,{children:[t&&n&&m(ct,{label:`Toggle ${t(u)?"":"(excluded)"}`,onPress:c(()=>{n(u)},"onPress")}),r&&m(ct,{label:"Generate code",onPress:c(()=>{r?.(u)},"onPress")})]})},u.id))})}c(lt,"WorkspaceElementsTreeItem");function Wd({onComplete:s}){const{config:e,updateConfig:t,fetchElements:n,getSyncedElementsByType:r}=ge(),[i,o]=J(""),a=e,l=c(h=>{o(h),setTimeout(()=>o(""),2e3)},"setFlash"),u=c(async(h,g)=>{try{await t({[h]:g}),l("\u2705 Configuration updated!")}catch{l("\u274C Error updating configuration")}},"updateField"),d=c(async()=>{try{if(e){const h=tt.saveToFile(e);l(h?"\u2705 Configuration saved successfully!":"\u274C Failed to save configuration"),await n();const g=r(N.Action);await rr({out:a?.outputDir??"",target:a?.projectType??"typescript",schemasOnly:!1,membraneInterfaces:{actions:g.filter(y=>!a?.excludedActionKeys?.includes(y.key)).map(y=>y.data)}}),l("\u2705 Code generated successfully!")}}catch{l("\u274C Error saving configuration")}},"handleSaveConfig"),f=c(async()=>{try{const h=tt.loadConfig();h?(await t(h),l("\u2705 Configuration reloaded successfully!")):l("\u274C No configuration found to reload")}catch{l("\u274C Error reloading configuration")}},"handleReloadConfig");return _(C,{flexDirection:"column",gap:1,children:[m(v,{bold:!0,color:"cyan",children:"\u2699\uFE0F Membrane Configuration Manager"}),m(C,{paddingX:2,children:_(ye,{showHelp:!0,children:[_(ye.Item,{label:"Configuration",isInitiallyExpanded:!0,children:[_(ye.Item,{label:"Project",children:[m(ye.TextField,{label:"Workspace Key",value:a?.workspaceKey??"",onChange:c(h=>u("workspaceKey",h),"onChange"),disabled:!0}),m(Ud,{label:"Workspace Secret",value:a?.workspaceSecret??"",onChange:c(h=>u("workspaceSecret",h),"onChange"),disabled:!0}),m(ye.TextField,{label:"API URI",value:a?.apiUri??"",onChange:c(h=>u("apiUri",h),"onChange")}),m(ye.TextField,{label:"Test Customer ID",value:a?.testCustomerId??"",onChange:c(h=>u("testCustomerId",h),"onChange")})]}),_(ye.Item,{label:"Code Generation",isInitiallyExpanded:!0,children:[_(ye.Item,{label:"Project Type",isInitiallyExpanded:!0,value:a?.projectType,renderValue:c(({value:h})=>m(v,{children:h==="typescript"?"TypeScript":h==="openapi"?"OpenAPI":"(Not set)"}),"renderValue"),children:[m(ct,{label:"Update to TypeScript",onPress:c(()=>u("projectType","typescript"),"onPress")}),m(ct,{label:"Update to OpenAPI",onPress:c(()=>u("projectType","openapi"),"onPress")})]}),m(ye.TextField,{label:"Project dir",value:a?.outputDir??"",onChange:c(h=>u("outputDir",h),"onChange")})]}),_(ye.Item,{label:"Workspace Elements",children:[m(lt,{label:"Actions",elementType:N.Action,isActionExcluded:c(h=>a?.excludedActionKeys?.includes(h.key)??!1,"isActionExcluded"),toggleAction:c(h=>u("excludedActionKeys",[...a?.excludedActionKeys??[],h.key]),"toggleAction"),generateCode:c(h=>{(async()=>{try{await rr({out:a?.outputDir??"",target:a?.projectType??"typescript",schemasOnly:!1,membraneInterfaces:{actions:[h]}}),l("\u2705 Code generated successfully!")}catch{l("\u274C Error generating code")}})()},"generateCode")}),m(lt,{label:"Flows",elementType:N.Flow}),m(lt,{label:"Data Sources",elementType:N.DataSource}),m(lt,{label:"Field Mappings",elementType:N.FieldMapping}),m(lt,{label:"Packages",elementType:N.Package}),m(lt,{label:"App Data Schemas",elementType:N.AppDataSchema}),m(lt,{label:"App Event Types",elementType:N.AppEventType})]})]}),m(ct,{label:"Save Configuration",onPress:d,hotkey:"s"}),m(ct,{label:"Reload Configuration",onPress:f,hotkey:"r"}),m(ct,{label:"Exit",onPress:c(()=>s?.(),"onPress"),hotkey:"escape"})]})}),i&&m(C,{paddingX:2,children:m(v,{color:i.includes("\u2705")?"green":"red",children:i})})]})}c(Wd,"ConfigManager");const Ia=Ys(process.cwd());function Jd({cwd:s,children:e}){return m(Ia.Provider,{value:s,children:e})}c(Jd,"CwdProvider");function Hd(){return Xs(Ia)}c(Hd,"useCwd");function ps({cwd:s,children:e,membraneCLIService:t}){const n=s||process.cwd();return m(Jd,{cwd:n,children:m(wl,{value:{fetcher:jl()},children:m(jd,{membraneCLIService:t,children:e})})})}c(ps,"Layout");function Vd(s,e){s.command("config").alias("install").description("\u26A0\uFE0F EXPERIMENTAL: Manage local membrane configuration with interactive UI").addHelpText("after",["","Examples:"," membrane config # Open interactive config manager",""].join(`
145
+ `)).action(()=>{In($e.createElement(ps,{membraneCLIService:e,children:$e.createElement(Wd,{onComplete:c(()=>process.exit(0),"onComplete")})}))})}c(Vd,"setupConfigCommand");function Gd({currentPat:s,onSubmit:e}){const[t,n]=J(""),[r,i]=J(!1),[o,a]=J(null);return _(C,{flexDirection:"column",borderStyle:"round",borderTop:!0,width:70,paddingX:1,children:[m(C,{marginTop:-1,marginBottom:1,children:m(v,{bold:!0,children:"\u{1F511} Enter your Personal Access Token"})}),m(v,{children:"Please provide your Personal Access Token. You can find it here:"}),m(C,{marginTop:1,marginBottom:1,children:m(v,{color:"yellow",children:"https://console.integration.app/w/0/manage-account/api-token"})}),s&&m(v,{dimColor:!0,children:"Press Enter to keep your current token or type a new one."}),m(Pi,{mask:"*",placeholder:`${s?"******":"Enter your token here..."}`,value:t,onChange:n,onSubmit:c(async u=>{a(null),i(!0);try{await e(u),n("")}catch{a("Invalid token. Please try again.")}finally{i(!1)}},"handleSubmit")}),r&&m(C,{marginTop:1,children:_(v,{children:[m(An,{type:"dots"})," Validating token..."]})}),o&&m(v,{color:"red",children:o})]})}c(Gd,"PersonalAccessTokenInput");function Aa({onExit:s,showEscOption:e=!0}){const[t,n]=J(""),{data:r,error:i,isLoading:o}=Oi("/account"),{updateConfig:a}=ge(),l=r?.workspaces,u=o;if(Qe((p,w)=>{w.escape&&s?.()}),u)return _(C,{children:[m(An,{}),m(v,{children:" Fetching workspaces..."})]});if(i)return _(C,{flexDirection:"column",children:[_(v,{color:"red",children:["Error: ",i.message]}),m(C,{marginTop:1,children:m(v,{color:"grey",children:"Press ESC to go back"})})]});const d=l?.filter(p=>p.name.toLowerCase().includes(t.toLowerCase()))??[],f=d.map(p=>({label:p.name,value:p.id})),h=f.length,g=l?.length??0;async function y(p){const w=d.find($=>$.id===p);if(!w)return;const{key:T,secret:E}=w;!T||!E||(await a({workspaceKey:T,workspaceSecret:E}),s?.())}return c(y,"handleSelect"),_(C,{flexDirection:"column",borderStyle:"round",borderTop:!0,width:70,paddingX:1,children:[m(C,{marginTop:-1,children:m(v,{bold:!0,children:"\u{1F4C1} Select your workspace"})}),_(C,{marginTop:1,children:[m(v,{children:"Search: "}),m(bl,{placeholder:"Enter a search query...",onChange:n})]}),g>5&&_(v,{children:["Showing ",h," of ",g," workspaces."]}),m(C,{marginTop:1,children:m(Sl,{options:f,onChange:c(p=>{p&&y(p)},"onChange")})}),e&&m(C,{marginTop:1,children:m(v,{color:"grey",children:"Press ESC to go back"})})]})}c(Aa,"SelectWorkspace");var rn=(s=>(s[s.Authenticate=0]="Authenticate",s[s.ConnectWorkspace=1]="ConnectWorkspace",s))(rn||{});const zd={0:"Authenticate in Membrane",1:"Connect a Membrane Workspace"},Gr=[rn.Authenticate,rn.ConnectWorkspace];function Oa({onComplete:s}){const{config:e}=ge(),[t,n]=J(!1),[r,i]=J(0),o=!!(e?.workspaceKey&&e?.workspaceSecret),a=Di(),l=Gr[r],u=r+1,d=Gr.length,f=Gr.map((y,p)=>{let w="pending";return p<r?w="done":p===r&&(w="current"),{id:y,label:zd[y],status:w}});async function h(y){const p=a&&y===""?a:y,w=new ji;try{await w.request("/account",{headers:{Authorization:`Bearer ${p}`}}),Dl(p),i(T=>T+1)}catch(T){console.error(T)}}c(h,"handlePatSubmit");function g(){n(!0),s&&s()}return c(g,"handleWorkspaceSelected"),Qe((y,p)=>{o&&p.escape&&s&&s()}),t?m(C,{children:m(v,{children:"\u2705 Setup complete. You are ready to go!"})}):_(C,{flexDirection:"column",alignSelf:"flex-start",gap:1,children:[_(C,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:70,children:[m(C,{marginTop:-1,marginBottom:1,children:_(v,{bold:!0,children:["\u{1F6E0}\uFE0F Setup \u2014"," ",_(v,{color:"cyan",children:["Step ",u," of ",d]}),o&&m(v,{color:"grey",children:" [esc: go back]"})]})}),m(C,{flexDirection:"column",paddingLeft:2,children:f.map(y=>m(Yd,{status:y.status,label:y.label},y.id))})]}),l===rn.Authenticate&&m(Gd,{currentPat:a,onSubmit:h}),l===rn.ConnectWorkspace&&m(Aa,{onExit:g,showEscOption:!1})]})}c(Oa,"Setup");function Yd({status:s,label:e}){return _(C,{children:[_(C,{width:2,children:[s==="current"&&m(An,{type:"dots"}),s==="done"&&m(v,{children:"\u2705"})]}),m(v,{dimColor:s!=="current",children:e})]})}c(Yd,"StepDisplay");function Xd(s,e){s.command("init").description("Run interactive setup for Membrane project").option("--key <key>","Workspace key for non-interactive setup").option("--secret <secret>","Workspace secret for non-interactive setup").addHelpText("after",["","Examples:"," membrane init # Run interactive setup"," membrane init --key KEY --secret SEC # Non-interactive setup with key and secret",""].join(`
146
+ `)).action(t=>{t.key&&t.secret?tt.saveToFile({workspaceKey:t.key,workspaceSecret:t.secret})?(console.error("\u2705 Configuration saved to membrane.config.yml"),process.exit(0)):(console.error("Error writing configuration file"),process.exit(1)):t.key||t.secret?(console.error("Error: Both --key and --secret must be provided for non-interactive mode"),process.exit(1)):In($e.createElement(ps,{membraneCLIService:e,children:$e.createElement(Oa,{onComplete:c(()=>process.exit(0),"onComplete")})}))})}c(Xd,"setupInitCommand");async function $a(s,e,t){const n={iss:s,exp:Math.floor(Date.now()/1e3)+600,isAdmin:!0};return t&&(n.id=t),Qs.sign(n,e)}c($a,"generateMcpAccessToken");async function Zd(s,e){return(await Ht.get(`${s}/docs-json`,{headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}})).data}c(Zd,"fetchOpenApiSchema");function Ge(s,e=!0,t,n=new Set){if(!s)return e?W.string():W.string().optional();if(Object.keys(s).length===0)return e?W.any():W.any().optional();if(s.$ref){const i=s.$ref.replace("#/components/schemas/","");if(n.has(i))return W.any();if(n.add(i),t?.schemas?.[i]){const o=t.schemas[i];return Ge(o,e,t,n)}return W.any()}let r;if(s.type==="object"||s.properties){const i={};if(s.properties)for(const[o,a]of Object.entries(s.properties)){const l=s.required?.includes(o)??!1;i[o]=Ge(a,l,t,n)}if(Object.keys(i).length>0){if(r=W.object(i),s.additionalProperties)if(typeof s.additionalProperties=="object"){const o=Ge(s.additionalProperties,!1,t,n);r=r.catchall(o)}else s.additionalProperties===!0&&(r=r.passthrough())}else if(s.additionalProperties&&typeof s.additionalProperties=="object"){const o=Ge(s.additionalProperties,!1,t,n);r=W.record(W.string(),o)}else r=W.record(W.string(),W.any())}else if(s.type==="array"){const i=s.items?Ge(s.items,!0,t,n):W.any();r=W.array(i)}else if(s.anyOf)r=W.any();else{switch(s.type){case"integer":r=W.coerce.number().int();break;case"number":r=W.coerce.number();break;case"boolean":r=W.coerce.boolean();break;case"string":default:r=W.string();break}s.format==="uuid"?r=W.string().uuid():s.format==="email"?r=W.string().email():s.format==="date"?r=W.string().regex(/^\d{4}-\d{2}-\d{2}$/):s.format==="date-time"&&(r=W.string().datetime()),s.enum&&(r=W.enum(s.enum)),(s.type==="integer"||s.type==="number")&&(s.minimum!==void 0&&(r=r.min(s.minimum)),s.maximum!==void 0&&(r=r.max(s.maximum))),s.type==="string"&&(s.minLength!==void 0&&(r=r.min(s.minLength)),s.maxLength!==void 0&&(r=r.max(s.maxLength)))}return e?r:r.optional()}c(Ge,"convertOpenApiSchemaToZod");function Na(s){const e=s.match(/\{([^}]+)\}/g);return e?e.map(t=>t.slice(1,-1)):[]}c(Na,"extractPathParameters");function Qd(s,e,t,n,r,i,o,a){const l=s.operationId||`${t}_${e.replace(/[^a-zA-Z0-9]/g,"_")}`,u=s.description||s.summary||`${t.toUpperCase()} ${e}`,d={},f={},h={};if(s.parameters){for(const y of s.parameters)if(y.in==="path")f[y.name]=Ge(y.schema,!0,o).describe(y.description||`Path parameter: ${y.name}`);else if(y.in==="query"){const p=y.required===!0;h[y.name]=Ge(y.schema,p,o).describe(y.description||`Query parameter: ${y.name}`)}}if(Object.keys(f).length>0&&(d.params=W.object(f).describe("Path parameters")),Object.keys(h).length>0&&(d.query=W.object(h).describe("Query parameters")),s.requestBody&&s.requestBody.content){const y=s.requestBody.required===!0;if(s.requestBody.content["application/json"]){const p=s.requestBody.content["application/json"].schema;p?d.body=Ge(p,y,o).describe("Request body (JSON)"):d.body=W.any().describe("Request body (JSON)")}else s.requestBody.content["application/octet-stream"]||s.requestBody.content["text/plain"]?d.body=y?W.string().describe("Request body (binary/text)"):W.string().optional().describe("Request body (binary/text)"):d.body=W.any().describe("Request body")}const g=Object.keys(d).length>0?W.object(d):W.object({});return{name:l,description:u,parameters:g,async execute(y){try{const p=Na(e);if(p.length>0){if(!y.params)throw new Error(`Missing required path parameters: ${p.join(", ")}`);const M=p.filter(j=>!(j in y.params));if(M.length>0)throw new Error(`Missing required path parameters: ${M.join(", ")}`)}let w=`${n}${e}`;if(y.params)for(const[M,j]of Object.entries(y.params)){const O=`{${M}}`;w.includes(O)&&(w=w.replace(O,String(j)))}const T=Na(w);if(T.length>0)throw new Error(`Unresolved path parameters: ${T.join(", ")}`);const E=new URLSearchParams;if(y.query)for(const[M,j]of Object.entries(y.query))j!=null&&E.append(M,String(j));E.toString()&&(w+=`?${E.toString()}`);const $=await $a(r,i,a),I={method:t.toUpperCase(),headers:{Authorization:`Bearer ${$}`}};y.body&&t.toLowerCase()!=="get"&&(s.requestBody?.content?.["application/json"]?(I.headers["Content-Type"]="application/json",I.data=y.body):s.requestBody?.content?.["application/octet-stream"]?(I.headers["Content-Type"]="application/octet-stream",I.data=y.body):s.requestBody?.content?.["text/plain"]?(I.headers["Content-Type"]="text/plain",I.data=y.body):(I.headers["Content-Type"]="application/json",I.data=y.body));const x=await Ht.request({url:w,...I});return{content:[{type:"text",text:x.data===""?"":JSON.stringify(x.data,null,2)}]}}catch(p){return Ht.isAxiosError(p)?{content:[{type:"text",text:`Error: ${p.response?.data?`HTTP ${p.response.status}: ${p.response.statusText} - ${JSON.stringify(p.response.data)}`:`HTTP ${p.response?.status||"unknown"}: ${p.message}`}`}],isError:!0}:p instanceof Error?{content:[{type:"text",text:`Error: API call failed: ${p.message}`}],isError:!0}:{content:[{type:"text",text:"Error: API call failed with unknown error"}],isError:!0}}}}}c(Qd,"createApiTool");function ef(s,e,t,n,r){const i=[];if(!s.paths)return i;const o=s.components||{};for(const[a,l]of Object.entries(s.paths))if(typeof l=="object"&&l!==null){for(const[u,d]of Object.entries(l))if(["get","post","put","delete","patch"].includes(u)&&d&&typeof d=="object"){const f=Qd(d,a,u,e,t,n,o,r);i.push(f)}}return i}c(ef,"convertOpenApiToTools");function tf(s){s.command("mcp").description("Launch MCP server with OpenAPI endpoints as tools (API URI is read from environment variables or membrane.config.yml)").addHelpText("after",["","Examples:"," membrane mcp # Launch MCP server using API URI from env vars or membrane.config.yml",""].join(`
147
+ `)).action(async()=>{try{process.env.FASTMCP_SUPPRESS_WARNINGS="true";const e=$n();e||(console.error("No configuration found. Please set MEMBRANE_WORKSPACE_KEY and MEMBRANE_WORKSPACE_SECRET environment variables, or run `membrane init` first."),process.exit(1)),(!e.workspaceKey||!e.workspaceSecret)&&(console.error("Missing workspace credentials. Please provide them in the configuration file, command line, or environment variables."),process.exit(1));const t=e.apiUri||or,n=await $a(e.workspaceKey,e.workspaceSecret,e.testCustomerId),r=await Zd(t,n),i=ef(r,t,e.workspaceKey,e.workspaceSecret,e.testCustomerId),o=new vl({name:"Membrane API",instructions:`This MCP server lets you interact with Membrane to configure, run, and troubleshoot integrations.
148
148
  Use it for anything related to Membrane or integrations.
149
- `,version:"1.0.0"});for(const u of i){const d=u.execute;u.execute=async f=>(Rd(process.pid,process.cwd()),d(f)),o.addTool(u)}Wr({isRunning:!0,startTime:new Date().toISOString(),toolsCount:i.length,lastActivity:new Date().toISOString(),processId:process.pid,cwd:process.cwd(),agentName:process.env.AGENT_NAME||"Unnamed Agent"});const a=setInterval(()=>{Wr({processId:process.pid,cwd:process.cwd(),lastActivity:new Date().toISOString()})},5e3),l=c(async()=>{clearInterval(a),sn(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",()=>{sn(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(ef,"setupMcpCommand");const tf={info:"\u{1F4DD}",success:"\u2728",warning:"\u26A0\uFE0F",error:"\u274C",debug:"\u{1F50D}"},nf={info:k.white,success:k.green,warning:k.yellow,error:k.red,debug:k.gray};class H{static{c(this,"Logger")}static formatMessage(e,t,n={icon:!1}){const r=n.timestamp?`${k.gray(new Date().toISOString())} `:"",i=n.prefix?`${k.gray(n.prefix)} `:"",o=n.suffix?` ${k.gray(n.suffix)}`:"",a=tf[t],l=nf[t];return`${r}${n.icon?a:""} ${i}${l(e)}${o}`}static info(e,t){let n=k.white;if(t?.color&&(n=k[t.color.toLowerCase()]||k.white),t?.timestamp){const r=new Date().toLocaleTimeString();console.debug(`${k.gray(`[${r}]`)} ${n(e)}`)}else console.debug(n(e))}static group(e,t){}static groupEnd(){}static newLine(){}static success(e,t){console.debug(this.formatMessage(e,"success",t))}static warning(e,t){console.debug(this.formatMessage(e,"warning",t))}static error(e,t){console.error(this.formatMessage(e,"error",t))}static debug(e,t){t?.prefix?console.debug(k.gray(`[${t.prefix}] ${e}`),t.error?`
149
+ `,version:"1.0.0"});for(const u of i){const d=u.execute;u.execute=async f=>(Ld(process.pid,process.cwd()),d(f)),o.addTool(u)}Wr({isRunning:!0,startTime:new Date().toISOString(),toolsCount:i.length,lastActivity:new Date().toISOString(),processId:process.pid,cwd:process.cwd(),agentName:process.env.AGENT_NAME||"Unnamed Agent"});const a=setInterval(()=>{Wr({processId:process.pid,cwd:process.cwd(),lastActivity:new Date().toISOString()})},5e3),l=c(async()=>{clearInterval(a),sn(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",()=>{sn(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(tf,"setupMcpCommand");const nf={info:"\u{1F4DD}",success:"\u2728",warning:"\u26A0\uFE0F",error:"\u274C",debug:"\u{1F50D}"},sf={info:k.white,success:k.green,warning:k.yellow,error:k.red,debug:k.gray};class H{static{c(this,"Logger")}static formatMessage(e,t,n={icon:!1}){const r=n.timestamp?`${k.gray(new Date().toISOString())} `:"",i=n.prefix?`${k.gray(n.prefix)} `:"",o=n.suffix?` ${k.gray(n.suffix)}`:"",a=nf[t],l=sf[t];return`${r}${n.icon?a:""} ${i}${l(e)}${o}`}static info(e,t){let n=k.white;if(t?.color&&(n=k[t.color.toLowerCase()]||k.white),t?.timestamp){const r=new Date().toLocaleTimeString();console.debug(`${k.gray(`[${r}]`)} ${n(e)}`)}else console.debug(n(e))}static group(e,t){}static groupEnd(){}static newLine(){}static success(e,t){console.debug(this.formatMessage(e,"success",t))}static warning(e,t){console.debug(this.formatMessage(e,"warning",t))}static error(e,t){console.error(this.formatMessage(e,"error",t))}static debug(e,t){t?.prefix?console.debug(k.gray(`[${t.prefix}] ${e}`),t.error?`
150
150
  ${k.red(t.error)}`:""):console.debug(k.gray(e),t?.error?`
151
- ${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]),r=e.map(i=>{const o={};return n.forEach(a=>{o[a]=i[a]}),o});console.table(r,n)}static divider(){}}function sf(s){s.command("open").description("Open the workspace in the browser").addHelpText("after",["","Examples:"," membrane open # Open workspace in browser",""].join(`
152
- `)).action(async()=>{try{H.header("Opening Workspace in Browser"),H.info("Loading configuration...");const e=$n();if(!e)throw new Error("No configuration found. Please set MEMBRANE_WORKSPACE_KEY and MEMBRANE_WORKSPACE_SECRET environment variables, or run `membrane init` first.");if(!e.workspaceKey||!e.workspaceSecret)throw new Error("Missing workspace credentials");H.info("Retrieving workspace ID...");const n=`https://console.integration.app/w/${await Bi(process.cwd())}`;H.info(`Opening ${n}...`);const{default:r}=await import("open");await r(n),H.success("Browser opened successfully")}catch(e){e instanceof Error&&(H.error(e.message),process.exit(1)),H.error("An unknown error occurred"),process.exit(1)}})}c(sf,"setupOpenCommand");async function Na(s,e,t={}){const{jobId:n,accessKey:r}=await e(),i=`${n}:${r}`;b.debug(`[background-job] Started job ${n}`);const o=Date.now(),{pollIntervalMs:a=1e3,timeoutMs:l=3e5}=t;for(;;){if(Date.now()-o>l)throw new Error(`Background job ${n} timed out after ${l}ms`);await new Promise(f=>setTimeout(f,a));const d=await s.get(`background-jobs/${i}`);if(d.status==="completed"){if(b.debug(`[background-job] Completed job ${n}`),!d.result)throw new Error(`Background job ${n} completed but returned no result`);return d.result}if(d.status==="failed"){const f=d.failedReason||"Unknown error";throw b.error(`[background-job] Failed job ${n}: ${f}`),d.stacktrace&&b.error(`Stacktrace: ${d.stacktrace.join(`
153
- `)}`),new Error(`Background job ${n} failed: ${f}`)}b.debug(`[background-job] Polling job ${n} (status: ${d.status})`)}}c(Na,"pollBackgroundJob");function rf(s,e){zr(P.dirname(s)),A.writeFileSync(s,e)}c(rf,"writeFile");function of(s){A.existsSync(s)&&A.rmSync(s)}c(of,"deleteFile");function xa(s){A.existsSync(s)&&A.rmSync(s,{recursive:!0,force:!0})}c(xa,"deleteDir");function af(s,e=!0){if(A.existsSync(s))try{const t=A.readFileSync(s,"utf8");return Se.load(t)||void 0}catch(t){if(!e)return;if(t instanceof Error){const n=P.relative(process.cwd(),s);throw new Error(`Failed to parse YAML file "${n}": ${t.message}`)}throw t}}c(af,"readYaml");function Pa(s,e,t){try{zr(P.dirname(s));const n=Se.dump(e,t);A.writeFileSync(s,n,"utf8")}catch(n){if(n instanceof Error){const r=P.relative(process.cwd(),s);throw new Error(`Failed to write YAML file "${r}": ${n.message}`)}throw n}return e}c(Pa,"writeYaml");function zr(s){A.existsSync(s)||A.mkdirSync(s,{recursive:!0})}c(zr,"ensureDirExists");function Ma(s,e=!0){if(!A.existsSync(s)||!A.statSync(s).isDirectory())return;let t=A.readdirSync(s);t.length>0&&(t.forEach(n=>Ma(P.join(s,n),!1)),t=A.readdirSync(s)),t.length===0&&!e&&A.rmdirSync(s)}c(Ma,"cleanupEmptyFolders");async function cf(s){return new Promise(async(e,t)=>{const n=$i("zip",{zlib:{level:9}}),r=[];n.on("data",o=>r.push(o)),n.on("end",()=>e(Buffer.concat(r))),n.on("error",o=>t(o));const i=new Map;for(const o of s[N.Integration]||[])i.set(o.uuid,o.key);for(const[o,a]of Object.entries(s))for(const l of a){const u=l.key,d=i.get(l.integrationUuid),f=Zc(o,u,d),h=Se.dump(l);n.append(h,{name:f})}n.finalize()})}c(cf,"createMembraneZip");async function Ra(s,e){const t=await Pi.loadAsync(s),n=[];for(const[r,i]of Object.entries(t.files)){if(i.dir)continue;const o=ft(r);if(!o)continue;const a=await i.async("string"),l=Se.load(a);if(!l)continue;const u=await e(r,l,o);u!==void 0&&n.push(u)}return n}c(Ra,"iterateZipItems");async function lf(s){const e=await Pi.loadAsync(s),t={};for(const[n,r]of Object.entries(e.files)){if(r.dir)continue;const i=ft(n);if(!i)continue;const o=await r.async("string"),a=Se.load(o);t[i.type]||(t[i.type]=[]),t[i.type].push(a)}return t}c(lf,"readMembraneZip");async function uf(s=process.cwd()){const e=await La(he(s)),t={};for(const{data:n,type:r}of e)t[r]||(t[r]=[]),t[r].push(n);return t}c(uf,"readMembraneDir");async function La(s){const e=Da(s),t=[];for(const n of e){if(n.isDirectory())continue;const r=ft(n.path);if(!r)continue;const i=await n.readContent(),o=Se.load(i),a=P.join(s,n.path);t.push({filePath:a,data:o,type:r.type})}return t}c(La,"iterateMembraneFiles");function Da(s,e){const t=[];if(e||(e=s),!A.existsSync(e)||e.startsWith(P.join(s,"connectors")))return t;const n=A.readdirSync(e,{withFileTypes:!0});for(const r of n){const i=P.join(e,r.name),o=P.relative(s,i);r.isDirectory()?t.push(...Da(s,i)):r.isFile()&&ft(o)&&t.push({path:o,isDirectory:c(()=>!1,"isDirectory"),readContent:c(async()=>A.readFileSync(i,"utf8"),"readContent")})}return t}c(Da,"getMembraneFiles");function df(){const s={},e=P.join(he(process.cwd()),"connectors");if(!A.existsSync(e))return s;const t=A.readdirSync(e);for(const n of t){const r=P.join(e,n);if(!A.statSync(r).isDirectory())continue;const i=P.join(r,`${n}.yml`),o=af(i,!1);if(!o?.uuid)continue;const a=new Set,l=A.readdirSync(r);for(const u of l){if(u.endsWith(".yml"))continue;const d=P.join(r,u);A.statSync(d).isDirectory()&&a.add(u=="development"?"":u)}s[o.uuid]={key:n,versions:Array.from(a)}}return s}c(df,"readConnectorsDir");function ms(s,e){const t=P.join(he(process.cwd()),"connectors",s);return e==""?P.join(t,"development"):e?P.join(t,e):t}c(ms,"getConnectorPath");const ja=300,Fa=6e4;async function ff(){const s=await K.withClient(async t=>Na(t,()=>t.get("export"),{pollIntervalMs:ja,timeoutMs:Fa}));if(!s)throw new Error("Failed to export workspace");const e=await Ht.get(s.downloadUrl,{responseType:"arraybuffer"});return Buffer.from(e.data)}c(ff,"downloadWorkspaceExport");async function hf(s,e){const t=await K.withClient(async r=>Na(r,()=>r.get(`connectors/${s}/export`,{version:e}),{pollIntervalMs:ja,timeoutMs:Fa}));if(!t)throw new Error("Failed to export connector version");const n=await Ht.get(t.downloadUrl,{responseType:"arraybuffer"});return Buffer.from(n.data)}c(hf,"exportConnector");function pf(s){s.command("pull").description("Pull workspace data from specified workspace").option("--force","Overwrite conflicts with remote data",!1).addHelpText("after",["","Examples:"," membrane pull # Pull from default workspace"," membrane pull --force # Overwrite conflicts with remote data",""].join(`
154
- `)).action(async e=>{try{const t=await mf(e);wf(t.workspaceExport,t.connectors)}catch(t){Sf(t),process.exit(1)}})}c(pf,"setupPullCommand");async function mf(s){const e=await uf(),t=await cf(e),n=await ff(),r=await lf(n),i=Qc(e,r);Array.from(i[ht.DELETE]).length>0&&!s.force&&(await bf(i,t),H.error("Use --force to delete local elements"),process.exit(1));const a=await La(he(process.cwd()));for(const{filePath:u,data:d}of a)i[ht.DELETE].has(d.uuid)&&of(u);return Ma(he(process.cwd())),await Ra(n,(u,d)=>{if(ft(u)&&(i[ht.CREATE].has(d.uuid)||i[ht.UPDATE].has(d.uuid))){const h=q.join(he(process.cwd()),u);Pa(h,d)}}),{connectors:await gf(r[N.Integration]),workspaceExport:r}}c(mf,"pullWorkspace");async function gf(s){const e=new Map;for(const r of s??[]){const{connectorUuid:i,connectorVersion:o}=r;i&&(e.has(i)||e.set(i,new Set),e.get(i).add(o??""))}const t=df(),n=new Map;for(const[r,{key:i,versions:o}]of Object.entries(t)){if(!e.has(r)){const u=ms(i);xa(u);continue}const a=e.get(r);for(const u of o)if(!a.has(u)){const d=ms(i,u);xa(d)}const l=new Set(o);for(const u of a)l.has(u)||(n.has(r)||n.set(r,new Set),n.get(r).add(u))}for(const[r,i]of e.entries())t[r]||n.set(r,i);return await Promise.all(Array.from(n.entries()).map(([r,i])=>yf(r,Array.from(i)))),Array.from(n.keys())}c(gf,"pullConnectors");async function yf(s,e){const t=await K.withClient(i=>i.get(`connectors/${s}`),!1);if(!t||!t.key)return;const n=ms(t.key),r=q.join(n,`${t.key}.yml`);Pa(r,t);for(const i of e){const o=await hf(s,i),a=ms(t.key,i);if(rf(q.join(a,"src.zip"),o),!i){const l=q.join(a,"src");zr(l),await(await Ni.Open.buffer(o)).extract({path:l})}}}c(yf,"pullConnector");function wf(s,e=[]){const t=Object.values(s).reduce((n,r)=>n+(r?.length??0),0)+e.length;H.info(`\u25CF Pulled workspace elements \xB7 ${t}`);for(const n of Object.keys(s)){const r=s[n];H.info(`\u2514\u2500\u2500 ${n}s \xB7 ${r?.length??0}`)}e.length>0&&H.info(`\u2514\u2500\u2500 connectors \xB7 ${e.length}`)}c(wf,"showStats");async function bf(s,e){const t=Array.from(s[ht.DELETE]).length;H.info(`\u2299 Pull: conflicts detected \xB7 ${t}`),await Ra(e,(n,r)=>{ft(n)&&s[ht.DELETE].has(r.uuid)&&H.info(`\u2514\u2500\u2500 ./membrane/${n} (deleted in remote)`)})}c(bf,"showConflicts");async function Sf(s){H.error("\u25A0 Error"),H.error(`\u2514\u2500\u2500 ${s.message}`),H.error(` ${s.stack}`)}c(Sf,"showError");const Yr=c(s=>{switch(s){case"error":return"red";case"success":return"green";case"warning":return"yellow";default:return}},"getLogColor");function qa(s,e){return e<3?s.slice(0,Math.max(0,e)):s.length<=e?s:`${s.slice(0,e-3)}...`}c(qa,"truncateText");function Ba({children:s}){const{state:e,logs:t}=ge();return!e||e===D.NOT_INITIALIZED?_(C,{gap:1,flexDirection:"row",children:[m(Sl,{type:"dots"}),m(v,{children:"Initializing..."})]}):e===D.SETTING_UP?m(C,{gap:1,flexDirection:"row",children:m(v,{children:"No workspace selected. Please run `membrane init` to select a workspace."})}):e===D.ERROR?m(C,{flexDirection:"column",children:t.slice().map((n,r)=>m(v,{color:Yr(n.type),children:n.message},n.timestamp+r))}):s}c(Ba,"EnsureInitialized");function Ka(){const{stats:s}=ge(),e=Object.entries(s).filter(([t,n])=>n>0);return e.length===0?null:_(C,{flexDirection:"column",children:[m(C,{children:m(C,{width:12,children:m(v,{color:"grey",children:"Elements:"})})}),m(C,{flexDirection:"column",marginLeft:1,children:e.map(([t,n])=>_(C,{children:[m(C,{width:20,children:_(v,{children:[t,":"]})}),m(v,{color:"green",children:n})]},t))})]})}c(Ka,"ElementStats");const gs=[{value:"sync",label:"Continue (overwrite/delete)",key:""},{value:"exit",label:"Cancel",key:""}];function Cf(){const{state:s,resolveConflicts:e,exit:t}=ge(),[n,r]=J(0),[i,o]=J(!1),[a,l]=J(!1);return Qe((u,d)=>{if(!i){if(d.ctrl&&u.toLowerCase()==="r"){l(!a);return}d.upArrow?r(f=>f>0?f-1:gs.length-1):d.downArrow?r(f=>f<gs.length-1?f+1:0):u.toLowerCase()==="y"?r(0):u.toLowerCase()==="n"?r(1):(d.return||u===" ")&&(o(!0),gs[n].value==="sync"?e({watch:!0}):t())}}),Ze(()=>{s!==D.CONFLICTS&&i&&o(!1)},[s,i]),_(C,{flexDirection:"column",paddingTop:1,children:[m(C,{children:m(C,{flexDirection:"row",gap:2,children:m(v,{bold:!0,color:"white",children:"Conflicts with remote"})})}),m(C,{children:m(v,{color:"grey",children:"The remote workspace has changes that aren't in your local workspace:"})}),m(C,{marginTop:1,marginLeft:2,children:m(Ua,{isExpanded:a})}),_(C,{marginTop:2,flexDirection:"row",gap:1,children:[m(v,{color:"white",bold:!0,children:"What would you like to do?"}),m(v,{color:"grey",children:"[up/down, enter]"})]}),m(C,{children:i?_(C,{flexDirection:"row",gap:1,children:[m(An,{type:"dots"}),m(v,{color:"blue",bold:!0,children:"Syncing with remote..."})]}):m(C,{flexDirection:"column",children:gs.map((u,d)=>m(C,{flexDirection:"column",children:_(C,{flexDirection:"row",gap:1,children:[m(v,{color:n===d?"cyan":"grey",children:n===d?"\u25B6":" "}),m(v,{color:n===d?"cyan":"grey",bold:n===d,children:u.label})]})},u.value))})})]})}c(Cf,"ResolveChangesUI");const vf={[Ne.UPDATE]:{incoming:{label:"Elements updated in remote",description:"(to be overwritten from remote)"},outgoing:{label:"Elements updated locally",description:"(to be pushed to remote)"}},[Ne.DELETE]:{incoming:{label:"Elements not existing in remote",description:"(to be deleted locally)"},outgoing:{label:"Elements deleted locally",description:"(to be deleted from remote)"}},[Ne.CREATE]:{incoming:{label:"Elements created in remote",description:"(to be created locally)"},outgoing:{label:"Elements created locally",description:"(to be created in remote)"}}};function Ua({isExpanded:s,showControls:e=!0}){const{conflicts:t}=ge(),n=5,r=il(()=>{const i={};return t.forEach(o=>{const a=`${o.type}-${o.direction}`;i[a]||(i[a]=[]),i[a].push(o)}),i},[t]);return m(C,{flexDirection:"column",children:Object.entries(r).map(([i,o])=>{if(o.length===0)return null;const[a,l]=i.split("-"),u=vf[a][l];return _(C,{flexDirection:"column",children:[_(C,{flexDirection:"row",gap:1,children:[_(v,{color:"yellow",children:[u.label," (",o.length,")"]}),m(v,{color:"white",children:u.description})]}),(s?o:o.slice(0,n)).map(d=>m(C,{marginLeft:2,children:_(v,{color:"grey",children:["\u2022 ",d.element.id," (",d.element.relativePath,")"]})},d.element.id)),!s&&o.length>n&&m(C,{marginLeft:2,children:_(v,{color:"cyan",children:["... and ",o.length-n," more",e?" (press Ctrl+R to show all)":""]})}),s&&o.length>n&&e&&m(C,{marginLeft:2,children:m(v,{color:"cyan",children:"(press Ctrl+R to collapse)"})})]},i)})})}c(Ua,"Conflicts");function kf(s){return m(Ba,{children:m(Tf,{options:s})})}c(kf,"Push");function Tf({options:s}){const{logs:e,state:t,conflicts:n,push:r}=ge();Ze(()=>{r(s)},[]);const i=t===D.CONFLICTS;return _(C,{flexDirection:"column",children:[e.slice().map((o,a)=>m(v,{color:Yr(o.type),children:o.message},o.timestamp+a)),i&&_(Jt,{children:[_(v,{color:"yellow",bold:!0,children:["Found ",n.length," conflicts with remote:"]}),m(Ua,{isExpanded:!s.watch,showControls:!1}),m(v,{color:"red",children:"Out of sync with remote, use --force to overwrite conflict changes"})]}),t===D.SYNCED&&m(Ka,{})]})}c(Tf,"PushActivity");function Ef(){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(Ef,"getWatchModeCallback");function _f(s,e){s.command("push").description("Push workspace data to specified workspace").option("--force","Overwrite conflicts with local data",!1).option("--watch","Watch for changes and push automatically",!1).option("--save-logs","Save logs to a file",!1).option("--verbose","Show verbose debug logs",!1).option("--rps <number>","Maximum requests per second (default: 80)",t=>parseInt(t,10)).addHelpText("after",["","Examples:"," membrane push # Push to default workspace"," membrane push --force # Overwrite conflicts with local data"," membrane push --rps 5 # Limit to 5 requests per second",""].join(`
155
- `)).action(async t=>{const n=t.watch?Ef():()=>process.exit(0);In($e.createElement(ps,{membraneCLIService:e,children:$e.createElement(kf,{...t,onComplete:n})}))})}c(_f,"setupPushCommand");const Xr=[{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=P.join(process.cwd(),".mcp.json"),e={mcpServers:{membrane:{command:"membrane",args:["mcp"],env:{AGENT_NAME:"Claude Code"}}}};let t={};if(A.existsSync(s))try{t=JSON.parse(A.readFileSync(s,"utf8"))}catch{t={}}const n={...t,mcpServers:{...t.mcpServers,...e.mcpServers}};return A.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=P.join(process.cwd(),".cursor"),e=P.join(s,"mcp.json");A.existsSync(s)||A.mkdirSync(s);const t={mcpServers:{membrane:{command:"membrane",args:["mcp"],env:{AGENT_NAME:"Cursor"}}}};let n={};if(A.existsSync(e))try{n=JSON.parse(A.readFileSync(e,"utf8"))}catch{n={}}const r={...n,mcpServers:{...n.mcpServers,...t.mcpServers}};return A.writeFileSync(e,JSON.stringify(r,null,2)),`MCP server configuration added to ${e}`},"addConfig")}];function If({onExit:s,onComplete:e}){const[t,n]=J(0),[r,i]=J(!1),[o,a]=J(null),[l,u]=J(""),[d,f]=J("");Qe((y,p)=>{if(l||d){(p.escape||y==="q"||p.return)&&e();return}if(r)p.return||y===" "?h(o):p.escape&&(i(!1),a(null));else if(p.escape)s();else if(p.upArrow||y==="k")n(Math.max(0,t-1));else if(p.downArrow||y==="j")n(Math.min(Xr.length-1,t+1));else if(p.return||y===" "){const w=Xr[t];a(w),i(!0)}});const h=c(y=>{try{const p=y.addConfig();u(p)}catch(p){f(`Failed to write configuration: ${p.message||p}`)}},"addMcpConfiguration"),g=Math.min(80,process.stdout.columns||80);return l?_(C,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:g,children:[m(C,{marginTop:-1,marginBottom:1,children:_(v,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",m(v,{color:"green",children:"Success"})]})}),_(C,{flexDirection:"column",paddingLeft:2,children:[m(v,{color:"green",children:l}),m(C,{marginTop:1,children:m(v,{color:"grey",children:"The agent will now be able to use Membrane's integration capabilities."})})]}),m(C,{marginTop:1,paddingLeft:2,children:m(v,{color:"white",children:"[esc/q/enter: exit]"})})]}):d?_(C,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:g,children:[m(C,{marginTop:-1,marginBottom:1,children:_(v,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",m(v,{color:"red",children:"Error"})]})}),m(C,{flexDirection:"column",paddingLeft:2,children:m(v,{color:"red",children:d})}),m(C,{marginTop:1,children:m(v,{color:"grey",children:"[esc/q/enter: exit]"})})]}):r&&o?_(C,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:g,children:[m(C,{marginTop:-1,marginBottom:1,children:_(v,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",m(v,{color:"cyan",children:"Confirmation"})]})}),_(C,{flexDirection:"column",paddingLeft:2,children:[_(v,{children:["Connect ",m(v,{bold:!0,children:o.name})," to Membrane via MCP?"]}),m(C,{marginTop:1,children:m(v,{color:"grey",children:"This will add an MCP server configuration that allows the agent to use Membrane's integration capabilities."})}),m(C,{marginTop:1,children:m(v,{color:"yellow",bold:!0,children:o.actionDescription})}),m(C,{marginTop:2,marginBottom:1,children:_(v,{children:[m(v,{color:"white",bold:!0,children:"[Enter] Confirm"})," ",m(v,{color:"gray",children:"[Esc] Cancel"})]})})]})]}):_(C,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:g,children:[m(C,{marginTop:-1,marginBottom:1,children:_(v,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",m(v,{color:"cyan",children:"Select Agent"})]})}),_(C,{flexDirection:"column",paddingLeft:2,children:[m(v,{color:"grey",children:"Choose an agent to connect to Membrane via MCP:"}),m(C,{marginTop:1,children:m(v,{color:"grey",children:"This will add an MCP server configuration that allows the agent to use Membrane's integration capabilities."})}),m(C,{marginTop:1,flexDirection:"column",children:Xr.map((y,p)=>_(C,{children:[_(v,{color:t===p?"cyan":"white",children:[t===p?"\u25B6 ":" ",y.name]}),_(v,{color:"grey",children:[" \u2014 ",y.description]})]},y.id))})]}),m(C,{marginTop:1,children:m(v,{color:"grey",children:"[\u2191\u2193: select] [enter: choose] [esc: exit]"})})]})}c(If,"AddMcpServerScreen");function Af(){const[s,e]=J(null),[t,n]=J([]),[r,i]=J(null);return Ze(()=>{const o=c(({status:l})=>{e(l),i(null)},"handleMcpStatusChanged"),a=c(({servers:l})=>{n(l),i(null)},"handleMcpServersChanged");return He.on(Q.McpStatusChanged,o),He.on(Q.McpServersChanged,a),()=>{He.off(Q.McpStatusChanged,o),He.off(Q.McpServersChanged,a)}},[]),{mcpStatus:s,allMcpServers:t,error:r,isRunning:s?.isRunning||!1,toolsCount:s?.toolsCount||0,totalRequests:s?.totalRequests||0,lastActivity:s?.lastActivity,processId:s?.processId,serverCount:t.length}}c(Af,"useMcpStatus");function Of(){const{error:s,serverCount:e,allMcpServers:t}=Af(),n=Math.min(100,process.stdout.columns||100);return _(C,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:n,children:[m(C,{marginTop:-1,marginBottom:0,flexDirection:"column",children:_(v,{bold:!0,children:["\u{1F916} Connected AI Agents:"," ",s?m(v,{color:"red",children:"error reading status"}):e===0?m(v,{color:"yellow",children:"none"}):m(v,{color:"green",children:e})]})}),!s&&e===0&&m(C,{marginTop:1,children:_(v,{color:"grey",children:["Connect your AI agents to Membrane.",m(ol,{}),"It will give them tools and context to build integrations."]})}),t.length>0&&m(C,{flexDirection:"column",paddingLeft:2,marginTop:1,children:t.map((r,i)=>m(C,{children:_(v,{color:"grey",children:["#",i+1," ",r.agentName,": ",r.totalRequests," calls"]})},r.processId))}),m(C,{marginTop:1,children:m(v,{color:"grey",children:"[a: connect an agent]"})})]})}c(Of,"Agent");const Zr=5,$f=6;function Nf(){const{logs:s}=ge(),[e,t]=J(0),n=Math.min(100,process.stdout.columns||100),r=Zr,i=Math.max(0,s.length-r-e),o=s.length-e,a=s.slice(i,o),l=n-$f,u=e<s.length-r,d=e>0;return Qe((f,h)=>{if(s.length!==0)if(h.upArrow){const g=Math.max(0,s.length-r);t(y=>Math.min(g,y+1))}else h.downArrow?t(g=>Math.max(0,g-1)):(f==="G"||f==="g")&&t(0)}),_(C,{flexDirection:"column",paddingTop:1,children:[_(v,{color:"grey",children:["Recent Activity (",i+1,"-",o," of ",s.length,"):",s.length>Zr&&m(v,{color:"grey",children:" [arrows: scroll] [g: end]"})]}),a.map((f,h)=>m(C,{marginLeft:1,children:m(v,{color:Yr(f.type),children:qa(f.message,l)})},f.timestamp+h)),s.length>Zr&&_(C,{marginLeft:1,flexDirection:"row",children:[u&&m(v,{color:"grey",children:"\u2191 "}),d&&m(v,{color:"grey",children:"\u2193 "})]})]})}c(Nf,"Logs");function xf(){const{config:s,state:e,logs:t,currentWorkspace:n,pull:r}=ge(),i=n?.name,o=i?qa(i,30):s?.workspaceKey,a=Math.min(100,process.stdout.columns||100);return Ze(()=>{r({watch:!0})},[]),_(C,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:a,children:[m(C,{marginTop:-1,marginBottom:1,children:_(C,{flexDirection:"row",gap:1,children:[m(v,{bold:!0,children:"\u{1F504} Workspace"}),_(v,{color:Mf(e),children:[" [",Pf(e),"] "]})]})}),_(C,{children:[m(C,{width:12,children:m(v,{color:"grey",children:"Local:"})}),m(v,{color:"grey",children:process.cwd()})]}),_(C,{children:[m(C,{width:12,children:m(v,{color:"grey",children:"Remote:"})}),s?.workspaceKey?_(v,{color:"grey",children:[o," [o: open in console] [w: change]"]}):_(v,{children:[m(v,{color:"yellow",children:"not selected"})," [w: select]"]})]}),e===D.CONFLICTS?m(Cf,{}):_(Jt,{children:[m(C,{paddingTop:1,children:m(Ka,{})}),t.length>0&&m(Nf,{})]})]})}c(xf,"Workspace");function Pf(s){switch(s){case D.PULLING:return"pulling";case D.PUSHING:return"pushing";case D.CONFLICTS:return"conflicts";case D.SYNCED:return"synced";case D.ERROR:return"error";case D.WATCHING:return"tracking changes";case D.RESOLVING:return"resolving";case D.NOT_SYNCED:return"not synced";case D.INITIALIZED:return"initialized";case D.SETTING_UP:return"setup required";default:return"unknown"}}c(Pf,"getStatusDisplay");function Mf(s){switch(s){case D.PULLING:return"yellow";case D.PUSHING:return"yellow";case D.CONFLICTS:return"red";case D.SYNCED:return"green";case D.ERROR:return"red";case D.WATCHING:return"green";case D.RESOLVING:return"yellow";case D.NOT_SYNCED:return"grey";case D.SETTING_UP:return"yellow";default:return"grey"}}c(Mf,"getStatusColor");const Rf="https://console.integration.app/w";function Lf(){const s=Jd(),e=Zs(!0),{exit:t,state:n}=ge(),[r,i]=J(null),o=r??(n===D.SETTING_UP?"setup":"main");Qe(l=>{o==="main"&&(l==="w"&&i("workspace-selection"),l==="a"&&i("add-mcp-server"),l==="o"&&n===D.INITIALIZED&&a(),l==="s"&&i("setup"))});async function a(){try{const l=await Bi(s),u=`${Rf}/${l}`,d=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";vl(`${d} "${u}"`)}catch(l){console.error("Failed to open workspace:",l),t()}}return c(a,"handleOpenWorkspace"),Ze(()=>(e.current=!0,()=>{e.current=!1}),[]),o==="workspace-selection"?m(Ia,{onExit:c(()=>i(null),"onExit")}):o==="add-mcp-server"?m(If,{onExit:c(()=>i(null),"onExit"),onComplete:c(()=>i(null),"onComplete")}):o==="setup"?m(Aa,{onComplete:c(()=>i(null),"onComplete")},Date.now()):m(Ba,{children:_(C,{flexDirection:"column",children:[m(C,{flexGrow:1,children:m(Of,{})}),m(xf,{}),m(C,{paddingLeft:2,children:m(v,{color:"grey",children:"[s: (re-)setup]"})})]})})}c(Lf,"Main");const Df=c(()=>[k.yellow("\u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510"),k.yellow("\u2502 \u26A0\uFE0F EXPERIMENTAL FEATURE WARNING \u2502"),k.yellow("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524"),k.yellow("\u2502 Real-time agent mode is experimental and subject to changes. \u2502"),k.yellow("\u2502 Use in production environments is not recommended. \u2502"),k.yellow("\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518"),""].join(`
156
- `),"createExperimentalWarning$1");function jf(s,e){s.command("sync").description("\u26A0\uFE0F EXPERIMENTAL: Sync workspace data in real-time - This feature is experimental and subject to changes. Use in production environments is not recommended.").option("--watch","Watch for changes and sync automatically",!1).option("--rps <number>","Maximum requests per second (default: 80)",t=>parseInt(t,10)).addHelpText("after",["","Examples:"," membrane sync --watch # Start real-time sync with watch mode"," membrane sync --watch --rps 5 # Limit to 5 requests per second",""].join(`
157
- `)).action(async t=>{if(t.watch||(console.error("Error: The sync command requires the --watch flag"),console.error("Usage: membrane sync --watch"),process.exit(1)),t.rps!==void 0){const n=t.rps;!isNaN(n)&&n>0&&n<=1e3?K.init({maxRequestsPerSecond:n}):(b.error(`Invalid RPS value: ${n}. Must be between 1 and 1000.`),process.exit(1))}console.warn(Df()),In($e.createElement(ps,{cwd:process.cwd(),membraneCLIService:e,children:$e.createElement(Lf)}))})}c(jf,"setupSyncCommand");class Ff{static{c(this,"BaseRunner")}constructor(e={}){if(this.options=e,this.fsPaths=ar(),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}function L(s,e,t,n,r){if(typeof e=="function"?s!==e||!0:!e.has(s))throw new TypeError("Cannot write private member to an object whose class did not declare it");return e.set(s,t),t}c(L,"__classPrivateFieldSet");function S(s,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?s!==e||!n:!e.has(s))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(s):n?n.value:e.get(s)}c(S,"__classPrivateFieldGet");let Wa=c(function(){const{crypto:s}=globalThis;if(s?.randomUUID)return Wa=s.randomUUID.bind(s),s.randomUUID();const e=new Uint8Array(1),t=s?()=>s.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,n=>(+n^t()&15>>+n/4).toString(16))},"uuid4");function on(s){return typeof s=="object"&&s!==null&&("name"in s&&s.name==="AbortError"||"message"in s&&String(s.message).includes("FetchRequestCanceledException"))}c(on,"isAbortError");const Qr=c(s=>{if(s instanceof Error)return s;if(typeof s=="object"&&s!==null){try{if(Object.prototype.toString.call(s)==="[object Error]"){const e=new Error(s.message,s.cause?{cause:s.cause}:{});return s.stack&&(e.stack=s.stack),s.cause&&!e.cause&&(e.cause=s.cause),s.name&&(e.name=s.name),e}}catch{}try{return new Error(JSON.stringify(s))}catch{}}return new Error(s)},"castToError");class F extends Error{static{c(this,"AnthropicError")}}class re extends F{static{c(this,"APIError")}constructor(e,t,n,r){super(`${re.makeMessage(e,t,n)}`),this.status=e,this.headers=r,this.requestID=r?.get("request-id"),this.error=t}static makeMessage(e,t,n){const r=t?.message?typeof t.message=="string"?t.message:JSON.stringify(t.message):t?JSON.stringify(t):n;return e&&r?`${e} ${r}`:e?`${e} status code (no body)`:r||"(no status code or body)"}static generate(e,t,n,r){if(!e||!r)return new ys({message:n,cause:Qr(t)});const i=t;return e===400?new Ha(e,i,n,r):e===401?new Va(e,i,n,r):e===403?new Ga(e,i,n,r):e===404?new za(e,i,n,r):e===409?new Ya(e,i,n,r):e===422?new Xa(e,i,n,r):e===429?new Za(e,i,n,r):e>=500?new Qa(e,i,n,r):new re(e,i,n,r)}}class ke extends re{static{c(this,"APIUserAbortError")}constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}}class ys extends re{static{c(this,"APIConnectionError")}constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}}class Ja extends ys{static{c(this,"APIConnectionTimeoutError")}constructor({message:e}={}){super({message:e??"Request timed out."})}}class Ha extends re{static{c(this,"BadRequestError")}}class Va extends re{static{c(this,"AuthenticationError")}}class Ga extends re{static{c(this,"PermissionDeniedError")}}class za extends re{static{c(this,"NotFoundError")}}class Ya extends re{static{c(this,"ConflictError")}}class Xa extends re{static{c(this,"UnprocessableEntityError")}}class Za extends re{static{c(this,"RateLimitError")}}class Qa extends re{static{c(this,"InternalServerError")}}const qf=/^[a-z][a-z0-9+.-]*:/i,Bf=c(s=>qf.test(s),"isAbsoluteURL");let ei=c(s=>(ei=Array.isArray,ei(s)),"isArray"),ec=ei;function tc(s){return typeof s!="object"?{}:s??{}}c(tc,"maybeObj");function Kf(s){if(!s)return!0;for(const e in s)return!1;return!0}c(Kf,"isEmptyObj");function Uf(s,e){return Object.prototype.hasOwnProperty.call(s,e)}c(Uf,"hasOwn");const Wf=c((s,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new F(`${s} must be an integer`);if(e<0)throw new F(`${s} must be a positive integer`);return e},"validatePositiveInteger"),nc=c(s=>{try{return JSON.parse(s)}catch{return}},"safeJSON"),Jf=c(s=>new Promise(e=>setTimeout(e,s)),"sleep"),Lt="0.62.0",Hf=c(()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u","isRunningInBrowser");function Vf(){return typeof Deno<"u"&&Deno.build!=null?"deno":typeof EdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}c(Vf,"getDetectedPlatform");const Gf=c(()=>{const s=Vf();if(s==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Lt,"X-Stainless-OS":rc(Deno.build.os),"X-Stainless-Arch":sc(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Lt,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(s==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Lt,"X-Stainless-OS":rc(globalThis.process.platform??"unknown"),"X-Stainless-Arch":sc(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};const e=zf();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Lt,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${e.browser}`,"X-Stainless-Runtime-Version":e.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Lt,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}},"getPlatformProperties");function zf(){if(typeof navigator>"u"||!navigator)return null;const s=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(const{key:e,pattern:t}of s){const n=t.exec(navigator.userAgent);if(n){const r=n[1]||0,i=n[2]||0,o=n[3]||0;return{browser:e,version:`${r}.${i}.${o}`}}}return null}c(zf,"getBrowserInfo");const sc=c(s=>s==="x32"?"x32":s==="x86_64"||s==="x64"?"x64":s==="arm"?"arm":s==="aarch64"||s==="arm64"?"arm64":s?`other:${s}`:"unknown","normalizeArch"),rc=c(s=>(s=s.toLowerCase(),s.includes("ios")?"iOS":s==="android"?"Android":s==="darwin"?"MacOS":s==="win32"?"Windows":s==="freebsd"?"FreeBSD":s==="openbsd"?"OpenBSD":s==="linux"?"Linux":s?`Other:${s}`:"Unknown"),"normalizePlatform");let ic;const Yf=c(()=>ic??(ic=Gf()),"getPlatformHeaders");function Xf(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new Anthropic({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}c(Xf,"getDefaultFetch");function oc(...s){const e=globalThis.ReadableStream;if(typeof e>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new e(...s)}c(oc,"makeReadableStream");function ac(s){let e=Symbol.asyncIterator in s?s[Symbol.asyncIterator]():s[Symbol.iterator]();return oc({start(){},async pull(t){const{done:n,value:r}=await e.next();n?t.close():t.enqueue(r)},async cancel(){await e.return?.()}})}c(ac,"ReadableStreamFrom");function ti(s){if(s[Symbol.asyncIterator])return s;const e=s.getReader();return{async next(){try{const t=await e.read();return t?.done&&e.releaseLock(),t}catch(t){throw e.releaseLock(),t}},async return(){const t=e.cancel();return e.releaseLock(),await t,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}c(ti,"ReadableStreamToAsyncIterable");async function Zf(s){if(s===null||typeof s!="object")return;if(s[Symbol.asyncIterator]){await s[Symbol.asyncIterator]().return?.();return}const e=s.getReader(),t=e.cancel();e.releaseLock(),await t}c(Zf,"CancelReadableStream");const Qf=c(({headers:s,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)}),"FallbackEncoder");function eh(s){let e=0;for(const r of s)e+=r.length;const t=new Uint8Array(e);let n=0;for(const r of s)t.set(r,n),n+=r.length;return t}c(eh,"concatBytes");let cc;function ni(s){let e;return(cc??(e=new globalThis.TextEncoder,cc=e.encode.bind(e)))(s)}c(ni,"encodeUTF8");let lc;function uc(s){let e;return(lc??(e=new globalThis.TextDecoder,lc=e.decode.bind(e)))(s)}c(uc,"decodeUTF8");var de,fe;class an{static{c(this,"LineDecoder")}constructor(){de.set(this,void 0),fe.set(this,void 0),L(this,de,new Uint8Array),L(this,fe,null)}decode(e){if(e==null)return[];const t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?ni(e):e;L(this,de,eh([S(this,de,"f"),t]));const n=[];let r;for(;(r=th(S(this,de,"f"),S(this,fe,"f")))!=null;){if(r.carriage&&S(this,fe,"f")==null){L(this,fe,r.index);continue}if(S(this,fe,"f")!=null&&(r.index!==S(this,fe,"f")+1||r.carriage)){n.push(uc(S(this,de,"f").subarray(0,S(this,fe,"f")-1))),L(this,de,S(this,de,"f").subarray(S(this,fe,"f"))),L(this,fe,null);continue}const i=S(this,fe,"f")!==null?r.preceding-1:r.preceding,o=uc(S(this,de,"f").subarray(0,i));n.push(o),L(this,de,S(this,de,"f").subarray(r.index)),L(this,fe,null)}return n}flush(){return S(this,de,"f").length?this.decode(`
151
+ ${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]),r=e.map(i=>{const o={};return n.forEach(a=>{o[a]=i[a]}),o});console.table(r,n)}static divider(){}}function rf(s){s.command("open").description("Open the workspace in the browser").addHelpText("after",["","Examples:"," membrane open # Open workspace in browser",""].join(`
152
+ `)).action(async()=>{try{H.header("Opening Workspace in Browser"),H.info("Loading configuration...");const e=$n();if(!e)throw new Error("No configuration found. Please set MEMBRANE_WORKSPACE_KEY and MEMBRANE_WORKSPACE_SECRET environment variables, or run `membrane init` first.");if(!e.workspaceKey||!e.workspaceSecret)throw new Error("Missing workspace credentials");H.info("Retrieving workspace ID...");const n=`https://console.integration.app/w/${await Ki(process.cwd())}`;H.info(`Opening ${n}...`);const{default:r}=await import("open");await r(n),H.success("Browser opened successfully")}catch(e){e instanceof Error&&(H.error(e.message),process.exit(1)),H.error("An unknown error occurred"),process.exit(1)}})}c(rf,"setupOpenCommand");async function xa(s,e,t={}){const{jobId:n,accessKey:r}=await e(),i=`${n}:${r}`;b.debug(`[background-job] Started job ${n}`);const o=Date.now(),{pollIntervalMs:a=1e3,timeoutMs:l=3e5}=t;for(;;){if(Date.now()-o>l)throw new Error(`Background job ${n} timed out after ${l}ms`);await new Promise(f=>setTimeout(f,a));const d=await s.get(`background-jobs/${i}`);if(d.status==="completed"){if(b.debug(`[background-job] Completed job ${n}`),!d.result)throw new Error(`Background job ${n} completed but returned no result`);return d.result}if(d.status==="failed"){const f=d.failedReason||"Unknown error";throw b.error(`[background-job] Failed job ${n}: ${f}`),d.stacktrace&&b.error(`Stacktrace: ${d.stacktrace.join(`
153
+ `)}`),new Error(`Background job ${n} failed: ${f}`)}b.debug(`[background-job] Polling job ${n} (status: ${d.status})`)}}c(xa,"pollBackgroundJob");function of(s,e){zr(P.dirname(s)),A.writeFileSync(s,e)}c(of,"writeFile");function af(s){A.existsSync(s)&&A.rmSync(s)}c(af,"deleteFile");function Pa(s){A.existsSync(s)&&A.rmSync(s,{recursive:!0,force:!0})}c(Pa,"deleteDir");function cf(s,e=!0){if(A.existsSync(s))try{const t=A.readFileSync(s,"utf8");return Se.load(t)||void 0}catch(t){if(!e)return;if(t instanceof Error){const n=P.relative(process.cwd(),s);throw new Error(`Failed to parse YAML file "${n}": ${t.message}`)}throw t}}c(cf,"readYaml");function Ma(s,e,t){try{zr(P.dirname(s));const n=Se.dump(e,t);A.writeFileSync(s,n,"utf8")}catch(n){if(n instanceof Error){const r=P.relative(process.cwd(),s);throw new Error(`Failed to write YAML file "${r}": ${n.message}`)}throw n}return e}c(Ma,"writeYaml");function zr(s){A.existsSync(s)||A.mkdirSync(s,{recursive:!0})}c(zr,"ensureDirExists");function Ra(s,e=!0){if(!A.existsSync(s)||!A.statSync(s).isDirectory())return;let t=A.readdirSync(s);t.length>0&&(t.forEach(n=>Ra(P.join(s,n),!1)),t=A.readdirSync(s)),t.length===0&&!e&&A.rmdirSync(s)}c(Ra,"cleanupEmptyFolders");async function lf(s){return new Promise(async(e,t)=>{const n=Ni("zip",{zlib:{level:9}}),r=[];n.on("data",o=>r.push(o)),n.on("end",()=>e(Buffer.concat(r))),n.on("error",o=>t(o));const i=new Map;for(const o of s[N.Integration]||[])i.set(o.uuid,o.key);for(const[o,a]of Object.entries(s))for(const l of a){const u=l.key,d=i.get(l.integrationUuid),f=Qc(o,u,d),h=Se.dump(l);n.append(h,{name:f})}n.finalize()})}c(lf,"createMembraneZip");async function La(s,e){const t=await Mi.loadAsync(s),n=[];for(const[r,i]of Object.entries(t.files)){if(i.dir)continue;const o=ft(r);if(!o)continue;const a=await i.async("string"),l=Se.load(a);if(!l)continue;const u=await e(r,l,o);u!==void 0&&n.push(u)}return n}c(La,"iterateZipItems");async function uf(s){const e=await Mi.loadAsync(s),t={};for(const[n,r]of Object.entries(e.files)){if(r.dir)continue;const i=ft(n);if(!i)continue;const o=await r.async("string"),a=Se.load(o);t[i.type]||(t[i.type]=[]),t[i.type].push(a)}return t}c(uf,"readMembraneZip");async function df(s=process.cwd()){const e=await Da(he(s)),t={};for(const{data:n,type:r}of e)t[r]||(t[r]=[]),t[r].push(n);return t}c(df,"readMembraneDir");async function Da(s){const e=ja(s),t=[];for(const n of e){if(n.isDirectory())continue;const r=ft(n.path);if(!r)continue;const i=await n.readContent(),o=Se.load(i),a=P.join(s,n.path);t.push({filePath:a,data:o,type:r.type})}return t}c(Da,"iterateMembraneFiles");function ja(s,e){const t=[];if(e||(e=s),!A.existsSync(e)||e.startsWith(P.join(s,"connectors")))return t;const n=A.readdirSync(e,{withFileTypes:!0});for(const r of n){const i=P.join(e,r.name),o=P.relative(s,i);r.isDirectory()?t.push(...ja(s,i)):r.isFile()&&ft(o)&&t.push({path:o,isDirectory:c(()=>!1,"isDirectory"),readContent:c(async()=>A.readFileSync(i,"utf8"),"readContent")})}return t}c(ja,"getMembraneFiles");function ff(){const s={},e=P.join(he(process.cwd()),"connectors");if(!A.existsSync(e))return s;const t=A.readdirSync(e);for(const n of t){const r=P.join(e,n);if(!A.statSync(r).isDirectory())continue;const i=P.join(r,`${n}.yml`),o=cf(i,!1);if(!o?.uuid)continue;const a=new Set,l=A.readdirSync(r);for(const u of l){if(u.endsWith(".yml"))continue;const d=P.join(r,u);A.statSync(d).isDirectory()&&a.add(u=="development"?"":u)}s[o.uuid]={key:n,versions:Array.from(a)}}return s}c(ff,"readConnectorsDir");function ms(s,e){const t=P.join(he(process.cwd()),"connectors",s);return e==""||e===Ei?P.join(t,"development"):e?P.join(t,e):t}c(ms,"getConnectorPath");const Fa=300,qa=6e4;async function hf(){const s=await K.withClient(async t=>xa(t,()=>t.get("export"),{pollIntervalMs:Fa,timeoutMs:qa}));if(!s)throw new Error("Failed to export workspace");const e=await Ht.get(s.downloadUrl,{responseType:"arraybuffer"});return Buffer.from(e.data)}c(hf,"downloadWorkspaceExport");async function pf(s,e){const t=await K.withClient(async r=>xa(r,()=>r.get(`connectors/${s}/export`,{version:e}),{pollIntervalMs:Fa,timeoutMs:qa}));if(!t)throw new Error("Failed to export connector version");const n=await Ht.get(t.downloadUrl,{responseType:"arraybuffer"});return Buffer.from(n.data)}c(pf,"exportConnector");function mf(s){s.command("pull").description("Pull workspace data from specified workspace").option("--force","Overwrite conflicts with remote data",!1).addHelpText("after",["","Examples:"," membrane pull # Pull from default workspace"," membrane pull --force # Overwrite conflicts with remote data",""].join(`
154
+ `)).action(async e=>{try{const t=await gf(e);bf(t.workspaceExport,t.connectors)}catch(t){Cf(t),process.exit(1)}})}c(mf,"setupPullCommand");async function gf(s){const e=await df(),t=await lf(e),n=await hf(),r=await uf(n),{comparison:i}=el(e,r);Array.from(i[ht.DELETE]).length>0&&!s.force&&(await Sf(i,t),H.error("Use --force to delete local elements"),process.exit(1));const a=await Da(he(process.cwd()));for(const{filePath:u,data:d}of a)i[ht.DELETE].has(d.uuid)&&af(u);return Ra(he(process.cwd())),await La(n,(u,d)=>{if(ft(u)&&(i[ht.CREATE].has(d.uuid)||i[ht.UPDATE].has(d.uuid))){const h=q.join(he(process.cwd()),u);Ma(h,d)}}),{connectors:await yf(r[N.Integration]),workspaceExport:r}}c(gf,"pullWorkspace");async function yf(s){const e=new Map;for(const r of s??[]){const{connectorUuid:i,connectorVersion:o}=r;i&&(e.has(i)||e.set(i,new Set),e.get(i).add(o??""))}const t=ff(),n=new Map;for(const[r,{key:i,versions:o}]of Object.entries(t)){if(!e.has(r)){const u=ms(i);Pa(u);continue}const a=e.get(r);for(const u of o)if(!a.has(u)){const d=ms(i,u);Pa(d)}const l=new Set(o);for(const u of a)l.has(u)||(n.has(r)||n.set(r,new Set),n.get(r).add(u))}for(const[r,i]of e.entries())t[r]||n.set(r,i);return await Promise.all(Array.from(n.entries()).map(([r,i])=>wf(r,Array.from(i)))),Array.from(n.keys())}c(yf,"pullConnectors");async function wf(s,e){const t=await K.withClient(i=>i.get(`connectors/${s}`),!1);if(!t||!t.key)return;const n=ms(t.key),r=q.join(n,`${t.key}.yml`);Ma(r,t);for(const i of e){const o=await pf(s,i),a=ms(t.key,i);if(of(q.join(a,"src.zip"),o),!i||i===Ei){const l=q.join(a,"src");zr(l),await(await xi.Open.buffer(o)).extract({path:l})}}}c(wf,"pullConnector");function bf(s,e=[]){const t=Object.values(s).reduce((n,r)=>n+(r?.length??0),0)+e.length;H.info(`\u25CF Pulled workspace elements \xB7 ${t}`);for(const n of Object.keys(s)){const r=s[n];H.info(`\u2514\u2500\u2500 ${n}s \xB7 ${r?.length??0}`)}e.length>0&&H.info(`\u2514\u2500\u2500 connectors \xB7 ${e.length}`)}c(bf,"showStats");async function Sf(s,e){const t=Array.from(s[ht.DELETE]).length;H.info(`\u2299 Pull: conflicts detected \xB7 ${t}`),await La(e,(n,r)=>{ft(n)&&s[ht.DELETE].has(r.uuid)&&H.info(`\u2514\u2500\u2500 ./membrane/${n} (deleted in remote)`)})}c(Sf,"showConflicts");async function Cf(s){H.error("\u25A0 Error"),H.error(`\u2514\u2500\u2500 ${s.message}`),H.error(` ${s.stack}`)}c(Cf,"showError");const Yr=c(s=>{switch(s){case"error":return"red";case"success":return"green";case"warning":return"yellow";default:return}},"getLogColor");function Ba(s,e){return e<3?s.slice(0,Math.max(0,e)):s.length<=e?s:`${s.slice(0,e-3)}...`}c(Ba,"truncateText");function Ka({children:s}){const{state:e,logs:t}=ge();return!e||e===D.NOT_INITIALIZED?_(C,{gap:1,flexDirection:"row",children:[m(Cl,{type:"dots"}),m(v,{children:"Initializing..."})]}):e===D.SETTING_UP?m(C,{gap:1,flexDirection:"row",children:m(v,{children:"No workspace selected. Please run `membrane init` to select a workspace."})}):e===D.ERROR?m(C,{flexDirection:"column",children:t.slice().map((n,r)=>m(v,{color:Yr(n.type),children:n.message},n.timestamp+r))}):s}c(Ka,"EnsureInitialized");function Ua(){const{stats:s}=ge(),e=Object.entries(s).filter(([t,n])=>n>0);return e.length===0?null:_(C,{flexDirection:"column",children:[m(C,{children:m(C,{width:12,children:m(v,{color:"grey",children:"Elements:"})})}),m(C,{flexDirection:"column",marginLeft:1,children:e.map(([t,n])=>_(C,{children:[m(C,{width:20,children:_(v,{children:[t,":"]})}),m(v,{color:"green",children:n})]},t))})]})}c(Ua,"ElementStats");const gs=[{value:"sync",label:"Continue (overwrite/delete)",key:""},{value:"exit",label:"Cancel",key:""}];function vf(){const{state:s,resolveConflicts:e,exit:t}=ge(),[n,r]=J(0),[i,o]=J(!1),[a,l]=J(!1);return Qe((u,d)=>{if(!i){if(d.ctrl&&u.toLowerCase()==="r"){l(!a);return}d.upArrow?r(f=>f>0?f-1:gs.length-1):d.downArrow?r(f=>f<gs.length-1?f+1:0):u.toLowerCase()==="y"?r(0):u.toLowerCase()==="n"?r(1):(d.return||u===" ")&&(o(!0),gs[n].value==="sync"?e({watch:!0}):t())}}),Ze(()=>{s!==D.CONFLICTS&&i&&o(!1)},[s,i]),_(C,{flexDirection:"column",paddingTop:1,children:[m(C,{children:m(C,{flexDirection:"row",gap:2,children:m(v,{bold:!0,color:"white",children:"Conflicts with remote"})})}),m(C,{children:m(v,{color:"grey",children:"The remote workspace has changes that aren't in your local workspace:"})}),m(C,{marginTop:1,marginLeft:2,children:m(Wa,{isExpanded:a})}),_(C,{marginTop:2,flexDirection:"row",gap:1,children:[m(v,{color:"white",bold:!0,children:"What would you like to do?"}),m(v,{color:"grey",children:"[up/down, enter]"})]}),m(C,{children:i?_(C,{flexDirection:"row",gap:1,children:[m(An,{type:"dots"}),m(v,{color:"blue",bold:!0,children:"Syncing with remote..."})]}):m(C,{flexDirection:"column",children:gs.map((u,d)=>m(C,{flexDirection:"column",children:_(C,{flexDirection:"row",gap:1,children:[m(v,{color:n===d?"cyan":"grey",children:n===d?"\u25B6":" "}),m(v,{color:n===d?"cyan":"grey",bold:n===d,children:u.label})]})},u.value))})})]})}c(vf,"ResolveChangesUI");const kf={[Ne.UPDATE]:{incoming:{label:"Elements updated in remote",description:"(to be overwritten from remote)"},outgoing:{label:"Elements updated locally",description:"(to be pushed to remote)"}},[Ne.DELETE]:{incoming:{label:"Elements not existing in remote",description:"(to be deleted locally)"},outgoing:{label:"Elements deleted locally",description:"(to be deleted from remote)"}},[Ne.CREATE]:{incoming:{label:"Elements created in remote",description:"(to be created locally)"},outgoing:{label:"Elements created locally",description:"(to be created in remote)"}}};function Wa({isExpanded:s,showControls:e=!0}){const{conflicts:t}=ge(),n=5,r=ol(()=>{const i={};return t.forEach(o=>{const a=`${o.type}-${o.direction}`;i[a]||(i[a]=[]),i[a].push(o)}),i},[t]);return m(C,{flexDirection:"column",children:Object.entries(r).map(([i,o])=>{if(o.length===0)return null;const[a,l]=i.split("-"),u=kf[a][l];return _(C,{flexDirection:"column",children:[_(C,{flexDirection:"row",gap:1,children:[_(v,{color:"yellow",children:[u.label," (",o.length,")"]}),m(v,{color:"white",children:u.description})]}),(s?o:o.slice(0,n)).map(d=>m(C,{marginLeft:2,children:_(v,{color:"grey",children:["\u2022 ",d.element.id," (",d.element.relativePath,")"]})},d.element.id)),!s&&o.length>n&&m(C,{marginLeft:2,children:_(v,{color:"cyan",children:["... and ",o.length-n," more",e?" (press Ctrl+R to show all)":""]})}),s&&o.length>n&&e&&m(C,{marginLeft:2,children:m(v,{color:"cyan",children:"(press Ctrl+R to collapse)"})})]},i)})})}c(Wa,"Conflicts");function Tf(s){return m(Ka,{children:m(Ef,{options:s})})}c(Tf,"Push");function Ef({options:s}){const{logs:e,state:t,conflicts:n,push:r}=ge();Ze(()=>{r(s)},[]);const i=t===D.CONFLICTS;return _(C,{flexDirection:"column",children:[e.slice().map((o,a)=>m(v,{color:Yr(o.type),children:o.message},o.timestamp+a)),i&&_(Jt,{children:[_(v,{color:"yellow",bold:!0,children:["Found ",n.length," conflicts with remote:"]}),m(Wa,{isExpanded:!s.watch,showControls:!1}),m(v,{color:"red",children:"Out of sync with remote, use --force to overwrite conflict changes"})]}),t===D.SYNCED&&m(Ua,{})]})}c(Ef,"PushActivity");function _f(){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(_f,"getWatchModeCallback");function If(s,e){s.command("push").description("Push workspace data to specified workspace").option("--force","Overwrite conflicts with local data",!1).option("--watch","Watch for changes and push automatically",!1).option("--save-logs","Save logs to a file",!1).option("--verbose","Show verbose debug logs",!1).option("--rps <number>","Maximum requests per second (default: 80)",t=>parseInt(t,10)).addHelpText("after",["","Examples:"," membrane push # Push to default workspace"," membrane push --force # Overwrite conflicts with local data"," membrane push --rps 5 # Limit to 5 requests per second",""].join(`
155
+ `)).action(async t=>{const n=t.watch?_f():()=>process.exit(0);In($e.createElement(ps,{membraneCLIService:e,children:$e.createElement(Tf,{...t,onComplete:n})}))})}c(If,"setupPushCommand");const Xr=[{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=P.join(process.cwd(),".mcp.json"),e={mcpServers:{membrane:{command:"membrane",args:["mcp"],env:{AGENT_NAME:"Claude Code"}}}};let t={};if(A.existsSync(s))try{t=JSON.parse(A.readFileSync(s,"utf8"))}catch{t={}}const n={...t,mcpServers:{...t.mcpServers,...e.mcpServers}};return A.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=P.join(process.cwd(),".cursor"),e=P.join(s,"mcp.json");A.existsSync(s)||A.mkdirSync(s);const t={mcpServers:{membrane:{command:"membrane",args:["mcp"],env:{AGENT_NAME:"Cursor"}}}};let n={};if(A.existsSync(e))try{n=JSON.parse(A.readFileSync(e,"utf8"))}catch{n={}}const r={...n,mcpServers:{...n.mcpServers,...t.mcpServers}};return A.writeFileSync(e,JSON.stringify(r,null,2)),`MCP server configuration added to ${e}`},"addConfig")}];function Af({onExit:s,onComplete:e}){const[t,n]=J(0),[r,i]=J(!1),[o,a]=J(null),[l,u]=J(""),[d,f]=J("");Qe((y,p)=>{if(l||d){(p.escape||y==="q"||p.return)&&e();return}if(r)p.return||y===" "?h(o):p.escape&&(i(!1),a(null));else if(p.escape)s();else if(p.upArrow||y==="k")n(Math.max(0,t-1));else if(p.downArrow||y==="j")n(Math.min(Xr.length-1,t+1));else if(p.return||y===" "){const w=Xr[t];a(w),i(!0)}});const h=c(y=>{try{const p=y.addConfig();u(p)}catch(p){f(`Failed to write configuration: ${p.message||p}`)}},"addMcpConfiguration"),g=Math.min(80,process.stdout.columns||80);return l?_(C,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:g,children:[m(C,{marginTop:-1,marginBottom:1,children:_(v,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",m(v,{color:"green",children:"Success"})]})}),_(C,{flexDirection:"column",paddingLeft:2,children:[m(v,{color:"green",children:l}),m(C,{marginTop:1,children:m(v,{color:"grey",children:"The agent will now be able to use Membrane's integration capabilities."})})]}),m(C,{marginTop:1,paddingLeft:2,children:m(v,{color:"white",children:"[esc/q/enter: exit]"})})]}):d?_(C,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:g,children:[m(C,{marginTop:-1,marginBottom:1,children:_(v,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",m(v,{color:"red",children:"Error"})]})}),m(C,{flexDirection:"column",paddingLeft:2,children:m(v,{color:"red",children:d})}),m(C,{marginTop:1,children:m(v,{color:"grey",children:"[esc/q/enter: exit]"})})]}):r&&o?_(C,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:g,children:[m(C,{marginTop:-1,marginBottom:1,children:_(v,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",m(v,{color:"cyan",children:"Confirmation"})]})}),_(C,{flexDirection:"column",paddingLeft:2,children:[_(v,{children:["Connect ",m(v,{bold:!0,children:o.name})," to Membrane via MCP?"]}),m(C,{marginTop:1,children:m(v,{color:"grey",children:"This will add an MCP server configuration that allows the agent to use Membrane's integration capabilities."})}),m(C,{marginTop:1,children:m(v,{color:"yellow",bold:!0,children:o.actionDescription})}),m(C,{marginTop:2,marginBottom:1,children:_(v,{children:[m(v,{color:"white",bold:!0,children:"[Enter] Confirm"})," ",m(v,{color:"gray",children:"[Esc] Cancel"})]})})]})]}):_(C,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:g,children:[m(C,{marginTop:-1,marginBottom:1,children:_(v,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",m(v,{color:"cyan",children:"Select Agent"})]})}),_(C,{flexDirection:"column",paddingLeft:2,children:[m(v,{color:"grey",children:"Choose an agent to connect to Membrane via MCP:"}),m(C,{marginTop:1,children:m(v,{color:"grey",children:"This will add an MCP server configuration that allows the agent to use Membrane's integration capabilities."})}),m(C,{marginTop:1,flexDirection:"column",children:Xr.map((y,p)=>_(C,{children:[_(v,{color:t===p?"cyan":"white",children:[t===p?"\u25B6 ":" ",y.name]}),_(v,{color:"grey",children:[" \u2014 ",y.description]})]},y.id))})]}),m(C,{marginTop:1,children:m(v,{color:"grey",children:"[\u2191\u2193: select] [enter: choose] [esc: exit]"})})]})}c(Af,"AddMcpServerScreen");function Of(){const[s,e]=J(null),[t,n]=J([]),[r,i]=J(null);return Ze(()=>{const o=c(({status:l})=>{e(l),i(null)},"handleMcpStatusChanged"),a=c(({servers:l})=>{n(l),i(null)},"handleMcpServersChanged");return He.on(Q.McpStatusChanged,o),He.on(Q.McpServersChanged,a),()=>{He.off(Q.McpStatusChanged,o),He.off(Q.McpServersChanged,a)}},[]),{mcpStatus:s,allMcpServers:t,error:r,isRunning:s?.isRunning||!1,toolsCount:s?.toolsCount||0,totalRequests:s?.totalRequests||0,lastActivity:s?.lastActivity,processId:s?.processId,serverCount:t.length}}c(Of,"useMcpStatus");function $f(){const{error:s,serverCount:e,allMcpServers:t}=Of(),n=Math.min(100,process.stdout.columns||100);return _(C,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:n,children:[m(C,{marginTop:-1,marginBottom:0,flexDirection:"column",children:_(v,{bold:!0,children:["\u{1F916} Connected AI Agents:"," ",s?m(v,{color:"red",children:"error reading status"}):e===0?m(v,{color:"yellow",children:"none"}):m(v,{color:"green",children:e})]})}),!s&&e===0&&m(C,{marginTop:1,children:_(v,{color:"grey",children:["Connect your AI agents to Membrane.",m(al,{}),"It will give them tools and context to build integrations."]})}),t.length>0&&m(C,{flexDirection:"column",paddingLeft:2,marginTop:1,children:t.map((r,i)=>m(C,{children:_(v,{color:"grey",children:["#",i+1," ",r.agentName,": ",r.totalRequests," calls"]})},r.processId))}),m(C,{marginTop:1,children:m(v,{color:"grey",children:"[a: connect an agent]"})})]})}c($f,"Agent");const Zr=5,Nf=6;function xf(){const{logs:s}=ge(),[e,t]=J(0),n=Math.min(100,process.stdout.columns||100),r=Zr,i=Math.max(0,s.length-r-e),o=s.length-e,a=s.slice(i,o),l=n-Nf,u=e<s.length-r,d=e>0;return Qe((f,h)=>{if(s.length!==0)if(h.upArrow){const g=Math.max(0,s.length-r);t(y=>Math.min(g,y+1))}else h.downArrow?t(g=>Math.max(0,g-1)):(f==="G"||f==="g")&&t(0)}),_(C,{flexDirection:"column",paddingTop:1,children:[_(v,{color:"grey",children:["Recent Activity (",i+1,"-",o," of ",s.length,"):",s.length>Zr&&m(v,{color:"grey",children:" [arrows: scroll] [g: end]"})]}),a.map((f,h)=>m(C,{marginLeft:1,children:m(v,{color:Yr(f.type),children:Ba(f.message,l)})},f.timestamp+h)),s.length>Zr&&_(C,{marginLeft:1,flexDirection:"row",children:[u&&m(v,{color:"grey",children:"\u2191 "}),d&&m(v,{color:"grey",children:"\u2193 "})]})]})}c(xf,"Logs");function Pf(){const{config:s,state:e,logs:t,currentWorkspace:n,pull:r}=ge(),i=n?.name,o=i?Ba(i,30):s?.workspaceKey,a=Math.min(100,process.stdout.columns||100);return Ze(()=>{r({watch:!0})},[]),_(C,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:a,children:[m(C,{marginTop:-1,marginBottom:1,children:_(C,{flexDirection:"row",gap:1,children:[m(v,{bold:!0,children:"\u{1F504} Workspace"}),_(v,{color:Rf(e),children:[" [",Mf(e),"] "]})]})}),_(C,{children:[m(C,{width:12,children:m(v,{color:"grey",children:"Local:"})}),m(v,{color:"grey",children:process.cwd()})]}),_(C,{children:[m(C,{width:12,children:m(v,{color:"grey",children:"Remote:"})}),s?.workspaceKey?_(v,{color:"grey",children:[o," [o: open in console] [w: change]"]}):_(v,{children:[m(v,{color:"yellow",children:"not selected"})," [w: select]"]})]}),e===D.CONFLICTS?m(vf,{}):_(Jt,{children:[m(C,{paddingTop:1,children:m(Ua,{})}),t.length>0&&m(xf,{})]})]})}c(Pf,"Workspace");function Mf(s){switch(s){case D.PULLING:return"pulling";case D.PUSHING:return"pushing";case D.CONFLICTS:return"conflicts";case D.SYNCED:return"synced";case D.ERROR:return"error";case D.WATCHING:return"tracking changes";case D.RESOLVING:return"resolving";case D.NOT_SYNCED:return"not synced";case D.INITIALIZED:return"initialized";case D.SETTING_UP:return"setup required";default:return"unknown"}}c(Mf,"getStatusDisplay");function Rf(s){switch(s){case D.PULLING:return"yellow";case D.PUSHING:return"yellow";case D.CONFLICTS:return"red";case D.SYNCED:return"green";case D.ERROR:return"red";case D.WATCHING:return"green";case D.RESOLVING:return"yellow";case D.NOT_SYNCED:return"grey";case D.SETTING_UP:return"yellow";default:return"grey"}}c(Rf,"getStatusColor");const Lf="https://console.integration.app/w";function Df(){const s=Hd(),e=Zs(!0),{exit:t,state:n}=ge(),[r,i]=J(null),o=r??(n===D.SETTING_UP?"setup":"main");Qe(l=>{o==="main"&&(l==="w"&&i("workspace-selection"),l==="a"&&i("add-mcp-server"),l==="o"&&n===D.INITIALIZED&&a(),l==="s"&&i("setup"))});async function a(){try{const l=await Ki(s),u=`${Lf}/${l}`,d=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";kl(`${d} "${u}"`)}catch(l){console.error("Failed to open workspace:",l),t()}}return c(a,"handleOpenWorkspace"),Ze(()=>(e.current=!0,()=>{e.current=!1}),[]),o==="workspace-selection"?m(Aa,{onExit:c(()=>i(null),"onExit")}):o==="add-mcp-server"?m(Af,{onExit:c(()=>i(null),"onExit"),onComplete:c(()=>i(null),"onComplete")}):o==="setup"?m(Oa,{onComplete:c(()=>i(null),"onComplete")},Date.now()):m(Ka,{children:_(C,{flexDirection:"column",children:[m(C,{flexGrow:1,children:m($f,{})}),m(Pf,{}),m(C,{paddingLeft:2,children:m(v,{color:"grey",children:"[s: (re-)setup]"})})]})})}c(Df,"Main");const jf=c(()=>[k.yellow("\u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510"),k.yellow("\u2502 \u26A0\uFE0F EXPERIMENTAL FEATURE WARNING \u2502"),k.yellow("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524"),k.yellow("\u2502 Real-time agent mode is experimental and subject to changes. \u2502"),k.yellow("\u2502 Use in production environments is not recommended. \u2502"),k.yellow("\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518"),""].join(`
156
+ `),"createExperimentalWarning$1");function Ff(s,e){s.command("sync").description("\u26A0\uFE0F EXPERIMENTAL: Sync workspace data in real-time - This feature is experimental and subject to changes. Use in production environments is not recommended.").option("--watch","Watch for changes and sync automatically",!1).option("--rps <number>","Maximum requests per second (default: 80)",t=>parseInt(t,10)).addHelpText("after",["","Examples:"," membrane sync --watch # Start real-time sync with watch mode"," membrane sync --watch --rps 5 # Limit to 5 requests per second",""].join(`
157
+ `)).action(async t=>{if(t.watch||(console.error("Error: The sync command requires the --watch flag"),console.error("Usage: membrane sync --watch"),process.exit(1)),t.rps!==void 0){const n=t.rps;!isNaN(n)&&n>0&&n<=1e3?K.init({maxRequestsPerSecond:n}):(b.error(`Invalid RPS value: ${n}. Must be between 1 and 1000.`),process.exit(1))}console.warn(jf()),In($e.createElement(ps,{cwd:process.cwd(),membraneCLIService:e,children:$e.createElement(Df)}))})}c(Ff,"setupSyncCommand");class qf{static{c(this,"BaseRunner")}constructor(e={}){if(this.options=e,this.fsPaths=ar(),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}function L(s,e,t,n,r){if(typeof e=="function"?s!==e||!0:!e.has(s))throw new TypeError("Cannot write private member to an object whose class did not declare it");return e.set(s,t),t}c(L,"__classPrivateFieldSet");function S(s,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?s!==e||!n:!e.has(s))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(s):n?n.value:e.get(s)}c(S,"__classPrivateFieldGet");let Ja=c(function(){const{crypto:s}=globalThis;if(s?.randomUUID)return Ja=s.randomUUID.bind(s),s.randomUUID();const e=new Uint8Array(1),t=s?()=>s.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,n=>(+n^t()&15>>+n/4).toString(16))},"uuid4");function on(s){return typeof s=="object"&&s!==null&&("name"in s&&s.name==="AbortError"||"message"in s&&String(s.message).includes("FetchRequestCanceledException"))}c(on,"isAbortError");const Qr=c(s=>{if(s instanceof Error)return s;if(typeof s=="object"&&s!==null){try{if(Object.prototype.toString.call(s)==="[object Error]"){const e=new Error(s.message,s.cause?{cause:s.cause}:{});return s.stack&&(e.stack=s.stack),s.cause&&!e.cause&&(e.cause=s.cause),s.name&&(e.name=s.name),e}}catch{}try{return new Error(JSON.stringify(s))}catch{}}return new Error(s)},"castToError");class F extends Error{static{c(this,"AnthropicError")}}class re extends F{static{c(this,"APIError")}constructor(e,t,n,r){super(`${re.makeMessage(e,t,n)}`),this.status=e,this.headers=r,this.requestID=r?.get("request-id"),this.error=t}static makeMessage(e,t,n){const r=t?.message?typeof t.message=="string"?t.message:JSON.stringify(t.message):t?JSON.stringify(t):n;return e&&r?`${e} ${r}`:e?`${e} status code (no body)`:r||"(no status code or body)"}static generate(e,t,n,r){if(!e||!r)return new ys({message:n,cause:Qr(t)});const i=t;return e===400?new Va(e,i,n,r):e===401?new Ga(e,i,n,r):e===403?new za(e,i,n,r):e===404?new Ya(e,i,n,r):e===409?new Xa(e,i,n,r):e===422?new Za(e,i,n,r):e===429?new Qa(e,i,n,r):e>=500?new ec(e,i,n,r):new re(e,i,n,r)}}class ke extends re{static{c(this,"APIUserAbortError")}constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}}class ys extends re{static{c(this,"APIConnectionError")}constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}}class Ha extends ys{static{c(this,"APIConnectionTimeoutError")}constructor({message:e}={}){super({message:e??"Request timed out."})}}class Va extends re{static{c(this,"BadRequestError")}}class Ga extends re{static{c(this,"AuthenticationError")}}class za extends re{static{c(this,"PermissionDeniedError")}}class Ya extends re{static{c(this,"NotFoundError")}}class Xa extends re{static{c(this,"ConflictError")}}class Za extends re{static{c(this,"UnprocessableEntityError")}}class Qa extends re{static{c(this,"RateLimitError")}}class ec extends re{static{c(this,"InternalServerError")}}const Bf=/^[a-z][a-z0-9+.-]*:/i,Kf=c(s=>Bf.test(s),"isAbsoluteURL");let ei=c(s=>(ei=Array.isArray,ei(s)),"isArray"),tc=ei;function nc(s){return typeof s!="object"?{}:s??{}}c(nc,"maybeObj");function Uf(s){if(!s)return!0;for(const e in s)return!1;return!0}c(Uf,"isEmptyObj");function Wf(s,e){return Object.prototype.hasOwnProperty.call(s,e)}c(Wf,"hasOwn");const Jf=c((s,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new F(`${s} must be an integer`);if(e<0)throw new F(`${s} must be a positive integer`);return e},"validatePositiveInteger"),sc=c(s=>{try{return JSON.parse(s)}catch{return}},"safeJSON"),Hf=c(s=>new Promise(e=>setTimeout(e,s)),"sleep"),Lt="0.62.0",Vf=c(()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u","isRunningInBrowser");function Gf(){return typeof Deno<"u"&&Deno.build!=null?"deno":typeof EdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}c(Gf,"getDetectedPlatform");const zf=c(()=>{const s=Gf();if(s==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Lt,"X-Stainless-OS":ic(Deno.build.os),"X-Stainless-Arch":rc(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Lt,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(s==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Lt,"X-Stainless-OS":ic(globalThis.process.platform??"unknown"),"X-Stainless-Arch":rc(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};const e=Yf();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Lt,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${e.browser}`,"X-Stainless-Runtime-Version":e.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Lt,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}},"getPlatformProperties");function Yf(){if(typeof navigator>"u"||!navigator)return null;const s=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(const{key:e,pattern:t}of s){const n=t.exec(navigator.userAgent);if(n){const r=n[1]||0,i=n[2]||0,o=n[3]||0;return{browser:e,version:`${r}.${i}.${o}`}}}return null}c(Yf,"getBrowserInfo");const rc=c(s=>s==="x32"?"x32":s==="x86_64"||s==="x64"?"x64":s==="arm"?"arm":s==="aarch64"||s==="arm64"?"arm64":s?`other:${s}`:"unknown","normalizeArch"),ic=c(s=>(s=s.toLowerCase(),s.includes("ios")?"iOS":s==="android"?"Android":s==="darwin"?"MacOS":s==="win32"?"Windows":s==="freebsd"?"FreeBSD":s==="openbsd"?"OpenBSD":s==="linux"?"Linux":s?`Other:${s}`:"Unknown"),"normalizePlatform");let oc;const Xf=c(()=>oc??(oc=zf()),"getPlatformHeaders");function Zf(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new Anthropic({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}c(Zf,"getDefaultFetch");function ac(...s){const e=globalThis.ReadableStream;if(typeof e>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new e(...s)}c(ac,"makeReadableStream");function cc(s){let e=Symbol.asyncIterator in s?s[Symbol.asyncIterator]():s[Symbol.iterator]();return ac({start(){},async pull(t){const{done:n,value:r}=await e.next();n?t.close():t.enqueue(r)},async cancel(){await e.return?.()}})}c(cc,"ReadableStreamFrom");function ti(s){if(s[Symbol.asyncIterator])return s;const e=s.getReader();return{async next(){try{const t=await e.read();return t?.done&&e.releaseLock(),t}catch(t){throw e.releaseLock(),t}},async return(){const t=e.cancel();return e.releaseLock(),await t,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}c(ti,"ReadableStreamToAsyncIterable");async function Qf(s){if(s===null||typeof s!="object")return;if(s[Symbol.asyncIterator]){await s[Symbol.asyncIterator]().return?.();return}const e=s.getReader(),t=e.cancel();e.releaseLock(),await t}c(Qf,"CancelReadableStream");const eh=c(({headers:s,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)}),"FallbackEncoder");function th(s){let e=0;for(const r of s)e+=r.length;const t=new Uint8Array(e);let n=0;for(const r of s)t.set(r,n),n+=r.length;return t}c(th,"concatBytes");let lc;function ni(s){let e;return(lc??(e=new globalThis.TextEncoder,lc=e.encode.bind(e)))(s)}c(ni,"encodeUTF8");let uc;function dc(s){let e;return(uc??(e=new globalThis.TextDecoder,uc=e.decode.bind(e)))(s)}c(dc,"decodeUTF8");var de,fe;class an{static{c(this,"LineDecoder")}constructor(){de.set(this,void 0),fe.set(this,void 0),L(this,de,new Uint8Array),L(this,fe,null)}decode(e){if(e==null)return[];const t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?ni(e):e;L(this,de,th([S(this,de,"f"),t]));const n=[];let r;for(;(r=nh(S(this,de,"f"),S(this,fe,"f")))!=null;){if(r.carriage&&S(this,fe,"f")==null){L(this,fe,r.index);continue}if(S(this,fe,"f")!=null&&(r.index!==S(this,fe,"f")+1||r.carriage)){n.push(dc(S(this,de,"f").subarray(0,S(this,fe,"f")-1))),L(this,de,S(this,de,"f").subarray(S(this,fe,"f"))),L(this,fe,null);continue}const i=S(this,fe,"f")!==null?r.preceding-1:r.preceding,o=dc(S(this,de,"f").subarray(0,i));n.push(o),L(this,de,S(this,de,"f").subarray(r.index)),L(this,fe,null)}return n}flush(){return S(this,de,"f").length?this.decode(`
158
158
  `):[]}}de=new WeakMap,fe=new WeakMap,an.NEWLINE_CHARS=new Set([`
159
- `,"\r"]),an.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function th(s,e){for(let r=e??0;r<s.length;r++){if(s[r]===10)return{preceding:r,index:r+1,carriage:!1};if(s[r]===13)return{preceding:r,index:r+1,carriage:!0}}return null}c(th,"findNewlineIndex");function nh(s){for(let n=0;n<s.length-1;n++){if(s[n]===10&&s[n+1]===10||s[n]===13&&s[n+1]===13)return n+2;if(s[n]===13&&s[n+1]===10&&n+3<s.length&&s[n+2]===13&&s[n+3]===10)return n+4}return-1}c(nh,"findDoubleNewlineIndex");const ws={off:0,error:200,warn:300,info:400,debug:500},dc=c((s,e,t)=>{if(s){if(Uf(ws,s))return s;ie(t).warn(`${e} was set to ${JSON.stringify(s)}, expected one of ${JSON.stringify(Object.keys(ws))}`)}},"parseLogLevel");function cn(){}c(cn,"noop");function bs(s,e,t){return!e||ws[s]>ws[t]?cn:e[s].bind(e)}c(bs,"makeLogFn");const sh={error:cn,warn:cn,info:cn,debug:cn};let fc=new WeakMap;function ie(s){const e=s.logger,t=s.logLevel??"off";if(!e)return sh;const n=fc.get(e);if(n&&n[0]===t)return n[1];const r={error:bs("error",e,t),warn:bs("warn",e,t),info:bs("info",e,t),debug:bs("debug",e,t)};return fc.set(e,[t,r]),r}c(ie,"loggerFor");const ut=c(s=>(s.options&&(s.options={...s.options},delete s.options.headers),s.headers&&(s.headers=Object.fromEntries((s.headers instanceof Headers?[...s.headers]:Object.entries(s.headers)).map(([e,t])=>[e,e.toLowerCase()==="x-api-key"||e.toLowerCase()==="authorization"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":t]))),"retryOfRequestLogID"in s&&(s.retryOfRequestLogID&&(s.retryOf=s.retryOfRequestLogID),delete s.retryOfRequestLogID),s),"formatRequestDetails");var ln;class Oe{static{c(this,"Stream")}constructor(e,t,n){this.iterator=e,ln.set(this,void 0),this.controller=t,L(this,ln,n)}static fromSSEResponse(e,t,n){let r=!1;const i=n?ie(n):console;async function*o(){if(r)throw new F("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");r=!0;let a=!1;try{for await(const l of rh(e,t)){if(l.event==="completion")try{yield JSON.parse(l.data)}catch(u){throw i.error("Could not parse message into JSON:",l.data),i.error("From chunk:",l.raw),u}if(l.event==="message_start"||l.event==="message_delta"||l.event==="message_stop"||l.event==="content_block_start"||l.event==="content_block_delta"||l.event==="content_block_stop")try{yield JSON.parse(l.data)}catch(u){throw i.error("Could not parse message into JSON:",l.data),i.error("From chunk:",l.raw),u}if(l.event!=="ping"&&l.event==="error")throw new re(void 0,nc(l.data)??l.data,void 0,e.headers)}a=!0}catch(l){if(on(l))return;throw l}finally{a||t.abort()}}return c(o,"iterator"),new Oe(o,t,n)}static fromReadableStream(e,t,n){let r=!1;async function*i(){const a=new an,l=ti(e);for await(const u of l)for(const d of a.decode(u))yield d;for(const u of a.flush())yield u}c(i,"iterLines");async function*o(){if(r)throw new F("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");r=!0;let a=!1;try{for await(const l of i())a||l&&(yield JSON.parse(l));a=!0}catch(l){if(on(l))return;throw l}finally{a||t.abort()}}return c(o,"iterator"),new Oe(o,t,n)}[(ln=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){const e=[],t=[],n=this.iterator(),r=c(i=>({next:c(()=>{if(i.length===0){const o=n.next();e.push(o),t.push(o)}return i.shift()},"next")}),"teeIterator");return[new Oe(()=>r(e),this.controller,S(this,ln,"f")),new Oe(()=>r(t),this.controller,S(this,ln,"f"))]}toReadableStream(){const e=this;let t;return oc({async start(){t=e[Symbol.asyncIterator]()},async pull(n){try{const{value:r,done:i}=await t.next();if(i)return n.close();const o=ni(JSON.stringify(r)+`
160
- `);n.enqueue(o)}catch(r){n.error(r)}},async cancel(){await t.return?.()}})}}async function*rh(s,e){if(!s.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new F("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new F("Attempted to iterate over a response with no body");const t=new oh,n=new an,r=ti(s.body);for await(const i of ih(r))for(const o of n.decode(i)){const a=t.decode(o);a&&(yield a)}for(const i of n.flush()){const o=t.decode(i);o&&(yield o)}}c(rh,"_iterSSEMessages");async function*ih(s){let e=new Uint8Array;for await(const t of s){if(t==null)continue;const n=t instanceof ArrayBuffer?new Uint8Array(t):typeof t=="string"?ni(t):t;let r=new Uint8Array(e.length+n.length);r.set(e),r.set(n,e.length),e=r;let i;for(;(i=nh(e))!==-1;)yield e.slice(0,i),e=e.slice(i)}e.length>0&&(yield e)}c(ih,"iterSSEChunks");class oh{static{c(this,"SSEDecoder")}constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;const i={event:this.event,data:this.data.join(`
161
- `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],i}if(this.chunks.push(e),e.startsWith(":"))return null;let[t,n,r]=ah(e,":");return r.startsWith(" ")&&(r=r.substring(1)),t==="event"?this.event=r:t==="data"&&this.data.push(r),null}}function ah(s,e){const t=s.indexOf(e);return t!==-1?[s.substring(0,t),e,s.substring(t+e.length)]:[s,"",""]}c(ah,"partition");async function hc(s,e){const{response:t,requestLogID:n,retryOfRequestLogID:r,startTime:i}=e,o=await(async()=>{if(e.options.stream)return ie(s).debug("response",t.status,t.url,t.headers,t.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(t,e.controller):Oe.fromSSEResponse(t,e.controller);if(t.status===204)return null;if(e.options.__binaryResponse)return t;const l=t.headers.get("content-type")?.split(";")[0]?.trim();if(l?.includes("application/json")||l?.endsWith("+json")){const f=await t.json();return pc(f,t)}return await t.text()})();return ie(s).debug(`[${n}] response parsed`,ut({retryOfRequestLogID:r,url:t.url,status:t.status,body:o,durationMs:Date.now()-i})),o}c(hc,"defaultParseResponse");function pc(s,e){return!s||typeof s!="object"||Array.isArray(s)?s:Object.defineProperty(s,"_request_id",{value:e.headers.get("request-id"),enumerable:!1})}c(pc,"addRequestID");var un;class Fs extends Promise{static{c(this,"APIPromise")}constructor(e,t,n=hc){super(r=>{r(null)}),this.responsePromise=t,this.parseResponse=n,un.set(this,void 0),L(this,un,e)}_thenUnwrap(e){return new Fs(S(this,un,"f"),this.responsePromise,async(t,n)=>pc(e(await this.parseResponse(t,n),n),n.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){const[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t,request_id:t.headers.get("request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(S(this,un,"f"),e))),this.parsedPromise}then(e,t){return this.parse().then(e,t)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}}un=new WeakMap;var Ss;class ch{static{c(this,"AbstractPage")}constructor(e,t,n,r){Ss.set(this,void 0),L(this,Ss,e),this.options=r,this.response=t,this.body=n}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){const e=this.nextPageRequestOptions();if(!e)throw new F("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await S(this,Ss,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(Ss=new WeakMap,Symbol.asyncIterator)](){for await(const e of this.iterPages())for(const t of e.getPaginatedItems())yield t}}class lh extends Fs{static{c(this,"PagePromise")}constructor(e,t,n){super(e,t,async(r,i)=>new n(r,i.response,await hc(r,i),i.options))}async*[Symbol.asyncIterator](){const e=await this;for await(const t of e)yield t}}class dn extends ch{static{c(this,"Page")}constructor(e,t,n,r){super(e,t,n,r),this.data=n.data||[],this.has_more=n.has_more||!1,this.first_id=n.first_id||null,this.last_id=n.last_id||null}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){if(this.options.query?.before_id){const t=this.first_id;return t?{...this.options,query:{...tc(this.options.query),before_id:t}}:null}const e=this.last_id;return e?{...this.options,query:{...tc(this.options.query),after_id:e}}:null}}const mc=c(()=>{if(typeof File>"u"){const{process:s}=globalThis,e=typeof s?.versions?.node=="string"&&parseInt(s.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(e?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}},"checkFileSupport");function Dt(s,e,t){return mc(),new File(s,e??"unknown_file",t)}c(Dt,"makeFile");function Cs(s){return(typeof s=="object"&&s!==null&&("name"in s&&s.name&&String(s.name)||"url"in s&&s.url&&String(s.url)||"filename"in s&&s.filename&&String(s.filename)||"path"in s&&s.path&&String(s.path))||"").split(/[\\/]/).pop()||void 0}c(Cs,"getName");const gc=c(s=>s!=null&&typeof s=="object"&&typeof s[Symbol.asyncIterator]=="function","isAsyncIterable"),uh=c(async(s,e)=>({...s,body:await fh(s.body,e)}),"multipartFormRequestOptions"),yc=new WeakMap;function dh(s){const e=typeof s=="function"?s:s.fetch,t=yc.get(e);if(t)return t;const n=(async()=>{try{const r="Response"in e?e.Response:(await e("data:,")).constructor,i=new FormData;return i.toString()!==await new r(i).text()}catch{return!0}})();return yc.set(e,n),n}c(dh,"supportsFormData");const fh=c(async(s,e)=>{if(!await dh(e))throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");const t=new FormData;return await Promise.all(Object.entries(s||{}).map(([n,r])=>si(t,n,r))),t},"createForm"),hh=c(s=>s instanceof Blob&&"name"in s,"isNamedBlob"),si=c(async(s,e,t)=>{if(t!==void 0){if(t==null)throw new TypeError(`Received null for "${e}"; to pass null in FormData, you must use the string 'null'`);if(typeof t=="string"||typeof t=="number"||typeof t=="boolean")s.append(e,String(t));else if(t instanceof Response){let n={};const r=t.headers.get("Content-Type");r&&(n={type:r}),s.append(e,Dt([await t.blob()],Cs(t),n))}else if(gc(t))s.append(e,Dt([await new Response(ac(t)).blob()],Cs(t)));else if(hh(t))s.append(e,Dt([t],Cs(t),{type:t.type}));else if(Array.isArray(t))await Promise.all(t.map(n=>si(s,e+"[]",n)));else if(typeof t=="object")await Promise.all(Object.entries(t).map(([n,r])=>si(s,`${e}[${n}]`,r)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${t} instead`)}},"addFormValue"),wc=c(s=>s!=null&&typeof s=="object"&&typeof s.size=="number"&&typeof s.type=="string"&&typeof s.text=="function"&&typeof s.slice=="function"&&typeof s.arrayBuffer=="function","isBlobLike"),ph=c(s=>s!=null&&typeof s=="object"&&typeof s.name=="string"&&typeof s.lastModified=="number"&&wc(s),"isFileLike"),mh=c(s=>s!=null&&typeof s=="object"&&typeof s.url=="string"&&typeof s.blob=="function","isResponseLike");async function gh(s,e,t){if(mc(),s=await s,e||(e=Cs(s)),ph(s))return s instanceof File&&e==null&&t==null?s:Dt([await s.arrayBuffer()],e??s.name,{type:s.type,lastModified:s.lastModified,...t});if(mh(s)){const r=await s.blob();return e||(e=new URL(s.url).pathname.split(/[\\/]/).pop()),Dt(await ri(r),e,t)}const n=await ri(s);if(!t?.type){const r=n.find(i=>typeof i=="object"&&"type"in i&&i.type);typeof r=="string"&&(t={...t,type:r})}return Dt(n,e,t)}c(gh,"toFile");async function ri(s){let e=[];if(typeof s=="string"||ArrayBuffer.isView(s)||s instanceof ArrayBuffer)e.push(s);else if(wc(s))e.push(s instanceof Blob?s:await s.arrayBuffer());else if(gc(s))for await(const t of s)e.push(...await ri(t));else{const t=s?.constructor?.name;throw new Error(`Unexpected data type: ${typeof s}${t?`; constructor: ${t}`:""}${yh(s)}`)}return e}c(ri,"getBytes");function yh(s){return typeof s!="object"||s===null?"":`; props: [${Object.getOwnPropertyNames(s).map(t=>`"${t}"`).join(", ")}]`}c(yh,"propsForError");class Le{static{c(this,"APIResource")}constructor(e){this._client=e}}const bc=Symbol.for("brand.privateNullableHeaders");function*wh(s){if(!s)return;if(bc in s){const{values:n,nulls:r}=s;yield*n.entries();for(const i of r)yield[i,null];return}let e=!1,t;s instanceof Headers?t=s.entries():ec(s)?t=s:(e=!0,t=Object.entries(s??{}));for(let n of t){const r=n[0];if(typeof r!="string")throw new TypeError("expected header name to be a string");const i=ec(n[1])?n[1]:[n[1]];let o=!1;for(const a of i)a!==void 0&&(e&&!o&&(o=!0,yield[r,null]),yield[r,a])}}c(wh,"iterateHeaders");const z=c(s=>{const e=new Headers,t=new Set;for(const n of s){const r=new Set;for(const[i,o]of wh(n)){const a=i.toLowerCase();r.has(a)||(e.delete(i),r.add(a)),o===null?(e.delete(i),t.add(a)):(e.append(i,o),t.delete(a))}}return{[bc]:!0,values:e,nulls:t}},"buildHeaders");function Sc(s){return s.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}c(Sc,"encodeURIPath");const Cc=Object.freeze(Object.create(null)),bh=c((s=Sc)=>c(function(t,...n){if(t.length===1)return t[0];let r=!1;const i=[],o=t.reduce((d,f,h)=>{/[?#]/.test(f)&&(r=!0);const g=n[h];let y=(r?encodeURIComponent:s)(""+g);return h!==n.length&&(g==null||typeof g=="object"&&g.toString===Object.getPrototypeOf(Object.getPrototypeOf(g.hasOwnProperty??Cc)??Cc)?.toString)&&(y=g+"",i.push({start:d.length+f.length,length:y.length,error:`Value of type ${Object.prototype.toString.call(g).slice(8,-1)} is not a valid path parameter`})),d+f+(h===n.length?"":y)},""),a=o.split(/[?#]/,1)[0],l=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi;let u;for(;(u=l.exec(a))!==null;)i.push({start:u.index,length:u[0].length,error:`Value "${u[0]}" can't be safely passed as a path parameter`});if(i.sort((d,f)=>d.start-f.start),i.length>0){let d=0;const f=i.reduce((h,g)=>{const y=" ".repeat(g.start-d),p="^".repeat(g.length);return d=g.start+g.length,h+y+p},"");throw new F(`Path parameters result in path with invalid segments:
159
+ `,"\r"]),an.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function nh(s,e){for(let r=e??0;r<s.length;r++){if(s[r]===10)return{preceding:r,index:r+1,carriage:!1};if(s[r]===13)return{preceding:r,index:r+1,carriage:!0}}return null}c(nh,"findNewlineIndex");function sh(s){for(let n=0;n<s.length-1;n++){if(s[n]===10&&s[n+1]===10||s[n]===13&&s[n+1]===13)return n+2;if(s[n]===13&&s[n+1]===10&&n+3<s.length&&s[n+2]===13&&s[n+3]===10)return n+4}return-1}c(sh,"findDoubleNewlineIndex");const ws={off:0,error:200,warn:300,info:400,debug:500},fc=c((s,e,t)=>{if(s){if(Wf(ws,s))return s;ie(t).warn(`${e} was set to ${JSON.stringify(s)}, expected one of ${JSON.stringify(Object.keys(ws))}`)}},"parseLogLevel");function cn(){}c(cn,"noop");function bs(s,e,t){return!e||ws[s]>ws[t]?cn:e[s].bind(e)}c(bs,"makeLogFn");const rh={error:cn,warn:cn,info:cn,debug:cn};let hc=new WeakMap;function ie(s){const e=s.logger,t=s.logLevel??"off";if(!e)return rh;const n=hc.get(e);if(n&&n[0]===t)return n[1];const r={error:bs("error",e,t),warn:bs("warn",e,t),info:bs("info",e,t),debug:bs("debug",e,t)};return hc.set(e,[t,r]),r}c(ie,"loggerFor");const ut=c(s=>(s.options&&(s.options={...s.options},delete s.options.headers),s.headers&&(s.headers=Object.fromEntries((s.headers instanceof Headers?[...s.headers]:Object.entries(s.headers)).map(([e,t])=>[e,e.toLowerCase()==="x-api-key"||e.toLowerCase()==="authorization"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":t]))),"retryOfRequestLogID"in s&&(s.retryOfRequestLogID&&(s.retryOf=s.retryOfRequestLogID),delete s.retryOfRequestLogID),s),"formatRequestDetails");var ln;class Oe{static{c(this,"Stream")}constructor(e,t,n){this.iterator=e,ln.set(this,void 0),this.controller=t,L(this,ln,n)}static fromSSEResponse(e,t,n){let r=!1;const i=n?ie(n):console;async function*o(){if(r)throw new F("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");r=!0;let a=!1;try{for await(const l of ih(e,t)){if(l.event==="completion")try{yield JSON.parse(l.data)}catch(u){throw i.error("Could not parse message into JSON:",l.data),i.error("From chunk:",l.raw),u}if(l.event==="message_start"||l.event==="message_delta"||l.event==="message_stop"||l.event==="content_block_start"||l.event==="content_block_delta"||l.event==="content_block_stop")try{yield JSON.parse(l.data)}catch(u){throw i.error("Could not parse message into JSON:",l.data),i.error("From chunk:",l.raw),u}if(l.event!=="ping"&&l.event==="error")throw new re(void 0,sc(l.data)??l.data,void 0,e.headers)}a=!0}catch(l){if(on(l))return;throw l}finally{a||t.abort()}}return c(o,"iterator"),new Oe(o,t,n)}static fromReadableStream(e,t,n){let r=!1;async function*i(){const a=new an,l=ti(e);for await(const u of l)for(const d of a.decode(u))yield d;for(const u of a.flush())yield u}c(i,"iterLines");async function*o(){if(r)throw new F("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");r=!0;let a=!1;try{for await(const l of i())a||l&&(yield JSON.parse(l));a=!0}catch(l){if(on(l))return;throw l}finally{a||t.abort()}}return c(o,"iterator"),new Oe(o,t,n)}[(ln=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){const e=[],t=[],n=this.iterator(),r=c(i=>({next:c(()=>{if(i.length===0){const o=n.next();e.push(o),t.push(o)}return i.shift()},"next")}),"teeIterator");return[new Oe(()=>r(e),this.controller,S(this,ln,"f")),new Oe(()=>r(t),this.controller,S(this,ln,"f"))]}toReadableStream(){const e=this;let t;return ac({async start(){t=e[Symbol.asyncIterator]()},async pull(n){try{const{value:r,done:i}=await t.next();if(i)return n.close();const o=ni(JSON.stringify(r)+`
160
+ `);n.enqueue(o)}catch(r){n.error(r)}},async cancel(){await t.return?.()}})}}async function*ih(s,e){if(!s.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new F("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new F("Attempted to iterate over a response with no body");const t=new ah,n=new an,r=ti(s.body);for await(const i of oh(r))for(const o of n.decode(i)){const a=t.decode(o);a&&(yield a)}for(const i of n.flush()){const o=t.decode(i);o&&(yield o)}}c(ih,"_iterSSEMessages");async function*oh(s){let e=new Uint8Array;for await(const t of s){if(t==null)continue;const n=t instanceof ArrayBuffer?new Uint8Array(t):typeof t=="string"?ni(t):t;let r=new Uint8Array(e.length+n.length);r.set(e),r.set(n,e.length),e=r;let i;for(;(i=sh(e))!==-1;)yield e.slice(0,i),e=e.slice(i)}e.length>0&&(yield e)}c(oh,"iterSSEChunks");class ah{static{c(this,"SSEDecoder")}constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;const i={event:this.event,data:this.data.join(`
161
+ `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],i}if(this.chunks.push(e),e.startsWith(":"))return null;let[t,n,r]=ch(e,":");return r.startsWith(" ")&&(r=r.substring(1)),t==="event"?this.event=r:t==="data"&&this.data.push(r),null}}function ch(s,e){const t=s.indexOf(e);return t!==-1?[s.substring(0,t),e,s.substring(t+e.length)]:[s,"",""]}c(ch,"partition");async function pc(s,e){const{response:t,requestLogID:n,retryOfRequestLogID:r,startTime:i}=e,o=await(async()=>{if(e.options.stream)return ie(s).debug("response",t.status,t.url,t.headers,t.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(t,e.controller):Oe.fromSSEResponse(t,e.controller);if(t.status===204)return null;if(e.options.__binaryResponse)return t;const l=t.headers.get("content-type")?.split(";")[0]?.trim();if(l?.includes("application/json")||l?.endsWith("+json")){const f=await t.json();return mc(f,t)}return await t.text()})();return ie(s).debug(`[${n}] response parsed`,ut({retryOfRequestLogID:r,url:t.url,status:t.status,body:o,durationMs:Date.now()-i})),o}c(pc,"defaultParseResponse");function mc(s,e){return!s||typeof s!="object"||Array.isArray(s)?s:Object.defineProperty(s,"_request_id",{value:e.headers.get("request-id"),enumerable:!1})}c(mc,"addRequestID");var un;class Fs extends Promise{static{c(this,"APIPromise")}constructor(e,t,n=pc){super(r=>{r(null)}),this.responsePromise=t,this.parseResponse=n,un.set(this,void 0),L(this,un,e)}_thenUnwrap(e){return new Fs(S(this,un,"f"),this.responsePromise,async(t,n)=>mc(e(await this.parseResponse(t,n),n),n.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){const[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t,request_id:t.headers.get("request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(S(this,un,"f"),e))),this.parsedPromise}then(e,t){return this.parse().then(e,t)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}}un=new WeakMap;var Ss;class lh{static{c(this,"AbstractPage")}constructor(e,t,n,r){Ss.set(this,void 0),L(this,Ss,e),this.options=r,this.response=t,this.body=n}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){const e=this.nextPageRequestOptions();if(!e)throw new F("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await S(this,Ss,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(Ss=new WeakMap,Symbol.asyncIterator)](){for await(const e of this.iterPages())for(const t of e.getPaginatedItems())yield t}}class uh extends Fs{static{c(this,"PagePromise")}constructor(e,t,n){super(e,t,async(r,i)=>new n(r,i.response,await pc(r,i),i.options))}async*[Symbol.asyncIterator](){const e=await this;for await(const t of e)yield t}}class dn extends lh{static{c(this,"Page")}constructor(e,t,n,r){super(e,t,n,r),this.data=n.data||[],this.has_more=n.has_more||!1,this.first_id=n.first_id||null,this.last_id=n.last_id||null}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){if(this.options.query?.before_id){const t=this.first_id;return t?{...this.options,query:{...nc(this.options.query),before_id:t}}:null}const e=this.last_id;return e?{...this.options,query:{...nc(this.options.query),after_id:e}}:null}}const gc=c(()=>{if(typeof File>"u"){const{process:s}=globalThis,e=typeof s?.versions?.node=="string"&&parseInt(s.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(e?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}},"checkFileSupport");function Dt(s,e,t){return gc(),new File(s,e??"unknown_file",t)}c(Dt,"makeFile");function Cs(s){return(typeof s=="object"&&s!==null&&("name"in s&&s.name&&String(s.name)||"url"in s&&s.url&&String(s.url)||"filename"in s&&s.filename&&String(s.filename)||"path"in s&&s.path&&String(s.path))||"").split(/[\\/]/).pop()||void 0}c(Cs,"getName");const yc=c(s=>s!=null&&typeof s=="object"&&typeof s[Symbol.asyncIterator]=="function","isAsyncIterable"),dh=c(async(s,e)=>({...s,body:await hh(s.body,e)}),"multipartFormRequestOptions"),wc=new WeakMap;function fh(s){const e=typeof s=="function"?s:s.fetch,t=wc.get(e);if(t)return t;const n=(async()=>{try{const r="Response"in e?e.Response:(await e("data:,")).constructor,i=new FormData;return i.toString()!==await new r(i).text()}catch{return!0}})();return wc.set(e,n),n}c(fh,"supportsFormData");const hh=c(async(s,e)=>{if(!await fh(e))throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");const t=new FormData;return await Promise.all(Object.entries(s||{}).map(([n,r])=>si(t,n,r))),t},"createForm"),ph=c(s=>s instanceof Blob&&"name"in s,"isNamedBlob"),si=c(async(s,e,t)=>{if(t!==void 0){if(t==null)throw new TypeError(`Received null for "${e}"; to pass null in FormData, you must use the string 'null'`);if(typeof t=="string"||typeof t=="number"||typeof t=="boolean")s.append(e,String(t));else if(t instanceof Response){let n={};const r=t.headers.get("Content-Type");r&&(n={type:r}),s.append(e,Dt([await t.blob()],Cs(t),n))}else if(yc(t))s.append(e,Dt([await new Response(cc(t)).blob()],Cs(t)));else if(ph(t))s.append(e,Dt([t],Cs(t),{type:t.type}));else if(Array.isArray(t))await Promise.all(t.map(n=>si(s,e+"[]",n)));else if(typeof t=="object")await Promise.all(Object.entries(t).map(([n,r])=>si(s,`${e}[${n}]`,r)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${t} instead`)}},"addFormValue"),bc=c(s=>s!=null&&typeof s=="object"&&typeof s.size=="number"&&typeof s.type=="string"&&typeof s.text=="function"&&typeof s.slice=="function"&&typeof s.arrayBuffer=="function","isBlobLike"),mh=c(s=>s!=null&&typeof s=="object"&&typeof s.name=="string"&&typeof s.lastModified=="number"&&bc(s),"isFileLike"),gh=c(s=>s!=null&&typeof s=="object"&&typeof s.url=="string"&&typeof s.blob=="function","isResponseLike");async function yh(s,e,t){if(gc(),s=await s,e||(e=Cs(s)),mh(s))return s instanceof File&&e==null&&t==null?s:Dt([await s.arrayBuffer()],e??s.name,{type:s.type,lastModified:s.lastModified,...t});if(gh(s)){const r=await s.blob();return e||(e=new URL(s.url).pathname.split(/[\\/]/).pop()),Dt(await ri(r),e,t)}const n=await ri(s);if(!t?.type){const r=n.find(i=>typeof i=="object"&&"type"in i&&i.type);typeof r=="string"&&(t={...t,type:r})}return Dt(n,e,t)}c(yh,"toFile");async function ri(s){let e=[];if(typeof s=="string"||ArrayBuffer.isView(s)||s instanceof ArrayBuffer)e.push(s);else if(bc(s))e.push(s instanceof Blob?s:await s.arrayBuffer());else if(yc(s))for await(const t of s)e.push(...await ri(t));else{const t=s?.constructor?.name;throw new Error(`Unexpected data type: ${typeof s}${t?`; constructor: ${t}`:""}${wh(s)}`)}return e}c(ri,"getBytes");function wh(s){return typeof s!="object"||s===null?"":`; props: [${Object.getOwnPropertyNames(s).map(t=>`"${t}"`).join(", ")}]`}c(wh,"propsForError");class Le{static{c(this,"APIResource")}constructor(e){this._client=e}}const Sc=Symbol.for("brand.privateNullableHeaders");function*bh(s){if(!s)return;if(Sc in s){const{values:n,nulls:r}=s;yield*n.entries();for(const i of r)yield[i,null];return}let e=!1,t;s instanceof Headers?t=s.entries():tc(s)?t=s:(e=!0,t=Object.entries(s??{}));for(let n of t){const r=n[0];if(typeof r!="string")throw new TypeError("expected header name to be a string");const i=tc(n[1])?n[1]:[n[1]];let o=!1;for(const a of i)a!==void 0&&(e&&!o&&(o=!0,yield[r,null]),yield[r,a])}}c(bh,"iterateHeaders");const z=c(s=>{const e=new Headers,t=new Set;for(const n of s){const r=new Set;for(const[i,o]of bh(n)){const a=i.toLowerCase();r.has(a)||(e.delete(i),r.add(a)),o===null?(e.delete(i),t.add(a)):(e.append(i,o),t.delete(a))}}return{[Sc]:!0,values:e,nulls:t}},"buildHeaders");function Cc(s){return s.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}c(Cc,"encodeURIPath");const vc=Object.freeze(Object.create(null)),Sh=c((s=Cc)=>c(function(t,...n){if(t.length===1)return t[0];let r=!1;const i=[],o=t.reduce((d,f,h)=>{/[?#]/.test(f)&&(r=!0);const g=n[h];let y=(r?encodeURIComponent:s)(""+g);return h!==n.length&&(g==null||typeof g=="object"&&g.toString===Object.getPrototypeOf(Object.getPrototypeOf(g.hasOwnProperty??vc)??vc)?.toString)&&(y=g+"",i.push({start:d.length+f.length,length:y.length,error:`Value of type ${Object.prototype.toString.call(g).slice(8,-1)} is not a valid path parameter`})),d+f+(h===n.length?"":y)},""),a=o.split(/[?#]/,1)[0],l=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi;let u;for(;(u=l.exec(a))!==null;)i.push({start:u.index,length:u[0].length,error:`Value "${u[0]}" can't be safely passed as a path parameter`});if(i.sort((d,f)=>d.start-f.start),i.length>0){let d=0;const f=i.reduce((h,g)=>{const y=" ".repeat(g.start-d),p="^".repeat(g.length);return d=g.start+g.length,h+y+p},"");throw new F(`Path parameters result in path with invalid segments:
162
162
  ${i.map(h=>h.error).join(`
163
163
  `)}
164
164
  ${o}
165
- ${f}`)}return o},"path2"),"createPathTagFunction"),Te=bh(Sc);class vc extends Le{static{c(this,"Files")}list(e={},t){const{betas:n,...r}=e??{};return this._client.getAPIList("/v1/files",dn,{query:r,...t,headers:z([{"anthropic-beta":[...n??[],"files-api-2025-04-14"].toString()},t?.headers])})}delete(e,t={},n){const{betas:r}=t??{};return this._client.delete(Te`/v1/files/${e}`,{...n,headers:z([{"anthropic-beta":[...r??[],"files-api-2025-04-14"].toString()},n?.headers])})}download(e,t={},n){const{betas:r}=t??{};return this._client.get(Te`/v1/files/${e}/content`,{...n,headers:z([{"anthropic-beta":[...r??[],"files-api-2025-04-14"].toString(),Accept:"application/binary"},n?.headers]),__binaryResponse:!0})}retrieveMetadata(e,t={},n){const{betas:r}=t??{};return this._client.get(Te`/v1/files/${e}`,{...n,headers:z([{"anthropic-beta":[...r??[],"files-api-2025-04-14"].toString()},n?.headers])})}upload(e,t){const{betas:n,...r}=e;return this._client.post("/v1/files",uh({body:r,...t,headers:z([{"anthropic-beta":[...n??[],"files-api-2025-04-14"].toString()},t?.headers])},this._client))}}let kc=class extends Le{static{c(this,"Models")}retrieve(e,t={},n){const{betas:r}=t??{};return this._client.get(Te`/v1/models/${e}?beta=true`,{...n,headers:z([{...r?.toString()!=null?{"anthropic-beta":r?.toString()}:void 0},n?.headers])})}list(e={},t){const{betas:n,...r}=e??{};return this._client.getAPIList("/v1/models?beta=true",dn,{query:r,...t,headers:z([{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void 0},t?.headers])})}};class qs{static{c(this,"JSONLDecoder")}constructor(e,t){this.iterator=e,this.controller=t}async*decoder(){const e=new an;for await(const t of this.iterator)for(const n of e.decode(t))yield JSON.parse(n);for(const t of e.flush())yield JSON.parse(t)}[Symbol.asyncIterator](){return this.decoder()}static fromResponse(e,t){if(!e.body)throw t.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new F("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new F("Attempted to iterate over a response with no body");return new qs(ti(e.body),t)}}let Tc=class extends Le{static{c(this,"Batches")}create(e,t){const{betas:n,...r}=e;return this._client.post("/v1/messages/batches?beta=true",{body:r,...t,headers:z([{"anthropic-beta":[...n??[],"message-batches-2024-09-24"].toString()},t?.headers])})}retrieve(e,t={},n){const{betas:r}=t??{};return this._client.get(Te`/v1/messages/batches/${e}?beta=true`,{...n,headers:z([{"anthropic-beta":[...r??[],"message-batches-2024-09-24"].toString()},n?.headers])})}list(e={},t){const{betas:n,...r}=e??{};return this._client.getAPIList("/v1/messages/batches?beta=true",dn,{query:r,...t,headers:z([{"anthropic-beta":[...n??[],"message-batches-2024-09-24"].toString()},t?.headers])})}delete(e,t={},n){const{betas:r}=t??{};return this._client.delete(Te`/v1/messages/batches/${e}?beta=true`,{...n,headers:z([{"anthropic-beta":[...r??[],"message-batches-2024-09-24"].toString()},n?.headers])})}cancel(e,t={},n){const{betas:r}=t??{};return this._client.post(Te`/v1/messages/batches/${e}/cancel?beta=true`,{...n,headers:z([{"anthropic-beta":[...r??[],"message-batches-2024-09-24"].toString()},n?.headers])})}async results(e,t={},n){const r=await this.retrieve(e);if(!r.results_url)throw new F(`No batch \`results_url\`; Has it finished processing? ${r.processing_status} - ${r.id}`);const{betas:i}=t??{};return this._client.get(r.results_url,{...n,headers:z([{"anthropic-beta":[...i??[],"message-batches-2024-09-24"].toString(),Accept:"application/binary"},n?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((o,a)=>qs.fromResponse(a.response,a.controller))}};const Sh=c(s=>{let e=0,t=[];for(;e<s.length;){let n=s[e];if(n==="\\"){e++;continue}if(n==="{"){t.push({type:"brace",value:"{"}),e++;continue}if(n==="}"){t.push({type:"brace",value:"}"}),e++;continue}if(n==="["){t.push({type:"paren",value:"["}),e++;continue}if(n==="]"){t.push({type:"paren",value:"]"}),e++;continue}if(n===":"){t.push({type:"separator",value:":"}),e++;continue}if(n===","){t.push({type:"delimiter",value:","}),e++;continue}if(n==='"'){let a="",l=!1;for(n=s[++e];n!=='"';){if(e===s.length){l=!0;break}if(n==="\\"){if(e++,e===s.length){l=!0;break}a+=n+s[e],n=s[++e]}else a+=n,n=s[++e]}n=s[++e],l||t.push({type:"string",value:a});continue}if(n&&/\s/.test(n)){e++;continue}let i=/[0-9]/;if(n&&i.test(n)||n==="-"||n==="."){let a="";for(n==="-"&&(a+=n,n=s[++e]);n&&i.test(n)||n===".";)a+=n,n=s[++e];t.push({type:"number",value:a});continue}let o=/[a-z]/i;if(n&&o.test(n)){let a="";for(;n&&o.test(n)&&e!==s.length;)a+=n,n=s[++e];if(a=="true"||a=="false"||a==="null")t.push({type:"name",value:a});else{e++;continue}continue}e++}return t},"tokenize"),jt=c(s=>{if(s.length===0)return s;let e=s[s.length-1];switch(e.type){case"separator":return s=s.slice(0,s.length-1),jt(s);case"number":let t=e.value[e.value.length-1];if(t==="."||t==="-")return s=s.slice(0,s.length-1),jt(s);case"string":let n=s[s.length-2];if(n?.type==="delimiter")return s=s.slice(0,s.length-1),jt(s);if(n?.type==="brace"&&n.value==="{")return s=s.slice(0,s.length-1),jt(s);break;case"delimiter":return s=s.slice(0,s.length-1),jt(s)}return s},"strip"),Ch=c(s=>{let e=[];return s.map(t=>{t.type==="brace"&&(t.value==="{"?e.push("}"):e.splice(e.lastIndexOf("}"),1)),t.type==="paren"&&(t.value==="["?e.push("]"):e.splice(e.lastIndexOf("]"),1))}),e.length>0&&e.reverse().map(t=>{t==="}"?s.push({type:"brace",value:"}"}):t==="]"&&s.push({type:"paren",value:"]"})}),s},"unstrip"),vh=c(s=>{let e="";return s.map(t=>{switch(t.type){case"string":e+='"'+t.value+'"';break;default:e+=t.value;break}}),e},"generate"),Ec=c(s=>JSON.parse(vh(Ch(jt(Sh(s))))),"partialParse");var we,ze,fn,vs,hn,pn,ks,mn,De,gn,Ts,Es,Ft,_s,Is,ii,_c,As,oi,ai,ci,Ic;const Ac="__json_buf";function Oc(s){return s.type==="tool_use"||s.type==="server_tool_use"||s.type==="mcp_tool_use"}c(Oc,"tracksToolInput$1");class Bs{static{c(this,"BetaMessageStream")}constructor(){we.add(this),this.messages=[],this.receivedMessages=[],ze.set(this,void 0),this.controller=new AbortController,fn.set(this,void 0),vs.set(this,()=>{}),hn.set(this,()=>{}),pn.set(this,void 0),ks.set(this,()=>{}),mn.set(this,()=>{}),De.set(this,{}),gn.set(this,!1),Ts.set(this,!1),Es.set(this,!1),Ft.set(this,!1),_s.set(this,void 0),Is.set(this,void 0),As.set(this,e=>{if(L(this,Ts,!0),on(e)&&(e=new ke),e instanceof ke)return L(this,Es,!0),this._emit("abort",e);if(e instanceof F)return this._emit("error",e);if(e instanceof Error){const t=new F(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new F(String(e)))}),L(this,fn,new Promise((e,t)=>{L(this,vs,e,"f"),L(this,hn,t,"f")})),L(this,pn,new Promise((e,t)=>{L(this,ks,e,"f"),L(this,mn,t,"f")})),S(this,fn,"f").catch(()=>{}),S(this,pn,"f").catch(()=>{})}get response(){return S(this,_s,"f")}get request_id(){return S(this,Is,"f")}async withResponse(){const e=await S(this,fn,"f");if(!e)throw new Error("Could not resolve a `Response` object");return{data:this,response:e,request_id:e.headers.get("request-id")}}static fromReadableStream(e){const t=new Bs;return t._run(()=>t._fromReadableStream(e)),t}static createMessage(e,t,n){const r=new Bs;for(const i of t.messages)r._addMessageParam(i);return r._run(()=>r._createMessage(e,{...t,stream:!0},{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),r}_run(e){e().then(()=>{this._emitFinal(),this._emit("end")},S(this,As,"f"))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,t=!0){this.receivedMessages.push(e),t&&this._emit("message",e)}async _createMessage(e,t,n){const r=n?.signal;let i;r&&(r.aborted&&this.controller.abort(),i=this.controller.abort.bind(this.controller),r.addEventListener("abort",i));try{S(this,we,"m",oi).call(this);const{response:o,data:a}=await e.create({...t,stream:!0},{...n,signal:this.controller.signal}).withResponse();this._connected(o);for await(const l of a)S(this,we,"m",ai).call(this,l);if(a.controller.signal?.aborted)throw new ke;S(this,we,"m",ci).call(this)}finally{r&&i&&r.removeEventListener("abort",i)}}_connected(e){this.ended||(L(this,_s,e),L(this,Is,e?.headers.get("request-id")),S(this,vs,"f").call(this,e),this._emit("connect"))}get ended(){return S(this,gn,"f")}get errored(){return S(this,Ts,"f")}get aborted(){return S(this,Es,"f")}abort(){this.controller.abort()}on(e,t){return(S(this,De,"f")[e]||(S(this,De,"f")[e]=[])).push({listener:t}),this}off(e,t){const n=S(this,De,"f")[e];if(!n)return this;const r=n.findIndex(i=>i.listener===t);return r>=0&&n.splice(r,1),this}once(e,t){return(S(this,De,"f")[e]||(S(this,De,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,n)=>{L(this,Ft,!0),e!=="error"&&this.once("error",n),this.once(e,t)})}async done(){L(this,Ft,!0),await S(this,pn,"f")}get currentMessage(){return S(this,ze,"f")}async finalMessage(){return await this.done(),S(this,we,"m",ii).call(this)}async finalText(){return await this.done(),S(this,we,"m",_c).call(this)}_emit(e,...t){if(S(this,gn,"f"))return;e==="end"&&(L(this,gn,!0),S(this,ks,"f").call(this));const n=S(this,De,"f")[e];if(n&&(S(this,De,"f")[e]=n.filter(r=>!r.once),n.forEach(({listener:r})=>r(...t))),e==="abort"){const r=t[0];!S(this,Ft,"f")&&!n?.length&&Promise.reject(r),S(this,hn,"f").call(this,r),S(this,mn,"f").call(this,r),this._emit("end");return}if(e==="error"){const r=t[0];!S(this,Ft,"f")&&!n?.length&&Promise.reject(r),S(this,hn,"f").call(this,r),S(this,mn,"f").call(this,r),this._emit("end")}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit("finalMessage",S(this,we,"m",ii).call(this))}async _fromReadableStream(e,t){const n=t?.signal;let r;n&&(n.aborted&&this.controller.abort(),r=this.controller.abort.bind(this.controller),n.addEventListener("abort",r));try{S(this,we,"m",oi).call(this),this._connected(null);const i=Oe.fromReadableStream(e,this.controller);for await(const o of i)S(this,we,"m",ai).call(this,o);if(i.controller.signal?.aborted)throw new ke;S(this,we,"m",ci).call(this)}finally{n&&r&&n.removeEventListener("abort",r)}}[(ze=new WeakMap,fn=new WeakMap,vs=new WeakMap,hn=new WeakMap,pn=new WeakMap,ks=new WeakMap,mn=new WeakMap,De=new WeakMap,gn=new WeakMap,Ts=new WeakMap,Es=new WeakMap,Ft=new WeakMap,_s=new WeakMap,Is=new WeakMap,As=new WeakMap,we=new WeakSet,ii=c(function(){if(this.receivedMessages.length===0)throw new F("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},"_BetaMessageStream_getFinalMessage2"),_c=c(function(){if(this.receivedMessages.length===0)throw new F("stream ended without producing a Message with role=assistant");const t=this.receivedMessages.at(-1).content.filter(n=>n.type==="text").map(n=>n.text);if(t.length===0)throw new F("stream ended without producing a content block with type=text");return t.join(" ")},"_BetaMessageStream_getFinalText2"),oi=c(function(){this.ended||L(this,ze,void 0)},"_BetaMessageStream_beginRequest2"),ai=c(function(t){if(this.ended)return;const n=S(this,we,"m",Ic).call(this,t);switch(this._emit("streamEvent",t,n),t.type){case"content_block_delta":{const r=n.content.at(-1);switch(t.delta.type){case"text_delta":{r.type==="text"&&this._emit("text",t.delta.text,r.text||"");break}case"citations_delta":{r.type==="text"&&this._emit("citation",t.delta.citation,r.citations??[]);break}case"input_json_delta":{Oc(r)&&r.input&&this._emit("inputJson",t.delta.partial_json,r.input);break}case"thinking_delta":{r.type==="thinking"&&this._emit("thinking",t.delta.thinking,r.thinking);break}case"signature_delta":{r.type==="thinking"&&this._emit("signature",r.signature);break}default:t.delta}break}case"message_stop":{this._addMessageParam(n),this._addMessage(n,!0);break}case"content_block_stop":{this._emit("contentBlock",n.content.at(-1));break}case"message_start":{L(this,ze,n);break}}},"_BetaMessageStream_addStreamEvent2"),ci=c(function(){if(this.ended)throw new F("stream has ended, this shouldn't happen");const t=S(this,ze,"f");if(!t)throw new F("request ended without sending any chunks");return L(this,ze,void 0),t},"_BetaMessageStream_endRequest2"),Ic=c(function(t){let n=S(this,ze,"f");if(t.type==="message_start"){if(n)throw new F(`Unexpected event order, got ${t.type} before receiving "message_stop"`);return t.message}if(!n)throw new F(`Unexpected event order, got ${t.type} before "message_start"`);switch(t.type){case"message_stop":return n;case"message_delta":return n.container=t.delta.container,n.stop_reason=t.delta.stop_reason,n.stop_sequence=t.delta.stop_sequence,n.usage.output_tokens=t.usage.output_tokens,t.usage.input_tokens!=null&&(n.usage.input_tokens=t.usage.input_tokens),t.usage.cache_creation_input_tokens!=null&&(n.usage.cache_creation_input_tokens=t.usage.cache_creation_input_tokens),t.usage.cache_read_input_tokens!=null&&(n.usage.cache_read_input_tokens=t.usage.cache_read_input_tokens),t.usage.server_tool_use!=null&&(n.usage.server_tool_use=t.usage.server_tool_use),n;case"content_block_start":return n.content.push(t.content_block),n;case"content_block_delta":{const r=n.content.at(t.index);switch(t.delta.type){case"text_delta":{r?.type==="text"&&(n.content[t.index]={...r,text:(r.text||"")+t.delta.text});break}case"citations_delta":{r?.type==="text"&&(n.content[t.index]={...r,citations:[...r.citations??[],t.delta.citation]});break}case"input_json_delta":{if(r&&Oc(r)){let i=r[Ac]||"";i+=t.delta.partial_json;const o={...r};if(Object.defineProperty(o,Ac,{value:i,enumerable:!1,writable:!0}),i)try{o.input=Ec(i)}catch(a){const l=new F(`Unable to parse tool parameter JSON from model. Please retry your request or adjust your prompt. Error: ${a}. JSON: ${i}`);S(this,As,"f").call(this,l)}n.content[t.index]=o}break}case"thinking_delta":{r?.type==="thinking"&&(n.content[t.index]={...r,thinking:r.thinking+t.delta.thinking});break}case"signature_delta":{r?.type==="thinking"&&(n.content[t.index]={...r,signature:t.delta.signature});break}default:t.delta}return n}case"content_block_stop":return n}},"_BetaMessageStream_accumulateMessage2"),Symbol.asyncIterator)](){const e=[],t=[];let n=!1;return this.on("streamEvent",r=>{const i=t.shift();i?i.resolve(r):e.push(r)}),this.on("end",()=>{n=!0;for(const r of t)r.resolve(void 0);t.length=0}),this.on("abort",r=>{n=!0;for(const i of t)i.reject(r);t.length=0}),this.on("error",r=>{n=!0;for(const i of t)i.reject(r);t.length=0}),{next:c(async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((i,o)=>t.push({resolve:i,reject:o})).then(i=>i?{value:i,done:!1}:{value:void 0,done:!0}),"next"),return:c(async()=>(this.abort(),{value:void 0,done:!0}),"return")}}toReadableStream(){return new Oe(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function Pp(s){}c(Pp,"checkNever$1");const $c={"claude-opus-4-20250514":8192,"claude-opus-4-0":8192,"claude-4-opus-20250514":8192,"anthropic.claude-opus-4-20250514-v1:0":8192,"claude-opus-4@20250514":8192,"claude-opus-4-1-20250805":8192,"anthropic.claude-opus-4-1-20250805-v1:0":8192,"claude-opus-4-1@20250805":8192},Nc={"claude-1.3":"November 6th, 2024","claude-1.3-100k":"November 6th, 2024","claude-instant-1.1":"November 6th, 2024","claude-instant-1.1-100k":"November 6th, 2024","claude-instant-1.2":"November 6th, 2024","claude-3-sonnet-20240229":"July 21st, 2025","claude-3-opus-20240229":"January 5th, 2026","claude-2.1":"July 21st, 2025","claude-2.0":"July 21st, 2025","claude-3-5-sonnet-20241022":"October 22, 2025","claude-3-5-sonnet-20240620":"October 22, 2025"};let li=class extends Le{static{c(this,"Messages")}constructor(){super(...arguments),this.batches=new Tc(this._client)}create(e,t){const{betas:n,...r}=e;r.model in Nc&&console.warn(`The model '${r.model}' is deprecated and will reach end-of-life on ${Nc[r.model]}
166
- Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);let i=this._client._options.timeout;if(!r.stream&&i==null){const o=$c[r.model]??void 0;i=this._client.calculateNonstreamingTimeout(r.max_tokens,o)}return this._client.post("/v1/messages?beta=true",{body:r,timeout:i??6e5,...t,headers:z([{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void 0},t?.headers]),stream:e.stream??!1})}stream(e,t){return Bs.createMessage(this,e,t)}countTokens(e,t){const{betas:n,...r}=e;return this._client.post("/v1/messages/count_tokens?beta=true",{body:r,...t,headers:z([{"anthropic-beta":[...n??[],"token-counting-2024-11-01"].toString()},t?.headers])})}};li.Batches=Tc;class yn extends Le{static{c(this,"Beta")}constructor(){super(...arguments),this.models=new kc(this._client),this.messages=new li(this._client),this.files=new vc(this._client)}}yn.Models=kc,yn.Messages=li,yn.Files=vc;class xc extends Le{static{c(this,"Completions")}create(e,t){const{betas:n,...r}=e;return this._client.post("/v1/complete",{body:r,timeout:this._client._options.timeout??6e5,...t,headers:z([{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void 0},t?.headers]),stream:e.stream??!1})}}var be,Ye,wn,Os,bn,Sn,$s,Cn,je,vn,Ns,xs,qt,Ps,Ms,ui,Pc,di,fi,hi,pi,Mc;const Rc="__json_buf";function Lc(s){return s.type==="tool_use"||s.type==="server_tool_use"}c(Lc,"tracksToolInput");class Ks{static{c(this,"MessageStream")}constructor(){be.add(this),this.messages=[],this.receivedMessages=[],Ye.set(this,void 0),this.controller=new AbortController,wn.set(this,void 0),Os.set(this,()=>{}),bn.set(this,()=>{}),Sn.set(this,void 0),$s.set(this,()=>{}),Cn.set(this,()=>{}),je.set(this,{}),vn.set(this,!1),Ns.set(this,!1),xs.set(this,!1),qt.set(this,!1),Ps.set(this,void 0),Ms.set(this,void 0),di.set(this,e=>{if(L(this,Ns,!0),on(e)&&(e=new ke),e instanceof ke)return L(this,xs,!0),this._emit("abort",e);if(e instanceof F)return this._emit("error",e);if(e instanceof Error){const t=new F(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new F(String(e)))}),L(this,wn,new Promise((e,t)=>{L(this,Os,e,"f"),L(this,bn,t,"f")})),L(this,Sn,new Promise((e,t)=>{L(this,$s,e,"f"),L(this,Cn,t,"f")})),S(this,wn,"f").catch(()=>{}),S(this,Sn,"f").catch(()=>{})}get response(){return S(this,Ps,"f")}get request_id(){return S(this,Ms,"f")}async withResponse(){const e=await S(this,wn,"f");if(!e)throw new Error("Could not resolve a `Response` object");return{data:this,response:e,request_id:e.headers.get("request-id")}}static fromReadableStream(e){const t=new Ks;return t._run(()=>t._fromReadableStream(e)),t}static createMessage(e,t,n){const r=new Ks;for(const i of t.messages)r._addMessageParam(i);return r._run(()=>r._createMessage(e,{...t,stream:!0},{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),r}_run(e){e().then(()=>{this._emitFinal(),this._emit("end")},S(this,di,"f"))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,t=!0){this.receivedMessages.push(e),t&&this._emit("message",e)}async _createMessage(e,t,n){const r=n?.signal;let i;r&&(r.aborted&&this.controller.abort(),i=this.controller.abort.bind(this.controller),r.addEventListener("abort",i));try{S(this,be,"m",fi).call(this);const{response:o,data:a}=await e.create({...t,stream:!0},{...n,signal:this.controller.signal}).withResponse();this._connected(o);for await(const l of a)S(this,be,"m",hi).call(this,l);if(a.controller.signal?.aborted)throw new ke;S(this,be,"m",pi).call(this)}finally{r&&i&&r.removeEventListener("abort",i)}}_connected(e){this.ended||(L(this,Ps,e),L(this,Ms,e?.headers.get("request-id")),S(this,Os,"f").call(this,e),this._emit("connect"))}get ended(){return S(this,vn,"f")}get errored(){return S(this,Ns,"f")}get aborted(){return S(this,xs,"f")}abort(){this.controller.abort()}on(e,t){return(S(this,je,"f")[e]||(S(this,je,"f")[e]=[])).push({listener:t}),this}off(e,t){const n=S(this,je,"f")[e];if(!n)return this;const r=n.findIndex(i=>i.listener===t);return r>=0&&n.splice(r,1),this}once(e,t){return(S(this,je,"f")[e]||(S(this,je,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,n)=>{L(this,qt,!0),e!=="error"&&this.once("error",n),this.once(e,t)})}async done(){L(this,qt,!0),await S(this,Sn,"f")}get currentMessage(){return S(this,Ye,"f")}async finalMessage(){return await this.done(),S(this,be,"m",ui).call(this)}async finalText(){return await this.done(),S(this,be,"m",Pc).call(this)}_emit(e,...t){if(S(this,vn,"f"))return;e==="end"&&(L(this,vn,!0),S(this,$s,"f").call(this));const n=S(this,je,"f")[e];if(n&&(S(this,je,"f")[e]=n.filter(r=>!r.once),n.forEach(({listener:r})=>r(...t))),e==="abort"){const r=t[0];!S(this,qt,"f")&&!n?.length&&Promise.reject(r),S(this,bn,"f").call(this,r),S(this,Cn,"f").call(this,r),this._emit("end");return}if(e==="error"){const r=t[0];!S(this,qt,"f")&&!n?.length&&Promise.reject(r),S(this,bn,"f").call(this,r),S(this,Cn,"f").call(this,r),this._emit("end")}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit("finalMessage",S(this,be,"m",ui).call(this))}async _fromReadableStream(e,t){const n=t?.signal;let r;n&&(n.aborted&&this.controller.abort(),r=this.controller.abort.bind(this.controller),n.addEventListener("abort",r));try{S(this,be,"m",fi).call(this),this._connected(null);const i=Oe.fromReadableStream(e,this.controller);for await(const o of i)S(this,be,"m",hi).call(this,o);if(i.controller.signal?.aborted)throw new ke;S(this,be,"m",pi).call(this)}finally{n&&r&&n.removeEventListener("abort",r)}}[(Ye=new WeakMap,wn=new WeakMap,Os=new WeakMap,bn=new WeakMap,Sn=new WeakMap,$s=new WeakMap,Cn=new WeakMap,je=new WeakMap,vn=new WeakMap,Ns=new WeakMap,xs=new WeakMap,qt=new WeakMap,Ps=new WeakMap,Ms=new WeakMap,di=new WeakMap,be=new WeakSet,ui=c(function(){if(this.receivedMessages.length===0)throw new F("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},"_MessageStream_getFinalMessage2"),Pc=c(function(){if(this.receivedMessages.length===0)throw new F("stream ended without producing a Message with role=assistant");const t=this.receivedMessages.at(-1).content.filter(n=>n.type==="text").map(n=>n.text);if(t.length===0)throw new F("stream ended without producing a content block with type=text");return t.join(" ")},"_MessageStream_getFinalText2"),fi=c(function(){this.ended||L(this,Ye,void 0)},"_MessageStream_beginRequest2"),hi=c(function(t){if(this.ended)return;const n=S(this,be,"m",Mc).call(this,t);switch(this._emit("streamEvent",t,n),t.type){case"content_block_delta":{const r=n.content.at(-1);switch(t.delta.type){case"text_delta":{r.type==="text"&&this._emit("text",t.delta.text,r.text||"");break}case"citations_delta":{r.type==="text"&&this._emit("citation",t.delta.citation,r.citations??[]);break}case"input_json_delta":{Lc(r)&&r.input&&this._emit("inputJson",t.delta.partial_json,r.input);break}case"thinking_delta":{r.type==="thinking"&&this._emit("thinking",t.delta.thinking,r.thinking);break}case"signature_delta":{r.type==="thinking"&&this._emit("signature",r.signature);break}default:t.delta}break}case"message_stop":{this._addMessageParam(n),this._addMessage(n,!0);break}case"content_block_stop":{this._emit("contentBlock",n.content.at(-1));break}case"message_start":{L(this,Ye,n);break}}},"_MessageStream_addStreamEvent2"),pi=c(function(){if(this.ended)throw new F("stream has ended, this shouldn't happen");const t=S(this,Ye,"f");if(!t)throw new F("request ended without sending any chunks");return L(this,Ye,void 0),t},"_MessageStream_endRequest2"),Mc=c(function(t){let n=S(this,Ye,"f");if(t.type==="message_start"){if(n)throw new F(`Unexpected event order, got ${t.type} before receiving "message_stop"`);return t.message}if(!n)throw new F(`Unexpected event order, got ${t.type} before "message_start"`);switch(t.type){case"message_stop":return n;case"message_delta":return n.stop_reason=t.delta.stop_reason,n.stop_sequence=t.delta.stop_sequence,n.usage.output_tokens=t.usage.output_tokens,t.usage.input_tokens!=null&&(n.usage.input_tokens=t.usage.input_tokens),t.usage.cache_creation_input_tokens!=null&&(n.usage.cache_creation_input_tokens=t.usage.cache_creation_input_tokens),t.usage.cache_read_input_tokens!=null&&(n.usage.cache_read_input_tokens=t.usage.cache_read_input_tokens),t.usage.server_tool_use!=null&&(n.usage.server_tool_use=t.usage.server_tool_use),n;case"content_block_start":return n.content.push({...t.content_block}),n;case"content_block_delta":{const r=n.content.at(t.index);switch(t.delta.type){case"text_delta":{r?.type==="text"&&(n.content[t.index]={...r,text:(r.text||"")+t.delta.text});break}case"citations_delta":{r?.type==="text"&&(n.content[t.index]={...r,citations:[...r.citations??[],t.delta.citation]});break}case"input_json_delta":{if(r&&Lc(r)){let i=r[Rc]||"";i+=t.delta.partial_json;const o={...r};Object.defineProperty(o,Rc,{value:i,enumerable:!1,writable:!0}),i&&(o.input=Ec(i)),n.content[t.index]=o}break}case"thinking_delta":{r?.type==="thinking"&&(n.content[t.index]={...r,thinking:r.thinking+t.delta.thinking});break}case"signature_delta":{r?.type==="thinking"&&(n.content[t.index]={...r,signature:t.delta.signature});break}default:t.delta}return n}case"content_block_stop":return n}},"_MessageStream_accumulateMessage2"),Symbol.asyncIterator)](){const e=[],t=[];let n=!1;return this.on("streamEvent",r=>{const i=t.shift();i?i.resolve(r):e.push(r)}),this.on("end",()=>{n=!0;for(const r of t)r.resolve(void 0);t.length=0}),this.on("abort",r=>{n=!0;for(const i of t)i.reject(r);t.length=0}),this.on("error",r=>{n=!0;for(const i of t)i.reject(r);t.length=0}),{next:c(async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((i,o)=>t.push({resolve:i,reject:o})).then(i=>i?{value:i,done:!1}:{value:void 0,done:!0}),"next"),return:c(async()=>(this.abort(),{value:void 0,done:!0}),"return")}}toReadableStream(){return new Oe(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function Rp(s){}c(Rp,"checkNever");class Dc extends Le{static{c(this,"Batches")}create(e,t){return this._client.post("/v1/messages/batches",{body:e,...t})}retrieve(e,t){return this._client.get(Te`/v1/messages/batches/${e}`,t)}list(e={},t){return this._client.getAPIList("/v1/messages/batches",dn,{query:e,...t})}delete(e,t){return this._client.delete(Te`/v1/messages/batches/${e}`,t)}cancel(e,t){return this._client.post(Te`/v1/messages/batches/${e}/cancel`,t)}async results(e,t){const n=await this.retrieve(e);if(!n.results_url)throw new F(`No batch \`results_url\`; Has it finished processing? ${n.processing_status} - ${n.id}`);return this._client.get(n.results_url,{...t,headers:z([{Accept:"application/binary"},t?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((r,i)=>qs.fromResponse(i.response,i.controller))}}class mi extends Le{static{c(this,"Messages")}constructor(){super(...arguments),this.batches=new Dc(this._client)}create(e,t){e.model in jc&&console.warn(`The model '${e.model}' is deprecated and will reach end-of-life on ${jc[e.model]}
167
- Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);let n=this._client._options.timeout;if(!e.stream&&n==null){const r=$c[e.model]??void 0;n=this._client.calculateNonstreamingTimeout(e.max_tokens,r)}return this._client.post("/v1/messages",{body:e,timeout:n??6e5,...t,stream:e.stream??!1})}stream(e,t){return Ks.createMessage(this,e,t)}countTokens(e,t){return this._client.post("/v1/messages/count_tokens",{body:e,...t})}}const jc={"claude-1.3":"November 6th, 2024","claude-1.3-100k":"November 6th, 2024","claude-instant-1.1":"November 6th, 2024","claude-instant-1.1-100k":"November 6th, 2024","claude-instant-1.2":"November 6th, 2024","claude-3-sonnet-20240229":"July 21st, 2025","claude-3-opus-20240229":"January 5th, 2026","claude-2.1":"July 21st, 2025","claude-2.0":"July 21st, 2025","claude-3-5-sonnet-20241022":"October 22, 2025","claude-3-5-sonnet-20240620":"October 22, 2025"};mi.Batches=Dc;class Fc extends Le{static{c(this,"Models")}retrieve(e,t={},n){const{betas:r}=t??{};return this._client.get(Te`/v1/models/${e}`,{...n,headers:z([{...r?.toString()!=null?{"anthropic-beta":r?.toString()}:void 0},n?.headers])})}list(e={},t){const{betas:n,...r}=e??{};return this._client.getAPIList("/v1/models",dn,{query:r,...t,headers:z([{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void 0},t?.headers])})}}const Rs=c(s=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[s]?.trim()??void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(s)?.trim()},"readEnv");var gi,yi,Ls,qc;const kh="\\n\\nHuman:",Th="\\n\\nAssistant:";class ee{static{c(this,"BaseAnthropic")}constructor({baseURL:e=Rs("ANTHROPIC_BASE_URL"),apiKey:t=Rs("ANTHROPIC_API_KEY")??null,authToken:n=Rs("ANTHROPIC_AUTH_TOKEN")??null,...r}={}){gi.add(this),Ls.set(this,void 0);const i={apiKey:t,authToken:n,...r,baseURL:e||"https://api.anthropic.com"};if(!i.dangerouslyAllowBrowser&&Hf())throw new F(`It looks like you're running in a browser-like environment.
165
+ ${f}`)}return o},"path2"),"createPathTagFunction"),Te=Sh(Cc);class kc extends Le{static{c(this,"Files")}list(e={},t){const{betas:n,...r}=e??{};return this._client.getAPIList("/v1/files",dn,{query:r,...t,headers:z([{"anthropic-beta":[...n??[],"files-api-2025-04-14"].toString()},t?.headers])})}delete(e,t={},n){const{betas:r}=t??{};return this._client.delete(Te`/v1/files/${e}`,{...n,headers:z([{"anthropic-beta":[...r??[],"files-api-2025-04-14"].toString()},n?.headers])})}download(e,t={},n){const{betas:r}=t??{};return this._client.get(Te`/v1/files/${e}/content`,{...n,headers:z([{"anthropic-beta":[...r??[],"files-api-2025-04-14"].toString(),Accept:"application/binary"},n?.headers]),__binaryResponse:!0})}retrieveMetadata(e,t={},n){const{betas:r}=t??{};return this._client.get(Te`/v1/files/${e}`,{...n,headers:z([{"anthropic-beta":[...r??[],"files-api-2025-04-14"].toString()},n?.headers])})}upload(e,t){const{betas:n,...r}=e;return this._client.post("/v1/files",dh({body:r,...t,headers:z([{"anthropic-beta":[...n??[],"files-api-2025-04-14"].toString()},t?.headers])},this._client))}}let Tc=class extends Le{static{c(this,"Models")}retrieve(e,t={},n){const{betas:r}=t??{};return this._client.get(Te`/v1/models/${e}?beta=true`,{...n,headers:z([{...r?.toString()!=null?{"anthropic-beta":r?.toString()}:void 0},n?.headers])})}list(e={},t){const{betas:n,...r}=e??{};return this._client.getAPIList("/v1/models?beta=true",dn,{query:r,...t,headers:z([{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void 0},t?.headers])})}};class qs{static{c(this,"JSONLDecoder")}constructor(e,t){this.iterator=e,this.controller=t}async*decoder(){const e=new an;for await(const t of this.iterator)for(const n of e.decode(t))yield JSON.parse(n);for(const t of e.flush())yield JSON.parse(t)}[Symbol.asyncIterator](){return this.decoder()}static fromResponse(e,t){if(!e.body)throw t.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new F("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new F("Attempted to iterate over a response with no body");return new qs(ti(e.body),t)}}let Ec=class extends Le{static{c(this,"Batches")}create(e,t){const{betas:n,...r}=e;return this._client.post("/v1/messages/batches?beta=true",{body:r,...t,headers:z([{"anthropic-beta":[...n??[],"message-batches-2024-09-24"].toString()},t?.headers])})}retrieve(e,t={},n){const{betas:r}=t??{};return this._client.get(Te`/v1/messages/batches/${e}?beta=true`,{...n,headers:z([{"anthropic-beta":[...r??[],"message-batches-2024-09-24"].toString()},n?.headers])})}list(e={},t){const{betas:n,...r}=e??{};return this._client.getAPIList("/v1/messages/batches?beta=true",dn,{query:r,...t,headers:z([{"anthropic-beta":[...n??[],"message-batches-2024-09-24"].toString()},t?.headers])})}delete(e,t={},n){const{betas:r}=t??{};return this._client.delete(Te`/v1/messages/batches/${e}?beta=true`,{...n,headers:z([{"anthropic-beta":[...r??[],"message-batches-2024-09-24"].toString()},n?.headers])})}cancel(e,t={},n){const{betas:r}=t??{};return this._client.post(Te`/v1/messages/batches/${e}/cancel?beta=true`,{...n,headers:z([{"anthropic-beta":[...r??[],"message-batches-2024-09-24"].toString()},n?.headers])})}async results(e,t={},n){const r=await this.retrieve(e);if(!r.results_url)throw new F(`No batch \`results_url\`; Has it finished processing? ${r.processing_status} - ${r.id}`);const{betas:i}=t??{};return this._client.get(r.results_url,{...n,headers:z([{"anthropic-beta":[...i??[],"message-batches-2024-09-24"].toString(),Accept:"application/binary"},n?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((o,a)=>qs.fromResponse(a.response,a.controller))}};const Ch=c(s=>{let e=0,t=[];for(;e<s.length;){let n=s[e];if(n==="\\"){e++;continue}if(n==="{"){t.push({type:"brace",value:"{"}),e++;continue}if(n==="}"){t.push({type:"brace",value:"}"}),e++;continue}if(n==="["){t.push({type:"paren",value:"["}),e++;continue}if(n==="]"){t.push({type:"paren",value:"]"}),e++;continue}if(n===":"){t.push({type:"separator",value:":"}),e++;continue}if(n===","){t.push({type:"delimiter",value:","}),e++;continue}if(n==='"'){let a="",l=!1;for(n=s[++e];n!=='"';){if(e===s.length){l=!0;break}if(n==="\\"){if(e++,e===s.length){l=!0;break}a+=n+s[e],n=s[++e]}else a+=n,n=s[++e]}n=s[++e],l||t.push({type:"string",value:a});continue}if(n&&/\s/.test(n)){e++;continue}let i=/[0-9]/;if(n&&i.test(n)||n==="-"||n==="."){let a="";for(n==="-"&&(a+=n,n=s[++e]);n&&i.test(n)||n===".";)a+=n,n=s[++e];t.push({type:"number",value:a});continue}let o=/[a-z]/i;if(n&&o.test(n)){let a="";for(;n&&o.test(n)&&e!==s.length;)a+=n,n=s[++e];if(a=="true"||a=="false"||a==="null")t.push({type:"name",value:a});else{e++;continue}continue}e++}return t},"tokenize"),jt=c(s=>{if(s.length===0)return s;let e=s[s.length-1];switch(e.type){case"separator":return s=s.slice(0,s.length-1),jt(s);case"number":let t=e.value[e.value.length-1];if(t==="."||t==="-")return s=s.slice(0,s.length-1),jt(s);case"string":let n=s[s.length-2];if(n?.type==="delimiter")return s=s.slice(0,s.length-1),jt(s);if(n?.type==="brace"&&n.value==="{")return s=s.slice(0,s.length-1),jt(s);break;case"delimiter":return s=s.slice(0,s.length-1),jt(s)}return s},"strip"),vh=c(s=>{let e=[];return s.map(t=>{t.type==="brace"&&(t.value==="{"?e.push("}"):e.splice(e.lastIndexOf("}"),1)),t.type==="paren"&&(t.value==="["?e.push("]"):e.splice(e.lastIndexOf("]"),1))}),e.length>0&&e.reverse().map(t=>{t==="}"?s.push({type:"brace",value:"}"}):t==="]"&&s.push({type:"paren",value:"]"})}),s},"unstrip"),kh=c(s=>{let e="";return s.map(t=>{switch(t.type){case"string":e+='"'+t.value+'"';break;default:e+=t.value;break}}),e},"generate"),_c=c(s=>JSON.parse(kh(vh(jt(Ch(s))))),"partialParse");var we,ze,fn,vs,hn,pn,ks,mn,De,gn,Ts,Es,Ft,_s,Is,ii,Ic,As,oi,ai,ci,Ac;const Oc="__json_buf";function $c(s){return s.type==="tool_use"||s.type==="server_tool_use"||s.type==="mcp_tool_use"}c($c,"tracksToolInput$1");class Bs{static{c(this,"BetaMessageStream")}constructor(){we.add(this),this.messages=[],this.receivedMessages=[],ze.set(this,void 0),this.controller=new AbortController,fn.set(this,void 0),vs.set(this,()=>{}),hn.set(this,()=>{}),pn.set(this,void 0),ks.set(this,()=>{}),mn.set(this,()=>{}),De.set(this,{}),gn.set(this,!1),Ts.set(this,!1),Es.set(this,!1),Ft.set(this,!1),_s.set(this,void 0),Is.set(this,void 0),As.set(this,e=>{if(L(this,Ts,!0),on(e)&&(e=new ke),e instanceof ke)return L(this,Es,!0),this._emit("abort",e);if(e instanceof F)return this._emit("error",e);if(e instanceof Error){const t=new F(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new F(String(e)))}),L(this,fn,new Promise((e,t)=>{L(this,vs,e,"f"),L(this,hn,t,"f")})),L(this,pn,new Promise((e,t)=>{L(this,ks,e,"f"),L(this,mn,t,"f")})),S(this,fn,"f").catch(()=>{}),S(this,pn,"f").catch(()=>{})}get response(){return S(this,_s,"f")}get request_id(){return S(this,Is,"f")}async withResponse(){const e=await S(this,fn,"f");if(!e)throw new Error("Could not resolve a `Response` object");return{data:this,response:e,request_id:e.headers.get("request-id")}}static fromReadableStream(e){const t=new Bs;return t._run(()=>t._fromReadableStream(e)),t}static createMessage(e,t,n){const r=new Bs;for(const i of t.messages)r._addMessageParam(i);return r._run(()=>r._createMessage(e,{...t,stream:!0},{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),r}_run(e){e().then(()=>{this._emitFinal(),this._emit("end")},S(this,As,"f"))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,t=!0){this.receivedMessages.push(e),t&&this._emit("message",e)}async _createMessage(e,t,n){const r=n?.signal;let i;r&&(r.aborted&&this.controller.abort(),i=this.controller.abort.bind(this.controller),r.addEventListener("abort",i));try{S(this,we,"m",oi).call(this);const{response:o,data:a}=await e.create({...t,stream:!0},{...n,signal:this.controller.signal}).withResponse();this._connected(o);for await(const l of a)S(this,we,"m",ai).call(this,l);if(a.controller.signal?.aborted)throw new ke;S(this,we,"m",ci).call(this)}finally{r&&i&&r.removeEventListener("abort",i)}}_connected(e){this.ended||(L(this,_s,e),L(this,Is,e?.headers.get("request-id")),S(this,vs,"f").call(this,e),this._emit("connect"))}get ended(){return S(this,gn,"f")}get errored(){return S(this,Ts,"f")}get aborted(){return S(this,Es,"f")}abort(){this.controller.abort()}on(e,t){return(S(this,De,"f")[e]||(S(this,De,"f")[e]=[])).push({listener:t}),this}off(e,t){const n=S(this,De,"f")[e];if(!n)return this;const r=n.findIndex(i=>i.listener===t);return r>=0&&n.splice(r,1),this}once(e,t){return(S(this,De,"f")[e]||(S(this,De,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,n)=>{L(this,Ft,!0),e!=="error"&&this.once("error",n),this.once(e,t)})}async done(){L(this,Ft,!0),await S(this,pn,"f")}get currentMessage(){return S(this,ze,"f")}async finalMessage(){return await this.done(),S(this,we,"m",ii).call(this)}async finalText(){return await this.done(),S(this,we,"m",Ic).call(this)}_emit(e,...t){if(S(this,gn,"f"))return;e==="end"&&(L(this,gn,!0),S(this,ks,"f").call(this));const n=S(this,De,"f")[e];if(n&&(S(this,De,"f")[e]=n.filter(r=>!r.once),n.forEach(({listener:r})=>r(...t))),e==="abort"){const r=t[0];!S(this,Ft,"f")&&!n?.length&&Promise.reject(r),S(this,hn,"f").call(this,r),S(this,mn,"f").call(this,r),this._emit("end");return}if(e==="error"){const r=t[0];!S(this,Ft,"f")&&!n?.length&&Promise.reject(r),S(this,hn,"f").call(this,r),S(this,mn,"f").call(this,r),this._emit("end")}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit("finalMessage",S(this,we,"m",ii).call(this))}async _fromReadableStream(e,t){const n=t?.signal;let r;n&&(n.aborted&&this.controller.abort(),r=this.controller.abort.bind(this.controller),n.addEventListener("abort",r));try{S(this,we,"m",oi).call(this),this._connected(null);const i=Oe.fromReadableStream(e,this.controller);for await(const o of i)S(this,we,"m",ai).call(this,o);if(i.controller.signal?.aborted)throw new ke;S(this,we,"m",ci).call(this)}finally{n&&r&&n.removeEventListener("abort",r)}}[(ze=new WeakMap,fn=new WeakMap,vs=new WeakMap,hn=new WeakMap,pn=new WeakMap,ks=new WeakMap,mn=new WeakMap,De=new WeakMap,gn=new WeakMap,Ts=new WeakMap,Es=new WeakMap,Ft=new WeakMap,_s=new WeakMap,Is=new WeakMap,As=new WeakMap,we=new WeakSet,ii=c(function(){if(this.receivedMessages.length===0)throw new F("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},"_BetaMessageStream_getFinalMessage2"),Ic=c(function(){if(this.receivedMessages.length===0)throw new F("stream ended without producing a Message with role=assistant");const t=this.receivedMessages.at(-1).content.filter(n=>n.type==="text").map(n=>n.text);if(t.length===0)throw new F("stream ended without producing a content block with type=text");return t.join(" ")},"_BetaMessageStream_getFinalText2"),oi=c(function(){this.ended||L(this,ze,void 0)},"_BetaMessageStream_beginRequest2"),ai=c(function(t){if(this.ended)return;const n=S(this,we,"m",Ac).call(this,t);switch(this._emit("streamEvent",t,n),t.type){case"content_block_delta":{const r=n.content.at(-1);switch(t.delta.type){case"text_delta":{r.type==="text"&&this._emit("text",t.delta.text,r.text||"");break}case"citations_delta":{r.type==="text"&&this._emit("citation",t.delta.citation,r.citations??[]);break}case"input_json_delta":{$c(r)&&r.input&&this._emit("inputJson",t.delta.partial_json,r.input);break}case"thinking_delta":{r.type==="thinking"&&this._emit("thinking",t.delta.thinking,r.thinking);break}case"signature_delta":{r.type==="thinking"&&this._emit("signature",r.signature);break}default:t.delta}break}case"message_stop":{this._addMessageParam(n),this._addMessage(n,!0);break}case"content_block_stop":{this._emit("contentBlock",n.content.at(-1));break}case"message_start":{L(this,ze,n);break}}},"_BetaMessageStream_addStreamEvent2"),ci=c(function(){if(this.ended)throw new F("stream has ended, this shouldn't happen");const t=S(this,ze,"f");if(!t)throw new F("request ended without sending any chunks");return L(this,ze,void 0),t},"_BetaMessageStream_endRequest2"),Ac=c(function(t){let n=S(this,ze,"f");if(t.type==="message_start"){if(n)throw new F(`Unexpected event order, got ${t.type} before receiving "message_stop"`);return t.message}if(!n)throw new F(`Unexpected event order, got ${t.type} before "message_start"`);switch(t.type){case"message_stop":return n;case"message_delta":return n.container=t.delta.container,n.stop_reason=t.delta.stop_reason,n.stop_sequence=t.delta.stop_sequence,n.usage.output_tokens=t.usage.output_tokens,t.usage.input_tokens!=null&&(n.usage.input_tokens=t.usage.input_tokens),t.usage.cache_creation_input_tokens!=null&&(n.usage.cache_creation_input_tokens=t.usage.cache_creation_input_tokens),t.usage.cache_read_input_tokens!=null&&(n.usage.cache_read_input_tokens=t.usage.cache_read_input_tokens),t.usage.server_tool_use!=null&&(n.usage.server_tool_use=t.usage.server_tool_use),n;case"content_block_start":return n.content.push(t.content_block),n;case"content_block_delta":{const r=n.content.at(t.index);switch(t.delta.type){case"text_delta":{r?.type==="text"&&(n.content[t.index]={...r,text:(r.text||"")+t.delta.text});break}case"citations_delta":{r?.type==="text"&&(n.content[t.index]={...r,citations:[...r.citations??[],t.delta.citation]});break}case"input_json_delta":{if(r&&$c(r)){let i=r[Oc]||"";i+=t.delta.partial_json;const o={...r};if(Object.defineProperty(o,Oc,{value:i,enumerable:!1,writable:!0}),i)try{o.input=_c(i)}catch(a){const l=new F(`Unable to parse tool parameter JSON from model. Please retry your request or adjust your prompt. Error: ${a}. JSON: ${i}`);S(this,As,"f").call(this,l)}n.content[t.index]=o}break}case"thinking_delta":{r?.type==="thinking"&&(n.content[t.index]={...r,thinking:r.thinking+t.delta.thinking});break}case"signature_delta":{r?.type==="thinking"&&(n.content[t.index]={...r,signature:t.delta.signature});break}default:t.delta}return n}case"content_block_stop":return n}},"_BetaMessageStream_accumulateMessage2"),Symbol.asyncIterator)](){const e=[],t=[];let n=!1;return this.on("streamEvent",r=>{const i=t.shift();i?i.resolve(r):e.push(r)}),this.on("end",()=>{n=!0;for(const r of t)r.resolve(void 0);t.length=0}),this.on("abort",r=>{n=!0;for(const i of t)i.reject(r);t.length=0}),this.on("error",r=>{n=!0;for(const i of t)i.reject(r);t.length=0}),{next:c(async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((i,o)=>t.push({resolve:i,reject:o})).then(i=>i?{value:i,done:!1}:{value:void 0,done:!0}),"next"),return:c(async()=>(this.abort(),{value:void 0,done:!0}),"return")}}toReadableStream(){return new Oe(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function Mp(s){}c(Mp,"checkNever$1");const Nc={"claude-opus-4-20250514":8192,"claude-opus-4-0":8192,"claude-4-opus-20250514":8192,"anthropic.claude-opus-4-20250514-v1:0":8192,"claude-opus-4@20250514":8192,"claude-opus-4-1-20250805":8192,"anthropic.claude-opus-4-1-20250805-v1:0":8192,"claude-opus-4-1@20250805":8192},xc={"claude-1.3":"November 6th, 2024","claude-1.3-100k":"November 6th, 2024","claude-instant-1.1":"November 6th, 2024","claude-instant-1.1-100k":"November 6th, 2024","claude-instant-1.2":"November 6th, 2024","claude-3-sonnet-20240229":"July 21st, 2025","claude-3-opus-20240229":"January 5th, 2026","claude-2.1":"July 21st, 2025","claude-2.0":"July 21st, 2025","claude-3-5-sonnet-20241022":"October 22, 2025","claude-3-5-sonnet-20240620":"October 22, 2025"};let li=class extends Le{static{c(this,"Messages")}constructor(){super(...arguments),this.batches=new Ec(this._client)}create(e,t){const{betas:n,...r}=e;r.model in xc&&console.warn(`The model '${r.model}' is deprecated and will reach end-of-life on ${xc[r.model]}
166
+ Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);let i=this._client._options.timeout;if(!r.stream&&i==null){const o=Nc[r.model]??void 0;i=this._client.calculateNonstreamingTimeout(r.max_tokens,o)}return this._client.post("/v1/messages?beta=true",{body:r,timeout:i??6e5,...t,headers:z([{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void 0},t?.headers]),stream:e.stream??!1})}stream(e,t){return Bs.createMessage(this,e,t)}countTokens(e,t){const{betas:n,...r}=e;return this._client.post("/v1/messages/count_tokens?beta=true",{body:r,...t,headers:z([{"anthropic-beta":[...n??[],"token-counting-2024-11-01"].toString()},t?.headers])})}};li.Batches=Ec;class yn extends Le{static{c(this,"Beta")}constructor(){super(...arguments),this.models=new Tc(this._client),this.messages=new li(this._client),this.files=new kc(this._client)}}yn.Models=Tc,yn.Messages=li,yn.Files=kc;class Pc extends Le{static{c(this,"Completions")}create(e,t){const{betas:n,...r}=e;return this._client.post("/v1/complete",{body:r,timeout:this._client._options.timeout??6e5,...t,headers:z([{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void 0},t?.headers]),stream:e.stream??!1})}}var be,Ye,wn,Os,bn,Sn,$s,Cn,je,vn,Ns,xs,qt,Ps,Ms,ui,Mc,di,fi,hi,pi,Rc;const Lc="__json_buf";function Dc(s){return s.type==="tool_use"||s.type==="server_tool_use"}c(Dc,"tracksToolInput");class Ks{static{c(this,"MessageStream")}constructor(){be.add(this),this.messages=[],this.receivedMessages=[],Ye.set(this,void 0),this.controller=new AbortController,wn.set(this,void 0),Os.set(this,()=>{}),bn.set(this,()=>{}),Sn.set(this,void 0),$s.set(this,()=>{}),Cn.set(this,()=>{}),je.set(this,{}),vn.set(this,!1),Ns.set(this,!1),xs.set(this,!1),qt.set(this,!1),Ps.set(this,void 0),Ms.set(this,void 0),di.set(this,e=>{if(L(this,Ns,!0),on(e)&&(e=new ke),e instanceof ke)return L(this,xs,!0),this._emit("abort",e);if(e instanceof F)return this._emit("error",e);if(e instanceof Error){const t=new F(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new F(String(e)))}),L(this,wn,new Promise((e,t)=>{L(this,Os,e,"f"),L(this,bn,t,"f")})),L(this,Sn,new Promise((e,t)=>{L(this,$s,e,"f"),L(this,Cn,t,"f")})),S(this,wn,"f").catch(()=>{}),S(this,Sn,"f").catch(()=>{})}get response(){return S(this,Ps,"f")}get request_id(){return S(this,Ms,"f")}async withResponse(){const e=await S(this,wn,"f");if(!e)throw new Error("Could not resolve a `Response` object");return{data:this,response:e,request_id:e.headers.get("request-id")}}static fromReadableStream(e){const t=new Ks;return t._run(()=>t._fromReadableStream(e)),t}static createMessage(e,t,n){const r=new Ks;for(const i of t.messages)r._addMessageParam(i);return r._run(()=>r._createMessage(e,{...t,stream:!0},{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),r}_run(e){e().then(()=>{this._emitFinal(),this._emit("end")},S(this,di,"f"))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,t=!0){this.receivedMessages.push(e),t&&this._emit("message",e)}async _createMessage(e,t,n){const r=n?.signal;let i;r&&(r.aborted&&this.controller.abort(),i=this.controller.abort.bind(this.controller),r.addEventListener("abort",i));try{S(this,be,"m",fi).call(this);const{response:o,data:a}=await e.create({...t,stream:!0},{...n,signal:this.controller.signal}).withResponse();this._connected(o);for await(const l of a)S(this,be,"m",hi).call(this,l);if(a.controller.signal?.aborted)throw new ke;S(this,be,"m",pi).call(this)}finally{r&&i&&r.removeEventListener("abort",i)}}_connected(e){this.ended||(L(this,Ps,e),L(this,Ms,e?.headers.get("request-id")),S(this,Os,"f").call(this,e),this._emit("connect"))}get ended(){return S(this,vn,"f")}get errored(){return S(this,Ns,"f")}get aborted(){return S(this,xs,"f")}abort(){this.controller.abort()}on(e,t){return(S(this,je,"f")[e]||(S(this,je,"f")[e]=[])).push({listener:t}),this}off(e,t){const n=S(this,je,"f")[e];if(!n)return this;const r=n.findIndex(i=>i.listener===t);return r>=0&&n.splice(r,1),this}once(e,t){return(S(this,je,"f")[e]||(S(this,je,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,n)=>{L(this,qt,!0),e!=="error"&&this.once("error",n),this.once(e,t)})}async done(){L(this,qt,!0),await S(this,Sn,"f")}get currentMessage(){return S(this,Ye,"f")}async finalMessage(){return await this.done(),S(this,be,"m",ui).call(this)}async finalText(){return await this.done(),S(this,be,"m",Mc).call(this)}_emit(e,...t){if(S(this,vn,"f"))return;e==="end"&&(L(this,vn,!0),S(this,$s,"f").call(this));const n=S(this,je,"f")[e];if(n&&(S(this,je,"f")[e]=n.filter(r=>!r.once),n.forEach(({listener:r})=>r(...t))),e==="abort"){const r=t[0];!S(this,qt,"f")&&!n?.length&&Promise.reject(r),S(this,bn,"f").call(this,r),S(this,Cn,"f").call(this,r),this._emit("end");return}if(e==="error"){const r=t[0];!S(this,qt,"f")&&!n?.length&&Promise.reject(r),S(this,bn,"f").call(this,r),S(this,Cn,"f").call(this,r),this._emit("end")}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit("finalMessage",S(this,be,"m",ui).call(this))}async _fromReadableStream(e,t){const n=t?.signal;let r;n&&(n.aborted&&this.controller.abort(),r=this.controller.abort.bind(this.controller),n.addEventListener("abort",r));try{S(this,be,"m",fi).call(this),this._connected(null);const i=Oe.fromReadableStream(e,this.controller);for await(const o of i)S(this,be,"m",hi).call(this,o);if(i.controller.signal?.aborted)throw new ke;S(this,be,"m",pi).call(this)}finally{n&&r&&n.removeEventListener("abort",r)}}[(Ye=new WeakMap,wn=new WeakMap,Os=new WeakMap,bn=new WeakMap,Sn=new WeakMap,$s=new WeakMap,Cn=new WeakMap,je=new WeakMap,vn=new WeakMap,Ns=new WeakMap,xs=new WeakMap,qt=new WeakMap,Ps=new WeakMap,Ms=new WeakMap,di=new WeakMap,be=new WeakSet,ui=c(function(){if(this.receivedMessages.length===0)throw new F("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},"_MessageStream_getFinalMessage2"),Mc=c(function(){if(this.receivedMessages.length===0)throw new F("stream ended without producing a Message with role=assistant");const t=this.receivedMessages.at(-1).content.filter(n=>n.type==="text").map(n=>n.text);if(t.length===0)throw new F("stream ended without producing a content block with type=text");return t.join(" ")},"_MessageStream_getFinalText2"),fi=c(function(){this.ended||L(this,Ye,void 0)},"_MessageStream_beginRequest2"),hi=c(function(t){if(this.ended)return;const n=S(this,be,"m",Rc).call(this,t);switch(this._emit("streamEvent",t,n),t.type){case"content_block_delta":{const r=n.content.at(-1);switch(t.delta.type){case"text_delta":{r.type==="text"&&this._emit("text",t.delta.text,r.text||"");break}case"citations_delta":{r.type==="text"&&this._emit("citation",t.delta.citation,r.citations??[]);break}case"input_json_delta":{Dc(r)&&r.input&&this._emit("inputJson",t.delta.partial_json,r.input);break}case"thinking_delta":{r.type==="thinking"&&this._emit("thinking",t.delta.thinking,r.thinking);break}case"signature_delta":{r.type==="thinking"&&this._emit("signature",r.signature);break}default:t.delta}break}case"message_stop":{this._addMessageParam(n),this._addMessage(n,!0);break}case"content_block_stop":{this._emit("contentBlock",n.content.at(-1));break}case"message_start":{L(this,Ye,n);break}}},"_MessageStream_addStreamEvent2"),pi=c(function(){if(this.ended)throw new F("stream has ended, this shouldn't happen");const t=S(this,Ye,"f");if(!t)throw new F("request ended without sending any chunks");return L(this,Ye,void 0),t},"_MessageStream_endRequest2"),Rc=c(function(t){let n=S(this,Ye,"f");if(t.type==="message_start"){if(n)throw new F(`Unexpected event order, got ${t.type} before receiving "message_stop"`);return t.message}if(!n)throw new F(`Unexpected event order, got ${t.type} before "message_start"`);switch(t.type){case"message_stop":return n;case"message_delta":return n.stop_reason=t.delta.stop_reason,n.stop_sequence=t.delta.stop_sequence,n.usage.output_tokens=t.usage.output_tokens,t.usage.input_tokens!=null&&(n.usage.input_tokens=t.usage.input_tokens),t.usage.cache_creation_input_tokens!=null&&(n.usage.cache_creation_input_tokens=t.usage.cache_creation_input_tokens),t.usage.cache_read_input_tokens!=null&&(n.usage.cache_read_input_tokens=t.usage.cache_read_input_tokens),t.usage.server_tool_use!=null&&(n.usage.server_tool_use=t.usage.server_tool_use),n;case"content_block_start":return n.content.push({...t.content_block}),n;case"content_block_delta":{const r=n.content.at(t.index);switch(t.delta.type){case"text_delta":{r?.type==="text"&&(n.content[t.index]={...r,text:(r.text||"")+t.delta.text});break}case"citations_delta":{r?.type==="text"&&(n.content[t.index]={...r,citations:[...r.citations??[],t.delta.citation]});break}case"input_json_delta":{if(r&&Dc(r)){let i=r[Lc]||"";i+=t.delta.partial_json;const o={...r};Object.defineProperty(o,Lc,{value:i,enumerable:!1,writable:!0}),i&&(o.input=_c(i)),n.content[t.index]=o}break}case"thinking_delta":{r?.type==="thinking"&&(n.content[t.index]={...r,thinking:r.thinking+t.delta.thinking});break}case"signature_delta":{r?.type==="thinking"&&(n.content[t.index]={...r,signature:t.delta.signature});break}default:t.delta}return n}case"content_block_stop":return n}},"_MessageStream_accumulateMessage2"),Symbol.asyncIterator)](){const e=[],t=[];let n=!1;return this.on("streamEvent",r=>{const i=t.shift();i?i.resolve(r):e.push(r)}),this.on("end",()=>{n=!0;for(const r of t)r.resolve(void 0);t.length=0}),this.on("abort",r=>{n=!0;for(const i of t)i.reject(r);t.length=0}),this.on("error",r=>{n=!0;for(const i of t)i.reject(r);t.length=0}),{next:c(async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((i,o)=>t.push({resolve:i,reject:o})).then(i=>i?{value:i,done:!1}:{value:void 0,done:!0}),"next"),return:c(async()=>(this.abort(),{value:void 0,done:!0}),"return")}}toReadableStream(){return new Oe(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function Lp(s){}c(Lp,"checkNever");class jc extends Le{static{c(this,"Batches")}create(e,t){return this._client.post("/v1/messages/batches",{body:e,...t})}retrieve(e,t){return this._client.get(Te`/v1/messages/batches/${e}`,t)}list(e={},t){return this._client.getAPIList("/v1/messages/batches",dn,{query:e,...t})}delete(e,t){return this._client.delete(Te`/v1/messages/batches/${e}`,t)}cancel(e,t){return this._client.post(Te`/v1/messages/batches/${e}/cancel`,t)}async results(e,t){const n=await this.retrieve(e);if(!n.results_url)throw new F(`No batch \`results_url\`; Has it finished processing? ${n.processing_status} - ${n.id}`);return this._client.get(n.results_url,{...t,headers:z([{Accept:"application/binary"},t?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((r,i)=>qs.fromResponse(i.response,i.controller))}}class mi extends Le{static{c(this,"Messages")}constructor(){super(...arguments),this.batches=new jc(this._client)}create(e,t){e.model in Fc&&console.warn(`The model '${e.model}' is deprecated and will reach end-of-life on ${Fc[e.model]}
167
+ Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);let n=this._client._options.timeout;if(!e.stream&&n==null){const r=Nc[e.model]??void 0;n=this._client.calculateNonstreamingTimeout(e.max_tokens,r)}return this._client.post("/v1/messages",{body:e,timeout:n??6e5,...t,stream:e.stream??!1})}stream(e,t){return Ks.createMessage(this,e,t)}countTokens(e,t){return this._client.post("/v1/messages/count_tokens",{body:e,...t})}}const Fc={"claude-1.3":"November 6th, 2024","claude-1.3-100k":"November 6th, 2024","claude-instant-1.1":"November 6th, 2024","claude-instant-1.1-100k":"November 6th, 2024","claude-instant-1.2":"November 6th, 2024","claude-3-sonnet-20240229":"July 21st, 2025","claude-3-opus-20240229":"January 5th, 2026","claude-2.1":"July 21st, 2025","claude-2.0":"July 21st, 2025","claude-3-5-sonnet-20241022":"October 22, 2025","claude-3-5-sonnet-20240620":"October 22, 2025"};mi.Batches=jc;class qc extends Le{static{c(this,"Models")}retrieve(e,t={},n){const{betas:r}=t??{};return this._client.get(Te`/v1/models/${e}`,{...n,headers:z([{...r?.toString()!=null?{"anthropic-beta":r?.toString()}:void 0},n?.headers])})}list(e={},t){const{betas:n,...r}=e??{};return this._client.getAPIList("/v1/models",dn,{query:r,...t,headers:z([{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void 0},t?.headers])})}}const Rs=c(s=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[s]?.trim()??void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(s)?.trim()},"readEnv");var gi,yi,Ls,Bc;const Th="\\n\\nHuman:",Eh="\\n\\nAssistant:";class ee{static{c(this,"BaseAnthropic")}constructor({baseURL:e=Rs("ANTHROPIC_BASE_URL"),apiKey:t=Rs("ANTHROPIC_API_KEY")??null,authToken:n=Rs("ANTHROPIC_AUTH_TOKEN")??null,...r}={}){gi.add(this),Ls.set(this,void 0);const i={apiKey:t,authToken:n,...r,baseURL:e||"https://api.anthropic.com"};if(!i.dangerouslyAllowBrowser&&Vf())throw new F(`It looks like you're running in a browser-like environment.
168
168
 
169
169
  This is disabled by default, as it risks exposing your secret API credentials to attackers.
170
170
  If you understand the risks and have appropriate mitigations in place,
171
171
  you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
172
172
 
173
173
  new Anthropic({ apiKey, dangerouslyAllowBrowser: true });
174
- `);this.baseURL=i.baseURL,this.timeout=i.timeout??yi.DEFAULT_TIMEOUT,this.logger=i.logger??console;const o="warn";this.logLevel=o,this.logLevel=dc(i.logLevel,"ClientOptions.logLevel",this)??dc(Rs("ANTHROPIC_LOG"),"process.env['ANTHROPIC_LOG']",this)??o,this.fetchOptions=i.fetchOptions,this.maxRetries=i.maxRetries??2,this.fetch=i.fetch??Xf(),L(this,Ls,Qf),this._options=i,this.apiKey=t,this.authToken=n}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,authToken:this.authToken,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t}){if(!(this.apiKey&&e.get("x-api-key"))&&!t.has("x-api-key")&&!(this.authToken&&e.get("authorization"))&&!t.has("authorization"))throw new Error('Could not resolve authentication method. Expected either apiKey or authToken to be set. Or for one of the "X-Api-Key" or "Authorization" headers to be explicitly omitted')}async authHeaders(e){return z([await this.apiKeyAuth(e),await this.bearerAuth(e)])}async apiKeyAuth(e){if(this.apiKey!=null)return z([{"X-Api-Key":this.apiKey}])}async bearerAuth(e){if(this.authToken!=null)return z([{Authorization:`Bearer ${this.authToken}`}])}stringifyQuery(e){return Object.entries(e).filter(([t,n])=>typeof n<"u").map(([t,n])=>{if(typeof n=="string"||typeof n=="number"||typeof n=="boolean")return`${encodeURIComponent(t)}=${encodeURIComponent(n)}`;if(n===null)return`${encodeURIComponent(t)}=`;throw new F(`Cannot stringify type ${typeof n}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join("&")}getUserAgent(){return`${this.constructor.name}/JS ${Lt}`}defaultIdempotencyKey(){return`stainless-node-retry-${Wa()}`}makeStatusError(e,t,n,r){return re.generate(e,t,n,r)}buildURL(e,t,n){const r=!S(this,gi,"m",qc).call(this)&&n||this.baseURL,i=Bf(e)?new URL(e):new URL(r+(r.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),o=this.defaultQuery();return Kf(o)||(t={...o,...t}),typeof t=="object"&&t&&!Array.isArray(t)&&(i.search=this.stringifyQuery(t)),i.toString()}_calculateNonstreamingTimeout(e){if(3600*e/128e3>600)throw new F("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#streaming-responses for more details");return 600*1e3}async prepareOptions(e){}async prepareRequest(e,{url:t,options:n}){}get(e,t){return this.methodRequest("get",e,t)}post(e,t){return this.methodRequest("post",e,t)}patch(e,t){return this.methodRequest("patch",e,t)}put(e,t){return this.methodRequest("put",e,t)}delete(e,t){return this.methodRequest("delete",e,t)}methodRequest(e,t,n){return this.request(Promise.resolve(n).then(r=>({method:e,path:t,...r})))}request(e,t=null){return new Fs(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,n){const r=await e,i=r.maxRetries??this.maxRetries;t==null&&(t=i),await this.prepareOptions(r);const{req:o,url:a,timeout:l}=await this.buildRequest(r,{retryCount:i-t});await this.prepareRequest(o,{url:a,options:r});const u="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),d=n===void 0?"":`, retryOf: ${n}`,f=Date.now();if(ie(this).debug(`[${u}] sending request`,ut({retryOfRequestLogID:n,method:r.method,url:a,options:r,headers:o.headers})),r.signal?.aborted)throw new ke;const h=new AbortController,g=await this.fetchWithTimeout(a,o,l,h).catch(Qr),y=Date.now();if(g instanceof globalThis.Error){const T=`retrying, ${t} attempts remaining`;if(r.signal?.aborted)throw new ke;const E=on(g)||/timed? ?out/i.test(String(g)+("cause"in g?String(g.cause):""));if(t)return ie(this).info(`[${u}] connection ${E?"timed out":"failed"} - ${T}`),ie(this).debug(`[${u}] connection ${E?"timed out":"failed"} (${T})`,ut({retryOfRequestLogID:n,url:a,durationMs:y-f,message:g.message})),this.retryRequest(r,t,n??u);throw ie(this).info(`[${u}] connection ${E?"timed out":"failed"} - error; no more retries left`),ie(this).debug(`[${u}] connection ${E?"timed out":"failed"} (error; no more retries left)`,ut({retryOfRequestLogID:n,url:a,durationMs:y-f,message:g.message})),E?new Ja:new ys({cause:g})}const p=[...g.headers.entries()].filter(([T])=>T==="request-id").map(([T,E])=>", "+T+": "+JSON.stringify(E)).join(""),w=`[${u}${d}${p}] ${o.method} ${a} ${g.ok?"succeeded":"failed"} with status ${g.status} in ${y-f}ms`;if(!g.ok){const T=await this.shouldRetry(g);if(t&&T){const j=`retrying, ${t} attempts remaining`;return await Zf(g.body),ie(this).info(`${w} - ${j}`),ie(this).debug(`[${u}] response error (${j})`,ut({retryOfRequestLogID:n,url:g.url,status:g.status,headers:g.headers,durationMs:y-f})),this.retryRequest(r,t,n??u,g.headers)}const E=T?"error; no more retries left":"error; not retryable";ie(this).info(`${w} - ${E}`);const $=await g.text().catch(j=>Qr(j).message),I=nc($),x=I?void 0:$;throw ie(this).debug(`[${u}] response error (${E})`,ut({retryOfRequestLogID:n,url:g.url,status:g.status,headers:g.headers,message:x,durationMs:Date.now()-f})),this.makeStatusError(g.status,I,x,g.headers)}return ie(this).info(w),ie(this).debug(`[${u}] response start`,ut({retryOfRequestLogID:n,url:g.url,status:g.status,headers:g.headers,durationMs:y-f})),{response:g,options:r,controller:h,requestLogID:u,retryOfRequestLogID:n,startTime:f}}getAPIList(e,t,n){return this.requestAPIList(t,{method:"get",path:e,...n})}requestAPIList(e,t){const n=this.makeRequest(t,null,void 0);return new lh(this,n,e)}async fetchWithTimeout(e,t,n,r){const{signal:i,method:o,...a}=t||{};i&&i.addEventListener("abort",()=>r.abort());const l=setTimeout(()=>r.abort(),n),u=globalThis.ReadableStream&&a.body instanceof globalThis.ReadableStream||typeof a.body=="object"&&a.body!==null&&Symbol.asyncIterator in a.body,d={signal:r.signal,...u?{duplex:"half"}:{},method:"GET",...a};o&&(d.method=o.toUpperCase());try{return await this.fetch.call(void 0,e,d)}finally{clearTimeout(l)}}async shouldRetry(e){const t=e.headers.get("x-should-retry");return t==="true"?!0:t==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,t,n,r){let i;const o=r?.get("retry-after-ms");if(o){const l=parseFloat(o);Number.isNaN(l)||(i=l)}const a=r?.get("retry-after");if(a&&!i){const l=parseFloat(a);Number.isNaN(l)?i=Date.parse(a)-Date.now():i=l*1e3}if(!(i&&0<=i&&i<60*1e3)){const l=e.maxRetries??this.maxRetries;i=this.calculateDefaultRetryTimeoutMillis(t,l)}return await Jf(i),this.makeRequest(e,t-1,n)}calculateDefaultRetryTimeoutMillis(e,t){const i=t-e,o=Math.min(.5*Math.pow(2,i),8),a=1-Math.random()*.25;return o*a*1e3}calculateNonstreamingTimeout(e,t){if(36e5*e/128e3>6e5||t!=null&&e>t)throw new F("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#long-requests for more details");return 6e5}async buildRequest(e,{retryCount:t=0}={}){const n={...e},{method:r,path:i,query:o,defaultBaseURL:a}=n,l=this.buildURL(i,o,a);"timeout"in n&&Wf("timeout",n.timeout),n.timeout=n.timeout??this.timeout;const{bodyHeaders:u,body:d}=this.buildBody({options:n}),f=await this.buildHeaders({options:e,method:r,bodyHeaders:u,retryCount:t});return{req:{method:r,headers:f,...n.signal&&{signal:n.signal},...globalThis.ReadableStream&&d instanceof globalThis.ReadableStream&&{duplex:"half"},...d&&{body:d},...this.fetchOptions??{},...n.fetchOptions??{}},url:l,timeout:n.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:n,retryCount:r}){let i={};this.idempotencyHeader&&t!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),i[this.idempotencyHeader]=e.idempotencyKey);const o=z([i,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(r),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...Yf(),...this._options.dangerouslyAllowBrowser?{"anthropic-dangerous-direct-browser-access":"true"}:void 0,"anthropic-version":"2023-06-01"},await this.authHeaders(e),this._options.defaultHeaders,n,e.headers]);return this.validateHeaders(o),o.values}buildBody({options:{body:e,headers:t}}){if(!e)return{bodyHeaders:void 0,body:void 0};const n=z([t]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e=="string"&&n.values.has("content-type")||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:e}:typeof e=="object"&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&typeof e.next=="function")?{bodyHeaders:void 0,body:ac(e)}:S(this,Ls,"f").call(this,{body:e,headers:n})}}yi=ee,Ls=new WeakMap,gi=new WeakSet,qc=c(function(){return this.baseURL!=="https://api.anthropic.com"},"_BaseAnthropic_baseURLOverridden2"),ee.Anthropic=yi,ee.HUMAN_PROMPT=kh,ee.AI_PROMPT=Th,ee.DEFAULT_TIMEOUT=6e5,ee.AnthropicError=F,ee.APIError=re,ee.APIConnectionError=ys,ee.APIConnectionTimeoutError=Ja,ee.APIUserAbortError=ke,ee.NotFoundError=za,ee.ConflictError=Ya,ee.RateLimitError=Za,ee.BadRequestError=Ha,ee.AuthenticationError=Va,ee.InternalServerError=Qa,ee.PermissionDeniedError=Ga,ee.UnprocessableEntityError=Xa,ee.toFile=gh;class kn extends ee{static{c(this,"Anthropic")}constructor(){super(...arguments),this.completions=new xc(this),this.messages=new mi(this),this.models=new Fc(this),this.beta=new yn(this)}}kn.Completions=xc,kn.Messages=mi,kn.Models=Fc,kn.Beta=yn;const Eh="claude-sonnet-4-20250514";class vi{static{c(this,"TestEnvironment")}client;connectionId;testsDir;testBasePath;options;llm;state={};constructor({connectionId:e,testsDir:t,testBasePath:n,client:r,options:i,llm:o}){this.client=r,this.connectionId=e,this.testsDir=t,this.testBasePath=n,this.llm=o,this.options=i}static async create({connectionId:e,testBasePath:t,options:n}){const r=$n();if(!r)throw new Error("No configuration found. Please set MEMBRANE_WORKSPACE_KEY and MEMBRANE_WORKSPACE_SECRET environment variables, or run `membrane init` first.");if(!r.workspaceKey||!r.workspaceSecret)throw new Error("Missing workspace credentials");if(!r.anthropicApiKey)throw new Error("Anthropic API key not configured. Run `membrane init` to set up testing.");const i=new Ti({token:await this.createMembraneToken(r),apiUri:r.apiUri}),o=new kn({apiKey:r.anthropicApiKey}),a={complete:c(async({prompt:l,maxTokens:u})=>{const d=await o.messages.create({model:Eh,max_tokens:u,messages:[{role:"user",content:l}]});return d.content[0].type==="text"?d.content[0].text:""},"complete")};return new vi({client:i,options:n,connectionId:e,testsDir:"src/testing/tests",testBasePath:t,llm:a})}async run(e){this.state={};const t={};for(const n of e)await n.run(),er(t,n.getResult());this.writeResults(t)}async readYaml(e){const t=q.join(this.testsDir,this.testBasePath,this.connectionId,e);return ur(t)}async writeYaml(e,t){const n=q.join(this.testsDir,this.testBasePath,this.connectionId,e);B.mkdirSync(q.dirname(n),{recursive:!0}),B.writeFileSync(n,Se.dump(t,{noRefs:!0}))}writeResults(e){const t=q.join(this.testsDir,this.testBasePath,this.connectionId);B.mkdirSync(t,{recursive:!0});const n=q.join(t,"test-results.yaml");B.writeFileSync(n,Se.dump(e,{noRefs:!0})),console.debug(`[TestRunner] Results written to: ${n}`)}static async createMembraneToken(e){const t=e.testCustomerId||"test-customer",n={id:t,name:t},r={issuer:e.workspaceKey,expiresIn:7200,algorithm:"HS512"};return Qs.sign(n,e.workspaceSecret,r)}}Tl.interpolate=/{{([\s\S]+?)}}/g;function wi(s,e){if(typeof s=="string"){const t=kl(s),n={state:e,random:{number:c(()=>Vt.number.int(),"number"),alphaNumeric:c(i=>Vt.string.alphanumeric(i),"alphaNumeric")},faker:{company:{name:c(()=>Vt.company.name(),"name"),catchPhrase:c(()=>Vt.company.catchPhrase(),"catchPhrase")},internet:{email:c(()=>Vt.internet.email(),"email")}},entries:e["journal-entries"],orders:e["purchase-orders"]||e["sales-orders"],bills:e["vendor-bills"]},r=t(n);return s.includes("{{")&&s.includes("}}")&&(console.debug(`[TEMPLATE] Input: ${s}`),console.debug(`[TEMPLATE] Output: ${r}`)),r}return Array.isArray(s)?s.map(t=>wi(t,e)):typeof s=="object"&&s!==null?Object.fromEntries(Object.entries(s).map(([t,n])=>[t,wi(n,e)])):s}c(wi,"processNode");function _h(s,e){return wi(s,e)}c(_h,"handleTemplate");class Ih{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,r={},i={},o;for(;!t;)try{i=await e.readTestCase(),i||(i=await e.generateConfig(),await this.environment.writeYaml(e.getTestCasePath(),i),console.debug(`${k.bold.yellow("[initialized]")} ${k.yellow(e.path)}`)),o=_h(i,this.environment.state),await e.run(o),console.debug(`${k.bold.green("[success]")} ${k.yellow(e.path)}`),t=!0,r=e.getResult(),Js(this.result,e.path,r)}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}`)}}Js(this.result,e.path,{error:Ee(l)}),t=!0,r={error:Ee(l)}}const a={...o,result:r};await this.environment.writeYaml(e.getTestCasePath(),a)}async runTestSuite(e){await e.run(),er(this.result,e.getResult())}}class Xe{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,this.resultsLocator=""}async fix(e){const t=await this.readTestCase();if(!t)throw new Error(`No config found for test ${this.path}`);const n=await this.fixTestCase({config:t,error:e});console.debug(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 r=await e();r?(this.logMsg(`\u2705 ${t}`),this.assertions.push({message:t,result:r})):(this.logMsg(`\u274C ${t}`),this.assertions.push({message:t,result:!1,details:n}))}catch(r){this.assertions.push({message:t,result:!1,details:Ee(r)}),this.logMsg(`\u274C ${t}: ${r.message}`)}}logMsg(e){console.debug(`${" ".repeat(this.level*2)}${e}`)}getTestCasePath(){return`${this.path}.test.yml`}}function bi(s,e){const t={};for(const n in e){if(!(n in s)){t[n]=e[n];continue}const r=s[n],i=e[n];if(r&&i&&typeof r=="object"&&typeof i=="object"){if(Array.isArray(r)&&Array.isArray(i)){const o=i.filter(a=>!r.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)||!Si(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(r)&&!Array.isArray(i)){const o=bi(r,i);o!==null&&(t[n]=o)}else t[n]=i;continue}Si(r,i)||(t[n]=i)}return Object.keys(t).length===0?null:t}c(bi,"getNotMatchingSubFields");function Si(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(Si,"softCompare");class Ah extends Xe{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=Hs(this.dataCollection);if(this.dataCollection.findById){const i=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).findById({id:t.id});await this.assert(()=>!!i.record,"Record is returned from findById"),i.record&&(this.environment.state[this.dataCollectionKey]={createdRecordId:t.id,createdRecord:i.record.fields});const o=Ei(n),a=En(e.input.fields,o,{skipUnknownFields:!0}),l=En(i.record.fields,o),u=bi(l,a);await this.assert(()=>!u,"Returned fields match created fields",{difference:u,sentFields:a,receivedFields:l})}const r=el(n??{});if(r.length>0){const i={};r.forEach(a=>{const l=tl(e.input.fields,a);typeof l<"u"&&Js(i,a,l)});const o=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).create({fields:i});await this.assert(()=>!!o.id,"Record can be created with schema-defined required fields only")}}async generateConfig(){const e=Hs(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=Ee(t),r=Hs(this.dataCollection),i=await this.getExampleRecordsForSchema(r),o=`I'm trying to create a data record in a data collection with the following fields schema:
174
+ `);this.baseURL=i.baseURL,this.timeout=i.timeout??yi.DEFAULT_TIMEOUT,this.logger=i.logger??console;const o="warn";this.logLevel=o,this.logLevel=fc(i.logLevel,"ClientOptions.logLevel",this)??fc(Rs("ANTHROPIC_LOG"),"process.env['ANTHROPIC_LOG']",this)??o,this.fetchOptions=i.fetchOptions,this.maxRetries=i.maxRetries??2,this.fetch=i.fetch??Zf(),L(this,Ls,eh),this._options=i,this.apiKey=t,this.authToken=n}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,authToken:this.authToken,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t}){if(!(this.apiKey&&e.get("x-api-key"))&&!t.has("x-api-key")&&!(this.authToken&&e.get("authorization"))&&!t.has("authorization"))throw new Error('Could not resolve authentication method. Expected either apiKey or authToken to be set. Or for one of the "X-Api-Key" or "Authorization" headers to be explicitly omitted')}async authHeaders(e){return z([await this.apiKeyAuth(e),await this.bearerAuth(e)])}async apiKeyAuth(e){if(this.apiKey!=null)return z([{"X-Api-Key":this.apiKey}])}async bearerAuth(e){if(this.authToken!=null)return z([{Authorization:`Bearer ${this.authToken}`}])}stringifyQuery(e){return Object.entries(e).filter(([t,n])=>typeof n<"u").map(([t,n])=>{if(typeof n=="string"||typeof n=="number"||typeof n=="boolean")return`${encodeURIComponent(t)}=${encodeURIComponent(n)}`;if(n===null)return`${encodeURIComponent(t)}=`;throw new F(`Cannot stringify type ${typeof n}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join("&")}getUserAgent(){return`${this.constructor.name}/JS ${Lt}`}defaultIdempotencyKey(){return`stainless-node-retry-${Ja()}`}makeStatusError(e,t,n,r){return re.generate(e,t,n,r)}buildURL(e,t,n){const r=!S(this,gi,"m",Bc).call(this)&&n||this.baseURL,i=Kf(e)?new URL(e):new URL(r+(r.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),o=this.defaultQuery();return Uf(o)||(t={...o,...t}),typeof t=="object"&&t&&!Array.isArray(t)&&(i.search=this.stringifyQuery(t)),i.toString()}_calculateNonstreamingTimeout(e){if(3600*e/128e3>600)throw new F("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#streaming-responses for more details");return 600*1e3}async prepareOptions(e){}async prepareRequest(e,{url:t,options:n}){}get(e,t){return this.methodRequest("get",e,t)}post(e,t){return this.methodRequest("post",e,t)}patch(e,t){return this.methodRequest("patch",e,t)}put(e,t){return this.methodRequest("put",e,t)}delete(e,t){return this.methodRequest("delete",e,t)}methodRequest(e,t,n){return this.request(Promise.resolve(n).then(r=>({method:e,path:t,...r})))}request(e,t=null){return new Fs(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,n){const r=await e,i=r.maxRetries??this.maxRetries;t==null&&(t=i),await this.prepareOptions(r);const{req:o,url:a,timeout:l}=await this.buildRequest(r,{retryCount:i-t});await this.prepareRequest(o,{url:a,options:r});const u="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),d=n===void 0?"":`, retryOf: ${n}`,f=Date.now();if(ie(this).debug(`[${u}] sending request`,ut({retryOfRequestLogID:n,method:r.method,url:a,options:r,headers:o.headers})),r.signal?.aborted)throw new ke;const h=new AbortController,g=await this.fetchWithTimeout(a,o,l,h).catch(Qr),y=Date.now();if(g instanceof globalThis.Error){const T=`retrying, ${t} attempts remaining`;if(r.signal?.aborted)throw new ke;const E=on(g)||/timed? ?out/i.test(String(g)+("cause"in g?String(g.cause):""));if(t)return ie(this).info(`[${u}] connection ${E?"timed out":"failed"} - ${T}`),ie(this).debug(`[${u}] connection ${E?"timed out":"failed"} (${T})`,ut({retryOfRequestLogID:n,url:a,durationMs:y-f,message:g.message})),this.retryRequest(r,t,n??u);throw ie(this).info(`[${u}] connection ${E?"timed out":"failed"} - error; no more retries left`),ie(this).debug(`[${u}] connection ${E?"timed out":"failed"} (error; no more retries left)`,ut({retryOfRequestLogID:n,url:a,durationMs:y-f,message:g.message})),E?new Ha:new ys({cause:g})}const p=[...g.headers.entries()].filter(([T])=>T==="request-id").map(([T,E])=>", "+T+": "+JSON.stringify(E)).join(""),w=`[${u}${d}${p}] ${o.method} ${a} ${g.ok?"succeeded":"failed"} with status ${g.status} in ${y-f}ms`;if(!g.ok){const T=await this.shouldRetry(g);if(t&&T){const j=`retrying, ${t} attempts remaining`;return await Qf(g.body),ie(this).info(`${w} - ${j}`),ie(this).debug(`[${u}] response error (${j})`,ut({retryOfRequestLogID:n,url:g.url,status:g.status,headers:g.headers,durationMs:y-f})),this.retryRequest(r,t,n??u,g.headers)}const E=T?"error; no more retries left":"error; not retryable";ie(this).info(`${w} - ${E}`);const $=await g.text().catch(j=>Qr(j).message),I=sc($),x=I?void 0:$;throw ie(this).debug(`[${u}] response error (${E})`,ut({retryOfRequestLogID:n,url:g.url,status:g.status,headers:g.headers,message:x,durationMs:Date.now()-f})),this.makeStatusError(g.status,I,x,g.headers)}return ie(this).info(w),ie(this).debug(`[${u}] response start`,ut({retryOfRequestLogID:n,url:g.url,status:g.status,headers:g.headers,durationMs:y-f})),{response:g,options:r,controller:h,requestLogID:u,retryOfRequestLogID:n,startTime:f}}getAPIList(e,t,n){return this.requestAPIList(t,{method:"get",path:e,...n})}requestAPIList(e,t){const n=this.makeRequest(t,null,void 0);return new uh(this,n,e)}async fetchWithTimeout(e,t,n,r){const{signal:i,method:o,...a}=t||{};i&&i.addEventListener("abort",()=>r.abort());const l=setTimeout(()=>r.abort(),n),u=globalThis.ReadableStream&&a.body instanceof globalThis.ReadableStream||typeof a.body=="object"&&a.body!==null&&Symbol.asyncIterator in a.body,d={signal:r.signal,...u?{duplex:"half"}:{},method:"GET",...a};o&&(d.method=o.toUpperCase());try{return await this.fetch.call(void 0,e,d)}finally{clearTimeout(l)}}async shouldRetry(e){const t=e.headers.get("x-should-retry");return t==="true"?!0:t==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,t,n,r){let i;const o=r?.get("retry-after-ms");if(o){const l=parseFloat(o);Number.isNaN(l)||(i=l)}const a=r?.get("retry-after");if(a&&!i){const l=parseFloat(a);Number.isNaN(l)?i=Date.parse(a)-Date.now():i=l*1e3}if(!(i&&0<=i&&i<60*1e3)){const l=e.maxRetries??this.maxRetries;i=this.calculateDefaultRetryTimeoutMillis(t,l)}return await Hf(i),this.makeRequest(e,t-1,n)}calculateDefaultRetryTimeoutMillis(e,t){const i=t-e,o=Math.min(.5*Math.pow(2,i),8),a=1-Math.random()*.25;return o*a*1e3}calculateNonstreamingTimeout(e,t){if(36e5*e/128e3>6e5||t!=null&&e>t)throw new F("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#long-requests for more details");return 6e5}async buildRequest(e,{retryCount:t=0}={}){const n={...e},{method:r,path:i,query:o,defaultBaseURL:a}=n,l=this.buildURL(i,o,a);"timeout"in n&&Jf("timeout",n.timeout),n.timeout=n.timeout??this.timeout;const{bodyHeaders:u,body:d}=this.buildBody({options:n}),f=await this.buildHeaders({options:e,method:r,bodyHeaders:u,retryCount:t});return{req:{method:r,headers:f,...n.signal&&{signal:n.signal},...globalThis.ReadableStream&&d instanceof globalThis.ReadableStream&&{duplex:"half"},...d&&{body:d},...this.fetchOptions??{},...n.fetchOptions??{}},url:l,timeout:n.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:n,retryCount:r}){let i={};this.idempotencyHeader&&t!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),i[this.idempotencyHeader]=e.idempotencyKey);const o=z([i,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(r),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...Xf(),...this._options.dangerouslyAllowBrowser?{"anthropic-dangerous-direct-browser-access":"true"}:void 0,"anthropic-version":"2023-06-01"},await this.authHeaders(e),this._options.defaultHeaders,n,e.headers]);return this.validateHeaders(o),o.values}buildBody({options:{body:e,headers:t}}){if(!e)return{bodyHeaders:void 0,body:void 0};const n=z([t]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e=="string"&&n.values.has("content-type")||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:e}:typeof e=="object"&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&typeof e.next=="function")?{bodyHeaders:void 0,body:cc(e)}:S(this,Ls,"f").call(this,{body:e,headers:n})}}yi=ee,Ls=new WeakMap,gi=new WeakSet,Bc=c(function(){return this.baseURL!=="https://api.anthropic.com"},"_BaseAnthropic_baseURLOverridden2"),ee.Anthropic=yi,ee.HUMAN_PROMPT=Th,ee.AI_PROMPT=Eh,ee.DEFAULT_TIMEOUT=6e5,ee.AnthropicError=F,ee.APIError=re,ee.APIConnectionError=ys,ee.APIConnectionTimeoutError=Ha,ee.APIUserAbortError=ke,ee.NotFoundError=Ya,ee.ConflictError=Xa,ee.RateLimitError=Qa,ee.BadRequestError=Va,ee.AuthenticationError=Ga,ee.InternalServerError=ec,ee.PermissionDeniedError=za,ee.UnprocessableEntityError=Za,ee.toFile=yh;class kn extends ee{static{c(this,"Anthropic")}constructor(){super(...arguments),this.completions=new Pc(this),this.messages=new mi(this),this.models=new qc(this),this.beta=new yn(this)}}kn.Completions=Pc,kn.Messages=mi,kn.Models=qc,kn.Beta=yn;const _h="claude-sonnet-4-20250514";class vi{static{c(this,"TestEnvironment")}client;connectionId;testsDir;testBasePath;options;llm;state={};constructor({connectionId:e,testsDir:t,testBasePath:n,client:r,options:i,llm:o}){this.client=r,this.connectionId=e,this.testsDir=t,this.testBasePath=n,this.llm=o,this.options=i}static async create({connectionId:e,testBasePath:t,options:n}){const r=$n();if(!r)throw new Error("No configuration found. Please set MEMBRANE_WORKSPACE_KEY and MEMBRANE_WORKSPACE_SECRET environment variables, or run `membrane init` first.");if(!r.workspaceKey||!r.workspaceSecret)throw new Error("Missing workspace credentials");if(!r.anthropicApiKey)throw new Error("Anthropic API key not configured. Run `membrane init` to set up testing.");const i=new Ti({token:await this.createMembraneToken(r),apiUri:r.apiUri}),o=new kn({apiKey:r.anthropicApiKey}),a={complete:c(async({prompt:l,maxTokens:u})=>{const d=await o.messages.create({model:_h,max_tokens:u,messages:[{role:"user",content:l}]});return d.content[0].type==="text"?d.content[0].text:""},"complete")};return new vi({client:i,options:n,connectionId:e,testsDir:"src/testing/tests",testBasePath:t,llm:a})}async run(e){this.state={};const t={};for(const n of e)await n.run(),er(t,n.getResult());this.writeResults(t)}async readYaml(e){const t=q.join(this.testsDir,this.testBasePath,this.connectionId,e);return ur(t)}async writeYaml(e,t){const n=q.join(this.testsDir,this.testBasePath,this.connectionId,e);B.mkdirSync(q.dirname(n),{recursive:!0}),B.writeFileSync(n,Se.dump(t,{noRefs:!0}))}writeResults(e){const t=q.join(this.testsDir,this.testBasePath,this.connectionId);B.mkdirSync(t,{recursive:!0});const n=q.join(t,"test-results.yaml");B.writeFileSync(n,Se.dump(e,{noRefs:!0})),console.debug(`[TestRunner] Results written to: ${n}`)}static async createMembraneToken(e){const t=e.testCustomerId||"test-customer",n={id:t,name:t},r={issuer:e.workspaceKey,expiresIn:7200,algorithm:"HS512"};return Qs.sign(n,e.workspaceSecret,r)}}El.interpolate=/{{([\s\S]+?)}}/g;function wi(s,e){if(typeof s=="string"){const t=Tl(s),n={state:e,random:{number:c(()=>Vt.number.int(),"number"),alphaNumeric:c(i=>Vt.string.alphanumeric(i),"alphaNumeric")},faker:{company:{name:c(()=>Vt.company.name(),"name"),catchPhrase:c(()=>Vt.company.catchPhrase(),"catchPhrase")},internet:{email:c(()=>Vt.internet.email(),"email")}},entries:e["journal-entries"],orders:e["purchase-orders"]||e["sales-orders"],bills:e["vendor-bills"]},r=t(n);return s.includes("{{")&&s.includes("}}")&&(console.debug(`[TEMPLATE] Input: ${s}`),console.debug(`[TEMPLATE] Output: ${r}`)),r}return Array.isArray(s)?s.map(t=>wi(t,e)):typeof s=="object"&&s!==null?Object.fromEntries(Object.entries(s).map(([t,n])=>[t,wi(n,e)])):s}c(wi,"processNode");function Ih(s,e){return wi(s,e)}c(Ih,"handleTemplate");class Ah{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,r={},i={},o;for(;!t;)try{i=await e.readTestCase(),i||(i=await e.generateConfig(),await this.environment.writeYaml(e.getTestCasePath(),i),console.debug(`${k.bold.yellow("[initialized]")} ${k.yellow(e.path)}`)),o=Ih(i,this.environment.state),await e.run(o),console.debug(`${k.bold.green("[success]")} ${k.yellow(e.path)}`),t=!0,r=e.getResult(),Js(this.result,e.path,r)}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}`)}}Js(this.result,e.path,{error:Ee(l)}),t=!0,r={error:Ee(l)}}const a={...o,result:r};await this.environment.writeYaml(e.getTestCasePath(),a)}async runTestSuite(e){await e.run(),er(this.result,e.getResult())}}class Xe{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,this.resultsLocator=""}async fix(e){const t=await this.readTestCase();if(!t)throw new Error(`No config found for test ${this.path}`);const n=await this.fixTestCase({config:t,error:e});console.debug(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 r=await e();r?(this.logMsg(`\u2705 ${t}`),this.assertions.push({message:t,result:r})):(this.logMsg(`\u274C ${t}`),this.assertions.push({message:t,result:!1,details:n}))}catch(r){this.assertions.push({message:t,result:!1,details:Ee(r)}),this.logMsg(`\u274C ${t}: ${r.message}`)}}logMsg(e){console.debug(`${" ".repeat(this.level*2)}${e}`)}getTestCasePath(){return`${this.path}.test.yml`}}function bi(s,e){const t={};for(const n in e){if(!(n in s)){t[n]=e[n];continue}const r=s[n],i=e[n];if(r&&i&&typeof r=="object"&&typeof i=="object"){if(Array.isArray(r)&&Array.isArray(i)){const o=i.filter(a=>!r.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)||!Si(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(r)&&!Array.isArray(i)){const o=bi(r,i);o!==null&&(t[n]=o)}else t[n]=i;continue}Si(r,i)||(t[n]=i)}return Object.keys(t).length===0?null:t}c(bi,"getNotMatchingSubFields");function Si(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(Si,"softCompare");class Oh extends Xe{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=Hs(this.dataCollection);if(this.dataCollection.findById){const i=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).findById({id:t.id});await this.assert(()=>!!i.record,"Record is returned from findById"),i.record&&(this.environment.state[this.dataCollectionKey]={createdRecordId:t.id,createdRecord:i.record.fields});const o=_i(n),a=En(e.input.fields,o,{skipUnknownFields:!0}),l=En(i.record.fields,o),u=bi(l,a);await this.assert(()=>!u,"Returned fields match created fields",{difference:u,sentFields:a,receivedFields:l})}const r=tl(n??{});if(r.length>0){const i={};r.forEach(a=>{const l=nl(e.input.fields,a);typeof l<"u"&&Js(i,a,l)});const o=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).create({fields:i});await this.assert(()=>!!o.id,"Record can be created with schema-defined required fields only")}}async generateConfig(){const e=Hs(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=Ee(t),r=Hs(this.dataCollection),i=await this.getExampleRecordsForSchema(r),o=`I'm trying to create a data record in a data collection with the following fields schema:
175
175
 
176
176
  ${JSON.stringify(r,null,2)}
177
177
 
@@ -211,7 +211,7 @@ ${JSON.stringify(r,null,2)}`).join(`
211
211
 
212
212
  `)}.
213
213
 
214
- 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 _i(e,r=>{if(r.referenceCollection){const i=r.referenceCollection.key,o=r.referenceCollection.parameters,a=`${i}:${JSON.stringify(o||{})}`;t.has(a)||(t.add(a),n.push({key:i,parameters:o}))}return r}),n}async fetchExampleRecords(e){return(await this.environment.client.connection(this.environment.connectionId).dataCollection(e.key).list({parameters:e.parameters})).records.map(n=>({id:n.id,fields:n.fields??{}}))}async getExampleRecordsForSchema(e){const t=await this.findReferenceCollections(e),n={};for(const r of t){const i=Ii(r);n[i]=await this.fetchExampleRecords(r)}return n}}class Oh extends Xe{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=Ee(t),r=`I'm trying to delete a record from a data collection.
214
+ 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 Ii(e,r=>{if(r.referenceCollection){const i=r.referenceCollection.key,o=r.referenceCollection.parameters,a=`${i}:${JSON.stringify(o||{})}`;t.has(a)||(t.add(a),n.push({key:i,parameters:o}))}return r}),n}async fetchExampleRecords(e){return(await this.environment.client.connection(this.environment.connectionId).dataCollection(e.key).list({parameters:e.parameters})).records.map(n=>({id:n.id,fields:n.fields??{}}))}async getExampleRecordsForSchema(e){const t=await this.findReferenceCollections(e),n={};for(const r of t){const i=Ai(r);n[i]=await this.fetchExampleRecords(r)}return n}}class $h extends Xe{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=Ee(t),r=`I'm trying to delete a record from a data collection.
215
215
 
216
216
  I tried to delete a record with this ID:
217
217
 
@@ -231,7 +231,7 @@ Format your response as a JSON object with two fields:
231
231
  "id": "fixed id"
232
232
  }.
233
233
 
234
- Only return the JSON object, no other text or wrapping (like \`\`\`json or \`\`\`).`,i=await this.environment.llm.complete({prompt:r,maxTokens:1e3}),o=JSON.parse(i.trim());return console.warn(k.bold.yellow("[auto-fix]"),`${this.path}:`,o.explanation),{input:{id:o.id}}}}class $h extends Xe{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=Ee(t),r=`I'm trying to find a record by ID in a data collection.
234
+ Only return the JSON object, no other text or wrapping (like \`\`\`json or \`\`\`).`,i=await this.environment.llm.complete({prompt:r,maxTokens:1e3}),o=JSON.parse(i.trim());return console.warn(k.bold.yellow("[auto-fix]"),`${this.path}:`,o.explanation),{input:{id:o.id}}}}class Nh extends Xe{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=Ee(t),r=`I'm trying to find a record by ID in a data collection.
235
235
 
236
236
  I tried to find a record with this ID:
237
237
 
@@ -251,7 +251,7 @@ Format your response as a JSON object with two fields:
251
251
  "id": "fixed id"
252
252
  }.
253
253
 
254
- Only return the JSON object, no other text or wrapping (like \`\`\`json or \`\`\`).`,i=await this.environment.llm.complete({prompt:r,maxTokens:1e3}),o=JSON.parse(i.trim());return console.warn(k.bold.yellow("[auto-fix]"),`${this.path}:`,o.explanation),{input:{id:o.id}}}}class Nh extends Xe{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:r}=e.input.sort,i=t.records;if(i.length>1)for(let o=1;o<i.length;o++){const a=i[o-1].fields?.[n],l=i[o].fields?.[n];a==null||l==null||(r==="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=Ee(t),r=`I'm trying to list records from a data collection.
254
+ Only return the JSON object, no other text or wrapping (like \`\`\`json or \`\`\`).`,i=await this.environment.llm.complete({prompt:r,maxTokens:1e3}),o=JSON.parse(i.trim());return console.warn(k.bold.yellow("[auto-fix]"),`${this.path}:`,o.explanation),{input:{id:o.id}}}}class xh extends Xe{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:r}=e.input.sort,i=t.records;if(i.length>1)for(let o=1;o<i.length;o++){const a=i[o-1].fields?.[n],l=i[o].fields?.[n];a==null||l==null||(r==="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=Ee(t),r=`I'm trying to list records from a data collection.
255
255
 
256
256
  I tried to list records with these parameters:
257
257
 
@@ -271,7 +271,7 @@ Format your response as a JSON object with two fields:
271
271
  "input": { ... fixed parameters ... }
272
272
  }.
273
273
 
274
- Only return the JSON object, no other text or wrapping (like \`\`\`json or \`\`\`).`,i=await this.environment.llm.complete({prompt:r,maxTokens:1e3}),o=JSON.parse(i.trim());return console.warn(k.bold.yellow("[auto-fix]"),`${this.path}:`,o.explanation),{input:o.input}}}class xh extends Xe{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,i=(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=i.fields?.[o];await this.assert(()=>Si(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={},r=t.fields||{},i=Object.entries(r).filter(([o,a])=>o!=="links"&&a!=null&&a!=="").slice(0,1);if(i.length===0)throw new Error("No usable fields found in record for matching");for(const[o,a]of i)n[o]=a;return{input:{query:n}}}async fixTestCase({config:e,error:t}){const n=Ee(t),r=`I'm trying to match a record in a data collection.
274
+ Only return the JSON object, no other text or wrapping (like \`\`\`json or \`\`\`).`,i=await this.environment.llm.complete({prompt:r,maxTokens:1e3}),o=JSON.parse(i.trim());return console.warn(k.bold.yellow("[auto-fix]"),`${this.path}:`,o.explanation),{input:o.input}}}class Ph extends Xe{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,i=(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=i.fields?.[o];await this.assert(()=>Si(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={},r=t.fields||{},i=Object.entries(r).filter(([o,a])=>o!=="links"&&a!=null&&a!=="").slice(0,1);if(i.length===0)throw new Error("No usable fields found in record for matching");for(const[o,a]of i)n[o]=a;return{input:{query:n}}}async fixTestCase({config:e,error:t}){const n=Ee(t),r=`I'm trying to match a record in a data collection.
275
275
 
276
276
  I tried to match a record with this query:
277
277
 
@@ -291,7 +291,7 @@ Format your response as a JSON object with two fields:
291
291
  "query": { ... fixed query ... }
292
292
  }.
293
293
 
294
- Only return the JSON object, no other text or wrapping (like \`\`\`json or \`\`\`).`,i=await this.environment.llm.complete({prompt:r,maxTokens:1e3}),o=JSON.parse(i.trim());return console.warn(k.bold.yellow("[auto-fix]"),`${this.path}:`,o.explanation),{input:{query:o.query}}}}class Ph extends Xe{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(r=>r.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.
294
+ Only return the JSON object, no other text or wrapping (like \`\`\`json or \`\`\`).`,i=await this.environment.llm.complete({prompt:r,maxTokens:1e3}),o=JSON.parse(i.trim());return console.warn(k.bold.yellow("[auto-fix]"),`${this.path}:`,o.explanation),{input:{query:o.query}}}}class Mh extends Xe{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(r=>r.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.
295
295
 
296
296
  Record fields:
297
297
  ${JSON.stringify(e,null,2)}
@@ -316,7 +316,7 @@ Format your response as a JSON object with two fields:
316
316
  "input": { ... fixed parameters ... }
317
317
  }.
318
318
 
319
- Only return the JSON object, no other text or wrapping (like \`\`\`json or \`\`\`).`,i=await this.environment.llm.complete({prompt:r,maxTokens:1e3}),o=JSON.parse(i.trim());return console.warn(k.bold.yellow("[auto-fix]"),`${this.path}:`,o.explanation),{input:o.input,expectedRecordId:e.expectedRecordId}}}class Mh extends Xe{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 Rh extends Xe{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 r=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).findById({id:n.id});await this.assert(()=>!!r.record,"Record is returned from findById");const i=Vs(this.dataCollection),o=Ei(i),a=En(e.input.fields,o,{skipUnknownFields:!0}),l=En(r.record.fields,o),u=bi(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 r=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).list({});if(!r?.records?.length)throw new Error(`No records found to test update for ${this.dataCollectionKey}`);e=r.records[0].id}const t=Vs(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=Ee(t),r=Vs(this.dataCollection),i=await this.getExampleRecordsForSchema(r),o=`I'm trying to update a data record in a data collection with the following fields schema:
319
+ Only return the JSON object, no other text or wrapping (like \`\`\`json or \`\`\`).`,i=await this.environment.llm.complete({prompt:r,maxTokens:1e3}),o=JSON.parse(i.trim());return console.warn(k.bold.yellow("[auto-fix]"),`${this.path}:`,o.explanation),{input:o.input,expectedRecordId:e.expectedRecordId}}}class Rh extends Xe{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 Lh extends Xe{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 r=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).findById({id:n.id});await this.assert(()=>!!r.record,"Record is returned from findById");const i=Vs(this.dataCollection),o=_i(i),a=En(e.input.fields,o,{skipUnknownFields:!0}),l=En(r.record.fields,o),u=bi(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 r=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).list({});if(!r?.records?.length)throw new Error(`No records found to test update for ${this.dataCollectionKey}`);e=r.records[0].id}const t=Vs(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=Ee(t),r=Vs(this.dataCollection),i=await this.getExampleRecordsForSchema(r),o=`I'm trying to update a data record in a data collection with the following fields schema:
320
320
 
321
321
  ${JSON.stringify(r,null,2)}
322
322
 
@@ -356,9 +356,9 @@ ${JSON.stringify(r,null,2)}`).join(`
356
356
 
357
357
  `)}.
358
358
 
359
- 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 _i(e,r=>{if(r.referenceCollection){const i=r.referenceCollection.key,o=r.referenceCollection.parameters,a=`${i}:${JSON.stringify(o||{})}`;t.has(a)||(t.add(a),n.push({key:i,parameters:o}))}return r}),n}async fetchExampleRecords(e){return(await this.environment.client.connection(this.environment.connectionId).dataCollection(e.key).list({parameters:e.parameters})).records.map(n=>({id:n.id,fields:n.fields||{}}))}async getExampleRecordsForSchema(e){const t=await this.findReferenceCollections(e),n={};for(const r of t){const i=Ii(r);n[i]=await this.fetchExampleRecords(r)}return n}}const Ci={spec:{testerClass:Mh},create:{testerClass:Ah,operationKey:"create"},"find-by-id":{testerClass:$h,operationKey:"findById"},list:{testerClass:Nh,operationKey:"list"},match:{testerClass:xh,operationKey:"match"},search:{testerClass:Ph,operationKey:"search"},update:{testerClass:Rh,operationKey:"update"},delete:{testerClass:Oh,operationKey:"delete"}};class Lh extends Ih{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);H.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=Ci[e];if(!n)throw new Error(`Unknown test method "${e}". Available: ${this.getAvailableTestMethods(t).join(", ")}`);const r="operationKey"in n?n.operationKey:void 0;if(!this.isOperationAvailable(t,r))throw new Error(`${r} operation not available for data collection "${this.dataCollectionKey}"`);return this.instantiateTester(n,t)}createAllAvailableTesters(e){return Object.entries(Ci).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(Ci).filter(([,t])=>{const n="operationKey"in t?t.operationKey:void 0;return this.isOperationAvailable(e,n)}).map(([t])=>t)}displayTestSummary(e){H.info(`\u{1F4CA} ${e} test${e===1?"":"s"} executed`)}}class Dh extends Ff{static{c(this,"TestRunner")}constructor(e){super(e)}async initialize(){H.debug("Initializing test runner",{prefix:"TestRunner"})}async run(){try{const{testPath:e,path:t,fix:n}=this.options,r=e.split("/");r.length<2&&(H.error("Invalid test path. Expected format: <type>/<name>[/additional/path][/method]"),process.exit(1));const[i,o,...a]=r;i!=="connectors"&&(H.error(`Test type "${i}" is not yet fully implemented. Currently only "connectors" is fully supported.`),H.error("Supported test types: connectors"),process.exit(1));const l=o,u=i,d=[...a,...t?t.split("/"):[]].join("/"),f=await vi.create({connectionId:l,testBasePath:u,options:{fix:n}}),g=await f.client.get(`connections/${l}/data`),y=[],p=d?d.split("/"):[];if(p.length===0||p[0]==="data"){p[0]==="data"&&p.shift();let T,E;p.length>=1&&(E=p[0],p.length>=2&&p[1].trim()!==""&&(T=p[1]));for(const $ of g){if(E&&E!==$.key)continue;const I=new Lh({environment:f,dataCollectionKey:$.key,testMethod:T});y.push(I)}}y.length===0&&(H.error(`No test suites found for path: ${e}${d?"/"+d:""}`),process.exit(1));const w={};for(const T of y){await T.run();const E=T.getResult();H.debug(`Suite ${T.constructor.name} result:`,{prefix:"TestRunner"}),er(w,E)}console.debug("[TestRunner] All results collected:",Object.keys(w)),f.writeResults(w)}catch(e){throw console.error("Error in TestRunner.run():",e),e}}}const Ds=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(`
360
- `),"createExperimentalWarning");function jh(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",Ds()).action(async()=>{console.warn(Ds()),H.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"),"",Ds()].join(`
361
- `)).action(async(t,n)=>{try{console.warn(Ds()),t||(H.error("Test path is required"),process.exit(1)),H.header(`Testing: ${t}`);const r=new Dh({testPath:t,path:n.path,fix:n.fix});await r.initialize(),await r.run(),H.success("Tests completed")}catch(r){r instanceof Error&&(H.error(r.message),process.exit(1)),H.error("An unknown error occurred"),process.exit(1)}})}c(jh,"setupTestCommand");const Fh=c(()=>{try{const s=Vc(import.meta.url),e=Hc(s),t=Us(e,"..","package.json");return JSON.parse(Jc(t,"utf-8")).version}catch{return"1.0.0"}},"getPackageVersion"),Bc=Fh();function qh(){const s=new Gc().name("membrane").description("Command-line interface for Membrane Agent").version(Bc,"-v, --version","Output the version number").option("--verbose","Enable verbose logging (shows debug messages)");s.configureHelp({sortSubcommands:!0,subcommandTerm:c(n=>k.cyan(n.name()),"subcommandTerm"),commandUsage:c(n=>n.name()==="membrane"?`${k.cyan(n.name())} ${k.gray("[options]")} ${k.cyan("[command]")}`:n.usage(),"commandUsage"),optionTerm:c(n=>{const r=n.flags;return`${k.gray("\u25B8")} ${k.cyan(r)}`},"optionTerm"),subcommandDescription:c(n=>k.gray(n.description()),"subcommandDescription"),optionDescription:c(n=>k.gray(n.description),"optionDescription"),commandDescription:c(n=>k.gray(n.description()),"commandDescription")}),s.addHelpText("beforeAll",`
362
- ${k.bold.cyan("Membrane Agent CLI")} ${k.gray(`v${Bc}`)}
359
+ 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 Ii(e,r=>{if(r.referenceCollection){const i=r.referenceCollection.key,o=r.referenceCollection.parameters,a=`${i}:${JSON.stringify(o||{})}`;t.has(a)||(t.add(a),n.push({key:i,parameters:o}))}return r}),n}async fetchExampleRecords(e){return(await this.environment.client.connection(this.environment.connectionId).dataCollection(e.key).list({parameters:e.parameters})).records.map(n=>({id:n.id,fields:n.fields||{}}))}async getExampleRecordsForSchema(e){const t=await this.findReferenceCollections(e),n={};for(const r of t){const i=Ai(r);n[i]=await this.fetchExampleRecords(r)}return n}}const Ci={spec:{testerClass:Rh},create:{testerClass:Oh,operationKey:"create"},"find-by-id":{testerClass:Nh,operationKey:"findById"},list:{testerClass:xh,operationKey:"list"},match:{testerClass:Ph,operationKey:"match"},search:{testerClass:Mh,operationKey:"search"},update:{testerClass:Lh,operationKey:"update"},delete:{testerClass:$h,operationKey:"delete"}};class Dh extends Ah{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);H.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=Ci[e];if(!n)throw new Error(`Unknown test method "${e}". Available: ${this.getAvailableTestMethods(t).join(", ")}`);const r="operationKey"in n?n.operationKey:void 0;if(!this.isOperationAvailable(t,r))throw new Error(`${r} operation not available for data collection "${this.dataCollectionKey}"`);return this.instantiateTester(n,t)}createAllAvailableTesters(e){return Object.entries(Ci).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(Ci).filter(([,t])=>{const n="operationKey"in t?t.operationKey:void 0;return this.isOperationAvailable(e,n)}).map(([t])=>t)}displayTestSummary(e){H.info(`\u{1F4CA} ${e} test${e===1?"":"s"} executed`)}}class jh extends qf{static{c(this,"TestRunner")}constructor(e){super(e)}async initialize(){H.debug("Initializing test runner",{prefix:"TestRunner"})}async run(){try{const{testPath:e,path:t,fix:n}=this.options,r=e.split("/");r.length<2&&(H.error("Invalid test path. Expected format: <type>/<name>[/additional/path][/method]"),process.exit(1));const[i,o,...a]=r;i!=="connectors"&&(H.error(`Test type "${i}" is not yet fully implemented. Currently only "connectors" is fully supported.`),H.error("Supported test types: connectors"),process.exit(1));const l=o,u=i,d=[...a,...t?t.split("/"):[]].join("/"),f=await vi.create({connectionId:l,testBasePath:u,options:{fix:n}}),g=await f.client.get(`connections/${l}/data`),y=[],p=d?d.split("/"):[];if(p.length===0||p[0]==="data"){p[0]==="data"&&p.shift();let T,E;p.length>=1&&(E=p[0],p.length>=2&&p[1].trim()!==""&&(T=p[1]));for(const $ of g){if(E&&E!==$.key)continue;const I=new Dh({environment:f,dataCollectionKey:$.key,testMethod:T});y.push(I)}}y.length===0&&(H.error(`No test suites found for path: ${e}${d?"/"+d:""}`),process.exit(1));const w={};for(const T of y){await T.run();const E=T.getResult();H.debug(`Suite ${T.constructor.name} result:`,{prefix:"TestRunner"}),er(w,E)}console.debug("[TestRunner] All results collected:",Object.keys(w)),f.writeResults(w)}catch(e){throw console.error("Error in TestRunner.run():",e),e}}}const Ds=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(`
360
+ `),"createExperimentalWarning");function Fh(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",Ds()).action(async()=>{console.warn(Ds()),H.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"),"",Ds()].join(`
361
+ `)).action(async(t,n)=>{try{console.warn(Ds()),t||(H.error("Test path is required"),process.exit(1)),H.header(`Testing: ${t}`);const r=new jh({testPath:t,path:n.path,fix:n.fix});await r.initialize(),await r.run(),H.success("Tests completed")}catch(r){r instanceof Error&&(H.error(r.message),process.exit(1)),H.error("An unknown error occurred"),process.exit(1)}})}c(Fh,"setupTestCommand");const qh=c(()=>{try{const s=Gc(import.meta.url),e=Vc(s),t=Us(e,"..","package.json");return JSON.parse(Hc(t,"utf-8")).version}catch{return"1.0.0"}},"getPackageVersion"),Kc=qh();function Bh(){const s=new zc().name("membrane").description("Command-line interface for Membrane Agent").version(Kc,"-v, --version","Output the version number").option("--verbose","Enable verbose logging (shows debug messages)");s.configureHelp({sortSubcommands:!0,subcommandTerm:c(n=>k.cyan(n.name()),"subcommandTerm"),commandUsage:c(n=>n.name()==="membrane"?`${k.cyan(n.name())} ${k.gray("[options]")} ${k.cyan("[command]")}`:n.usage(),"commandUsage"),optionTerm:c(n=>{const r=n.flags;return`${k.gray("\u25B8")} ${k.cyan(r)}`},"optionTerm"),subcommandDescription:c(n=>k.gray(n.description()),"subcommandDescription"),optionDescription:c(n=>k.gray(n.description),"optionDescription"),commandDescription:c(n=>k.gray(n.description()),"commandDescription")}),s.addHelpText("beforeAll",`
362
+ ${k.bold.cyan("Membrane Agent CLI")} ${k.gray(`v${Kc}`)}
363
363
 
364
- `);const e=new Ld(hs.Cli,process.cwd());pf(s),_f(s,e),jf(s,e),Yd(s,e),Nl(s,e),Hd(s,e),sf(s),jh(s),ef(s),process.argv.length===2&&(s.outputHelp(),process.exit(0)),s.parse(),s.opts().verbose&&b.setVerboseMode(!0)}c(qh,"runCLI"),qh();
364
+ `);const e=new Dd(hs.Cli,process.cwd());mf(s),If(s,e),Ff(s,e),Xd(s,e),xl(s,e),Vd(s,e),rf(s),Fh(s),tf(s),process.argv.length===2&&(s.outputHelp(),process.exit(0)),s.parse(),s.opts().verbose&&b.setVerboseMode(!0)}c(Bh,"runCLI"),Bh();