@membranehq/cli 1.1.1 → 1.1.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 +92 -92
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,76 +1,76 @@
1
1
  #!/usr/bin/env node
2
- var uc=Object.defineProperty;var c=(s,e)=>uc(s,"name",{value:e,configurable:!0});import{jsx as g,jsxs as E,Fragment as Ns}from"react/jsx-runtime";import*as q from"node:path";import{join as xs,resolve as hc,dirname as fc}from"node:path";import{useInput as st,Box as v,Text as C,Newline as dc,render as gn}from"ink";import pc from"minimist";import{SWRConfig as mc}from"swr";import rt,{createContext as ii,useState as J,useEffect as Ve,useContext as oi,useMemo as gc,useRef as yc}from"react";import ai from"swr/immutable";import{MembraneConfigLoader as wc,WorkspaceElementType as K,WorkspaceElementSpecs as De,MembraneAxiosInstance as bc,MembraneClient as ci,WorkspaceSyncEventType as Sc,ConnectorFileUpdateType as Ms,setValueAtLocator as Rs,extractMembraneErrorData as ke,getDataCollectionCreateFields as Ps,excludeWriteOnlyFieldsFromSchema as li,valueToSchema as yn,getRequiredFieldsFromSchema as vc,getValueAtLocator as Cc,walkSchema as ui,makeDataLocationPath as hi,getDataCollectionUpdateFields as Ls}from"@membranehq/sdk";import kc from"lodash/isEqual.js";import*as L from"node:fs";import{mkdirSync as _c,writeFileSync as Tc,readFileSync as Ec}from"node:fs";import Ge from"js-yaml";import fi from"os";import{EventEmitter as Oc}from"events";import B from"path";import Ac from"conf";import Ds from"jsonwebtoken";import*as Ic from"node:crypto";import{createHash as $c}from"node:crypto";import Nc from"chokidar";import{EventSource as xc}from"eventsource";import P from"fs";import Mc from"archiver";import Rc from"form-data";import Pc from"unzipper";import*as Lc from"node:os";import{exec as Dc}from"node:child_process";import{Spinner as jc,TextInput as Fc,Select as Kc}from"@inkjs/ui";import wn from"ink-spinner";import Bc from"ink-text-input";import{fileURLToPath as qc}from"node:url";import T from"chalk";import{Command as Uc}from"commander";import js from"axios";import{FastMCP as Wc}from"fastmcp";import{z as ne}from"zod";import Fs from"lodash/merge.js";import{faker as Lt}from"@faker-js/faker";import Jc from"lodash/template.js";import Hc from"lodash/templateSettings.js";class xt{static{c(this,"ConfigLoader")}static instance=null;sdkLoader;constructor(){this.sdkLoader=new wc}static getInstance(){return xt.instance||(xt.instance=new xt),xt.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 Dt=xt.getInstance();var j={},bn={},di;function pi(){if(di)return bn;di=1,Object.defineProperty(bn,"__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"),bn.default=s,bn}c(pi,"requireJsCamelcase");var Sn={},mi;function gi(){if(mi)return Sn;mi=1,Object.defineProperty(Sn,"__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"),Sn.default=s,Sn}c(gi,"requireJsSnakecase");var vn={},yi;function wi(){if(yi)return vn;yi=1,Object.defineProperty(vn,"__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"),vn.default=s,vn}c(wi,"requireJsPascalcase");var Cn={},bi;function Vc(){if(bi)return Cn;bi=1,Object.defineProperty(Cn,"__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"),Cn.default=s,Cn}c(Vc,"requireJsDotcase");var kn={},Si;function Gc(){if(Si)return kn;Si=1,Object.defineProperty(kn,"__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"),kn.default=s,kn}c(Gc,"requireJsPathcase");var _n={},vi;function zc(){if(vi)return _n;vi=1,Object.defineProperty(_n,"__esModule",{value:!0});function s(e){return e===void 0&&(e=""),e?String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/([a-z])([A-Z])/g,function(t,n,r){return n+"_"+r.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g," ").toLowerCase():""}return c(s,"toTextCase"),_n.default=s,_n}c(zc,"requireJsTextcase");var Tn={},Ci;function Yc(){if(Ci)return Tn;Ci=1,Object.defineProperty(Tn,"__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"),Tn.default=s,Tn}c(Yc,"requireJsSentencecase");var En={},ki;function Xc(){if(ki)return En;ki=1,Object.defineProperty(En,"__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"),En.default=s,En}c(Xc,"requireJsHeadercase");var On={},_i;function Ti(){if(_i)return On;_i=1,Object.defineProperty(On,"__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"),On.default=s,On}c(Ti,"requireJsKebabcase");var it={},Ks={},Ei;function ot(){return Ei||(Ei=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})}}(Ks)),Ks}c(ot,"requireUtils");var Oi;function Qc(){if(Oi)return it;Oi=1;var s=it&&it.__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,h=l.length;u<h;u++,a++)o[a]=l[u];return o};Object.defineProperty(it,"__esModule",{value:!0});var e=ot();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 h=u;if(e.isValidObject(u))e.belongToTypes(h,r.keepTypesOnRecursion)||(h=t(u,r));else if(e.isArrayObject(u)){var f=t({key:u},r);h=f.key}return h}))),i[l]=a}),i}return c(t,"lowerKeys"),it.default=t,it}c(Qc,"requireLowercaseKeysObject");var at={},Ai;function Zc(){if(Ai)return at;Ai=1;var s=at&&at.__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,h=l.length;u<h;u++,a++)o[a]=l[u];return o};Object.defineProperty(at,"__esModule",{value:!0});var e=ot();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 h=u;if(e.isValidObject(u))e.belongToTypes(h,r.keepTypesOnRecursion)||(h=t(u,r));else if(e.isArrayObject(u)){var f=t({key:u},r);h=f.key}return h}))),i[l]=a}),i}return c(t,"upperKeys"),at.default=t,at}c(Zc,"requireUppercaseKeysObject");var ct={},Ii;function el(){if(Ii)return ct;Ii=1;var s=ct&&ct.__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],h=0,f=u.length;h<f;h++,l++)a[l]=u[h];return a};Object.defineProperty(ct,"__esModule",{value:!0});var e=ot(),t=pi();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(h){var f=h;if(e.isValidObject(h))e.belongToTypes(f,i.keepTypesOnRecursion)||(f=n(h,i));else if(e.isArrayObject(h)){var p=n({key:h},i);f=p.key}return f}))),o[u]=l}),o}return c(n,"camelKeys"),ct.default=n,ct}c(el,"requireCamelcaseKeysObject");var lt={},$i;function tl(){if($i)return lt;$i=1;var s=lt&&lt.__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],h=0,f=u.length;h<f;h++,l++)a[l]=u[h];return a};Object.defineProperty(lt,"__esModule",{value:!0});var e=ot(),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(h){var f=h;if(e.isValidObject(h))e.belongToTypes(f,i.keepTypesOnRecursion)||(f=n(h,i));else if(e.isArrayObject(h)){var p=n({key:h},i);f=p.key}return f}))),o[u]=l}),o}return c(n,"snakeKeys"),lt.default=n,lt}c(tl,"requireSnakecaseKeysObject");var ut={},Ni;function nl(){if(Ni)return ut;Ni=1;var s=ut&&ut.__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],h=0,f=u.length;h<f;h++,l++)a[l]=u[h];return a};Object.defineProperty(ut,"__esModule",{value:!0});var e=ot(),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(h){var f=h;if(e.isValidObject(h))e.belongToTypes(f,i.keepTypesOnRecursion)||(f=n(h,i));else if(e.isArrayObject(h)){var p=n({key:h},i);f=p.key}return f}))),o[u]=l}),o}return c(n,"pascalKeys"),ut.default=n,ut}c(nl,"requirePascalcaseKeysObject");var ht={},xi;function sl(){if(xi)return ht;xi=1;var s=ht&&ht.__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],h=0,f=u.length;h<f;h++,l++)a[l]=u[h];return a};Object.defineProperty(ht,"__esModule",{value:!0});var e=ot(),t=Ti();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(h){var f=h;if(e.isValidObject(h))e.belongToTypes(f,i.keepTypesOnRecursion)||(f=n(h,i));else if(e.isArrayObject(h)){var p=n({key:h},i);f=p.key}return f}))),o[u]=l}),o}return c(n,"kebabKeys"),ht.default=n,ht}c(sl,"requireKebabcaseKeysObject");var Mi;function rl(){if(Mi)return j;Mi=1,Object.defineProperty(j,"__esModule",{value:!0}),j.kebabKeys=j.pascalKeys=j.snakeKeys=j.camelKeys=j.upperKeys=j.lowerKeys=j.toLowerCase=j.toUpperCase=j.toKebabCase=j.toHeaderCase=j.toSentenceCase=j.toTextCase=j.toPathCase=j.toDotCase=j.toPascalCase=j.toSnakeCase=j.toCamelCase=void 0;var s=pi();j.toCamelCase=s.default;var e=gi();j.toSnakeCase=e.default;var t=wi();j.toPascalCase=t.default;var n=Vc();j.toDotCase=n.default;var r=Gc();j.toPathCase=r.default;var i=zc();j.toTextCase=i.default;var o=Yc();j.toSentenceCase=o.default;var a=Xc();j.toHeaderCase=a.default;var l=Ti();j.toKebabCase=l.default;var u=Qc();j.lowerKeys=u.default;var h=Zc();j.upperKeys=h.default;var f=el();j.camelKeys=f.default;var p=tl();j.snakeKeys=p.default;var m=nl();j.pascalKeys=m.default;var y=sl();j.kebabKeys=y.default;var d=c(function(_){return String(_||"").toLowerCase()},"toLowerCase");j.toLowerCase=d;var w=c(function(_){return String(_||"").toUpperCase()},"toUpperCase");j.toUpperCase=w;var k={toCamelCase:s.default,toSnakeCase:e.default,toPascalCase:t.default,toDotCase:n.default,toPathCase:r.default,toTextCase:i.default,toSentenceCase:o.default,toHeaderCase:a.default,toKebabCase:l.default,toUpperCase:w,toLowerCase:d,lowerKeys:u.default,upperKeys:h.default,camelKeys:f.default,snakeKeys:p.default,pascalKeys:m.default,kebabKeys:y.default};return j.default=k,j}c(rl,"requireLib");var Bs,Ri;function il(){return Ri||(Ri=1,Bs=rl()),Bs}c(il,"requireJsConvertCase");var ol=il();const Oe={UPDATE:"update",DELETE:"delete",CREATE:"create"},ae={INCOMING:"incoming",OUTGOING:"outgoing"},le={[K.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")},[K.Connector]:{element:"connector",elements:"connectors",exportable:!1},[K.Action]:{element:"action",elements:"actions",integrationSpecific:!0,exportCleanup:c(s=>(delete s.integration,s),"exportCleanup")},[K.AppDataSchema]:{element:"appDataSchema",elements:"appDataSchemas"},[K.AppEventType]:{element:"appEventType",elements:"appEventTypes"},[K.DataLinkTable]:{element:"dataLinkTable",elements:"dataLinkTables"},[K.DataSource]:{element:"dataSource",elements:"dataSources",parentKey:"universalDataSourceId",integrationSpecific:!0},[K.FieldMapping]:{element:"fieldMapping",elements:"fieldMappings",integrationSpecific:!0,parentKey:"universalFieldMappingId",exportCleanup:c(s=>(delete s.dataSourceId,s),"exportCleanup")},[K.Flow]:{element:"flow",elements:"flows",integrationSpecific:!0,parentKey:"universalFlowId"}};function al(s){return delete s.workspaceId,delete s.createdAt,delete s.updatedAt,delete s.revision,Object.keys(s).map(e=>{e.match(/universal.*Revision/g)&&delete s[e]}),s}c(al,"baseExportCleanup");const cl="membrane",ll=["**/node_modules/**","**/.git/**","**/.DS_Store","**/Thumbs.db","**/*.tmp","**/*.swp","**/*.swo","**/*.log","**/*.lock","**/.cache/**","**/.next/**","**/.vscode/**","**/.idea/**","**/.logs/**"];function ft(s){return q.join(s,cl)}c(ft,"getMembraneDir");const ul=["id","workspaceId","integrationId","createdAt","updatedAt","revision","archivedAt","baseUri","state","appliedToIntegrations","dependencies"],Pi=[K.Action,K.FieldMapping,K.Flow,K.DataSource];class Q{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||Q.extractIntegrationKey(r)}get id(){return Q.makeId(this.type,this.key,this.integrationKey)}get dirPath(){const e=De[this.type].apiPath;if(this.integrationKey){const t=De[K.Integration].apiPath;return q.join(t,this.integrationKey,e,this.key)}return q.join(e,this.key)}get path(){return q.join(this.dirPath,"spec.yaml")}get relativePath(){return q.relative(ft(process.cwd()),this.path)}get absolutePath(){return q.resolve(q.join(ft(process.cwd()),this.path))}isEqual(e){if(this.id!==e.id)return!1;const t=this.clean(),n=e.clean();return kc(t,n)}hasParent(){const e=this.getParentKey();return!!e&&!!this.data?.[e]}clean(){const e={...this.data};return ul.forEach(t=>{delete e[t]}),Object.keys(e).forEach(t=>{t.match(/universal.*Revision/)&&delete e[t]}),e}getParentKey(){let e="parentId";return le?.[this.type]?.parentKey&&(e=le?.[this.type]?.parentKey),e}static new(e,t,n,r){return new Q(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 Q(e,t.key,n,t)}static fromPathAndData(e,t){const n=Q.parsePath(e);if(!t)return;const r=t?.key||n?.key;return n?Q.new(n.type,r,n.integrationKey,t):void 0}static fromElement(e){return new Q(e.type,e.key,e.integrationKey,{...e.data})}static idFromPath(e){const t=Q.parsePath(e);if(t)return Q.makeId(t.type,t.key,t.integrationKey)}static makeId(e,t,n){return e===K.Integration?`${e}:${t}`:Q.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(De).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,h=this.getElementTypeFromPath(l);if(h)return{type:h,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:h}=a.groups,f=this.getElementTypeFromPath(u);if(f)return{type:f,key:h,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(K).find(t=>De[t].apiPath===e)}static getRelativePath(e){return q.relative(ft(process.cwd()),e)}static isIntegrationSpecific(e){return Pi.includes(e)}static canBeIntegrationSpecific(e){return Pi.includes(e)}}const Y={LogAdded:"logAdded",StateChanged:"stateChanged",StatsChanged:"statsChanged",ConflictsChanged:"conflictsChanged",McpStatusChanged:"mcpStatusChanged",McpServersChanged:"mcpServersChanged",ConfigChanged:"configChanged"};class qs extends Oc{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 hl="membrane",fl="membrane.config.yml",Us="https://api.integration.app";function Ws(){const s=process.cwd(),e=q.join(s,hl),t=q.join(s,fl),n=e,r=q.join(n,"workspace.yaml");return{membraneDirPath:e,configPath:t,payloadDirPath:n,workspaceDataFilePath:r}}c(Ws,"getPaths");function Li(){return Ws().membraneDirPath}c(Li,"getBasePath");const dl={pat:{type:"string"},workspace:{type:"object"}},Di=new Ac({schema:dl,configName:"config",cwd:B.join(fi.homedir(),".membrane")}),pl=c(s=>{Di.set("pat",s)},"setPat"),ji=c(()=>Di.get("pat"),"getPat");class Fi{static{c(this,"AccountApiClient")}constructor(e=Us){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=ji();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 ml=c(s=>{const e=new Fi(Us);return t=>e.get(t)},"createAccountApiFetcher");function An(s){return Dt.loadConfig(s)}c(An,"readProjectConfig");class gl{static{c(this,"RequestLogger")}constructor(e=bc){this.axiosInstance=e}interceptorsConfigured=!1;setup(){if(this.interceptorsConfigured)return;const e=c(t=>(this.logError(t),Promise.reject(t)),"errorHandler");this.axiosInstance.interceptors.request.use(t=>{t.metadata={startTime:Date.now()};const{method:n,url:r}=this.getRequestDetails(t);return b.debug(`[Request]: ${n} ${r}`),t},e),this.axiosInstance.interceptors.response.use(t=>{const{method:n,url:r}=this.getRequestDetails(t.config),i=this.getDuration(t.config),{status:o,statusText:a}=t;return b.debug(`[Response]: ${n} ${r} - ${o} ${a} (${i}ms)`),t},e),this.interceptorsConfigured=!0}getRequestDetails(e){const t=e?.method?.toUpperCase()??"UNKNOWN";if(!e?.url)return{method:t,url:"unknown"};if(e.url.startsWith("http"))return{method:t,url:e.url};const r=`${e.baseURL??""}/${e.url}`.replace(/\/+/g,"/").replace(/:\//,"://");return{method:t,url:r}}getDuration(e){return Date.now()-(e?.metadata?.startTime??Date.now())}logError(e){const{method:t,url:n}=this.getRequestDetails(e.config),r=this.getDuration(e.config);if(e.response){const{status:i,statusText:o}=e.response;b.error(`[Response]: ${t} ${n} - ${i} ${o} (${r}ms)`),e.response.data&&b.error(`[Response Data]: ${JSON.stringify(e.response.data,null,2)}`)}}}class yl{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.min(this.maxRequestsPerSecond/4,20),this.maxRetries=e.maxRetries??3,this.retryDelay=e.retryDelay??1e3,this.requestTimeout=e.requestTimeout??12e4,this.enableJitter=e.enableJitter!==!1,this.requestLogger=new gl,this.requestLogger.setup()}async withClient(e,t=process.cwd()){return this.withRetry(async()=>{const n=await this.getClient(t);await this.acquireSemaphore();try{return await this.waitIfNeeded(),this.recordRequest(),await this.withTimeout(e(n),this.requestTimeout)}finally{this.releaseSemaphore()}},"API request")}async generateAccessToken(e,t){return Ds.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=An(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 ci({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 U=new yl;async function Ki(s){const{id:e}=await U.withClient(t=>t.get("org-workspace-id"),s);return e}c(Ki,"getWorkspaceId");class wl extends qs{static{c(this,"WorkspaceNotifications")}constructor(e){super(),this.config=e}clientId;heartbeatInterval;isCleaningUp=!1;async connectToRemote(){await this.registerWithRemoteServer(),await this.startHeartbeatLoop()}async setState(e){this.emit(Y.StateChanged,{state:e}),await this.emitRemote({status:e})}setConflicts(e){this.emit(Y.ConflictsChanged,{conflicts:e})}setConfig(e){this.emit(Y.ConfigChanged,{config:e})}setStats(e){this.emit(Y.StatsChanged,{stats:e})}addLog(e){this.emit(Y.LogAdded,{log:e})}setMcpStatus(e){this.emit(Y.McpStatusChanged,{status:e})}async setMcpServers(e){this.emit(Y.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 U.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 U.withClient(t=>t.post("/local-clients",{hostname:fi.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 U.withClient(e=>e.post(`/local-clients/${this.clientId}/keep-alive`,{}))})}async emitRemote(e){this.clientId&&await this.withErrorHandling(async()=>{await U.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 Ae=new wl({heartbeatIntervalMs:15e3}),Bi=xs(ft(process.cwd()),".logs");class bl{static{c(this,"WorkspaceLogger")}_logs;workspaceNotifications;verboseMode=!1;constructor(){this._logs=[],this.workspaceNotifications=Ae}setVerboseMode(e){this.verboseMode=e}getVerboseMode(){return this.verboseMode}get logs(){return[...this._logs]}get latestLogs(){return this._logs.slice(this._logs.length-5)}log(e,t="info"){const n={timestamp:new Date().toISOString(),message:e,type:t};this._logs.push(n),this._logs=this._logs.slice(0,1e3),(t!=="debug"||this.verboseMode)&&this.workspaceNotifications.addLog(n)}info(e){this.log(e,"info")}success(e){this.log(e,"success")}warning(e){this.log(e,"warning")}error(e){this.log(e,"error")}debug(e){this.log(e,"debug")}clear(){this._logs=[]}saveLogsToFile(e){if(this._logs.length===0)return null;try{const t=new Date().toISOString().replace(/[:.]/g,"_"),n=e?`-${e}`:"",r=`${t}${n}.txt`;_c(Bi,{recursive:!0});const i=xs(Bi,r),o=this._logs.map(a=>`[${a.timestamp}] ${a.type?.toUpperCase()||"INFO"}: ${a.message}`).join(`
3
- `);return Tc(i,o,"utf-8"),i}catch(t){return console.error("Failed to save logs:",t),null}}}const b=new bl;class qi{static{c(this,"BaseWorkspaceElementsRepository")}constructor(e){this.cache=e}connectorsMapping;setConnectorsMapping(e){this.connectorsMapping=e}async getElements(){const e=[];try{const t=await this.getIntegrations();e.push(...t);const n=[K.Integration,K.Connector],r=Object.keys(le),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 e.data.id&&t?t=await this.updateElement(e,t,{elements:this.cache.getAll(),connectorsMapping:this.connectorsMapping}):t=await this.createElement(e,{elements:this.cache.getAll(),connectorsMapping:this.connectorsMapping}),t}async getElementsByType(e,t){return[]}async createElement(e,t){return e}async updateElement(e,t,n){return t}async getElement(e){}async getIntegrations(){return[]}async deleteElement(e,t){}}class Sl extends qi{static{c(this,"LocalWorkspaceElementsRepository")}basePath;constructor(e){super(e),this.basePath=ft(process.cwd())}async getElementsByType(e,t){const n=[],r=q.join(this.basePath,De[e].apiPath),i=await this.readElementsInDir(r);n.push(...i);for(const o of t){const a=q.join(this.basePath,De[K.Integration].apiPath,o.key,De[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=q.join(this.basePath,t.dirPath),r=q.join(this.basePath,t.path);return L.existsSync(n)||L.mkdirSync(n,{recursive:!0}),L.writeFileSync(r,Ge.dump(e.data)),b.debug(`[local] Written ${t.relativePath}`),t}async deleteElement(e){const t=q.join(this.basePath,e.path),n=q.join(this.basePath,e.dirPath);L.existsSync(t)&&L.rmSync(t,{force:!0}),this.pruneEmptyDir(n),b.debug(`[local] Deleted ${e.relativePath}`)}async getIntegrations(){const e=q.join(this.basePath,De[K.Integration].apiPath);return this.readElementsInDir(e)}async readElement(e){if(!L.existsSync(e))return;const t=L.readFileSync(e,"utf8"),n=Ge.load(t);if(n)return Q.fromPathAndData(e,n)}async readElementsInDir(e){const t=[];if(!L.existsSync(e))return t;const n=L.readdirSync(e);if(n.length===0)return t;const r=n.map(async o=>{const a=q.join(e,o,"spec.yaml");return this.readElement(a)});return(await Promise.all(r)).filter(o=>o!=null)}pruneEmptyDir(e){try{if(!e.startsWith(this.basePath)||e===this.basePath||!L.existsSync(e)||L.readdirSync(e).length>0)return;L.rmdirSync(e),this.pruneEmptyDir(q.dirname(e))}catch(t){console.warn(`Failed to prune empty directory ${e}:`,t)}}}class vl extends qi{static{c(this,"RemoteWorkspaceElementsRepository")}async getElementsByType(e,t){const n=await this.findAll(e);if(!Q.canBeIntegrationSpecific(e))return n;for(const r of t){const i=r.key,o=r.data.id,a=await this.findAll(e,o?{integrationId:o}:{integrationKey:i});n.push(...a)}return n.length>0&&b.debug(`[remote] Fetched ${n.length} ${e}${n.length!==1?"s":""}`),n}async getElement(e){const t=await U.withClient(n=>n[le[e.type].element](e.data.id).get(),process.cwd());return Q.fromData(e.type,t)}async createElement(e,t){const n=e.clean();this.transformElementForCreate(e,n,t);const r=await U.withClient(o=>o[le[e.type].elements].create(n),process.cwd()),i=Q.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");const r=e.clean();this.transformElementForUpdate(e,r,n);const i=await U.withClient(a=>a[le[e.type].element](t.data.id).put(r),process.cwd()),o=Q.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 U.withClient(t=>t[le[e.type].element](e.data.id).archive(),process.cwd()),b.debug(`[remote] Deleted ${e.id}`)}async getIntegrations(){const t=(await U.withClient(n=>n.integrations.findAll(),process.cwd())).map(n=>Q.fromData(K.Integration,n));return t.length>0&&b.debug(`[remote] Fetched ${t.length} integrations`),t}async getByInternalId(e,t){let n;try{n=await U.withClient(r=>r[le[t].element](e).get())}catch{return}return Q.fromData(t,n)}transformElementForCreate(e,t,n){if(e.integrationKey){const r=n.elements.find(i=>i.type===K.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===K.Integration){const r=n.connectorsMapping?.[t.connectorId];r&&(t.connectorId=r)}this.transformParentDependency(e,t,n)}transformElementForUpdate(e,t,n){if(e.type===K.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===K.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.transformParentDependency(e,t,n)}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={}){return(await U.withClient(r=>r[le[e].elements].findAll(t),process.cwd())).filter(r=>r.key).map(r=>Q.fromData(e,r))}}const Js=Symbol.for("yaml.alias"),Hs=Symbol.for("yaml.document"),je=Symbol.for("yaml.map"),Ui=Symbol.for("yaml.pair"),_e=Symbol.for("yaml.scalar"),dt=Symbol.for("yaml.seq"),pe=Symbol.for("yaml.node.type"),Fe=c(s=>!!s&&typeof s=="object"&&s[pe]===Js,"isAlias"),ze=c(s=>!!s&&typeof s=="object"&&s[pe]===Hs,"isDocument"),pt=c(s=>!!s&&typeof s=="object"&&s[pe]===je,"isMap"),H=c(s=>!!s&&typeof s=="object"&&s[pe]===Ui,"isPair"),W=c(s=>!!s&&typeof s=="object"&&s[pe]===_e,"isScalar$1"),mt=c(s=>!!s&&typeof s=="object"&&s[pe]===dt,"isSeq");function G(s){if(s&&typeof s=="object")switch(s[pe]){case je:case dt:return!0}return!1}c(G,"isCollection$1");function z(s){if(s&&typeof s=="object")switch(s[pe]){case Js:case je:case _e:case dt:return!0}return!1}c(z,"isNode");const Wi=c(s=>(W(s)||G(s))&&!!s.anchor,"hasAnchor"),ce=Symbol("break visit"),Ji=Symbol("skip children"),Te=Symbol("remove node");function Ye(s,e){const t=Hi(e);ze(s)?gt(null,s.contents,t,Object.freeze([s]))===Te&&(s.contents=null):gt(null,s,t,Object.freeze([]))}c(Ye,"visit$1"),Ye.BREAK=ce,Ye.SKIP=Ji,Ye.REMOVE=Te;function gt(s,e,t,n){const r=Vi(s,e,t,n);if(z(r)||H(r))return Gi(s,n,r),gt(s,r,t,n);if(typeof r!="symbol"){if(G(e)){n=Object.freeze(n.concat(e));for(let i=0;i<e.items.length;++i){const o=gt(i,e.items[i],t,n);if(typeof o=="number")i=o-1;else{if(o===ce)return ce;o===Te&&(e.items.splice(i,1),i-=1)}}}else if(H(e)){n=Object.freeze(n.concat(e));const i=gt("key",e.key,t,n);if(i===ce)return ce;i===Te&&(e.key=null);const o=gt("value",e.value,t,n);if(o===ce)return ce;o===Te&&(e.value=null)}}return r}c(gt,"visit_");async function In(s,e){const t=Hi(e);ze(s)?await yt(null,s.contents,t,Object.freeze([s]))===Te&&(s.contents=null):await yt(null,s,t,Object.freeze([]))}c(In,"visitAsync"),In.BREAK=ce,In.SKIP=Ji,In.REMOVE=Te;async function yt(s,e,t,n){const r=await Vi(s,e,t,n);if(z(r)||H(r))return Gi(s,n,r),yt(s,r,t,n);if(typeof r!="symbol"){if(G(e)){n=Object.freeze(n.concat(e));for(let i=0;i<e.items.length;++i){const o=await yt(i,e.items[i],t,n);if(typeof o=="number")i=o-1;else{if(o===ce)return ce;o===Te&&(e.items.splice(i,1),i-=1)}}}else if(H(e)){n=Object.freeze(n.concat(e));const i=await yt("key",e.key,t,n);if(i===ce)return ce;i===Te&&(e.key=null);const o=await yt("value",e.value,t,n);if(o===ce)return ce;o===Te&&(e.value=null)}}return r}c(yt,"visitAsync_");function Hi(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(Hi,"initVisitor");function Vi(s,e,t,n){if(typeof t=="function")return t(s,e,n);if(pt(e))return t.Map?.(s,e,n);if(mt(e))return t.Seq?.(s,e,n);if(H(e))return t.Pair?.(s,e,n);if(W(e))return t.Scalar?.(s,e,n);if(Fe(e))return t.Alias?.(s,e,n)}c(Vi,"callVisitor");function Gi(s,e,t){const n=e[e.length-1];if(G(n))n.items[s]=t;else if(H(n))s==="key"?n.key=t:n.value=t;else if(ze(n))n.contents=t;else{const r=Fe(n)?"alias":"scalar";throw new Error(`Cannot replace node with ${r} parent`)}}c(Gi,"replaceNode");const Cl={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},kl=c(s=>s.replace(/[!,[\]{}]/g,e=>Cl[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+kl(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&&z(e.contents)){const i={};Ye(e.contents,(o,a)=>{z(a)&&a.tag&&(i[a.tag]=!0)}),r=Object.keys(i)}else r=[];for(const[i,o]of n)i==="!!"&&o==="tag:yaml.org,2002:"||(!e||r.some(a=>a.startsWith(o)))&&t.push(`%TAG ${i} ${o}`);return t.join(`
4
- `)}}oe.defaultYaml={explicit:!1,version:"1.2"},oe.defaultTags={"!!":"tag:yaml.org,2002:"};function zi(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(zi,"anchorIsValid");function Yi(s){const e=new Set;return Ye(s,{Value(t,n){n.anchor&&e.add(n.anchor)}}),e}c(Yi,"anchorNames");function Xi(s,e){for(let t=1;;++t){const n=`${s}${t}`;if(!e.has(n))return n}}c(Xi,"findNewAnchor");function _l(s,e){const t=[],n=new Map;let r=null;return{onAnchor:c(i=>{t.push(i),r??(r=Yi(s));const o=Xi(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&&(W(o.node)||G(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(_l,"createNodeAnchors");function wt(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=wt(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=wt(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=wt(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=wt(s,n,r,i);o===void 0?delete n[r]:o!==i&&(n[r]=o)}return s.call(e,t,n)}c(wt,"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||!Wi(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 Vs{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(!ze(e))throw new TypeError("A document argument is required");const o={anchors:new Map,doc:e,keep:!0,mapAsMap:t===!0,mapKeyWarned:!1,maxAliasCount:typeof n=="number"?n:100},a=me(this,"",o);if(typeof r=="function")for(const{count:l,res:u}of o.anchors.values())r(u,l);return typeof i=="function"?wt(i,{"":a},"",a):a}}class $n extends Vs{static{c(this,"Alias")}constructor(e){super(Js),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=[],Ye(e,{Node:c((i,o)=>{(Fe(o)||Wi(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=Nn(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(zi(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 Nn(s,e,t){if(Fe(e)){const n=e.resolve(s),r=t&&n&&t.get(n);return r?r.count*r.aliasCount:0}else if(G(e)){let n=0;for(const r of e.items){const i=Nn(s,r,t);i>n&&(n=i)}return n}else if(H(e)){const n=Nn(s,e.key,t),r=Nn(s,e.value,t);return Math.max(n,r)}return 1}c(Nn,"getAliasCount");const Qi=c(s=>!s||typeof s!="function"&&typeof s!="object","isScalarValue");class M extends Vs{static{c(this,"Scalar")}constructor(e){super(_e),this.value=e}toJSON(e,t){return t?.keep?this.value:me(this.value,e,t)}toString(){return String(this.value)}}M.BLOCK_FOLDED="BLOCK_FOLDED",M.BLOCK_LITERAL="BLOCK_LITERAL",M.PLAIN="PLAIN",M.QUOTE_DOUBLE="QUOTE_DOUBLE",M.QUOTE_SINGLE="QUOTE_SINGLE";const Tl="tag:yaml.org,2002:";function El(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(El,"findTagObject");function jt(s,e,t){if(ze(s)&&(s=s.contents),z(s))return s;if(H(s)){const f=t.schema[je].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 $n(l.anchor);l={anchor:null,node:null},a.set(s,l)}e?.startsWith("!!")&&(e=Tl+e.slice(2));let u=El(s,e,o.tags);if(!u){if(s&&typeof s.toJSON=="function"&&(s=s.toJSON()),!s||typeof s!="object"){const f=new M(s);return l&&(l.node=f),f}u=s instanceof Map?o[je]:Symbol.iterator in Object(s)?o[dt]:o[je]}i&&(i(u),delete t.onTagObj);const h=u?.createNode?u.createNode(t.schema,s,t):typeof u?.nodeClass?.from=="function"?u.nodeClass.from(t.schema,s,t):new M(s);return e?h.tag=e:u.default||(h.tag=u.tag),l&&(l.node=h),h}c(jt,"createNode");function xn(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 jt(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(xn,"collectionFromPath");const Ft=c(s=>s==null||typeof s=="object"&&!!s[Symbol.iterator]().next().done,"isEmptyPath");class Zi extends Vs{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=>z(n)||H(n)?n.clone(e):n),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(Ft(e))this.add(t);else{const[n,...r]=e,i=this.get(n,!0);if(G(i))i.addIn(r,t);else if(i===void 0&&this.schema)this.set(n,xn(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(G(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&&W(i)?i.value:i:G(i)?i.getIn(r,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!H(t))return!1;const n=t.value;return n==null||e&&W(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 G(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(G(i))i.setIn(r,t);else if(i===void 0&&this.schema)this.set(n,xn(this.schema,r,t));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${r}`)}}}const Ol=c(s=>s.replace(/^(?!$)(?: $)?/gm,"#"),"stringifyComment");function Ie(s,e){return/^\n+$/.test(s)?s.substring(1):e?s.replace(/^(?! *$)/gm,e):s}c(Ie,"indentComment");const Xe=c((s,e,t)=>s.endsWith(`
2
+ var hc=Object.defineProperty;var c=(s,e)=>hc(s,"name",{value:e,configurable:!0});import{jsx as g,jsxs as E,Fragment as Ns}from"react/jsx-runtime";import*as F from"node:path";import{join as xs,resolve as fc,dirname as dc}from"node:path";import{useInput as nt,Box as v,Text as C,Newline as pc,render as gn}from"ink";import mc from"minimist";import{SWRConfig as gc}from"swr";import st,{createContext as oi,useState as J,useEffect as Ve,useContext as ai,useMemo as yc,useRef as wc}from"react";import ci from"swr/immutable";import{MembraneConfigLoader as bc,WorkspaceElementType as B,WorkspaceElementSpecs as De,MembraneAxiosInstance as Sc,MembraneClient as li,WorkspaceSyncEventType as vc,ConnectorFileUpdateType as Ms,setValueAtLocator as Rs,extractMembraneErrorData as ke,getDataCollectionCreateFields as Ps,excludeWriteOnlyFieldsFromSchema as ui,valueToSchema as yn,getRequiredFieldsFromSchema as Cc,getValueAtLocator as kc,walkSchema as hi,makeDataLocationPath as fi,getDataCollectionUpdateFields as Ls}from"@membranehq/sdk";import _c from"lodash/isEqual.js";import*as P from"node:fs";import{mkdirSync as Tc,writeFileSync as Ec,readFileSync as Ac}from"node:fs";import di from"os";import{EventEmitter as Oc}from"events";import q from"path";import Ic from"conf";import Ds from"jsonwebtoken";import Pt from"js-yaml";import*as $c from"node:crypto";import{createHash as Nc}from"node:crypto";import xc from"chokidar";import{EventSource as Mc}from"eventsource";import D from"fs";import Rc from"archiver";import Pc from"form-data";import Lc from"unzipper";import*as Dc from"node:os";import{exec as jc}from"node:child_process";import{Spinner as Fc,TextInput as Kc,Select as Bc}from"@inkjs/ui";import wn from"ink-spinner";import qc from"ink-text-input";import{fileURLToPath as Uc}from"node:url";import T from"chalk";import{Command as Wc}from"commander";import js from"axios";import{FastMCP as Jc}from"fastmcp";import{z as ne}from"zod";import Fs from"lodash/merge.js";import{faker as Lt}from"@faker-js/faker";import Hc from"lodash/template.js";import Vc from"lodash/templateSettings.js";class Nt{static{c(this,"ConfigLoader")}static instance=null;sdkLoader;constructor(){this.sdkLoader=new bc}static getInstance(){return Nt.instance||(Nt.instance=new Nt),Nt.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 Dt=Nt.getInstance();var j={},bn={},pi;function mi(){if(pi)return bn;pi=1,Object.defineProperty(bn,"__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"),bn.default=s,bn}c(mi,"requireJsCamelcase");var Sn={},gi;function yi(){if(gi)return Sn;gi=1,Object.defineProperty(Sn,"__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"),Sn.default=s,Sn}c(yi,"requireJsSnakecase");var vn={},wi;function bi(){if(wi)return vn;wi=1,Object.defineProperty(vn,"__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"),vn.default=s,vn}c(bi,"requireJsPascalcase");var Cn={},Si;function Gc(){if(Si)return Cn;Si=1,Object.defineProperty(Cn,"__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"),Cn.default=s,Cn}c(Gc,"requireJsDotcase");var kn={},vi;function zc(){if(vi)return kn;vi=1,Object.defineProperty(kn,"__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"),kn.default=s,kn}c(zc,"requireJsPathcase");var _n={},Ci;function Yc(){if(Ci)return _n;Ci=1,Object.defineProperty(_n,"__esModule",{value:!0});function s(e){return e===void 0&&(e=""),e?String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/([a-z])([A-Z])/g,function(t,n,r){return n+"_"+r.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g," ").toLowerCase():""}return c(s,"toTextCase"),_n.default=s,_n}c(Yc,"requireJsTextcase");var Tn={},ki;function Xc(){if(ki)return Tn;ki=1,Object.defineProperty(Tn,"__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"),Tn.default=s,Tn}c(Xc,"requireJsSentencecase");var En={},_i;function Qc(){if(_i)return En;_i=1,Object.defineProperty(En,"__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"),En.default=s,En}c(Qc,"requireJsHeadercase");var An={},Ti;function Ei(){if(Ti)return An;Ti=1,Object.defineProperty(An,"__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"),An.default=s,An}c(Ei,"requireJsKebabcase");var rt={},Ks={},Ai;function it(){return Ai||(Ai=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})}}(Ks)),Ks}c(it,"requireUtils");var Oi;function Zc(){if(Oi)return rt;Oi=1;var s=rt&&rt.__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,h=l.length;u<h;u++,a++)o[a]=l[u];return o};Object.defineProperty(rt,"__esModule",{value:!0});var e=it();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 h=u;if(e.isValidObject(u))e.belongToTypes(h,r.keepTypesOnRecursion)||(h=t(u,r));else if(e.isArrayObject(u)){var f=t({key:u},r);h=f.key}return h}))),i[l]=a}),i}return c(t,"lowerKeys"),rt.default=t,rt}c(Zc,"requireLowercaseKeysObject");var ot={},Ii;function el(){if(Ii)return ot;Ii=1;var s=ot&&ot.__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,h=l.length;u<h;u++,a++)o[a]=l[u];return o};Object.defineProperty(ot,"__esModule",{value:!0});var e=it();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 h=u;if(e.isValidObject(u))e.belongToTypes(h,r.keepTypesOnRecursion)||(h=t(u,r));else if(e.isArrayObject(u)){var f=t({key:u},r);h=f.key}return h}))),i[l]=a}),i}return c(t,"upperKeys"),ot.default=t,ot}c(el,"requireUppercaseKeysObject");var at={},$i;function tl(){if($i)return at;$i=1;var s=at&&at.__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],h=0,f=u.length;h<f;h++,l++)a[l]=u[h];return a};Object.defineProperty(at,"__esModule",{value:!0});var e=it(),t=mi();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(h){var f=h;if(e.isValidObject(h))e.belongToTypes(f,i.keepTypesOnRecursion)||(f=n(h,i));else if(e.isArrayObject(h)){var p=n({key:h},i);f=p.key}return f}))),o[u]=l}),o}return c(n,"camelKeys"),at.default=n,at}c(tl,"requireCamelcaseKeysObject");var ct={},Ni;function nl(){if(Ni)return ct;Ni=1;var s=ct&&ct.__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],h=0,f=u.length;h<f;h++,l++)a[l]=u[h];return a};Object.defineProperty(ct,"__esModule",{value:!0});var e=it(),t=yi();function n(r,i){if(i===void 0&&(i=e.DefaultOption),!e.isValidObject(r))return null;i=e.validateOptions(i);var o={};return Object.keys(r).forEach(function(a){var l=r[a],u=t.default(a);i.recursive&&(e.isValidObject(l)?e.belongToTypes(l,i.keepTypesOnRecursion)||(l=n(l,i)):i.recursiveInArray&&e.isArrayObject(l)&&(l=s(l).map(function(h){var f=h;if(e.isValidObject(h))e.belongToTypes(f,i.keepTypesOnRecursion)||(f=n(h,i));else if(e.isArrayObject(h)){var p=n({key:h},i);f=p.key}return f}))),o[u]=l}),o}return c(n,"snakeKeys"),ct.default=n,ct}c(nl,"requireSnakecaseKeysObject");var lt={},xi;function sl(){if(xi)return lt;xi=1;var s=lt&&lt.__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],h=0,f=u.length;h<f;h++,l++)a[l]=u[h];return a};Object.defineProperty(lt,"__esModule",{value:!0});var e=it(),t=bi();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(h){var f=h;if(e.isValidObject(h))e.belongToTypes(f,i.keepTypesOnRecursion)||(f=n(h,i));else if(e.isArrayObject(h)){var p=n({key:h},i);f=p.key}return f}))),o[u]=l}),o}return c(n,"pascalKeys"),lt.default=n,lt}c(sl,"requirePascalcaseKeysObject");var ut={},Mi;function rl(){if(Mi)return ut;Mi=1;var s=ut&&ut.__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],h=0,f=u.length;h<f;h++,l++)a[l]=u[h];return a};Object.defineProperty(ut,"__esModule",{value:!0});var e=it(),t=Ei();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(h){var f=h;if(e.isValidObject(h))e.belongToTypes(f,i.keepTypesOnRecursion)||(f=n(h,i));else if(e.isArrayObject(h)){var p=n({key:h},i);f=p.key}return f}))),o[u]=l}),o}return c(n,"kebabKeys"),ut.default=n,ut}c(rl,"requireKebabcaseKeysObject");var Ri;function il(){if(Ri)return j;Ri=1,Object.defineProperty(j,"__esModule",{value:!0}),j.kebabKeys=j.pascalKeys=j.snakeKeys=j.camelKeys=j.upperKeys=j.lowerKeys=j.toLowerCase=j.toUpperCase=j.toKebabCase=j.toHeaderCase=j.toSentenceCase=j.toTextCase=j.toPathCase=j.toDotCase=j.toPascalCase=j.toSnakeCase=j.toCamelCase=void 0;var s=mi();j.toCamelCase=s.default;var e=yi();j.toSnakeCase=e.default;var t=bi();j.toPascalCase=t.default;var n=Gc();j.toDotCase=n.default;var r=zc();j.toPathCase=r.default;var i=Yc();j.toTextCase=i.default;var o=Xc();j.toSentenceCase=o.default;var a=Qc();j.toHeaderCase=a.default;var l=Ei();j.toKebabCase=l.default;var u=Zc();j.lowerKeys=u.default;var h=el();j.upperKeys=h.default;var f=tl();j.camelKeys=f.default;var p=nl();j.snakeKeys=p.default;var m=sl();j.pascalKeys=m.default;var y=rl();j.kebabKeys=y.default;var d=c(function(_){return String(_||"").toLowerCase()},"toLowerCase");j.toLowerCase=d;var w=c(function(_){return String(_||"").toUpperCase()},"toUpperCase");j.toUpperCase=w;var k={toCamelCase:s.default,toSnakeCase:e.default,toPascalCase:t.default,toDotCase:n.default,toPathCase:r.default,toTextCase:i.default,toSentenceCase:o.default,toHeaderCase:a.default,toKebabCase:l.default,toUpperCase:w,toLowerCase:d,lowerKeys:u.default,upperKeys:h.default,camelKeys:f.default,snakeKeys:p.default,pascalKeys:m.default,kebabKeys:y.default};return j.default=k,j}c(il,"requireLib");var Bs,Pi;function ol(){return Pi||(Pi=1,Bs=il()),Bs}c(ol,"requireJsConvertCase");var al=ol();const Ae={UPDATE:"update",DELETE:"delete",CREATE:"create"},ae={INCOMING:"incoming",OUTGOING:"outgoing"},le={[B.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")},[B.Connector]:{element:"connector",elements:"connectors",exportable:!1},[B.Action]:{element:"action",elements:"actions",integrationSpecific:!0,exportCleanup:c(s=>(delete s.integration,s),"exportCleanup")},[B.AppDataSchema]:{element:"appDataSchema",elements:"appDataSchemas"},[B.AppEventType]:{element:"appEventType",elements:"appEventTypes"},[B.DataLinkTable]:{element:"dataLinkTable",elements:"dataLinkTables"},[B.DataSource]:{element:"dataSource",elements:"dataSources",parentKey:"universalDataSourceId",integrationSpecific:!0},[B.FieldMapping]:{element:"fieldMapping",elements:"fieldMappings",integrationSpecific:!0,parentKey:"universalFieldMappingId",exportCleanup:c(s=>(delete s.dataSourceId,s),"exportCleanup")},[B.Flow]:{element:"flow",elements:"flows",integrationSpecific:!0,parentKey:"universalFlowId"}};function cl(s){return delete s.workspaceId,delete s.createdAt,delete s.updatedAt,delete s.revision,Object.keys(s).map(e=>{e.match(/universal.*Revision/g)&&delete s[e]}),s}c(cl,"baseExportCleanup");const ll="membrane",ul=["**/node_modules/**","**/.git/**","**/.DS_Store","**/Thumbs.db","**/*.tmp","**/*.swp","**/*.swo","**/*.log","**/*.lock","**/.cache/**","**/.next/**","**/.vscode/**","**/.idea/**","**/.logs/**"];function ht(s){return F.join(s,ll)}c(ht,"getMembraneDir");const hl=["id","workspaceId","integrationId","createdAt","updatedAt","revision","archivedAt","baseUri","state","appliedToIntegrations","dependencies"],Li=[B.Action,B.FieldMapping,B.Flow,B.DataSource];class Q{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||Q.extractIntegrationKey(r)}get id(){return Q.makeId(this.type,this.key,this.integrationKey)}get dirPath(){const e=De[this.type].apiPath;if(this.integrationKey){const t=De[B.Integration].apiPath;return F.join(t,this.integrationKey,e,this.key)}return F.join(e,this.key)}get path(){return F.join(this.dirPath,"spec.yaml")}get relativePath(){return F.relative(ht(process.cwd()),this.path)}get absolutePath(){return F.resolve(F.join(ht(process.cwd()),this.path))}isEqual(e){if(this.id!==e.id)return!1;const t=this.clean(),n=e.clean();return _c(t,n)}hasParent(){const e=this.getParentKey();return!!e&&!!this.data?.[e]}clean(){const e={...this.data};return hl.forEach(t=>{delete e[t]}),Object.keys(e).forEach(t=>{t.match(/universal.*Revision/)&&delete e[t]}),e}getParentKey(){let e="parentId";return le?.[this.type]?.parentKey&&(e=le?.[this.type]?.parentKey),e}static new(e,t,n,r){return new Q(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 Q(e,t.key,n,t)}static fromPathAndData(e,t){const n=Q.parsePath(e);if(!t)return;const r=t?.key||n?.key;return n?Q.new(n.type,r,n.integrationKey,t):void 0}static fromElement(e){return new Q(e.type,e.key,e.integrationKey,{...e.data})}static idFromPath(e){const t=Q.parsePath(e);if(t)return Q.makeId(t.type,t.key,t.integrationKey)}static makeId(e,t,n){return e===B.Integration?`${e}:${t}`:Q.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(De).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,h=this.getElementTypeFromPath(l);if(h)return{type:h,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:h}=a.groups,f=this.getElementTypeFromPath(u);if(f)return{type:f,key:h,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(B).find(t=>De[t].apiPath===e)}static getRelativePath(e){return F.relative(ht(process.cwd()),e)}static isIntegrationSpecific(e){return Li.includes(e)}static canBeIntegrationSpecific(e){return Li.includes(e)}}const Y={LogAdded:"logAdded",StateChanged:"stateChanged",StatsChanged:"statsChanged",ConflictsChanged:"conflictsChanged",McpStatusChanged:"mcpStatusChanged",McpServersChanged:"mcpServersChanged",ConfigChanged:"configChanged"};class qs extends Oc{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 fl="membrane",dl="membrane.config.yml",Us="https://api.integration.app";function Ws(){const s=process.cwd(),e=F.join(s,fl),t=F.join(s,dl),n=e,r=F.join(n,"workspace.yaml");return{membraneDirPath:e,configPath:t,payloadDirPath:n,workspaceDataFilePath:r}}c(Ws,"getPaths");function Di(){return Ws().membraneDirPath}c(Di,"getBasePath");const pl={pat:{type:"string"},workspace:{type:"object"}},ji=new Ic({schema:pl,configName:"config",cwd:q.join(di.homedir(),".membrane")}),ml=c(s=>{ji.set("pat",s)},"setPat"),Fi=c(()=>ji.get("pat"),"getPat");class Ki{static{c(this,"AccountApiClient")}constructor(e=Us){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=Fi();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 gl=c(s=>{const e=new Ki(Us);return t=>e.get(t)},"createAccountApiFetcher");function On(s){return Dt.loadConfig(s)}c(On,"readProjectConfig");class yl{static{c(this,"RequestLogger")}constructor(e=Sc){this.axiosInstance=e}interceptorsConfigured=!1;setup(){if(this.interceptorsConfigured)return;const e=c(t=>(this.logError(t),Promise.reject(t)),"errorHandler");this.axiosInstance.interceptors.request.use(t=>{t.metadata={startTime:Date.now()};const{method:n,url:r}=this.getRequestDetails(t);return b.debug(`[Request]: ${n} ${r}`),t},e),this.axiosInstance.interceptors.response.use(t=>{const{method:n,url:r}=this.getRequestDetails(t.config),i=this.getDuration(t.config),{status:o,statusText:a}=t;return b.debug(`[Response]: ${n} ${r} - ${o} ${a} (${i}ms)`),t},e),this.interceptorsConfigured=!0}getRequestDetails(e){const t=e?.method?.toUpperCase()??"UNKNOWN";if(!e?.url)return{method:t,url:"unknown"};if(e.url.startsWith("http"))return{method:t,url:e.url};const r=`${e.baseURL??""}/${e.url}`.replace(/\/+/g,"/").replace(/:\//,"://");return{method:t,url:r}}getDuration(e){return Date.now()-(e?.metadata?.startTime??Date.now())}logError(e){const{method:t,url:n}=this.getRequestDetails(e.config),r=this.getDuration(e.config);if(e.response){const{status:i,statusText:o}=e.response;b.error(`[Response]: ${t} ${n} - ${i} ${o} (${r}ms)`),e.response.data&&b.error(`[Response Data]: ${JSON.stringify(e.response.data,null,2)}`)}}}class wl{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.min(this.maxRequestsPerSecond/4,20),this.maxRetries=e.maxRetries??3,this.retryDelay=e.retryDelay??1e3,this.requestTimeout=e.requestTimeout??12e4,this.enableJitter=e.enableJitter!==!1,this.requestLogger=new yl,this.requestLogger.setup()}async withClient(e,t=process.cwd()){return this.withRetry(async()=>{const n=await this.getClient(t);await this.acquireSemaphore();try{return await this.waitIfNeeded(),this.recordRequest(),await this.withTimeout(e(n),this.requestTimeout)}finally{this.releaseSemaphore()}},"API request")}async generateAccessToken(e,t){return Ds.sign({name:"Membrane Agent",isAdmin:!0,exp:Math.floor(Date.now()/1e3)+3600,iss:e},t,{algorithm:"HS512"})}isTokenValid(){return Date.now()<this.tokenExpiry}getCurrentConfig(e){const t=On(e);return!t?.workspaceKey||!t?.workspaceSecret?null:{workspaceKey:t.workspaceKey,workspaceSecret:t.workspaceSecret,apiUri:t.apiUri}}async createClient(e){const t=await this.generateAccessToken(e.workspaceKey,e.workspaceSecret);return this.tokenExpiry=Date.now()+36e5,this.currentConfig=e,new li({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 U=new wl;async function Bi(s){const{id:e}=await U.withClient(t=>t.get("org-workspace-id"),s);return e}c(Bi,"getWorkspaceId");class bl extends qs{static{c(this,"WorkspaceNotifications")}constructor(e){super(),this.config=e}clientId;heartbeatInterval;isCleaningUp=!1;async connectToRemote(){await this.registerWithRemoteServer(),await this.startHeartbeatLoop()}async setState(e){this.emit(Y.StateChanged,{state:e}),await this.emitRemote({status:e})}setConflicts(e){this.emit(Y.ConflictsChanged,{conflicts:e})}setConfig(e){this.emit(Y.ConfigChanged,{config:e})}setStats(e){this.emit(Y.StatsChanged,{stats:e})}addLog(e){this.emit(Y.LogAdded,{log:e})}setMcpStatus(e){this.emit(Y.McpStatusChanged,{status:e})}async setMcpServers(e){this.emit(Y.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 U.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 U.withClient(t=>t.post("/local-clients",{hostname:di.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 U.withClient(e=>e.post(`/local-clients/${this.clientId}/keep-alive`,{}))})}async emitRemote(e){this.clientId&&await this.withErrorHandling(async()=>{await U.withClient(t=>t.patch(`/local-clients/${this.clientId}`,e))})}async withErrorHandling(e){try{return await e()}catch(t){const n=t instanceof Error?t.message:String(t);return this.addLog({timestamp:new Date().toISOString(),message:`Failed to connect to remote: ${n}`,type:"error"}),null}}}const Oe=new bl({heartbeatIntervalMs:15e3}),qi=xs(ht(process.cwd()),".logs");class Sl{static{c(this,"WorkspaceLogger")}_logs;workspaceNotifications;verboseMode=!1;constructor(){this._logs=[],this.workspaceNotifications=Oe}setVerboseMode(e){this.verboseMode=e}getVerboseMode(){return this.verboseMode}get logs(){return[...this._logs]}get latestLogs(){return this._logs.slice(this._logs.length-5)}log(e,t="info"){const n={timestamp:new Date().toISOString(),message:e,type:t};this._logs.push(n),this._logs=this._logs.slice(0,1e3),(t!=="debug"||this.verboseMode)&&this.workspaceNotifications.addLog(n)}info(e){this.log(e,"info")}success(e){this.log(e,"success")}warning(e){this.log(e,"warning")}error(e){this.log(e,"error")}debug(e){this.log(e,"debug")}clear(){this._logs=[]}saveLogsToFile(e){if(this._logs.length===0)return null;try{const t=new Date().toISOString().replace(/[:.]/g,"_"),n=e?`-${e}`:"",r=`${t}${n}.txt`;Tc(qi,{recursive:!0});const i=xs(qi,r),o=this._logs.map(a=>`[${a.timestamp}] ${a.type?.toUpperCase()||"INFO"}: ${a.message}`).join(`
3
+ `);return Ec(i,o,"utf-8"),i}catch(t){return console.error("Failed to save logs:",t),null}}}const b=new Sl;class Ui{static{c(this,"BaseWorkspaceElementsRepository")}constructor(e){this.cache=e}connectorsMapping;setConnectorsMapping(e){this.connectorsMapping=e}async getElements(){const e=[];try{const t=await this.getIntegrations();e.push(...t);const n=[B.Integration,B.Connector],r=Object.keys(le),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 e.data.id&&t?t=await this.updateElement(e,t,{elements:this.cache.getAll(),connectorsMapping:this.connectorsMapping}):t=await this.createElement(e,{elements:this.cache.getAll(),connectorsMapping:this.connectorsMapping}),t}async getElementsByType(e,t){return[]}async createElement(e,t){return e}async updateElement(e,t,n){return t}async getElement(e){}async getIntegrations(){return[]}async deleteElement(e,t){}}function Js(s,e=!0){if(P.existsSync(s))try{const t=P.readFileSync(s,"utf8");return Pt.load(t)||void 0}catch(t){if(!e)return;if(t instanceof Error){const n=F.relative(process.cwd(),s);throw new Error(`Failed to parse YAML file "${n}": ${t.message}`)}throw t}}c(Js,"readYaml");function vl(s,e,t){try{const n=Pt.dump(e,t);P.writeFileSync(s,n,"utf8")}catch(n){if(n instanceof Error){const r=F.relative(process.cwd(),s);throw new Error(`Failed to write YAML file "${r}": ${n.message}`)}throw n}}c(vl,"writeYaml");class Cl extends Ui{static{c(this,"LocalWorkspaceElementsRepository")}basePath;constructor(e){super(e),this.basePath=ht(process.cwd())}async getElementsByType(e,t){const n=[],r=F.join(this.basePath,De[e].apiPath),i=await this.readElementsInDir(r);n.push(...i);for(const o of t){const a=F.join(this.basePath,De[B.Integration].apiPath,o.key,De[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=F.join(this.basePath,t.dirPath),r=F.join(this.basePath,t.path);return P.existsSync(n)||P.mkdirSync(n,{recursive:!0}),vl(r,e.data),b.debug(`[local] Written ${t.relativePath}`),t}async deleteElement(e){const t=F.join(this.basePath,e.path),n=F.join(this.basePath,e.dirPath);P.existsSync(t)&&P.rmSync(t,{force:!0}),this.pruneEmptyDir(n),b.debug(`[local] Deleted ${e.relativePath}`)}async getIntegrations(){const e=F.join(this.basePath,De[B.Integration].apiPath);return this.readElementsInDir(e)}async readElement(e){const t=Js(e);if(t)return Q.fromPathAndData(e,t)}async readElementsInDir(e){const t=[];if(!P.existsSync(e))return t;const n=P.readdirSync(e);if(n.length===0)return t;const r=n.map(async o=>{const a=F.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||!P.existsSync(e)||P.readdirSync(e).length>0)return;P.rmdirSync(e),this.pruneEmptyDir(F.dirname(e))}catch(t){console.warn(`Failed to prune empty directory ${e}:`,t)}}}class kl extends Ui{static{c(this,"RemoteWorkspaceElementsRepository")}async getElementsByType(e,t){const n=await this.findAll(e);if(!Q.canBeIntegrationSpecific(e))return n;for(const r of t){const i=r.key,o=r.data.id,a=await this.findAll(e,o?{integrationId:o}:{integrationKey:i});n.push(...a)}return n.length>0&&b.debug(`[remote] Fetched ${n.length} ${e}${n.length!==1?"s":""}`),n}async getElement(e){const t=await U.withClient(n=>n[le[e.type].element](e.data.id).get(),process.cwd());return Q.fromData(e.type,t)}async createElement(e,t){const n=e.clean();this.transformElementForCreate(e,n,t);const r=await U.withClient(o=>o[le[e.type].elements].create(n),process.cwd()),i=Q.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");const r=e.clean();this.transformElementForUpdate(e,r,n);const i=await U.withClient(a=>a[le[e.type].element](t.data.id).put(r),process.cwd()),o=Q.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 U.withClient(t=>t[le[e.type].element](e.data.id).archive(),process.cwd()),b.debug(`[remote] Deleted ${e.id}`)}async getIntegrations(){const t=(await U.withClient(n=>n.integrations.findAll(),process.cwd())).map(n=>Q.fromData(B.Integration,n));return t.length>0&&b.debug(`[remote] Fetched ${t.length} integrations`),t}async getByInternalId(e,t){let n;try{n=await U.withClient(r=>r[le[t].element](e).get())}catch{return}return Q.fromData(t,n)}transformElementForCreate(e,t,n){if(e.integrationKey){const r=n.elements.find(i=>i.type===B.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===B.Integration){const r=n.connectorsMapping?.[t.connectorId];r&&(t.connectorId=r)}this.transformParentDependency(e,t,n)}transformElementForUpdate(e,t,n){if(e.type===B.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===B.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.transformParentDependency(e,t,n)}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={}){return(await U.withClient(r=>r[le[e].elements].findAll(t),process.cwd())).filter(r=>r.key).map(r=>Q.fromData(e,r))}}const Hs=Symbol.for("yaml.alias"),Vs=Symbol.for("yaml.document"),je=Symbol.for("yaml.map"),Wi=Symbol.for("yaml.pair"),_e=Symbol.for("yaml.scalar"),ft=Symbol.for("yaml.seq"),pe=Symbol.for("yaml.node.type"),Fe=c(s=>!!s&&typeof s=="object"&&s[pe]===Hs,"isAlias"),Ge=c(s=>!!s&&typeof s=="object"&&s[pe]===Vs,"isDocument"),dt=c(s=>!!s&&typeof s=="object"&&s[pe]===je,"isMap"),H=c(s=>!!s&&typeof s=="object"&&s[pe]===Wi,"isPair"),W=c(s=>!!s&&typeof s=="object"&&s[pe]===_e,"isScalar$1"),pt=c(s=>!!s&&typeof s=="object"&&s[pe]===ft,"isSeq");function G(s){if(s&&typeof s=="object")switch(s[pe]){case je:case ft:return!0}return!1}c(G,"isCollection$1");function z(s){if(s&&typeof s=="object")switch(s[pe]){case Hs:case je:case _e:case ft:return!0}return!1}c(z,"isNode");const Ji=c(s=>(W(s)||G(s))&&!!s.anchor,"hasAnchor"),ce=Symbol("break visit"),Hi=Symbol("skip children"),Te=Symbol("remove node");function ze(s,e){const t=Vi(e);Ge(s)?mt(null,s.contents,t,Object.freeze([s]))===Te&&(s.contents=null):mt(null,s,t,Object.freeze([]))}c(ze,"visit$1"),ze.BREAK=ce,ze.SKIP=Hi,ze.REMOVE=Te;function mt(s,e,t,n){const r=Gi(s,e,t,n);if(z(r)||H(r))return zi(s,n,r),mt(s,r,t,n);if(typeof r!="symbol"){if(G(e)){n=Object.freeze(n.concat(e));for(let i=0;i<e.items.length;++i){const o=mt(i,e.items[i],t,n);if(typeof o=="number")i=o-1;else{if(o===ce)return ce;o===Te&&(e.items.splice(i,1),i-=1)}}}else if(H(e)){n=Object.freeze(n.concat(e));const i=mt("key",e.key,t,n);if(i===ce)return ce;i===Te&&(e.key=null);const o=mt("value",e.value,t,n);if(o===ce)return ce;o===Te&&(e.value=null)}}return r}c(mt,"visit_");async function In(s,e){const t=Vi(e);Ge(s)?await gt(null,s.contents,t,Object.freeze([s]))===Te&&(s.contents=null):await gt(null,s,t,Object.freeze([]))}c(In,"visitAsync"),In.BREAK=ce,In.SKIP=Hi,In.REMOVE=Te;async function gt(s,e,t,n){const r=await Gi(s,e,t,n);if(z(r)||H(r))return zi(s,n,r),gt(s,r,t,n);if(typeof r!="symbol"){if(G(e)){n=Object.freeze(n.concat(e));for(let i=0;i<e.items.length;++i){const o=await gt(i,e.items[i],t,n);if(typeof o=="number")i=o-1;else{if(o===ce)return ce;o===Te&&(e.items.splice(i,1),i-=1)}}}else if(H(e)){n=Object.freeze(n.concat(e));const i=await gt("key",e.key,t,n);if(i===ce)return ce;i===Te&&(e.key=null);const o=await gt("value",e.value,t,n);if(o===ce)return ce;o===Te&&(e.value=null)}}return r}c(gt,"visitAsync_");function Vi(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(Vi,"initVisitor");function Gi(s,e,t,n){if(typeof t=="function")return t(s,e,n);if(dt(e))return t.Map?.(s,e,n);if(pt(e))return t.Seq?.(s,e,n);if(H(e))return t.Pair?.(s,e,n);if(W(e))return t.Scalar?.(s,e,n);if(Fe(e))return t.Alias?.(s,e,n)}c(Gi,"callVisitor");function zi(s,e,t){const n=e[e.length-1];if(G(n))n.items[s]=t;else if(H(n))s==="key"?n.key=t:n.value=t;else if(Ge(n))n.contents=t;else{const r=Fe(n)?"alias":"scalar";throw new Error(`Cannot replace node with ${r} parent`)}}c(zi,"replaceNode");const _l={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},Tl=c(s=>s.replace(/[!,[\]{}]/g,e=>_l[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+Tl(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&&z(e.contents)){const i={};ze(e.contents,(o,a)=>{z(a)&&a.tag&&(i[a.tag]=!0)}),r=Object.keys(i)}else r=[];for(const[i,o]of n)i==="!!"&&o==="tag:yaml.org,2002:"||(!e||r.some(a=>a.startsWith(o)))&&t.push(`%TAG ${i} ${o}`);return t.join(`
4
+ `)}}oe.defaultYaml={explicit:!1,version:"1.2"},oe.defaultTags={"!!":"tag:yaml.org,2002:"};function Yi(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(Yi,"anchorIsValid");function Xi(s){const e=new Set;return ze(s,{Value(t,n){n.anchor&&e.add(n.anchor)}}),e}c(Xi,"anchorNames");function Qi(s,e){for(let t=1;;++t){const n=`${s}${t}`;if(!e.has(n))return n}}c(Qi,"findNewAnchor");function El(s,e){const t=[],n=new Map;let r=null;return{onAnchor:c(i=>{t.push(i),r??(r=Xi(s));const o=Qi(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&&(W(o.node)||G(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(El,"createNodeAnchors");function yt(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=yt(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=yt(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=yt(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=yt(s,n,r,i);o===void 0?delete n[r]:o!==i&&(n[r]=o)}return s.call(e,t,n)}c(yt,"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||!Ji(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 Gs{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(!Ge(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"?yt(i,{"":a},"",a):a}}class $n extends Gs{static{c(this,"Alias")}constructor(e){super(Hs),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=[],ze(e,{Node:c((i,o)=>{(Fe(o)||Ji(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=Nn(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(Yi(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 Nn(s,e,t){if(Fe(e)){const n=e.resolve(s),r=t&&n&&t.get(n);return r?r.count*r.aliasCount:0}else if(G(e)){let n=0;for(const r of e.items){const i=Nn(s,r,t);i>n&&(n=i)}return n}else if(H(e)){const n=Nn(s,e.key,t),r=Nn(s,e.value,t);return Math.max(n,r)}return 1}c(Nn,"getAliasCount");const Zi=c(s=>!s||typeof s!="function"&&typeof s!="object","isScalarValue");class M extends Gs{static{c(this,"Scalar")}constructor(e){super(_e),this.value=e}toJSON(e,t){return t?.keep?this.value:me(this.value,e,t)}toString(){return String(this.value)}}M.BLOCK_FOLDED="BLOCK_FOLDED",M.BLOCK_LITERAL="BLOCK_LITERAL",M.PLAIN="PLAIN",M.QUOTE_DOUBLE="QUOTE_DOUBLE",M.QUOTE_SINGLE="QUOTE_SINGLE";const Al="tag:yaml.org,2002:";function Ol(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(Ol,"findTagObject");function jt(s,e,t){if(Ge(s)&&(s=s.contents),z(s))return s;if(H(s)){const f=t.schema[je].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 $n(l.anchor);l={anchor:null,node:null},a.set(s,l)}e?.startsWith("!!")&&(e=Al+e.slice(2));let u=Ol(s,e,o.tags);if(!u){if(s&&typeof s.toJSON=="function"&&(s=s.toJSON()),!s||typeof s!="object"){const f=new M(s);return l&&(l.node=f),f}u=s instanceof Map?o[je]:Symbol.iterator in Object(s)?o[ft]:o[je]}i&&(i(u),delete t.onTagObj);const h=u?.createNode?u.createNode(t.schema,s,t):typeof u?.nodeClass?.from=="function"?u.nodeClass.from(t.schema,s,t):new M(s);return e?h.tag=e:u.default||(h.tag=u.tag),l&&(l.node=h),h}c(jt,"createNode");function xn(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 jt(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(xn,"collectionFromPath");const Ft=c(s=>s==null||typeof s=="object"&&!!s[Symbol.iterator]().next().done,"isEmptyPath");class eo extends Gs{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=>z(n)||H(n)?n.clone(e):n),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(Ft(e))this.add(t);else{const[n,...r]=e,i=this.get(n,!0);if(G(i))i.addIn(r,t);else if(i===void 0&&this.schema)this.set(n,xn(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(G(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&&W(i)?i.value:i:G(i)?i.getIn(r,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!H(t))return!1;const n=t.value;return n==null||e&&W(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 G(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(G(i))i.setIn(r,t);else if(i===void 0&&this.schema)this.set(n,xn(this.schema,r,t));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${r}`)}}}const Il=c(s=>s.replace(/^(?!$)(?: $)?/gm,"#"),"stringifyComment");function Ie(s,e){return/^\n+$/.test(s)?s.substring(1):e?s.replace(/^(?! *$)/gm,e):s}c(Ie,"indentComment");const Ye=c((s,e,t)=>s.endsWith(`
5
5
  `)?Ie(t,e):t.includes(`
6
6
  `)?`
7
- `+Ie(t,e):(s.endsWith(" ")?"":" ")+t,"lineComment"),eo="flow",Gs="block",Mn="quoted";function Rn(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=[],h={};let f=r-e.length;typeof n=="number"&&(n>r-Math.max(2,i)?u.push(0):f=r-n);let p,m,y=!1,d=-1,w=-1,k=-1;t===Gs&&(d=to(s,d,e.length),d!==-1&&(f=d+l));for(let A;A=s[d+=1];){if(t===Mn&&A==="\\"){switch(w=d,s[d+1]){case"x":d+=3;break;case"u":d+=5;break;case"U":d+=9;break;default:d+=1}k=d}if(A===`
8
- `)t===Gs&&(d=to(s,d,e.length)),f=d+e.length+l,p=void 0;else{if(A===" "&&m&&m!==" "&&m!==`
9
- `&&m!==" "){const O=s[d+1];O&&O!==" "&&O!==`
10
- `&&O!==" "&&(p=d)}if(d>=f)if(p)u.push(p),f=p+l,p=void 0;else if(t===Mn){for(;m===" "||m===" ";)m=A,A=s[d+=1],y=!0;const O=d>k+1?d-2:w-1;if(h[O])return s;u.push(O),h[O]=!0,f=O+l,p=void 0}else y=!0}m=A}if(y&&a&&a(),u.length===0)return s;o&&o();let _=s.slice(0,u[0]);for(let A=0;A<u.length;++A){const O=u[A],$=u[A+1]||s.length;O===0?_=`
11
- ${e}${s.slice(0,$)}`:(t===Mn&&h[O]&&(_+=`${s[O]}\\`),_+=`
12
- ${e}${s.slice(O+1,$)}`)}return _}c(Rn,"foldFlowLines");function to(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!==`
13
- `);n=e,r=e+1,i=s[r]}return n}c(to,"consumeMoreIndentedLines");const Pn=c((s,e)=>({indentAtStart:e?s.indent.length:s.indentAtStart,lineWidth:s.options.lineWidth,minContentWidth:s.options.minContentWidth}),"getFoldOptions"),Ln=c(s=>/^(%|---|\.\.\.)/m.test(s),"containsDocumentMarker");function Al(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]===`
14
- `){if(i-o>n)return!0;if(o=i+1,r-o<=n)return!1}return!0}c(Al,"lineLengthOverLimit");function Kt(s,e){const t=JSON.stringify(s);if(e.options.doubleQuotedAsJSON)return t;const{implicitKey:n}=e,r=e.options.doubleQuotedMinMultiLineLength,i=e.indent||(Ln(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 h=t.substr(l+2,4);switch(h){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:h.substr(0,2)==="00"?o+="\\x"+h.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)+`
7
+ `+Ie(t,e):(s.endsWith(" ")?"":" ")+t,"lineComment"),to="flow",zs="block",Mn="quoted";function Rn(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=[],h={};let f=r-e.length;typeof n=="number"&&(n>r-Math.max(2,i)?u.push(0):f=r-n);let p,m,y=!1,d=-1,w=-1,k=-1;t===zs&&(d=no(s,d,e.length),d!==-1&&(f=d+l));for(let O;O=s[d+=1];){if(t===Mn&&O==="\\"){switch(w=d,s[d+1]){case"x":d+=3;break;case"u":d+=5;break;case"U":d+=9;break;default:d+=1}k=d}if(O===`
8
+ `)t===zs&&(d=no(s,d,e.length)),f=d+e.length+l,p=void 0;else{if(O===" "&&m&&m!==" "&&m!==`
9
+ `&&m!==" "){const A=s[d+1];A&&A!==" "&&A!==`
10
+ `&&A!==" "&&(p=d)}if(d>=f)if(p)u.push(p),f=p+l,p=void 0;else if(t===Mn){for(;m===" "||m===" ";)m=O,O=s[d+=1],y=!0;const A=d>k+1?d-2:w-1;if(h[A])return s;u.push(A),h[A]=!0,f=A+l,p=void 0}else y=!0}m=O}if(y&&a&&a(),u.length===0)return s;o&&o();let _=s.slice(0,u[0]);for(let O=0;O<u.length;++O){const A=u[O],$=u[O+1]||s.length;A===0?_=`
11
+ ${e}${s.slice(0,$)}`:(t===Mn&&h[A]&&(_+=`${s[A]}\\`),_+=`
12
+ ${e}${s.slice(A+1,$)}`)}return _}c(Rn,"foldFlowLines");function no(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!==`
13
+ `);n=e,r=e+1,i=s[r]}return n}c(no,"consumeMoreIndentedLines");const Pn=c((s,e)=>({indentAtStart:e?s.indent.length:s.indentAtStart,lineWidth:s.options.lineWidth,minContentWidth:s.options.minContentWidth}),"getFoldOptions"),Ln=c(s=>/^(%|---|\.\.\.)/m.test(s),"containsDocumentMarker");function $l(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]===`
14
+ `){if(i-o>n)return!0;if(o=i+1,r-o<=n)return!1}return!0}c($l,"lineLengthOverLimit");function Kt(s,e){const t=JSON.stringify(s);if(e.options.doubleQuotedAsJSON)return t;const{implicitKey:n}=e,r=e.options.doubleQuotedMinMultiLineLength,i=e.indent||(Ln(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 h=t.substr(l+2,4);switch(h){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:h.substr(0,2)==="00"?o+="\\x"+h.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
15
 
16
16
  `;t[l+2]==="\\"&&t[l+3]==="n"&&t[l+4]!=='"';)o+=`
17
- `,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:Rn(o,i,Mn,Pn(e,!1))}c(Kt,"doubleQuotedString");function zs(s,e){if(e.options.singleQuote===!1||e.implicitKey&&s.includes(`
17
+ `,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:Rn(o,i,Mn,Pn(e,!1))}c(Kt,"doubleQuotedString");function Ys(s,e){if(e.options.singleQuote===!1||e.implicitKey&&s.includes(`
18
18
  `)||/[ \t]\n|\n[ \t]/.test(s))return Kt(s,e);const t=e.indent||(Ln(s)?" ":""),n="'"+s.replace(/'/g,"''").replace(/\n+/g,`$&
19
- ${t}`)+"'";return e.implicitKey?n:Rn(n,t,eo,Pn(e,!1))}c(zs,"singleQuotedString");function bt(s,e){const{singleQuote:t}=e.options;let n;if(t===!1)n=Kt;else{const r=s.includes('"'),i=s.includes("'");r&&!i?n=zs:i&&!r?n=Kt:n=t?zs:Kt}return n(s,e)}c(bt,"quotedString");let Ys;try{Ys=new RegExp(`(^|(?<!
19
+ ${t}`)+"'";return e.implicitKey?n:Rn(n,t,to,Pn(e,!1))}c(Ys,"singleQuotedString");function wt(s,e){const{singleQuote:t}=e.options;let n;if(t===!1)n=Kt;else{const r=s.includes('"'),i=s.includes("'");r&&!i?n=Ys:i&&!r?n=Kt:n=t?Ys:Kt}return n(s,e)}c(wt,"quotedString");let Xs;try{Xs=new RegExp(`(^|(?<!
20
20
  ))
21
21
  +(?!
22
- |$)`,"g")}catch{Ys=/\n+(?!\n|$)/g}function Dn({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 bt(t,n);const u=n.indent||(n.forceBlockIndent||Ln(t)?" ":""),h=o==="literal"?!0:o==="folded"||e===M.BLOCK_FOLDED?!1:e===M.BLOCK_LITERAL?!0:!Al(t,l,u.length);if(!t)return h?`|
22
+ |$)`,"g")}catch{Xs=/\n+(?!\n|$)/g}function Dn({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 wt(t,n);const u=n.indent||(n.forceBlockIndent||Ln(t)?" ":""),h=o==="literal"?!0:o==="folded"||e===M.BLOCK_FOLDED?!1:e===M.BLOCK_LITERAL?!0:!$l(t,l,u.length);if(!t)return h?`|
23
23
  `:`>
24
24
  `;let f,p;for(p=t.length;p>0;--p){const $=t[p-1];if($!==`
25
25
  `&&$!==" "&&$!==" ")break}let m=t.substring(p);const y=m.indexOf(`
26
26
  `);y===-1?f="-":t===m||y!==m.length-1?(f="+",i&&i()):f="",m&&(t=t.slice(0,-m.length),m[m.length-1]===`
27
- `&&(m=m.slice(0,-1)),m=m.replace(Ys,`$&${u}`));let d=!1,w,k=-1;for(w=0;w<t.length;++w){const $=t[w];if($===" ")d=!0;else if($===`
28
- `)k=w;else break}let _=t.substring(0,k<w?k+1:w);_&&(t=t.substring(_.length),_=_.replace(/\n+/g,`$&${u}`));let O=(d?u?"2":"1":"")+f;if(s&&(O+=" "+a(s.replace(/ ?[\r\n]+/g," ")),r&&r()),!h){const $=t.replace(/\n+/g,`
29
- $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${u}`);let N=!1;const F=Pn(n,!0);o!=="folded"&&e!==M.BLOCK_FOLDED&&(F.onOverflow=()=>{N=!0});const I=Rn(`${_}${$}${m}`,u,Gs,F);if(!N)return`>${O}
30
- ${u}${I}`}return t=t.replace(/\n+/g,`$&${u}`),`|${O}
31
- ${u}${_}${t}${m}`}c(Dn,"blockString");function Il(s,e,t,n){const{type:r,value:i}=s,{actualString:o,implicitKey:a,indent:l,indentStep:u,inFlow:h}=e;if(a&&i.includes(`
32
- `)||h&&/[[\]{},]/.test(i))return bt(i,e);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(i))return a||h||!i.includes(`
33
- `)?bt(i,e):Dn(s,e,t,n);if(!a&&!h&&r!==M.PLAIN&&i.includes(`
34
- `))return Dn(s,e,t,n);if(Ln(i)){if(l==="")return e.forceBlockIndent=!0,Dn(s,e,t,n);if(a&&l===u)return bt(i,e)}const f=i.replace(/\n+/g,`$&
35
- ${l}`);if(o){const p=c(d=>d.default&&d.tag!=="tag:yaml.org,2002:str"&&d.test?.test(f),"test"),{compat:m,tags:y}=e.doc.schema;if(y.some(p)||m?.some(p))return bt(i,e)}return a?f:Rn(f,l,eo,Pn(e,!1))}c(Il,"plainString");function Bt(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!==M.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(a=M.QUOTE_DOUBLE);const l=c(h=>{switch(h){case M.BLOCK_FOLDED:case M.BLOCK_LITERAL:return r||i?bt(o.value,e):Dn(o,e,t,n);case M.QUOTE_DOUBLE:return Kt(o.value,e);case M.QUOTE_SINGLE:return zs(o.value,e);case M.PLAIN:return Il(o,e,t,n);default:return null}},"_stringify");let u=l(a);if(u===null){const{defaultKeyType:h,defaultStringType:f}=e.options,p=r&&h||f;if(u=l(p),u===null)throw new Error(`Unsupported default string type ${p}`)}return u}c(Bt,"stringifyString");function no(s,e){const t=Object.assign({blockQuote:!0,commentString:Ol,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(no,"createStringifyContext");function $l(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(W(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($l,"getTagObject");function Nl(s,e,{anchors:t,doc:n}){if(!n.directives)return"";const r=[],i=(W(s)||G(s))&&s.anchor;i&&zi(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(Nl,"stringifyProps");function St(s,e,t,n){if(H(s))return s.toString(e,t,n);if(Fe(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=z(s)?s:e.doc.createNode(s,{onTagObj:c(l=>r=l,"onTagObj")});r??(r=$l(e.doc.schema.tags,i));const o=Nl(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):W(i)?Bt(i,e,t,n):i.toString(e,t,n);return o?W(i)||a[0]==="{"||a[0]==="["?`${o} ${a}`:`${o}
36
- ${e.indent}${a}`:a}c(St,"stringify$2");function xl({key:s,value:e},t,n,r){const{allNullValues:i,doc:o,indent:a,indentStep:l,options:{commentString:u,indentSeq:h,simpleKeys:f}}=t;let p=z(s)&&s.comment||null;if(f){if(p)throw new Error("With simple keys, key nodes cannot have comments");if(G(s)||!z(s)&&typeof s=="object"){const F="With simple keys, collection cannot be used as a key value";throw new Error(F)}}let m=!f&&(!s||p&&e==null&&!t.inFlow||G(s)||(W(s)?s.type===M.BLOCK_FOLDED||s.type===M.BLOCK_LITERAL:typeof s=="object"));t=Object.assign({},t,{allNullValues:!1,implicitKey:!m&&(f||!i),indent:a+l});let y=!1,d=!1,w=St(s,t,()=>y=!0,()=>d=!0);if(!m&&!t.inFlow&&w.length>1024){if(f)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");m=!0}if(t.inFlow){if(i||e==null)return y&&n&&n(),w===""?"?":m?`? ${w}`:w}else if(i&&!f||e==null&&m)return w=`? ${w}`,p&&!y?w+=Xe(w,t.indent,u(p)):d&&r&&r(),w;y&&(p=null),m?(p&&(w+=Xe(w,t.indent,u(p))),w=`? ${w}
37
- ${a}:`):(w=`${w}:`,p&&(w+=Xe(w,t.indent,u(p))));let k,_,A;z(e)?(k=!!e.spaceBefore,_=e.commentBefore,A=e.comment):(k=!1,_=null,A=null,e&&typeof e=="object"&&(e=o.createNode(e))),t.implicitKey=!1,!m&&!p&&W(e)&&(t.indentAtStart=w.length+1),d=!1,!h&&l.length>=2&&!t.inFlow&&!m&&mt(e)&&!e.flow&&!e.tag&&!e.anchor&&(t.indent=t.indent.substring(2));let O=!1;const $=St(e,t,()=>O=!0,()=>d=!0);let N=" ";if(p||k||_){if(N=k?`
38
- `:"",_){const F=u(_);N+=`
39
- ${Ie(F,t.indent)}`}$===""&&!t.inFlow?N===`
27
+ `&&(m=m.slice(0,-1)),m=m.replace(Xs,`$&${u}`));let d=!1,w,k=-1;for(w=0;w<t.length;++w){const $=t[w];if($===" ")d=!0;else if($===`
28
+ `)k=w;else break}let _=t.substring(0,k<w?k+1:w);_&&(t=t.substring(_.length),_=_.replace(/\n+/g,`$&${u}`));let A=(d?u?"2":"1":"")+f;if(s&&(A+=" "+a(s.replace(/ ?[\r\n]+/g," ")),r&&r()),!h){const $=t.replace(/\n+/g,`
29
+ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${u}`);let N=!1;const K=Pn(n,!0);o!=="folded"&&e!==M.BLOCK_FOLDED&&(K.onOverflow=()=>{N=!0});const I=Rn(`${_}${$}${m}`,u,zs,K);if(!N)return`>${A}
30
+ ${u}${I}`}return t=t.replace(/\n+/g,`$&${u}`),`|${A}
31
+ ${u}${_}${t}${m}`}c(Dn,"blockString");function Nl(s,e,t,n){const{type:r,value:i}=s,{actualString:o,implicitKey:a,indent:l,indentStep:u,inFlow:h}=e;if(a&&i.includes(`
32
+ `)||h&&/[[\]{},]/.test(i))return wt(i,e);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(i))return a||h||!i.includes(`
33
+ `)?wt(i,e):Dn(s,e,t,n);if(!a&&!h&&r!==M.PLAIN&&i.includes(`
34
+ `))return Dn(s,e,t,n);if(Ln(i)){if(l==="")return e.forceBlockIndent=!0,Dn(s,e,t,n);if(a&&l===u)return wt(i,e)}const f=i.replace(/\n+/g,`$&
35
+ ${l}`);if(o){const p=c(d=>d.default&&d.tag!=="tag:yaml.org,2002:str"&&d.test?.test(f),"test"),{compat:m,tags:y}=e.doc.schema;if(y.some(p)||m?.some(p))return wt(i,e)}return a?f:Rn(f,l,to,Pn(e,!1))}c(Nl,"plainString");function Bt(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!==M.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(a=M.QUOTE_DOUBLE);const l=c(h=>{switch(h){case M.BLOCK_FOLDED:case M.BLOCK_LITERAL:return r||i?wt(o.value,e):Dn(o,e,t,n);case M.QUOTE_DOUBLE:return Kt(o.value,e);case M.QUOTE_SINGLE:return Ys(o.value,e);case M.PLAIN:return Nl(o,e,t,n);default:return null}},"_stringify");let u=l(a);if(u===null){const{defaultKeyType:h,defaultStringType:f}=e.options,p=r&&h||f;if(u=l(p),u===null)throw new Error(`Unsupported default string type ${p}`)}return u}c(Bt,"stringifyString");function so(s,e){const t=Object.assign({blockQuote:!0,commentString:Il,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(so,"createStringifyContext");function xl(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(W(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(xl,"getTagObject");function Ml(s,e,{anchors:t,doc:n}){if(!n.directives)return"";const r=[],i=(W(s)||G(s))&&s.anchor;i&&Yi(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(Ml,"stringifyProps");function bt(s,e,t,n){if(H(s))return s.toString(e,t,n);if(Fe(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=z(s)?s:e.doc.createNode(s,{onTagObj:c(l=>r=l,"onTagObj")});r??(r=xl(e.doc.schema.tags,i));const o=Ml(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):W(i)?Bt(i,e,t,n):i.toString(e,t,n);return o?W(i)||a[0]==="{"||a[0]==="["?`${o} ${a}`:`${o}
36
+ ${e.indent}${a}`:a}c(bt,"stringify$2");function Rl({key:s,value:e},t,n,r){const{allNullValues:i,doc:o,indent:a,indentStep:l,options:{commentString:u,indentSeq:h,simpleKeys:f}}=t;let p=z(s)&&s.comment||null;if(f){if(p)throw new Error("With simple keys, key nodes cannot have comments");if(G(s)||!z(s)&&typeof s=="object"){const K="With simple keys, collection cannot be used as a key value";throw new Error(K)}}let m=!f&&(!s||p&&e==null&&!t.inFlow||G(s)||(W(s)?s.type===M.BLOCK_FOLDED||s.type===M.BLOCK_LITERAL:typeof s=="object"));t=Object.assign({},t,{allNullValues:!1,implicitKey:!m&&(f||!i),indent:a+l});let y=!1,d=!1,w=bt(s,t,()=>y=!0,()=>d=!0);if(!m&&!t.inFlow&&w.length>1024){if(f)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");m=!0}if(t.inFlow){if(i||e==null)return y&&n&&n(),w===""?"?":m?`? ${w}`:w}else if(i&&!f||e==null&&m)return w=`? ${w}`,p&&!y?w+=Ye(w,t.indent,u(p)):d&&r&&r(),w;y&&(p=null),m?(p&&(w+=Ye(w,t.indent,u(p))),w=`? ${w}
37
+ ${a}:`):(w=`${w}:`,p&&(w+=Ye(w,t.indent,u(p))));let k,_,O;z(e)?(k=!!e.spaceBefore,_=e.commentBefore,O=e.comment):(k=!1,_=null,O=null,e&&typeof e=="object"&&(e=o.createNode(e))),t.implicitKey=!1,!m&&!p&&W(e)&&(t.indentAtStart=w.length+1),d=!1,!h&&l.length>=2&&!t.inFlow&&!m&&pt(e)&&!e.flow&&!e.tag&&!e.anchor&&(t.indent=t.indent.substring(2));let A=!1;const $=bt(e,t,()=>A=!0,()=>d=!0);let N=" ";if(p||k||_){if(N=k?`
38
+ `:"",_){const K=u(_);N+=`
39
+ ${Ie(K,t.indent)}`}$===""&&!t.inFlow?N===`
40
40
  `&&(N=`
41
41
 
42
42
  `):N+=`
43
- ${t.indent}`}else if(!m&&G(e)){const F=$[0],I=$.indexOf(`
44
- `),ee=I!==-1,Le=t.inFlow??e.flow??e.items.length===0;if(ee||!Le){let nt=!1;if(ee&&(F==="&"||F==="!")){let te=$.indexOf(" ");F==="&"&&te!==-1&&te<I&&$[te+1]==="!"&&(te=$.indexOf(" ",te+1)),(te===-1||I<te)&&(nt=!0)}nt||(N=`
43
+ ${t.indent}`}else if(!m&&G(e)){const K=$[0],I=$.indexOf(`
44
+ `),ee=I!==-1,Le=t.inFlow??e.flow??e.items.length===0;if(ee||!Le){let tt=!1;if(ee&&(K==="&"||K==="!")){let te=$.indexOf(" ");K==="&"&&te!==-1&&te<I&&$[te+1]==="!"&&(te=$.indexOf(" ",te+1)),(te===-1||I<te)&&(tt=!0)}tt||(N=`
45
45
  ${t.indent}`)}}else($===""||$[0]===`
46
- `)&&(N="");return w+=N+$,t.inFlow?O&&n&&n():A&&!O?w+=Xe(w,t.indent,u(A)):d&&r&&r(),w}c(xl,"stringifyPair");function so(s,e){(s==="debug"||s==="warn")&&console.warn(e)}c(so,"warn");const jn="<<",$e={identify:c(s=>s===jn||typeof s=="symbol"&&s.description===jn,"identify"),default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:c(()=>Object.assign(new M(Symbol(jn)),{addToJSMap:ro}),"resolve"),stringify:c(()=>jn,"stringify")},Ml=c((s,e)=>($e.identify(e)||W(e)&&(!e.type||e.type===M.PLAIN)&&$e.identify(e.value))&&s?.doc.schema.tags.some(t=>t.tag===$e.tag&&t.default),"isMergeKey");function ro(s,e,t){if(t=s&&Fe(t)?t.resolve(s.doc):t,mt(t))for(const n of t.items)Xs(s,e,n);else if(Array.isArray(t))for(const n of t)Xs(s,e,n);else Xs(s,e,t)}c(ro,"addMergeToJSMap");function Xs(s,e,t){const n=s&&Fe(t)?t.resolve(s.doc):t;if(!pt(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(Xs,"mergeValue");function io(s,e,{key:t,value:n}){if(z(t)&&t.addToJSMap)t.addToJSMap(s,e,n);else if(Ml(s,t))ro(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=Rl(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(io,"addPairToJSMap");function Rl(s,e,t){if(e===null)return"";if(typeof e!="object")return String(e);if(z(s)&&t?.doc){const n=no(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)+'..."'),so(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(Rl,"stringifyKey");function Qs(s,e,t){const n=jt(s,void 0,t),r=jt(e,void 0,t);return new se(n,r)}c(Qs,"createPair");class se{static{c(this,"Pair")}constructor(e,t=null){Object.defineProperty(this,pe,{value:Ui}),this.key=e,this.value=t}clone(e){let{key:t,value:n}=this;return z(t)&&(t=t.clone(e)),z(n)&&(n=n.clone(e)),new se(t,n)}toJSON(e,t){const n=t?.mapAsMap?new Map:{};return io(t,n,this)}toString(e,t,n){return e?.doc?xl(this,e,t,n):JSON.stringify(this)}}function oo(s,e,t){return(e.inFlow??s.flow?Ll:Pl)(s,e,t)}c(oo,"stringifyCollection");function Pl({comment:s,items:e},t,{blockItemPrefix:n,flowChars:r,itemIndent:i,onChompKeep:o,onComment:a}){const{indent:l,options:{commentString:u}}=t,h=Object.assign({},t,{indent:i,type:null});let f=!1;const p=[];for(let y=0;y<e.length;++y){const d=e[y];let w=null;if(z(d))!f&&d.spaceBefore&&p.push(""),Fn(t,p,d.commentBefore,f),d.comment&&(w=d.comment);else if(H(d)){const _=z(d.key)?d.key:null;_&&(!f&&_.spaceBefore&&p.push(""),Fn(t,p,_.commentBefore,f))}f=!1;let k=St(d,h,()=>w=null,()=>f=!0);w&&(k+=Xe(k,i,u(w))),f&&w&&(f=!1),p.push(n+k)}let m;if(p.length===0)m=r.start+r.end;else{m=p[0];for(let y=1;y<p.length;++y){const d=p[y];m+=d?`
46
+ `)&&(N="");return w+=N+$,t.inFlow?A&&n&&n():O&&!A?w+=Ye(w,t.indent,u(O)):d&&r&&r(),w}c(Rl,"stringifyPair");function ro(s,e){(s==="debug"||s==="warn")&&console.warn(e)}c(ro,"warn");const jn="<<",$e={identify:c(s=>s===jn||typeof s=="symbol"&&s.description===jn,"identify"),default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:c(()=>Object.assign(new M(Symbol(jn)),{addToJSMap:io}),"resolve"),stringify:c(()=>jn,"stringify")},Pl=c((s,e)=>($e.identify(e)||W(e)&&(!e.type||e.type===M.PLAIN)&&$e.identify(e.value))&&s?.doc.schema.tags.some(t=>t.tag===$e.tag&&t.default),"isMergeKey");function io(s,e,t){if(t=s&&Fe(t)?t.resolve(s.doc):t,pt(t))for(const n of t.items)Qs(s,e,n);else if(Array.isArray(t))for(const n of t)Qs(s,e,n);else Qs(s,e,t)}c(io,"addMergeToJSMap");function Qs(s,e,t){const n=s&&Fe(t)?t.resolve(s.doc):t;if(!dt(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(Qs,"mergeValue");function oo(s,e,{key:t,value:n}){if(z(t)&&t.addToJSMap)t.addToJSMap(s,e,n);else if(Pl(s,t))io(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=Ll(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 Ll(s,e,t){if(e===null)return"";if(typeof e!="object")return String(e);if(z(s)&&t?.doc){const n=so(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)+'..."'),ro(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(Ll,"stringifyKey");function Zs(s,e,t){const n=jt(s,void 0,t),r=jt(e,void 0,t);return new se(n,r)}c(Zs,"createPair");class se{static{c(this,"Pair")}constructor(e,t=null){Object.defineProperty(this,pe,{value:Wi}),this.key=e,this.value=t}clone(e){let{key:t,value:n}=this;return z(t)&&(t=t.clone(e)),z(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?Rl(this,e,t,n):JSON.stringify(this)}}function ao(s,e,t){return(e.inFlow??s.flow?jl:Dl)(s,e,t)}c(ao,"stringifyCollection");function Dl({comment:s,items:e},t,{blockItemPrefix:n,flowChars:r,itemIndent:i,onChompKeep:o,onComment:a}){const{indent:l,options:{commentString:u}}=t,h=Object.assign({},t,{indent:i,type:null});let f=!1;const p=[];for(let y=0;y<e.length;++y){const d=e[y];let w=null;if(z(d))!f&&d.spaceBefore&&p.push(""),Fn(t,p,d.commentBefore,f),d.comment&&(w=d.comment);else if(H(d)){const _=z(d.key)?d.key:null;_&&(!f&&_.spaceBefore&&p.push(""),Fn(t,p,_.commentBefore,f))}f=!1;let k=bt(d,h,()=>w=null,()=>f=!0);w&&(k+=Ye(k,i,u(w))),f&&w&&(f=!1),p.push(n+k)}let m;if(p.length===0)m=r.start+r.end;else{m=p[0];for(let y=1;y<p.length;++y){const d=p[y];m+=d?`
47
47
  ${l}${d}`:`
48
48
  `}}return s?(m+=`
49
- `+Ie(u(s),l),a&&a()):f&&o&&o(),m}c(Pl,"stringifyBlockCollection");function Ll({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,h=0;const f=[];for(let y=0;y<s.length;++y){const d=s[y];let w=null;if(z(d))d.spaceBefore&&f.push(""),Fn(e,f,d.commentBefore,!1),d.comment&&(w=d.comment);else if(H(d)){const _=z(d.key)?d.key:null;_&&(_.spaceBefore&&f.push(""),Fn(e,f,_.commentBefore,!1),_.comment&&(u=!0));const A=z(d.value)?d.value:null;A?(A.comment&&(w=A.comment),A.commentBefore&&(u=!0)):d.value==null&&_?.comment&&(w=_.comment)}w&&(u=!0);let k=St(d,l,()=>w=null);y<s.length-1&&(k+=","),w&&(k+=Xe(k,n,a(w))),!u&&(f.length>h||k.includes(`
49
+ `+Ie(u(s),l),a&&a()):f&&o&&o(),m}c(Dl,"stringifyBlockCollection");function jl({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,h=0;const f=[];for(let y=0;y<s.length;++y){const d=s[y];let w=null;if(z(d))d.spaceBefore&&f.push(""),Fn(e,f,d.commentBefore,!1),d.comment&&(w=d.comment);else if(H(d)){const _=z(d.key)?d.key:null;_&&(_.spaceBefore&&f.push(""),Fn(e,f,_.commentBefore,!1),_.comment&&(u=!0));const O=z(d.value)?d.value:null;O?(O.comment&&(w=O.comment),O.commentBefore&&(u=!0)):d.value==null&&_?.comment&&(w=_.comment)}w&&(u=!0);let k=bt(d,l,()=>w=null);y<s.length-1&&(k+=","),w&&(k+=Ye(k,n,a(w))),!u&&(f.length>h||k.includes(`
50
50
  `))&&(u=!0),f.push(k),h=f.length}const{start:p,end:m}=t;if(f.length===0)return p+m;if(!u){const y=f.reduce((d,w)=>d+w.length+2,2);u=e.options.lineWidth>0&&y>e.options.lineWidth}if(u){let y=p;for(const d of f)y+=d?`
51
51
  ${i}${r}${d}`:`
52
52
  `;return`${y}
53
- ${r}${m}`}else return`${p}${o}${f.join(" ")}${o}${m}`}c(Ll,"stringifyFlowCollection");function Fn({indent:s,options:{commentString:e}},t,n,r){if(n&&r&&(n=n.replace(/^\n+/,"")),n){const i=Ie(e(n),s);t.push(i.trimStart())}}c(Fn,"addCommentBefore");function Qe(s,e){const t=W(e)?e.value:e;for(const n of s)if(H(n)&&(n.key===e||n.key===t||W(n.key)&&n.key.value===t))return n}c(Qe,"findPair");class ue extends Zi{static{c(this,"YAMLMap")}static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(je,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(Qs(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;H(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=Qe(this.items,n.key),i=this.schema?.sortMapEntries;if(r){if(!t)throw new Error(`Key ${n.key} already set`);W(r.value)&&Qi(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=Qe(this.items,e);return t?this.items.splice(this.items.indexOf(t),1).length>0:!1}get(e,t){const r=Qe(this.items,e)?.value;return(!t&&W(r)?r.value:r)??void 0}has(e){return!!Qe(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)io(t,r,i);return r}toString(e,t,n){if(!e)return JSON.stringify(this);for(const r of this.items)if(!H(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})),oo(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:n,onComment:t})}}const vt={collection:"map",default:!0,nodeClass:ue,tag:"tag:yaml.org,2002:map",resolve(s,e){return pt(s)||e("Expected a mapping for this tag"),s},createNode:c((s,e,t)=>ue.from(s,e,t),"createNode")};class Ke extends Zi{static{c(this,"YAMLSeq")}static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(dt,e),this.items=[]}add(e){this.items.push(e)}delete(e){const t=Kn(e);return typeof t!="number"?!1:this.items.splice(t,1).length>0}get(e,t){const n=Kn(e);if(typeof n!="number")return;const r=this.items[n];return!t&&W(r)?r.value:r}has(e){const t=Kn(e);return typeof t=="number"&&t<this.items.length}set(e,t){const n=Kn(e);if(typeof n!="number")throw new Error(`Expected a valid index, not ${e}.`);const r=this.items[n];W(r)&&Qi(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?oo(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(jt(a,void 0,n))}}return i}}function Kn(s){let e=W(s)?s.value:s;return e&&typeof e=="string"&&(e=Number(e)),typeof e=="number"&&Number.isInteger(e)&&e>=0?e:null}c(Kn,"asItemIndex");const Ct={collection:"seq",default:!0,nodeClass:Ke,tag:"tag:yaml.org,2002:seq",resolve(s,e){return mt(s)||e("Expected a sequence for this tag"),s},createNode:c((s,e,t)=>Ke.from(s,e,t),"createNode")},Bn={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),Bt(s,e,t,n)}},qn={identify:c(s=>s==null,"identify"),createNode:c(()=>new M(null),"createNode"),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:c(()=>new M(null),"resolve"),stringify:c(({source:s},e)=>typeof s=="string"&&qn.test.test(s)?s:e.options.nullStr,"stringify")},Zs={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 M(s[0]==="t"||s[0]==="T"),"resolve"),stringify({source:s,value:e},t){if(s&&Zs.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 we({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(we,"stringifyNumber");const ao={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:we},co={identify:c(s=>typeof s=="number","identify"),default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:c(s=>parseFloat(s),"resolve"),stringify(s){const e=Number(s.value);return isFinite(e)?e.toExponential():we(s)}},lo={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 M(parseFloat(s)),t=s.indexOf(".");return t!==-1&&s[s.length-1]==="0"&&(e.minFractionDigits=s.length-t-1),e},stringify:we},Un=c(s=>typeof s=="bigint"||Number.isInteger(s),"intIdentify$2"),er=c((s,e,t,{intAsBigInt:n})=>n?BigInt(s):parseInt(s.substring(e),t),"intResolve$1");function uo(s,e,t){const{value:n}=s;return Un(n)&&n>=0?t+n.toString(e):we(s)}c(uo,"intStringify$1");const ho={identify:c(s=>Un(s)&&s>=0,"identify"),default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:c((s,e,t)=>er(s,2,8,t),"resolve"),stringify:c(s=>uo(s,8,"0o"),"stringify")},fo={identify:Un,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:c((s,e,t)=>er(s,0,10,t),"resolve"),stringify:we},po={identify:c(s=>Un(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)=>er(s,2,16,t),"resolve"),stringify:c(s=>uo(s,16,"0x"),"stringify")},Dl=[vt,Ct,Bn,qn,Zs,ho,fo,po,ao,co,lo];function mo(s){return typeof s=="bigint"||Number.isInteger(s)}c(mo,"intIdentify$1");const Wn=c(({value:s})=>JSON.stringify(s),"stringifyJSON"),jl=[{identify:c(s=>typeof s=="string","identify"),default:!0,tag:"tag:yaml.org,2002:str",resolve:c(s=>s,"resolve"),stringify:Wn},{identify:c(s=>s==null,"identify"),createNode:c(()=>new M(null),"createNode"),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:c(()=>null,"resolve"),stringify:Wn},{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:Wn},{identify:mo,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})=>mo(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:Wn}],Fl={default:!0,tag:"",test:/^/,resolve(s,e){return e(`Unresolved plain scalar ${JSON.stringify(s)}`),s}},Kl=[vt,Ct].concat(jl,Fl),tr={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=M.BLOCK_LITERAL),e!==M.QUOTE_DOUBLE){const l=Math.max(n.options.lineWidth-n.indent.length,n.options.minContentWidth),u=Math.ceil(a.length/l),h=new Array(u);for(let f=0,p=0;f<u;++f,p+=l)h[f]=a.substr(p,l);a=h.join(e===M.BLOCK_LITERAL?`
54
- `:" ")}return Bt({comment:s,type:e,value:a},n,r,i)}};function go(s,e){if(mt(s))for(let t=0;t<s.items.length;++t){let n=s.items[t];if(!H(n)){if(pt(n)){n.items.length>1&&e("Each pair must have its own sequence indicator");const r=n.items[0]||new se(new M(null));if(n.commentBefore&&(r.key.commentBefore=r.key.commentBefore?`${n.commentBefore}
53
+ ${r}${m}`}else return`${p}${o}${f.join(" ")}${o}${m}`}c(jl,"stringifyFlowCollection");function Fn({indent:s,options:{commentString:e}},t,n,r){if(n&&r&&(n=n.replace(/^\n+/,"")),n){const i=Ie(e(n),s);t.push(i.trimStart())}}c(Fn,"addCommentBefore");function Xe(s,e){const t=W(e)?e.value:e;for(const n of s)if(H(n)&&(n.key===e||n.key===t||W(n.key)&&n.key.value===t))return n}c(Xe,"findPair");class ue extends eo{static{c(this,"YAMLMap")}static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(je,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(Zs(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;H(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=Xe(this.items,n.key),i=this.schema?.sortMapEntries;if(r){if(!t)throw new Error(`Key ${n.key} already set`);W(r.value)&&Zi(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=Xe(this.items,e);return t?this.items.splice(this.items.indexOf(t),1).length>0:!1}get(e,t){const r=Xe(this.items,e)?.value;return(!t&&W(r)?r.value:r)??void 0}has(e){return!!Xe(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(!H(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})),ao(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:n,onComment:t})}}const St={collection:"map",default:!0,nodeClass:ue,tag:"tag:yaml.org,2002:map",resolve(s,e){return dt(s)||e("Expected a mapping for this tag"),s},createNode:c((s,e,t)=>ue.from(s,e,t),"createNode")};class Ke extends eo{static{c(this,"YAMLSeq")}static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(ft,e),this.items=[]}add(e){this.items.push(e)}delete(e){const t=Kn(e);return typeof t!="number"?!1:this.items.splice(t,1).length>0}get(e,t){const n=Kn(e);if(typeof n!="number")return;const r=this.items[n];return!t&&W(r)?r.value:r}has(e){const t=Kn(e);return typeof t=="number"&&t<this.items.length}set(e,t){const n=Kn(e);if(typeof n!="number")throw new Error(`Expected a valid index, not ${e}.`);const r=this.items[n];W(r)&&Zi(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?ao(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(jt(a,void 0,n))}}return i}}function Kn(s){let e=W(s)?s.value:s;return e&&typeof e=="string"&&(e=Number(e)),typeof e=="number"&&Number.isInteger(e)&&e>=0?e:null}c(Kn,"asItemIndex");const vt={collection:"seq",default:!0,nodeClass:Ke,tag:"tag:yaml.org,2002:seq",resolve(s,e){return pt(s)||e("Expected a sequence for this tag"),s},createNode:c((s,e,t)=>Ke.from(s,e,t),"createNode")},Bn={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),Bt(s,e,t,n)}},qn={identify:c(s=>s==null,"identify"),createNode:c(()=>new M(null),"createNode"),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:c(()=>new M(null),"resolve"),stringify:c(({source:s},e)=>typeof s=="string"&&qn.test.test(s)?s:e.options.nullStr,"stringify")},er={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 M(s[0]==="t"||s[0]==="T"),"resolve"),stringify({source:s,value:e},t){if(s&&er.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 we({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(we,"stringifyNumber");const co={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:we},lo={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():we(s)}},uo={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 M(parseFloat(s)),t=s.indexOf(".");return t!==-1&&s[s.length-1]==="0"&&(e.minFractionDigits=s.length-t-1),e},stringify:we},Un=c(s=>typeof s=="bigint"||Number.isInteger(s),"intIdentify$2"),tr=c((s,e,t,{intAsBigInt:n})=>n?BigInt(s):parseInt(s.substring(e),t),"intResolve$1");function ho(s,e,t){const{value:n}=s;return Un(n)&&n>=0?t+n.toString(e):we(s)}c(ho,"intStringify$1");const fo={identify:c(s=>Un(s)&&s>=0,"identify"),default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:c((s,e,t)=>tr(s,2,8,t),"resolve"),stringify:c(s=>ho(s,8,"0o"),"stringify")},po={identify:Un,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:c((s,e,t)=>tr(s,0,10,t),"resolve"),stringify:we},mo={identify:c(s=>Un(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)=>tr(s,2,16,t),"resolve"),stringify:c(s=>ho(s,16,"0x"),"stringify")},Fl=[St,vt,Bn,qn,er,fo,po,mo,co,lo,uo];function go(s){return typeof s=="bigint"||Number.isInteger(s)}c(go,"intIdentify$1");const Wn=c(({value:s})=>JSON.stringify(s),"stringifyJSON"),Kl=[{identify:c(s=>typeof s=="string","identify"),default:!0,tag:"tag:yaml.org,2002:str",resolve:c(s=>s,"resolve"),stringify:Wn},{identify:c(s=>s==null,"identify"),createNode:c(()=>new M(null),"createNode"),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:c(()=>null,"resolve"),stringify:Wn},{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:Wn},{identify:go,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})=>go(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:Wn}],Bl={default:!0,tag:"",test:/^/,resolve(s,e){return e(`Unresolved plain scalar ${JSON.stringify(s)}`),s}},ql=[St,vt].concat(Kl,Bl),nr={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=M.BLOCK_LITERAL),e!==M.QUOTE_DOUBLE){const l=Math.max(n.options.lineWidth-n.indent.length,n.options.minContentWidth),u=Math.ceil(a.length/l),h=new Array(u);for(let f=0,p=0;f<u;++f,p+=l)h[f]=a.substr(p,l);a=h.join(e===M.BLOCK_LITERAL?`
54
+ `:" ")}return Bt({comment:s,type:e,value:a},n,r,i)}};function yo(s,e){if(pt(s))for(let t=0;t<s.items.length;++t){let n=s.items[t];if(!H(n)){if(dt(n)){n.items.length>1&&e("Each pair must have its own sequence indicator");const r=n.items[0]||new se(new M(null));if(n.commentBefore&&(r.key.commentBefore=r.key.commentBefore?`${n.commentBefore}
55
55
  ${r.key.commentBefore}`:n.commentBefore),n.comment){const i=r.value??r.key;i.comment=i.comment?`${n.comment}
56
- ${i.comment}`:n.comment}n=r}s.items[t]=H(n)?n:new se(n)}}else e("Expected a sequence for this tag");return s}c(go,"resolvePairs");function yo(s,e,t){const{replacer:n}=t,r=new Ke(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(Qs(a,l,t))}return r}c(yo,"createPairs");const nr={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:go,createNode:yo};class Mt extends Ke{static{c(this,"YAMLOMap")}constructor(){super(),this.add=ue.prototype.add.bind(this),this.delete=ue.prototype.delete.bind(this),this.get=ue.prototype.get.bind(this),this.has=ue.prototype.has.bind(this),this.set=ue.prototype.set.bind(this),this.tag=Mt.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(H(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=yo(e,t,n),i=new this;return i.items=r.items,i}}Mt.tag="tag:yaml.org,2002:omap";const sr={collection:"seq",identify:c(s=>s instanceof Map,"identify"),nodeClass:Mt,default:!1,tag:"tag:yaml.org,2002:omap",resolve(s,e){const t=go(s,e),n=[];for(const{key:r}of t.items)W(r)&&(n.includes(r.value)?e(`Ordered maps must not include duplicate keys: ${r.value}`):n.push(r.value));return Object.assign(new Mt,t)},createNode:c((s,e,t)=>Mt.from(s,e,t),"createNode")};function wo({value:s,source:e},t){return e&&(s?bo:So).test.test(e)?e:s?t.options.trueStr:t.options.falseStr}c(wo,"boolStringify");const bo={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 M(!0),"resolve"),stringify:wo},So={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 M(!1),"resolve"),stringify:wo},Bl={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:we},ql={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():we(s)}},Ul={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 M(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:we},qt=c(s=>typeof s=="bigint"||Number.isInteger(s),"intIdentify");function Jn(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(Jn,"intResolve");function rr(s,e,t){const{value:n}=s;if(qt(n)){const r=n.toString(e);return n<0?"-"+t+r.substr(1):t+r}return we(s)}c(rr,"intStringify");const Wl={identify:qt,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:c((s,e,t)=>Jn(s,2,2,t),"resolve"),stringify:c(s=>rr(s,2,"0b"),"stringify")},Jl={identify:qt,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:c((s,e,t)=>Jn(s,1,8,t),"resolve"),stringify:c(s=>rr(s,8,"0"),"stringify")},Hl={identify:qt,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:c((s,e,t)=>Jn(s,0,10,t),"resolve"),stringify:we},Vl={identify:qt,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:c((s,e,t)=>Jn(s,2,16,t),"resolve"),stringify:c(s=>rr(s,16,"0x"),"stringify")};class Rt extends ue{static{c(this,"YAMLSet")}constructor(e){super(e),this.tag=Rt.tag}add(e){let t;H(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),Qe(this.items,t.key)||this.items.push(t)}get(e,t){const n=Qe(this.items,e);return!t&&H(n)?W(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=Qe(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(Qs(o,null,n));return i}}Rt.tag="tag:yaml.org,2002:set";const ir={collection:"map",identify:c(s=>s instanceof Set,"identify"),nodeClass:Rt,default:!1,tag:"tag:yaml.org,2002:set",createNode:c((s,e,t)=>Rt.from(s,e,t),"createNode"),resolve(s,e){if(pt(s)){if(s.hasAllNullValues(!0))return Object.assign(new Rt,s);e("Set items must all have null values")}else e("Expected a mapping for this tag");return s}};function or(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(or,"parseSexagesimal");function vo(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 we(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(vo,"stringifySexagesimal");const Co={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})=>or(s,t),"resolve"),stringify:vo},ko={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=>or(s,!1),"resolve"),stringify:vo},Hn={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(Hn.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 h=e[8];if(h&&h!=="Z"){let f=or(h,!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")},_o=[vt,Ct,Bn,qn,bo,So,Wl,Jl,Hl,Vl,Bl,ql,Ul,tr,$e,sr,nr,ir,Co,ko,Hn],To=new Map([["core",Dl],["failsafe",[vt,Ct,Bn]],["json",Kl],["yaml11",_o],["yaml-1.1",_o]]),Eo={binary:tr,bool:Zs,float:lo,floatExp:co,floatNaN:ao,floatTime:ko,int:fo,intHex:po,intOct:ho,intTime:Co,map:vt,merge:$e,null:qn,omap:sr,pairs:nr,seq:Ct,set:ir,timestamp:Hn},Gl={"tag:yaml.org,2002:binary":tr,"tag:yaml.org,2002:merge":$e,"tag:yaml.org,2002:omap":sr,"tag:yaml.org,2002:pairs":nr,"tag:yaml.org,2002:set":ir,"tag:yaml.org,2002:timestamp":Hn};function ar(s,e,t){const n=To.get(e);if(n&&!s)return t&&!n.includes($e)?n.concat($e):n.slice();let r=n;if(!r)if(Array.isArray(s))r=[];else{const i=Array.from(To.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($e)),r.reduce((i,o)=>{const a=typeof o=="string"?Eo[o]:o;if(!a){const l=JSON.stringify(o),u=Object.keys(Eo).map(h=>JSON.stringify(h)).join(", ");throw new Error(`Unknown custom tag ${l}; use one of ${u}`)}return i.includes(a)||i.push(a),i},[])}c(ar,"getTags");const zl=c((s,e)=>s.key<e.key?-1:s.key>e.key?1:0,"sortMapEntriesByKey");class Es{static{c(this,"Schema")}constructor({compat:e,customTags:t,merge:n,resolveKnownTags:r,schema:i,sortMapEntries:o,toStringDefaults:a}){this.compat=Array.isArray(e)?ar(e,"compat"):e?ar(null,e):null,this.name=typeof i=="string"&&i||"core",this.knownTags=r?Gl:{},this.tags=ar(t,this.name,n),this.toStringOptions=a??null,Object.defineProperty(this,je,{value:vt}),Object.defineProperty(this,_e,{value:Bn}),Object.defineProperty(this,dt,{value:Ct}),this.sortMapEntries=typeof o=="function"?o:o===!0?zl:null}clone(){const e=Object.create(Es.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}}function Yl(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=no(s,e),{commentString:i}=r.options;if(s.commentBefore){t.length!==1&&t.unshift("");const l=i(s.commentBefore);t.unshift(Ie(l,""))}let o=!1,a=null;if(s.contents){if(z(s.contents)){if(s.contents.spaceBefore&&n&&t.push(""),s.contents.commentBefore){const h=i(s.contents.commentBefore);t.push(Ie(h,""))}r.forceBlockIndent=!!s.comment,a=s.contents.comment}const l=a?void 0:()=>o=!0;let u=St(s.contents,r,()=>a=null,l);a&&(u+=Xe(u,"",i(a))),(u[0]==="|"||u[0]===">")&&t[t.length-1]==="---"?t[t.length-1]=`--- ${u}`:t.push(u)}else t.push(St(s.contents,r));if(s.directives?.docEnd)if(s.comment){const l=i(s.comment);l.includes(`
56
+ ${i.comment}`:n.comment}n=r}s.items[t]=H(n)?n:new se(n)}}else e("Expected a sequence for this tag");return s}c(yo,"resolvePairs");function wo(s,e,t){const{replacer:n}=t,r=new Ke(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(Zs(a,l,t))}return r}c(wo,"createPairs");const sr={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:yo,createNode:wo};class xt extends Ke{static{c(this,"YAMLOMap")}constructor(){super(),this.add=ue.prototype.add.bind(this),this.delete=ue.prototype.delete.bind(this),this.get=ue.prototype.get.bind(this),this.has=ue.prototype.has.bind(this),this.set=ue.prototype.set.bind(this),this.tag=xt.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(H(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=wo(e,t,n),i=new this;return i.items=r.items,i}}xt.tag="tag:yaml.org,2002:omap";const rr={collection:"seq",identify:c(s=>s instanceof Map,"identify"),nodeClass:xt,default:!1,tag:"tag:yaml.org,2002:omap",resolve(s,e){const t=yo(s,e),n=[];for(const{key:r}of t.items)W(r)&&(n.includes(r.value)?e(`Ordered maps must not include duplicate keys: ${r.value}`):n.push(r.value));return Object.assign(new xt,t)},createNode:c((s,e,t)=>xt.from(s,e,t),"createNode")};function bo({value:s,source:e},t){return e&&(s?So:vo).test.test(e)?e:s?t.options.trueStr:t.options.falseStr}c(bo,"boolStringify");const So={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 M(!0),"resolve"),stringify:bo},vo={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 M(!1),"resolve"),stringify:bo},Ul={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:we},Wl={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():we(s)}},Jl={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 M(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:we},qt=c(s=>typeof s=="bigint"||Number.isInteger(s),"intIdentify");function Jn(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(Jn,"intResolve");function ir(s,e,t){const{value:n}=s;if(qt(n)){const r=n.toString(e);return n<0?"-"+t+r.substr(1):t+r}return we(s)}c(ir,"intStringify");const Hl={identify:qt,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:c((s,e,t)=>Jn(s,2,2,t),"resolve"),stringify:c(s=>ir(s,2,"0b"),"stringify")},Vl={identify:qt,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:c((s,e,t)=>Jn(s,1,8,t),"resolve"),stringify:c(s=>ir(s,8,"0"),"stringify")},Gl={identify:qt,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:c((s,e,t)=>Jn(s,0,10,t),"resolve"),stringify:we},zl={identify:qt,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:c((s,e,t)=>Jn(s,2,16,t),"resolve"),stringify:c(s=>ir(s,16,"0x"),"stringify")};class Mt extends ue{static{c(this,"YAMLSet")}constructor(e){super(e),this.tag=Mt.tag}add(e){let t;H(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),Xe(this.items,t.key)||this.items.push(t)}get(e,t){const n=Xe(this.items,e);return!t&&H(n)?W(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=Xe(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(Zs(o,null,n));return i}}Mt.tag="tag:yaml.org,2002:set";const or={collection:"map",identify:c(s=>s instanceof Set,"identify"),nodeClass:Mt,default:!1,tag:"tag:yaml.org,2002:set",createNode:c((s,e,t)=>Mt.from(s,e,t),"createNode"),resolve(s,e){if(dt(s)){if(s.hasAllNullValues(!0))return Object.assign(new Mt,s);e("Set items must all have null values")}else e("Expected a mapping for this tag");return s}};function ar(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(ar,"parseSexagesimal");function Co(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 we(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(Co,"stringifySexagesimal");const ko={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})=>ar(s,t),"resolve"),stringify:Co},_o={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=>ar(s,!1),"resolve"),stringify:Co},Hn={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(Hn.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 h=e[8];if(h&&h!=="Z"){let f=ar(h,!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")},To=[St,vt,Bn,qn,So,vo,Hl,Vl,Gl,zl,Ul,Wl,Jl,nr,$e,rr,sr,or,ko,_o,Hn],Eo=new Map([["core",Fl],["failsafe",[St,vt,Bn]],["json",ql],["yaml11",To],["yaml-1.1",To]]),Ao={binary:nr,bool:er,float:uo,floatExp:lo,floatNaN:co,floatTime:_o,int:po,intHex:mo,intOct:fo,intTime:ko,map:St,merge:$e,null:qn,omap:rr,pairs:sr,seq:vt,set:or,timestamp:Hn},Yl={"tag:yaml.org,2002:binary":nr,"tag:yaml.org,2002:merge":$e,"tag:yaml.org,2002:omap":rr,"tag:yaml.org,2002:pairs":sr,"tag:yaml.org,2002:set":or,"tag:yaml.org,2002:timestamp":Hn};function cr(s,e,t){const n=Eo.get(e);if(n&&!s)return t&&!n.includes($e)?n.concat($e):n.slice();let r=n;if(!r)if(Array.isArray(s))r=[];else{const i=Array.from(Eo.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($e)),r.reduce((i,o)=>{const a=typeof o=="string"?Ao[o]:o;if(!a){const l=JSON.stringify(o),u=Object.keys(Ao).map(h=>JSON.stringify(h)).join(", ");throw new Error(`Unknown custom tag ${l}; use one of ${u}`)}return i.includes(a)||i.push(a),i},[])}c(cr,"getTags");const Xl=c((s,e)=>s.key<e.key?-1:s.key>e.key?1:0,"sortMapEntriesByKey");class Es{static{c(this,"Schema")}constructor({compat:e,customTags:t,merge:n,resolveKnownTags:r,schema:i,sortMapEntries:o,toStringDefaults:a}){this.compat=Array.isArray(e)?cr(e,"compat"):e?cr(null,e):null,this.name=typeof i=="string"&&i||"core",this.knownTags=r?Yl:{},this.tags=cr(t,this.name,n),this.toStringOptions=a??null,Object.defineProperty(this,je,{value:St}),Object.defineProperty(this,_e,{value:Bn}),Object.defineProperty(this,ft,{value:vt}),this.sortMapEntries=typeof o=="function"?o:o===!0?Xl:null}clone(){const e=Object.create(Es.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}}function Ql(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=so(s,e),{commentString:i}=r.options;if(s.commentBefore){t.length!==1&&t.unshift("");const l=i(s.commentBefore);t.unshift(Ie(l,""))}let o=!1,a=null;if(s.contents){if(z(s.contents)){if(s.contents.spaceBefore&&n&&t.push(""),s.contents.commentBefore){const h=i(s.contents.commentBefore);t.push(Ie(h,""))}r.forceBlockIndent=!!s.comment,a=s.contents.comment}const l=a?void 0:()=>o=!0;let u=bt(s.contents,r,()=>a=null,l);a&&(u+=Ye(u,"",i(a))),(u[0]==="|"||u[0]===">")&&t[t.length-1]==="---"?t[t.length-1]=`--- ${u}`:t.push(u)}else t.push(bt(s.contents,r));if(s.directives?.docEnd)if(s.comment){const l=i(s.comment);l.includes(`
57
57
  `)?(t.push("..."),t.push(Ie(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(Ie(i(l),"")))}return t.join(`
58
58
  `)+`
59
- `}c(Yl,"stringifyDocument");class Pt{static{c(this,"Document")}constructor(e,t,n){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,pe,{value:Hs});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(Pt.prototype,{[pe]:{value:Hs}});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=z(this.contents)?this.contents.clone(e.schema):this.contents,this.range&&(e.range=this.range.slice()),e}add(e){kt(this.contents)&&this.contents.add(e)}addIn(e,t){kt(this.contents)&&this.contents.addIn(e,t)}createAlias(e,t){if(!e.anchor){const n=Yi(this);e.anchor=!t||n.has(t)?Xi(t||"a",n):t}return new $n(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(_=>typeof _=="number"||_ instanceof String||_ instanceof Number,"keyToStr"),k=t.filter(w).map(String);k.length>0&&(t=t.concat(k)),r=t}else n===void 0&&t&&(n=t,t=void 0);const{aliasDuplicateObjects:i,anchorPrefix:o,flow:a,keepUndefined:l,onTagObj:u,tag:h}=n??{},{onAnchor:f,setAnchors:p,sourceObjects:m}=_l(this,o||"a"),y={aliasDuplicateObjects:i??!0,keepUndefined:l??!1,onAnchor:f,onTagObj:u,replacer:r,schema:this.schema,sourceObjects:m},d=jt(e,h,y);return a&&G(d)&&(d.flow=!0),p(),d}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 kt(this.contents)?this.contents.delete(e):!1}deleteIn(e){return Ft(e)?this.contents==null?!1:(this.contents=null,!0):kt(this.contents)?this.contents.deleteIn(e):!1}get(e,t){return G(this.contents)?this.contents.get(e,t):void 0}getIn(e,t){return Ft(e)?!t&&W(this.contents)?this.contents.value:this.contents:G(this.contents)?this.contents.getIn(e,t):void 0}has(e){return G(this.contents)?this.contents.has(e):!1}hasIn(e){return Ft(e)?this.contents!==void 0:G(this.contents)?this.contents.hasIn(e):!1}set(e,t){this.contents==null?this.contents=xn(this.schema,[e],t):kt(this.contents)&&this.contents.set(e,t)}setIn(e,t){Ft(e)?this.contents=t:this.contents==null?this.contents=xn(this.schema,Array.from(e),t):kt(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 Es(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:h}of a.anchors.values())i(h,u);return typeof o=="function"?wt(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 Yl(this,e)}}function kt(s){if(G(s))return!0;throw new Error("Expected a YAML collection as document contents")}c(kt,"assertCollection");class cr 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 Ze extends cr{static{c(this,"YAMLParseError")}constructor(e,t,n){super("YAMLParseError",e,t,n)}}class Oo extends cr{static{c(this,"YAMLWarning")}constructor(e,t,n){super("YAMLWarning",e,t,n)}}const Vn=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
59
+ `}c(Ql,"stringifyDocument");class Rt{static{c(this,"Document")}constructor(e,t,n){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,pe,{value:Vs});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(Rt.prototype,{[pe]:{value:Vs}});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=z(this.contents)?this.contents.clone(e.schema):this.contents,this.range&&(e.range=this.range.slice()),e}add(e){Ct(this.contents)&&this.contents.add(e)}addIn(e,t){Ct(this.contents)&&this.contents.addIn(e,t)}createAlias(e,t){if(!e.anchor){const n=Xi(this);e.anchor=!t||n.has(t)?Qi(t||"a",n):t}return new $n(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(_=>typeof _=="number"||_ instanceof String||_ instanceof Number,"keyToStr"),k=t.filter(w).map(String);k.length>0&&(t=t.concat(k)),r=t}else n===void 0&&t&&(n=t,t=void 0);const{aliasDuplicateObjects:i,anchorPrefix:o,flow:a,keepUndefined:l,onTagObj:u,tag:h}=n??{},{onAnchor:f,setAnchors:p,sourceObjects:m}=El(this,o||"a"),y={aliasDuplicateObjects:i??!0,keepUndefined:l??!1,onAnchor:f,onTagObj:u,replacer:r,schema:this.schema,sourceObjects:m},d=jt(e,h,y);return a&&G(d)&&(d.flow=!0),p(),d}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 Ct(this.contents)?this.contents.delete(e):!1}deleteIn(e){return Ft(e)?this.contents==null?!1:(this.contents=null,!0):Ct(this.contents)?this.contents.deleteIn(e):!1}get(e,t){return G(this.contents)?this.contents.get(e,t):void 0}getIn(e,t){return Ft(e)?!t&&W(this.contents)?this.contents.value:this.contents:G(this.contents)?this.contents.getIn(e,t):void 0}has(e){return G(this.contents)?this.contents.has(e):!1}hasIn(e){return Ft(e)?this.contents!==void 0:G(this.contents)?this.contents.hasIn(e):!1}set(e,t){this.contents==null?this.contents=xn(this.schema,[e],t):Ct(this.contents)&&this.contents.set(e,t)}setIn(e,t){Ft(e)?this.contents=t:this.contents==null?this.contents=xn(this.schema,Array.from(e),t):Ct(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 Es(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:h}of a.anchors.values())i(h,u);return typeof o=="function"?yt(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 Ql(this,e)}}function Ct(s){if(G(s))return!0;throw new Error("Expected a YAML collection as document contents")}c(Ct,"assertCollection");class lr 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 Qe extends lr{static{c(this,"YAMLParseError")}constructor(e,t,n){super("YAMLParseError",e,t,n)}}class Oo extends lr{static{c(this,"YAMLWarning")}constructor(e,t,n){super("YAMLWarning",e,t,n)}}const Vn=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
60
60
  `),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+=`:
61
61
 
62
62
  ${o}
63
63
  ${u}
64
- `}},"prettifyError");function _t(s,{flow:e,indicator:t,next:n,offset:r,onError:i,parentIndent:o,startOnNewline:a}){let l=!1,u=a,h=a,f="",p="",m=!1,y=!1,d=null,w=null,k=null,_=null,A=null,O=null,$=null;for(const I of s)switch(y&&(I.type!=="space"&&I.type!=="newline"&&I.type!=="comma"&&i(I.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),y=!1),d&&(u&&I.type!=="comment"&&I.type!=="newline"&&i(d,"TAB_AS_INDENT","Tabs are not allowed as indentation"),d=null),I.type){case"space":!e&&(t!=="doc-start"||n?.type!=="flow-collection")&&I.source.includes(" ")&&(d=I),h=!0;break;case"comment":{h||i(I,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");const ee=I.source.substring(1)||" ";f?f+=p+ee:f=ee,p="",u=!1;break}case"newline":u?f?f+=I.source:(!O||t!=="seq-item-ind")&&(l=!0):p+=I.source,u=!0,m=!0,(w||k)&&(_=I),h=!0;break;case"anchor":w&&i(I,"MULTIPLE_ANCHORS","A node can have at most one anchor"),I.source.endsWith(":")&&i(I.offset+I.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),w=I,$??($=I.offset),u=!1,h=!1,y=!0;break;case"tag":{k&&i(I,"MULTIPLE_TAGS","A node can have at most one tag"),k=I,$??($=I.offset),u=!1,h=!1,y=!0;break}case t:(w||k)&&i(I,"BAD_PROP_ORDER",`Anchors and tags must be after the ${I.source} indicator`),O&&i(I,"UNEXPECTED_TOKEN",`Unexpected ${I.source} in ${e??"collection"}`),O=I,u=t==="seq-item-ind"||t==="explicit-key-ind",h=!1;break;case"comma":if(e){A&&i(I,"UNEXPECTED_TOKEN",`Unexpected , in ${e}`),A=I,u=!1,h=!1;break}default:i(I,"UNEXPECTED_TOKEN",`Unexpected ${I.type} token`),u=!1,h=!1}const N=s[s.length-1],F=N?N.offset+N.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"),d&&(u&&d.indent<=o||n?.type==="block-map"||n?.type==="block-seq")&&i(d,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:A,found:O,spaceBefore:l,comment:f,hasNewline:m,anchor:w,tag:k,newlineAfterProp:_,end:F,start:$??F}}c(_t,"resolveProps");function Ut(s){if(!s)return null;switch(s.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(s.source.includes(`
65
- `))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(Ut(e.key)||Ut(e.value))return!0}return!1;default:return!0}}c(Ut,"containsNewline");function lr(s,e,t){if(e?.type==="flow-collection"){const n=e.end[0];n.indent===s&&(n.source==="]"||n.source==="}")&&Ut(e)&&t(n,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}c(lr,"flowIndentCheck");function Ao(s,e,t){const{uniqueKeys:n}=s.options;if(n===!1)return!1;const r=typeof n=="function"?n:(i,o)=>i===o||W(i)&&W(o)&&i.value===o.value;return e.some(i=>r(i.key,t))}c(Ao,"mapIncludes");const Io="All mapping items must start at the same column";function Xl({composeNode:s,composeEmptyNode:e},t,n,r,i){const o=i?.nodeClass??ue,a=new o(t.schema);t.atRoot&&(t.atRoot=!1);let l=n.offset,u=null;for(const h of n.items){const{start:f,key:p,sep:m,value:y}=h,d=_t(f,{indicator:"explicit-key-ind",next:p??m?.[0],offset:l,onError:r,parentIndent:n.indent,startOnNewline:!0}),w=!d.found;if(w){if(p&&(p.type==="block-seq"?r(l,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in p&&p.indent!==n.indent&&r(l,"BAD_INDENT",Io)),!d.anchor&&!d.tag&&!m){u=d.end,d.comment&&(a.comment?a.comment+=`
66
- `+d.comment:a.comment=d.comment);continue}(d.newlineAfterProp||Ut(p))&&r(p??f[f.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else d.found?.indent!==n.indent&&r(l,"BAD_INDENT",Io);t.atKey=!0;const k=d.end,_=p?s(t,p,d,r):e(t,k,f,null,d,r);t.schema.compat&&lr(n.indent,p,r),t.atKey=!1,Ao(t,a.items,_)&&r(k,"DUPLICATE_KEY","Map keys must be unique");const A=_t(m??[],{indicator:"map-value-ind",next:y,offset:_.range[2],onError:r,parentIndent:n.indent,startOnNewline:!p||p.type==="block-scalar"});if(l=A.end,A.found){w&&(y?.type==="block-map"&&!A.hasNewline&&r(l,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),t.options.strict&&d.start<A.found.offset-1024&&r(_.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));const O=y?s(t,y,A,r):e(t,l,m,null,A,r);t.schema.compat&&lr(n.indent,y,r),l=O.range[2];const $=new se(_,O);t.options.keepSourceTokens&&($.srcToken=h),a.items.push($)}else{w&&r(_.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),A.comment&&(_.comment?_.comment+=`
67
- `+A.comment:_.comment=A.comment);const O=new se(_);t.options.keepSourceTokens&&(O.srcToken=h),a.items.push(O)}}return u&&u<l&&r(u,"IMPOSSIBLE","Map comment with trailing content"),a.range=[n.offset,l,u??l],a}c(Xl,"resolveBlockMap");function Ql({composeNode:s,composeEmptyNode:e},t,n,r,i){const o=i?.nodeClass??Ke,a=new o(t.schema);t.atRoot&&(t.atRoot=!1),t.atKey&&(t.atKey=!1);let l=n.offset,u=null;for(const{start:h,value:f}of n.items){const p=_t(h,{indicator:"seq-item-ind",next:f,offset:l,onError:r,parentIndent:n.indent,startOnNewline:!0});if(!p.found)if(p.anchor||p.tag||f)f&&f.type==="block-seq"?r(p.end,"BAD_INDENT","All sequence items must start at the same column"):r(l,"MISSING_CHAR","Sequence item without - indicator");else{u=p.end,p.comment&&(a.comment=p.comment);continue}const m=f?s(t,f,p,r):e(t,p.end,h,null,p,r);t.schema.compat&&lr(n.indent,f,r),l=m.range[2],a.items.push(m)}return a.range=[n.offset,l,u??l],a}c(Ql,"resolveBlockSeq");function Wt(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 h=l.substring(1)||" ";r?r+=o+h:r=h,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(Wt,"resolveEnd");const ur="Block collections are not allowed within flow collections",hr=c(s=>s&&(s.type==="block-map"||s.type==="block-seq"),"isBlock");function Zl({composeNode:s,composeEmptyNode:e},t,n,r,i){const o=n.start.source==="{",a=o?"flow map":"flow sequence",l=i?.nodeClass??(o?ue:Ke),u=new l(t.schema);u.flow=!0;const h=t.atRoot;h&&(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 k=n.items[w],{start:_,key:A,sep:O,value:$}=k,N=_t(_,{flow:a,indicator:"explicit-key-ind",next:A??O?.[0],offset:f,onError:r,parentIndent:n.indent,startOnNewline:!1});if(!N.found){if(!N.anchor&&!N.tag&&!O&&!$){w===0&&N.comma?r(N.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`):w<n.items.length-1&&r(N.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${a}`),N.comment&&(u.comment?u.comment+=`
68
- `+N.comment:u.comment=N.comment),f=N.end;continue}!o&&t.options.strict&&Ut(A)&&r(A,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(w===0)N.comma&&r(N.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`);else if(N.comma||r(N.start,"MISSING_CHAR",`Missing , between ${a} items`),N.comment){let F="";e:for(const I of _)switch(I.type){case"comma":case"space":break;case"comment":F=I.source.substring(1);break e;default:break e}if(F){let I=u.items[u.items.length-1];H(I)&&(I=I.value??I.key),I.comment?I.comment+=`
69
- `+F:I.comment=F,N.comment=N.comment.substring(F.length+1)}}if(!o&&!O&&!N.found){const F=$?s(t,$,N,r):e(t,N.end,O,null,N,r);u.items.push(F),f=F.range[2],hr($)&&r(F.range,"BLOCK_IN_FLOW",ur)}else{t.atKey=!0;const F=N.end,I=A?s(t,A,N,r):e(t,F,_,null,N,r);hr(A)&&r(I.range,"BLOCK_IN_FLOW",ur),t.atKey=!1;const ee=_t(O??[],{flow:a,indicator:"map-value-ind",next:$,offset:I.range[2],onError:r,parentIndent:n.indent,startOnNewline:!1});if(ee.found){if(!o&&!N.found&&t.options.strict){if(O)for(const te of O){if(te===ee.found)break;if(te.type==="newline"){r(te,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}N.start<ee.found.offset-1024&&r(ee.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else $&&("source"in $&&$.source&&$.source[0]===":"?r($,"MISSING_CHAR",`Missing space after : in ${a}`):r(ee.start,"MISSING_CHAR",`Missing , or : between ${a} items`));const Le=$?s(t,$,ee,r):ee.found?e(t,ee.end,O,null,ee,r):null;Le?hr($)&&r(Le.range,"BLOCK_IN_FLOW",ur):ee.comment&&(I.comment?I.comment+=`
70
- `+ee.comment:I.comment=ee.comment);const nt=new se(I,Le);if(t.options.keepSourceTokens&&(nt.srcToken=k),o){const te=u;Ao(t,te.items,I)&&r(F,"DUPLICATE_KEY","Map keys must be unique"),te.items.push(nt)}else{const te=new ue(t.schema);te.flow=!0,te.items.push(nt);const ri=(Le??I).range;te.range=[I.range[0],ri[1],ri[2]],u.items.push(te)}f=Le?Le.range[2]:ee.end}}const p=o?"}":"]",[m,...y]=n.end;let d=f;if(m&&m.source===p)d=m.offset+m.source.length;else{const w=a[0].toUpperCase()+a.substring(1),k=h?`${w} must end with a ${p}`:`${w} in block collection must be sufficiently indented and end with a ${p}`;r(f,h?"MISSING_CHAR":"BAD_INDENT",k),m&&m.source.length!==1&&y.unshift(m)}if(y.length>0){const w=Wt(y,d,t.options.strict,r);w.comment&&(u.comment?u.comment+=`
71
- `+w.comment:u.comment=w.comment),u.range=[n.offset,d,w.offset]}else u.range=[n.offset,d,d];return u}c(Zl,"resolveFlowCollection");function fr(s,e,t,n,r,i){const o=t.type==="block-map"?Xl(s,e,t,n,i):t.type==="block-seq"?Ql(s,e,t,n,i):Zl(s,e,t,n,i),a=o.constructor;return r==="!"||r===a.tagName?(o.tag=a.tagName,o):(r&&(o.tag=r),o)}c(fr,"resolveCollection");function eu(s,e,t,n,r){const i=n.tag,o=i?e.directives.tagName(i.source,p=>r(i,"TAG_RESOLVE_FAILED",p)):null;if(t.type==="block-seq"){const{anchor:p,newlineAfterProp:m}=n,y=p&&i?p.offset>i.offset?p:i:p??i;y&&(!m||m.offset<y.offset)&&r(y,"MISSING_CHAR","Missing newline after block sequence props")}const a=t.type==="block-map"?"map":t.type==="block-seq"?"seq":t.start.source==="{"?"map":"seq";if(!i||!o||o==="!"||o===ue.tagName&&a==="map"||o===Ke.tagName&&a==="seq")return fr(s,e,t,r,o);let l=e.schema.tags.find(p=>p.tag===o&&p.collection===a);if(!l){const p=e.schema.knownTags[o];if(p&&p.collection===a)e.schema.tags.push(Object.assign({},p,{default:!1})),l=p;else return p?r(i,"BAD_COLLECTION_TYPE",`${p.tag} used for ${a} collection, but expects ${p.collection??"scalar"}`,!0):r(i,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),fr(s,e,t,r,o)}const u=fr(s,e,t,r,o,l),h=l.resolve?.(u,p=>r(i,"TAG_RESOLVE_FAILED",p),e.options)??u,f=z(h)?h:new M(h);return f.range=u.range,f.tag=o,l?.format&&(f.format=l.format),f}c(eu,"composeCollection");function $o(s,e,t){const n=e.offset,r=tu(e,s.options.strict,t);if(!r)return{value:"",type:null,comment:"",range:[n,n,n]};const i=r.mode===">"?M.BLOCK_FOLDED:M.BLOCK_LITERAL,o=e.source?nu(e.source):[];let a=o.length;for(let d=o.length-1;d>=0;--d){const w=o[d][1];if(w===""||w==="\r")a=d;else break}if(a===0){const d=r.chomp==="+"&&o.length>0?`
64
+ `}},"prettifyError");function kt(s,{flow:e,indicator:t,next:n,offset:r,onError:i,parentIndent:o,startOnNewline:a}){let l=!1,u=a,h=a,f="",p="",m=!1,y=!1,d=null,w=null,k=null,_=null,O=null,A=null,$=null;for(const I of s)switch(y&&(I.type!=="space"&&I.type!=="newline"&&I.type!=="comma"&&i(I.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),y=!1),d&&(u&&I.type!=="comment"&&I.type!=="newline"&&i(d,"TAB_AS_INDENT","Tabs are not allowed as indentation"),d=null),I.type){case"space":!e&&(t!=="doc-start"||n?.type!=="flow-collection")&&I.source.includes(" ")&&(d=I),h=!0;break;case"comment":{h||i(I,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");const ee=I.source.substring(1)||" ";f?f+=p+ee:f=ee,p="",u=!1;break}case"newline":u?f?f+=I.source:(!A||t!=="seq-item-ind")&&(l=!0):p+=I.source,u=!0,m=!0,(w||k)&&(_=I),h=!0;break;case"anchor":w&&i(I,"MULTIPLE_ANCHORS","A node can have at most one anchor"),I.source.endsWith(":")&&i(I.offset+I.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),w=I,$??($=I.offset),u=!1,h=!1,y=!0;break;case"tag":{k&&i(I,"MULTIPLE_TAGS","A node can have at most one tag"),k=I,$??($=I.offset),u=!1,h=!1,y=!0;break}case t:(w||k)&&i(I,"BAD_PROP_ORDER",`Anchors and tags must be after the ${I.source} indicator`),A&&i(I,"UNEXPECTED_TOKEN",`Unexpected ${I.source} in ${e??"collection"}`),A=I,u=t==="seq-item-ind"||t==="explicit-key-ind",h=!1;break;case"comma":if(e){O&&i(I,"UNEXPECTED_TOKEN",`Unexpected , in ${e}`),O=I,u=!1,h=!1;break}default:i(I,"UNEXPECTED_TOKEN",`Unexpected ${I.type} token`),u=!1,h=!1}const N=s[s.length-1],K=N?N.offset+N.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"),d&&(u&&d.indent<=o||n?.type==="block-map"||n?.type==="block-seq")&&i(d,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:O,found:A,spaceBefore:l,comment:f,hasNewline:m,anchor:w,tag:k,newlineAfterProp:_,end:K,start:$??K}}c(kt,"resolveProps");function Ut(s){if(!s)return null;switch(s.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(s.source.includes(`
65
+ `))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(Ut(e.key)||Ut(e.value))return!0}return!1;default:return!0}}c(Ut,"containsNewline");function ur(s,e,t){if(e?.type==="flow-collection"){const n=e.end[0];n.indent===s&&(n.source==="]"||n.source==="}")&&Ut(e)&&t(n,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}c(ur,"flowIndentCheck");function Io(s,e,t){const{uniqueKeys:n}=s.options;if(n===!1)return!1;const r=typeof n=="function"?n:(i,o)=>i===o||W(i)&&W(o)&&i.value===o.value;return e.some(i=>r(i.key,t))}c(Io,"mapIncludes");const $o="All mapping items must start at the same column";function Zl({composeNode:s,composeEmptyNode:e},t,n,r,i){const o=i?.nodeClass??ue,a=new o(t.schema);t.atRoot&&(t.atRoot=!1);let l=n.offset,u=null;for(const h of n.items){const{start:f,key:p,sep:m,value:y}=h,d=kt(f,{indicator:"explicit-key-ind",next:p??m?.[0],offset:l,onError:r,parentIndent:n.indent,startOnNewline:!0}),w=!d.found;if(w){if(p&&(p.type==="block-seq"?r(l,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in p&&p.indent!==n.indent&&r(l,"BAD_INDENT",$o)),!d.anchor&&!d.tag&&!m){u=d.end,d.comment&&(a.comment?a.comment+=`
66
+ `+d.comment:a.comment=d.comment);continue}(d.newlineAfterProp||Ut(p))&&r(p??f[f.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else d.found?.indent!==n.indent&&r(l,"BAD_INDENT",$o);t.atKey=!0;const k=d.end,_=p?s(t,p,d,r):e(t,k,f,null,d,r);t.schema.compat&&ur(n.indent,p,r),t.atKey=!1,Io(t,a.items,_)&&r(k,"DUPLICATE_KEY","Map keys must be unique");const O=kt(m??[],{indicator:"map-value-ind",next:y,offset:_.range[2],onError:r,parentIndent:n.indent,startOnNewline:!p||p.type==="block-scalar"});if(l=O.end,O.found){w&&(y?.type==="block-map"&&!O.hasNewline&&r(l,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),t.options.strict&&d.start<O.found.offset-1024&&r(_.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));const A=y?s(t,y,O,r):e(t,l,m,null,O,r);t.schema.compat&&ur(n.indent,y,r),l=A.range[2];const $=new se(_,A);t.options.keepSourceTokens&&($.srcToken=h),a.items.push($)}else{w&&r(_.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),O.comment&&(_.comment?_.comment+=`
67
+ `+O.comment:_.comment=O.comment);const A=new se(_);t.options.keepSourceTokens&&(A.srcToken=h),a.items.push(A)}}return u&&u<l&&r(u,"IMPOSSIBLE","Map comment with trailing content"),a.range=[n.offset,l,u??l],a}c(Zl,"resolveBlockMap");function eu({composeNode:s,composeEmptyNode:e},t,n,r,i){const o=i?.nodeClass??Ke,a=new o(t.schema);t.atRoot&&(t.atRoot=!1),t.atKey&&(t.atKey=!1);let l=n.offset,u=null;for(const{start:h,value:f}of n.items){const p=kt(h,{indicator:"seq-item-ind",next:f,offset:l,onError:r,parentIndent:n.indent,startOnNewline:!0});if(!p.found)if(p.anchor||p.tag||f)f&&f.type==="block-seq"?r(p.end,"BAD_INDENT","All sequence items must start at the same column"):r(l,"MISSING_CHAR","Sequence item without - indicator");else{u=p.end,p.comment&&(a.comment=p.comment);continue}const m=f?s(t,f,p,r):e(t,p.end,h,null,p,r);t.schema.compat&&ur(n.indent,f,r),l=m.range[2],a.items.push(m)}return a.range=[n.offset,l,u??l],a}c(eu,"resolveBlockSeq");function Wt(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 h=l.substring(1)||" ";r?r+=o+h:r=h,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(Wt,"resolveEnd");const hr="Block collections are not allowed within flow collections",fr=c(s=>s&&(s.type==="block-map"||s.type==="block-seq"),"isBlock");function tu({composeNode:s,composeEmptyNode:e},t,n,r,i){const o=n.start.source==="{",a=o?"flow map":"flow sequence",l=i?.nodeClass??(o?ue:Ke),u=new l(t.schema);u.flow=!0;const h=t.atRoot;h&&(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 k=n.items[w],{start:_,key:O,sep:A,value:$}=k,N=kt(_,{flow:a,indicator:"explicit-key-ind",next:O??A?.[0],offset:f,onError:r,parentIndent:n.indent,startOnNewline:!1});if(!N.found){if(!N.anchor&&!N.tag&&!A&&!$){w===0&&N.comma?r(N.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`):w<n.items.length-1&&r(N.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${a}`),N.comment&&(u.comment?u.comment+=`
68
+ `+N.comment:u.comment=N.comment),f=N.end;continue}!o&&t.options.strict&&Ut(O)&&r(O,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(w===0)N.comma&&r(N.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`);else if(N.comma||r(N.start,"MISSING_CHAR",`Missing , between ${a} items`),N.comment){let K="";e:for(const I of _)switch(I.type){case"comma":case"space":break;case"comment":K=I.source.substring(1);break e;default:break e}if(K){let I=u.items[u.items.length-1];H(I)&&(I=I.value??I.key),I.comment?I.comment+=`
69
+ `+K:I.comment=K,N.comment=N.comment.substring(K.length+1)}}if(!o&&!A&&!N.found){const K=$?s(t,$,N,r):e(t,N.end,A,null,N,r);u.items.push(K),f=K.range[2],fr($)&&r(K.range,"BLOCK_IN_FLOW",hr)}else{t.atKey=!0;const K=N.end,I=O?s(t,O,N,r):e(t,K,_,null,N,r);fr(O)&&r(I.range,"BLOCK_IN_FLOW",hr),t.atKey=!1;const ee=kt(A??[],{flow:a,indicator:"map-value-ind",next:$,offset:I.range[2],onError:r,parentIndent:n.indent,startOnNewline:!1});if(ee.found){if(!o&&!N.found&&t.options.strict){if(A)for(const te of A){if(te===ee.found)break;if(te.type==="newline"){r(te,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}N.start<ee.found.offset-1024&&r(ee.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else $&&("source"in $&&$.source&&$.source[0]===":"?r($,"MISSING_CHAR",`Missing space after : in ${a}`):r(ee.start,"MISSING_CHAR",`Missing , or : between ${a} items`));const Le=$?s(t,$,ee,r):ee.found?e(t,ee.end,A,null,ee,r):null;Le?fr($)&&r(Le.range,"BLOCK_IN_FLOW",hr):ee.comment&&(I.comment?I.comment+=`
70
+ `+ee.comment:I.comment=ee.comment);const tt=new se(I,Le);if(t.options.keepSourceTokens&&(tt.srcToken=k),o){const te=u;Io(t,te.items,I)&&r(K,"DUPLICATE_KEY","Map keys must be unique"),te.items.push(tt)}else{const te=new ue(t.schema);te.flow=!0,te.items.push(tt);const ii=(Le??I).range;te.range=[I.range[0],ii[1],ii[2]],u.items.push(te)}f=Le?Le.range[2]:ee.end}}const p=o?"}":"]",[m,...y]=n.end;let d=f;if(m&&m.source===p)d=m.offset+m.source.length;else{const w=a[0].toUpperCase()+a.substring(1),k=h?`${w} must end with a ${p}`:`${w} in block collection must be sufficiently indented and end with a ${p}`;r(f,h?"MISSING_CHAR":"BAD_INDENT",k),m&&m.source.length!==1&&y.unshift(m)}if(y.length>0){const w=Wt(y,d,t.options.strict,r);w.comment&&(u.comment?u.comment+=`
71
+ `+w.comment:u.comment=w.comment),u.range=[n.offset,d,w.offset]}else u.range=[n.offset,d,d];return u}c(tu,"resolveFlowCollection");function dr(s,e,t,n,r,i){const o=t.type==="block-map"?Zl(s,e,t,n,i):t.type==="block-seq"?eu(s,e,t,n,i):tu(s,e,t,n,i),a=o.constructor;return r==="!"||r===a.tagName?(o.tag=a.tagName,o):(r&&(o.tag=r),o)}c(dr,"resolveCollection");function nu(s,e,t,n,r){const i=n.tag,o=i?e.directives.tagName(i.source,p=>r(i,"TAG_RESOLVE_FAILED",p)):null;if(t.type==="block-seq"){const{anchor:p,newlineAfterProp:m}=n,y=p&&i?p.offset>i.offset?p:i:p??i;y&&(!m||m.offset<y.offset)&&r(y,"MISSING_CHAR","Missing newline after block sequence props")}const a=t.type==="block-map"?"map":t.type==="block-seq"?"seq":t.start.source==="{"?"map":"seq";if(!i||!o||o==="!"||o===ue.tagName&&a==="map"||o===Ke.tagName&&a==="seq")return dr(s,e,t,r,o);let l=e.schema.tags.find(p=>p.tag===o&&p.collection===a);if(!l){const p=e.schema.knownTags[o];if(p&&p.collection===a)e.schema.tags.push(Object.assign({},p,{default:!1})),l=p;else return p?r(i,"BAD_COLLECTION_TYPE",`${p.tag} used for ${a} collection, but expects ${p.collection??"scalar"}`,!0):r(i,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),dr(s,e,t,r,o)}const u=dr(s,e,t,r,o,l),h=l.resolve?.(u,p=>r(i,"TAG_RESOLVE_FAILED",p),e.options)??u,f=z(h)?h:new M(h);return f.range=u.range,f.tag=o,l?.format&&(f.format=l.format),f}c(nu,"composeCollection");function No(s,e,t){const n=e.offset,r=su(e,s.options.strict,t);if(!r)return{value:"",type:null,comment:"",range:[n,n,n]};const i=r.mode===">"?M.BLOCK_FOLDED:M.BLOCK_LITERAL,o=e.source?ru(e.source):[];let a=o.length;for(let d=o.length-1;d>=0;--d){const w=o[d][1];if(w===""||w==="\r")a=d;else break}if(a===0){const d=r.chomp==="+"&&o.length>0?`
72
72
  `.repeat(Math.max(1,o.length-1)):"";let w=n+r.length;return e.source&&(w+=e.source.length),{value:d,type:i,comment:r.comment,range:[n,w,w]}}let l=e.indent+r.indent,u=e.offset+r.length,h=0;for(let d=0;d<a;++d){const[w,k]=o[d];if(k===""||k==="\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),h=d,l===0&&!s.atRoot&&t(u,"BAD_INDENT","Block scalar values in collections must be indented");break}u+=w.length+k.length+1}for(let d=o.length-1;d>=a;--d)o[d][0].length>l&&(a=d+1);let f="",p="",m=!1;for(let d=0;d<h;++d)f+=o[d][0].slice(l)+`
73
- `;for(let d=h;d<a;++d){let[w,k]=o[d];u+=w.length+k.length+1;const _=k[k.length-1]==="\r";if(_&&(k=k.slice(0,-1)),k&&w.length<l){const O=`Block scalar lines must not be less indented than their ${r.indent?"explicit indentation indicator":"first line"}`;t(u-k.length-(_?2:1),"BAD_INDENT",O),w=""}i===M.BLOCK_LITERAL?(f+=p+w.slice(l)+k,p=`
73
+ `;for(let d=h;d<a;++d){let[w,k]=o[d];u+=w.length+k.length+1;const _=k[k.length-1]==="\r";if(_&&(k=k.slice(0,-1)),k&&w.length<l){const A=`Block scalar lines must not be less indented than their ${r.indent?"explicit indentation indicator":"first line"}`;t(u-k.length-(_?2:1),"BAD_INDENT",A),w=""}i===M.BLOCK_LITERAL?(f+=p+w.slice(l)+k,p=`
74
74
  `):w.length>l||k[0]===" "?(p===" "?p=`
75
75
  `:!m&&p===`
76
76
  `&&(p=`
@@ -83,46 +83,46 @@ ${u}
83
83
  `+o[d][0].slice(l);f[f.length-1]!==`
84
84
  `&&(f+=`
85
85
  `);break;default:f+=`
86
- `}const y=n+r.length+e.source.length;return{value:f,type:i,comment:r.comment,range:[n,y,y]}}c($o,"resolveBlockScalar");function tu({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 p=1;p<r.length;++p){const m=r[p];if(!a&&(m==="-"||m==="+"))a=m;else{const y=Number(m);!o&&y?o=y:l===-1&&(l=s+p)}}l!==-1&&n(l,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${r}`);let u=!1,h="",f=r.length;for(let p=1;p<e.length;++p){const m=e[p];switch(m.type){case"space":u=!0;case"newline":f+=m.source.length;break;case"comment":t&&!u&&n(m,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),f+=m.source.length,h=m.source.substring(1);break;case"error":n(m,"UNEXPECTED_TOKEN",m.message),f+=m.source.length;break;default:{const y=`Unexpected token in block scalar header: ${m.type}`;n(m,"UNEXPECTED_TOKEN",y);const d=m.source;d&&typeof d=="string"&&(f+=d.length)}}}return{mode:i,indent:o,chomp:a,comment:h,length:f}}c(tu,"parseBlockScalarHeader");function nu(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(nu,"splitLines");function No(s,e,t){const{offset:n,type:r,source:i,end:o}=s;let a,l;const u=c((p,m,y)=>t(n+p,m,y),"_onError");switch(r){case"scalar":a=M.PLAIN,l=su(i,u);break;case"single-quoted-scalar":a=M.QUOTE_SINGLE,l=ru(i,u);break;case"double-quoted-scalar":a=M.QUOTE_DOUBLE,l=iu(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 h=n+i.length,f=Wt(o,h,e,t);return{value:l,type:a,comment:f.comment,range:[n,h,f.offset]}}c(No,"resolveFlowScalar");function su(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}`),xo(s)}c(su,"plainValue");function ru(s,e){return(s[s.length-1]!=="'"||s.length===1)&&e(s.length,"MISSING_CHAR","Missing closing 'quote"),xo(s.slice(1,-1)).replace(/''/g,"'")}c(ru,"singleQuotedValue");function xo(s){let e,t;try{e=new RegExp(`(.*?)(?<![ ])[ ]*\r?
86
+ `}const y=n+r.length+e.source.length;return{value:f,type:i,comment:r.comment,range:[n,y,y]}}c(No,"resolveBlockScalar");function su({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 p=1;p<r.length;++p){const m=r[p];if(!a&&(m==="-"||m==="+"))a=m;else{const y=Number(m);!o&&y?o=y:l===-1&&(l=s+p)}}l!==-1&&n(l,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${r}`);let u=!1,h="",f=r.length;for(let p=1;p<e.length;++p){const m=e[p];switch(m.type){case"space":u=!0;case"newline":f+=m.source.length;break;case"comment":t&&!u&&n(m,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),f+=m.source.length,h=m.source.substring(1);break;case"error":n(m,"UNEXPECTED_TOKEN",m.message),f+=m.source.length;break;default:{const y=`Unexpected token in block scalar header: ${m.type}`;n(m,"UNEXPECTED_TOKEN",y);const d=m.source;d&&typeof d=="string"&&(f+=d.length)}}}return{mode:i,indent:o,chomp:a,comment:h,length:f}}c(su,"parseBlockScalarHeader");function ru(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(ru,"splitLines");function xo(s,e,t){const{offset:n,type:r,source:i,end:o}=s;let a,l;const u=c((p,m,y)=>t(n+p,m,y),"_onError");switch(r){case"scalar":a=M.PLAIN,l=iu(i,u);break;case"single-quoted-scalar":a=M.QUOTE_SINGLE,l=ou(i,u);break;case"double-quoted-scalar":a=M.QUOTE_DOUBLE,l=au(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 h=n+i.length,f=Wt(o,h,e,t);return{value:l,type:a,comment:f.comment,range:[n,h,f.offset]}}c(xo,"resolveFlowScalar");function iu(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}`),Mo(s)}c(iu,"plainValue");function ou(s,e){return(s[s.length-1]!=="'"||s.length===1)&&e(s.length,"MISSING_CHAR","Missing closing 'quote"),Mo(s.slice(1,-1)).replace(/''/g,"'")}c(ou,"singleQuotedValue");function Mo(s){let e,t;try{e=new RegExp(`(.*?)(?<![ ])[ ]*\r?
87
87
  `,"sy"),t=new RegExp(`[ ]*(.*?)(?:(?<![ ])[ ]*)?\r?
88
88
  `,"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===`
89
89
  `?r+=i:i=`
90
- `:(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(xo,"foldLines");function iu(s,e){let t="";for(let n=1;n<s.length-1;++n){const r=s[n];if(!(r==="\r"&&s[n+1]===`
90
+ `:(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(Mo,"foldLines");function au(s,e){let t="";for(let n=1;n<s.length-1;++n){const r=s[n];if(!(r==="\r"&&s[n+1]===`
91
91
  `))if(r===`
92
- `){const{fold:i,offset:o}=ou(s,n);t+=i,n=o}else if(r==="\\"){let i=s[++n];const o=au[i];if(o)t+=o;else if(i===`
92
+ `){const{fold:i,offset:o}=cu(s,n);t+=i,n=o}else if(r==="\\"){let i=s[++n];const o=lu[i];if(o)t+=o;else if(i===`
93
93
  `)for(i=s[n+1];i===" "||i===" ";)i=s[++n+1];else if(i==="\r"&&s[n+1]===`
94
- `)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+=cu(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!==`
94
+ `)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+=uu(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!==`
95
95
  `&&!(o==="\r"&&s[n+2]===`
96
- `)&&(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(iu,"doubleQuotedValue");function ou(s,e){let t="",n=s[e+1];for(;(n===" "||n===" "||n===`
96
+ `)&&(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(au,"doubleQuotedValue");function cu(s,e){let t="",n=s[e+1];for(;(n===" "||n===" "||n===`
97
97
  `||n==="\r")&&!(n==="\r"&&s[e+2]!==`
98
98
  `);)n===`
99
99
  `&&(t+=`
100
- `),e+=1,n=s[e+1];return t||(t=" "),{fold:t,offset:e}}c(ou,"foldNewline");const au={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
101
- `,r:"\r",t:" ",v:"\v",N:"\x85",_:"\xA0",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function cu(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(cu,"parseCharCode");function Mo(s,e,t,n){const{value:r,type:i,comment:o,range:a}=e.type==="block-scalar"?$o(s,e,n):No(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[_e]:l?u=lu(s.schema,r,l,t,n):e.type==="scalar"?u=uu(s,r,e,n):u=s.schema[_e];let h;try{const f=u.resolve(r,p=>n(t??e,"TAG_RESOLVE_FAILED",p),s.options);h=W(f)?f:new M(f)}catch(f){const p=f instanceof Error?f.message:String(f);n(t??e,"TAG_RESOLVE_FAILED",p),h=new M(r)}return h.range=a,h.source=r,i&&(h.type=i),l&&(h.tag=l),u.format&&(h.format=u.format),o&&(h.comment=o),h}c(Mo,"composeScalar");function lu(s,e,t,n,r){if(t==="!")return s[_e];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[_e])}c(lu,"findScalarTagByName");function uu({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[_e];if(t.compat){const a=t.compat.find(l=>l.default&&l.test?.test(n))??t[_e];if(o.tag!==a.tag){const l=e.tagString(o.tag),u=e.tagString(a.tag),h=`Value may be parsed as either ${l} or ${u}`;i(r,"TAG_RESOLVE_FAILED",h,!0)}}return o}c(uu,"findScalarTagByTest");function hu(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(hu,"emptyScalarPosition");const fu={composeNode:Ro,composeEmptyNode:dr};function Ro(s,e,t,n){const r=s.atKey,{spaceBefore:i,comment:o,anchor:a,tag:l}=t;let u,h=!0;switch(e.type){case"alias":u=du(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=Mo(s,e,l,n),a&&(u.anchor=a.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":u=eu(fu,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=dr(s,e.offset,void 0,null,t,n),h=!1}}return a&&u.anchor===""&&n(a,"BAD_ALIAS","Anchor cannot be an empty string"),r&&s.options.stringKeys&&(!W(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&&h&&(u.srcToken=e),u}c(Ro,"composeNode");function dr(s,e,t,n,{spaceBefore:r,comment:i,anchor:o,tag:a,end:l},u){const h={type:"scalar",offset:hu(e,t,n),indent:-1,source:""},f=Mo(s,h,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(dr,"composeEmptyNode");function du({options:s},{offset:e,source:t,end:n},r){const i=new $n(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=Wt(n,o,s.strict,r);return i.range=[e,o,a.offset],a.comment&&(i.comment=a.comment),i}c(du,"composeAlias");function pu(s,e,{offset:t,start:n,value:r,end:i},o){const a=Object.assign({_directives:e},s),l=new Pt(void 0,a),u={atKey:!1,atRoot:!0,directives:l.directives,options:l.options,schema:l.schema},h=_t(n,{indicator:"doc-start",next:r??i?.[0],offset:t,onError:o,parentIndent:0,startOnNewline:!0});h.found&&(l.directives.docStart=!0,r&&(r.type==="block-map"||r.type==="block-seq")&&!h.hasNewline&&o(h.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),l.contents=r?Ro(u,r,h,o):dr(u,h.end,n,null,h,o);const f=l.contents.range[2],p=Wt(i,f,!1,o);return p.comment&&(l.comment=p.comment),l.range=[t,f,p.offset],l}c(pu,"composeDoc");function Jt(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(Jt,"getErrorPos");function Po(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?`
100
+ `),e+=1,n=s[e+1];return t||(t=" "),{fold:t,offset:e}}c(cu,"foldNewline");const lu={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
101
+ `,r:"\r",t:" ",v:"\v",N:"\x85",_:"\xA0",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function uu(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(uu,"parseCharCode");function Ro(s,e,t,n){const{value:r,type:i,comment:o,range:a}=e.type==="block-scalar"?No(s,e,n):xo(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[_e]:l?u=hu(s.schema,r,l,t,n):e.type==="scalar"?u=fu(s,r,e,n):u=s.schema[_e];let h;try{const f=u.resolve(r,p=>n(t??e,"TAG_RESOLVE_FAILED",p),s.options);h=W(f)?f:new M(f)}catch(f){const p=f instanceof Error?f.message:String(f);n(t??e,"TAG_RESOLVE_FAILED",p),h=new M(r)}return h.range=a,h.source=r,i&&(h.type=i),l&&(h.tag=l),u.format&&(h.format=u.format),o&&(h.comment=o),h}c(Ro,"composeScalar");function hu(s,e,t,n,r){if(t==="!")return s[_e];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[_e])}c(hu,"findScalarTagByName");function fu({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[_e];if(t.compat){const a=t.compat.find(l=>l.default&&l.test?.test(n))??t[_e];if(o.tag!==a.tag){const l=e.tagString(o.tag),u=e.tagString(a.tag),h=`Value may be parsed as either ${l} or ${u}`;i(r,"TAG_RESOLVE_FAILED",h,!0)}}return o}c(fu,"findScalarTagByTest");function du(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(du,"emptyScalarPosition");const pu={composeNode:Po,composeEmptyNode:pr};function Po(s,e,t,n){const r=s.atKey,{spaceBefore:i,comment:o,anchor:a,tag:l}=t;let u,h=!0;switch(e.type){case"alias":u=mu(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=Ro(s,e,l,n),a&&(u.anchor=a.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":u=nu(pu,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),h=!1}}return a&&u.anchor===""&&n(a,"BAD_ALIAS","Anchor cannot be an empty string"),r&&s.options.stringKeys&&(!W(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&&h&&(u.srcToken=e),u}c(Po,"composeNode");function pr(s,e,t,n,{spaceBefore:r,comment:i,anchor:o,tag:a,end:l},u){const h={type:"scalar",offset:du(e,t,n),indent:-1,source:""},f=Ro(s,h,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 mu({options:s},{offset:e,source:t,end:n},r){const i=new $n(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=Wt(n,o,s.strict,r);return i.range=[e,o,a.offset],a.comment&&(i.comment=a.comment),i}c(mu,"composeAlias");function gu(s,e,{offset:t,start:n,value:r,end:i},o){const a=Object.assign({_directives:e},s),l=new Rt(void 0,a),u={atKey:!1,atRoot:!0,directives:l.directives,options:l.options,schema:l.schema},h=kt(n,{indicator:"doc-start",next:r??i?.[0],offset:t,onError:o,parentIndent:0,startOnNewline:!0});h.found&&(l.directives.docStart=!0,r&&(r.type==="block-map"||r.type==="block-seq")&&!h.hasNewline&&o(h.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),l.contents=r?Po(u,r,h,o):pr(u,h.end,n,null,h,o);const f=l.contents.range[2],p=Wt(i,f,!1,o);return p.comment&&(l.comment=p.comment),l.range=[t,f,p.offset],l}c(gu,"composeDoc");function Jt(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(Jt,"getErrorPos");function Lo(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?`
102
102
 
103
103
  `:`
104
- `)+(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(Po,"parsePrelude");class pr{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=Jt(t);i?this.warnings.push(new Oo(o,n,r)):this.errors.push(new Ze(o,n,r))},this.directives=new oe({version:e.version||"1.2"}),this.options=e}decorate(e,t){const{comment:n,afterEmptyLine:r}=Po(this.prelude);if(n){const i=e.contents;if(t)e.comment=e.comment?`${e.comment}
104
+ `)+(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(Lo,"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=Jt(t);i?this.warnings.push(new Oo(o,n,r)):this.errors.push(new Qe(o,n,r))},this.directives=new oe({version:e.version||"1.2"}),this.options=e}decorate(e,t){const{comment:n,afterEmptyLine:r}=Lo(this.prelude);if(n){const i=e.contents;if(t)e.comment=e.comment?`${e.comment}
105
105
  ${n}`:n;else if(r||e.directives.docStart||!i)e.commentBefore=n;else if(G(i)&&!i.flow&&i.items.length>0){let o=i.items[0];H(o)&&(o=o.key);const a=o.commentBefore;o.commentBefore=a?`${n}
106
106
  ${a}`:n}else{const o=i.commentBefore;i.commentBefore=o?`${n}
107
- ${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:Po(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=Jt(e);i[0]+=t,this.onError(i,"BAD_DIRECTIVE",n,r)}),this.prelude.push(e.source),this.atDirectives=!0;break;case"document":{const t=pu(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 Ze(Jt(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 Ze(Jt(e),"UNEXPECTED_TOKEN",n));break}this.doc.directives.docEnd=!0;const t=Wt(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}
108
- ${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.push(new Ze(Jt(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 Pt(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 mu(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 Ze([a,a+1],i,o)},"_onError");switch(s.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return No(s,e,n);case"block-scalar":return $o({options:{strict:e}},s,n)}}return null}c(mu,"resolveAsScalar");function gu(s,e){const{implicitKey:t=!1,indent:n,inFlow:r=!1,offset:i=-1,type:o="PLAIN"}=e,a=Bt({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:`
107
+ ${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:Lo(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=Jt(e);i[0]+=t,this.onError(i,"BAD_DIRECTIVE",n,r)}),this.prelude.push(e.source),this.atDirectives=!0;break;case"document":{const t=gu(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 Qe(Jt(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 Qe(Jt(e),"UNEXPECTED_TOKEN",n));break}this.doc.directives.docEnd=!0;const t=Wt(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}
108
+ ${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.push(new Qe(Jt(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 Rt(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 yu(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 Qe([a,a+1],i,o)},"_onError");switch(s.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return xo(s,e,n);case"block-scalar":return No({options:{strict:e}},s,n)}}return null}c(yu,"resolveAsScalar");function wu(s,e){const{implicitKey:t=!1,indent:n,inFlow:r=!1,offset:i=-1,type:o="PLAIN"}=e,a=Bt({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:`
109
109
  `}];switch(a[0]){case"|":case">":{const u=a.indexOf(`
110
110
  `),h=a.substring(0,u),f=a.substring(u+1)+`
111
- `,p=[{type:"block-scalar-header",offset:i,indent:n,source:h}];return Lo(p,l)||p.push({type:"newline",offset:-1,indent:n,source:`
112
- `}),{type:"block-scalar",offset:i,indent:n,props:p,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(gu,"createScalarToken");function yu(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=Bt({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">":wu(s,l);break;case'"':mr(s,l,"double-quoted-scalar");break;case"'":mr(s,l,"single-quoted-scalar");break;default:mr(s,l,"scalar")}}c(yu,"setScalarValue");function wu(s,e){const t=e.indexOf(`
111
+ `,p=[{type:"block-scalar-header",offset:i,indent:n,source:h}];return Do(p,l)||p.push({type:"newline",offset:-1,indent:n,source:`
112
+ `}),{type:"block-scalar",offset:i,indent:n,props:p,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(wu,"createScalarToken");function bu(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=Bt({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">":Su(s,l);break;case'"':gr(s,l,"double-quoted-scalar");break;case"'":gr(s,l,"single-quoted-scalar");break;default:gr(s,l,"scalar")}}c(bu,"setScalarValue");function Su(s,e){const t=e.indexOf(`
113
113
  `),n=e.substring(0,t),r=e.substring(t+1)+`
114
- `;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}];Lo(a,"end"in s?s.end:void 0)||a.push({type:"newline",offset:-1,indent:o,source:`
115
- `});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(wu,"setBlockScalarValue");function Lo(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(Lo,"addEndtoBlockProps");function mr(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:`
116
- `};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(mr,"setFlowScalarValue");const bu=c(s=>"type"in s?Gn(s):zn(s),"stringify$1");function Gn(s){switch(s.type){case"block-scalar":{let e="";for(const t of s.props)e+=Gn(t);return e+s.source}case"block-map":case"block-seq":{let e="";for(const t of s.items)e+=zn(t);return e}case"flow-collection":{let e=s.start.source;for(const t of s.items)e+=zn(t);for(const t of s.end)e+=t.source;return e}case"document":{let e=zn(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(Gn,"stringifyToken");function zn({start:s,key:e,sep:t,value:n}){let r="";for(const i of s)r+=i.source;if(e&&(r+=Gn(e)),t)for(const i of t)r+=i.source;return n&&(r+=Gn(n)),r}c(zn,"stringifyItem");const gr=Symbol("break visit"),Su=Symbol("skip children"),Do=Symbol("remove item");function et(s,e){"type"in s&&s.type==="document"&&(s={start:s.start,value:s.value}),jo(Object.freeze([]),s,e)}c(et,"visit"),et.BREAK=gr,et.SKIP=Su,et.REMOVE=Do,et.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},et.parentCollection=(s,e)=>{const t=et.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 jo(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=jo(Object.freeze(s.concat([[r,o]])),i.items[o],t);if(typeof a=="number")o=a-1;else{if(a===gr)return gr;a===Do&&(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(jo,"_visit");const Yn="\uFEFF",Xn="",Qn="",Ht="",vu=c(s=>!!s&&"items"in s,"isCollection"),Cu=c(s=>!!s&&(s.type==="scalar"||s.type==="single-quoted-scalar"||s.type==="double-quoted-scalar"||s.type==="block-scalar"),"isScalar");function ku(s){switch(s){case Yn:return"<BOM>";case Xn:return"<DOC>";case Qn:return"<FLOW_END>";case Ht:return"<SCALAR>";default:return JSON.stringify(s)}}c(ku,"prettyToken");function Fo(s){switch(s){case Yn:return"byte-order-mark";case Xn:return"doc-mode";case Qn:return"flow-error-end";case Ht:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case`
114
+ `;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}];Do(a,"end"in s?s.end:void 0)||a.push({type:"newline",offset:-1,indent:o,source:`
115
+ `});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(Su,"setBlockScalarValue");function Do(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(Do,"addEndtoBlockProps");function gr(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:`
116
+ `};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(gr,"setFlowScalarValue");const vu=c(s=>"type"in s?Gn(s):zn(s),"stringify$1");function Gn(s){switch(s.type){case"block-scalar":{let e="";for(const t of s.props)e+=Gn(t);return e+s.source}case"block-map":case"block-seq":{let e="";for(const t of s.items)e+=zn(t);return e}case"flow-collection":{let e=s.start.source;for(const t of s.items)e+=zn(t);for(const t of s.end)e+=t.source;return e}case"document":{let e=zn(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(Gn,"stringifyToken");function zn({start:s,key:e,sep:t,value:n}){let r="";for(const i of s)r+=i.source;if(e&&(r+=Gn(e)),t)for(const i of t)r+=i.source;return n&&(r+=Gn(n)),r}c(zn,"stringifyItem");const yr=Symbol("break visit"),Cu=Symbol("skip children"),jo=Symbol("remove item");function Ze(s,e){"type"in s&&s.type==="document"&&(s={start:s.start,value:s.value}),Fo(Object.freeze([]),s,e)}c(Ze,"visit"),Ze.BREAK=yr,Ze.SKIP=Cu,Ze.REMOVE=jo,Ze.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},Ze.parentCollection=(s,e)=>{const t=Ze.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 Fo(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=Fo(Object.freeze(s.concat([[r,o]])),i.items[o],t);if(typeof a=="number")o=a-1;else{if(a===yr)return yr;a===jo&&(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(Fo,"_visit");const Yn="\uFEFF",Xn="",Qn="",Ht="",ku=c(s=>!!s&&"items"in s,"isCollection"),_u=c(s=>!!s&&(s.type==="scalar"||s.type==="single-quoted-scalar"||s.type==="double-quoted-scalar"||s.type==="block-scalar"),"isScalar");function Tu(s){switch(s){case Yn:return"<BOM>";case Xn:return"<DOC>";case Qn:return"<FLOW_END>";case Ht:return"<SCALAR>";default:return JSON.stringify(s)}}c(Tu,"prettyToken");function Ko(s){switch(s){case Yn:return"byte-order-mark";case Xn:return"doc-mode";case Qn:return"flow-error-end";case Ht:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case`
117
117
  `:case`\r
118
- `: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(Fo,"tokenType");var _u=Object.freeze({__proto__:null,BOM:Yn,DOCUMENT:Xn,FLOW_END:Qn,SCALAR:Ht,createScalarToken:gu,isCollection:vu,isScalar:Cu,prettyToken:ku,resolveAsScalar:mu,setScalarValue:yu,stringify:bu,tokenType:Fo,visit:et});function be(s){switch(s){case void 0:case" ":case`
119
- `:case"\r":case" ":return!0;default:return!1}}c(be,"isEmpty");const Ko=new Set("0123456789ABCDEFabcdef"),Tu=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),Zn=new Set(",[]{}"),Eu=new Set(` ,[]{}
120
- \r `),yr=c(s=>!s||Eu.has(s),"isNotAnchorChar");class Bo{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===`
118
+ `: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(Ko,"tokenType");var Eu=Object.freeze({__proto__:null,BOM:Yn,DOCUMENT:Xn,FLOW_END:Qn,SCALAR:Ht,createScalarToken:wu,isCollection:ku,isScalar:_u,prettyToken:Tu,resolveAsScalar:yu,setScalarValue:bu,stringify:vu,tokenType:Ko,visit:Ze});function be(s){switch(s){case void 0:case" ":case`
119
+ `:case"\r":case" ":return!0;default:return!1}}c(be,"isEmpty");const Bo=new Set("0123456789ABCDEFabcdef"),Au=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),Zn=new Set(",[]{}"),Ou=new Set(` ,[]{}
120
+ \r `),wr=c(s=>!s||Ou.has(s),"isNotAnchorChar");class qo{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
121
  `?!0:t==="\r"?this.buffer[e+1]===`
122
122
  `:!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===`
123
123
  `||!r&&!this.atEnd)return e+n+1}return t===`
124
124
  `||n>=this.indentNext||!t&&!this.atEnd?e+n:-1}if(t==="-"||t==="."){const n=this.buffer.substr(e,3);if((n==="---"||n==="...")&&be(this.buffer[e+3]))return-1}return e}getLine(){let e=this.lineEndPos;return(typeof e!="number"||e!==-1&&e<this.pos)&&(e=this.buffer.indexOf(`
125
- `,this.pos),this.lineEndPos=e),e===-1?this.atEnd?this.buffer.substring(this.pos):null:(this.buffer[e-1]==="\r"&&(e-=1),this.buffer.substring(this.pos,e))}hasChars(e){return this.pos+e<=this.buffer.length}setNext(e){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=e,null}peek(e){return this.buffer.substr(this.pos,e)}*parseNext(e){switch(e){case"stream":return yield*this.parseStream();case"line-start":return yield*this.parseLineStart();case"block-start":return yield*this.parseBlockStart();case"doc":return yield*this.parseDocument();case"flow":return yield*this.parseFlowCollection();case"quoted-scalar":return yield*this.parseQuotedScalar();case"block-scalar":return yield*this.parseBlockScalar();case"plain-scalar":return yield*this.parsePlainScalar()}}*parseStream(){let e=this.getLine();if(e===null)return this.setNext("stream");if(e[0]===Yn&&(yield*this.pushCount(1),e=e.substring(1)),e[0]==="%"){let t=e.length,n=e.indexOf("#");for(;n!==-1;){const i=e[n-1];if(i===" "||i===" "){t=n-1;break}else n=e.indexOf("#",n+1)}for(;;){const i=e[t-1];if(i===" "||i===" ")t-=1;else break}const r=(yield*this.pushCount(t))+(yield*this.pushSpaces(!0));return yield*this.pushCount(e.length-r),this.pushNewline(),"stream"}if(this.atLineEnd()){const t=yield*this.pushSpaces(!0);return yield*this.pushCount(e.length-t),yield*this.pushNewline(),"stream"}return yield Xn,yield*this.parseLineStart()}*parseLineStart(){const e=this.charAt(0);if(!e&&!this.atEnd)return this.setNext("line-start");if(e==="-"||e==="."){if(!this.atEnd&&!this.hasChars(4))return this.setNext("line-start");const t=this.peek(3);if((t==="---"||t==="...")&&be(this.charAt(3)))return yield*this.pushCount(3),this.indentValue=0,this.indentNext=0,t==="---"?"doc":"stream"}return this.indentValue=yield*this.pushSpaces(!1),this.indentNext>this.indentValue&&!be(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){const[e,t]=this.peek(2);if(!t&&!this.atEnd)return this.setNext("block-start");if((e==="-"||e==="?"||e===":")&&be(t)){const n=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=n,yield*this.parseBlockStart()}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);const e=this.getLine();if(e===null)return this.setNext("doc");let t=yield*this.pushIndicators();switch(e[t]){case"#":yield*this.pushCount(e.length-t);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,"flow";case"}":case"]":return yield*this.pushCount(1),"doc";case"*":return yield*this.pushUntil(yr),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return t+=yield*this.parseBlockScalarHeader(),t+=yield*this.pushSpaces(!0),yield*this.pushCount(e.length-t),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let e,t,n=-1;do e=yield*this.pushNewline(),e>0?(t=yield*this.pushSpaces(!1),this.indentValue=n=t):t=0,t+=yield*this.pushSpaces(!0);while(e+t>0);const r=this.getLine();if(r===null)return this.setNext("flow");if((n!==-1&&n<this.indentNext&&r[0]!=="#"||n===0&&(r.startsWith("---")||r.startsWith("..."))&&be(r[3]))&&!(n===this.indentNext-1&&this.flowLevel===1&&(r[0]==="]"||r[0]==="}")))return this.flowLevel=0,yield Qn,yield*this.parseLineStart();let i=0;for(;r[i]===",";)i+=yield*this.pushCount(1),i+=yield*this.pushSpaces(!0),this.flowKey=!1;switch(i+=yield*this.pushIndicators(),r[i]){case void 0:return"flow";case"#":return yield*this.pushCount(r.length-i),"flow";case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel+=1,"flow";case"}":case"]":return yield*this.pushCount(1),this.flowKey=!0,this.flowLevel-=1,this.flowLevel?"flow":"doc";case"*":return yield*this.pushUntil(yr),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{const o=this.charAt(1);if(this.flowKey||be(o)||o===",")return this.flowKey=!1,yield*this.pushCount(1),yield*this.pushSpaces(!0),"flow"}default:return this.flowKey=!1,yield*this.parsePlainScalar()}}*parseQuotedScalar(){const e=this.charAt(0);let t=this.buffer.indexOf(e,this.pos+1);if(e==="'")for(;t!==-1&&this.buffer[t+1]==="'";)t=this.buffer.indexOf("'",t+2);else for(;t!==-1;){let i=0;for(;this.buffer[t-1-i]==="\\";)i+=1;if(i%2===0)break;t=this.buffer.indexOf('"',t+1)}const n=this.buffer.substring(0,t);let r=n.indexOf(`
125
+ `,this.pos),this.lineEndPos=e),e===-1?this.atEnd?this.buffer.substring(this.pos):null:(this.buffer[e-1]==="\r"&&(e-=1),this.buffer.substring(this.pos,e))}hasChars(e){return this.pos+e<=this.buffer.length}setNext(e){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=e,null}peek(e){return this.buffer.substr(this.pos,e)}*parseNext(e){switch(e){case"stream":return yield*this.parseStream();case"line-start":return yield*this.parseLineStart();case"block-start":return yield*this.parseBlockStart();case"doc":return yield*this.parseDocument();case"flow":return yield*this.parseFlowCollection();case"quoted-scalar":return yield*this.parseQuotedScalar();case"block-scalar":return yield*this.parseBlockScalar();case"plain-scalar":return yield*this.parsePlainScalar()}}*parseStream(){let e=this.getLine();if(e===null)return this.setNext("stream");if(e[0]===Yn&&(yield*this.pushCount(1),e=e.substring(1)),e[0]==="%"){let t=e.length,n=e.indexOf("#");for(;n!==-1;){const i=e[n-1];if(i===" "||i===" "){t=n-1;break}else n=e.indexOf("#",n+1)}for(;;){const i=e[t-1];if(i===" "||i===" ")t-=1;else break}const r=(yield*this.pushCount(t))+(yield*this.pushSpaces(!0));return yield*this.pushCount(e.length-r),this.pushNewline(),"stream"}if(this.atLineEnd()){const t=yield*this.pushSpaces(!0);return yield*this.pushCount(e.length-t),yield*this.pushNewline(),"stream"}return yield Xn,yield*this.parseLineStart()}*parseLineStart(){const e=this.charAt(0);if(!e&&!this.atEnd)return this.setNext("line-start");if(e==="-"||e==="."){if(!this.atEnd&&!this.hasChars(4))return this.setNext("line-start");const t=this.peek(3);if((t==="---"||t==="...")&&be(this.charAt(3)))return yield*this.pushCount(3),this.indentValue=0,this.indentNext=0,t==="---"?"doc":"stream"}return this.indentValue=yield*this.pushSpaces(!1),this.indentNext>this.indentValue&&!be(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){const[e,t]=this.peek(2);if(!t&&!this.atEnd)return this.setNext("block-start");if((e==="-"||e==="?"||e===":")&&be(t)){const n=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=n,yield*this.parseBlockStart()}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);const e=this.getLine();if(e===null)return this.setNext("doc");let t=yield*this.pushIndicators();switch(e[t]){case"#":yield*this.pushCount(e.length-t);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,"flow";case"}":case"]":return yield*this.pushCount(1),"doc";case"*":return yield*this.pushUntil(wr),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return t+=yield*this.parseBlockScalarHeader(),t+=yield*this.pushSpaces(!0),yield*this.pushCount(e.length-t),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let e,t,n=-1;do e=yield*this.pushNewline(),e>0?(t=yield*this.pushSpaces(!1),this.indentValue=n=t):t=0,t+=yield*this.pushSpaces(!0);while(e+t>0);const r=this.getLine();if(r===null)return this.setNext("flow");if((n!==-1&&n<this.indentNext&&r[0]!=="#"||n===0&&(r.startsWith("---")||r.startsWith("..."))&&be(r[3]))&&!(n===this.indentNext-1&&this.flowLevel===1&&(r[0]==="]"||r[0]==="}")))return this.flowLevel=0,yield Qn,yield*this.parseLineStart();let i=0;for(;r[i]===",";)i+=yield*this.pushCount(1),i+=yield*this.pushSpaces(!0),this.flowKey=!1;switch(i+=yield*this.pushIndicators(),r[i]){case void 0:return"flow";case"#":return yield*this.pushCount(r.length-i),"flow";case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel+=1,"flow";case"}":case"]":return yield*this.pushCount(1),this.flowKey=!0,this.flowLevel-=1,this.flowLevel?"flow":"doc";case"*":return yield*this.pushUntil(wr),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{const o=this.charAt(1);if(this.flowKey||be(o)||o===",")return this.flowKey=!1,yield*this.pushCount(1),yield*this.pushSpaces(!0),"flow"}default:return this.flowKey=!1,yield*this.parsePlainScalar()}}*parseQuotedScalar(){const e=this.charAt(0);let t=this.buffer.indexOf(e,this.pos+1);if(e==="'")for(;t!==-1&&this.buffer[t+1]==="'";)t=this.buffer.indexOf("'",t+2);else for(;t!==-1;){let i=0;for(;this.buffer[t-1-i]==="\\";)i+=1;if(i%2===0)break;t=this.buffer.indexOf('"',t+1)}const n=this.buffer.substring(0,t);let r=n.indexOf(`
126
126
  `,this.pos);if(r!==-1){for(;r!==-1;){const i=this.continueScalar(r+1);if(i===-1)break;r=n.indexOf(`
127
127
  `,i)}r!==-1&&(t=r-(n[r-1]==="\r"?2:1))}if(t===-1){if(!this.atEnd)return this.setNext("quoted-scalar");t=this.buffer.length}return yield*this.pushToIndex(t+1,!1),this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let e=this.pos;for(;;){const t=this.buffer[++e];if(t==="+")this.blockScalarKeep=!0;else if(t>"0"&&t<="9")this.blockScalarIndent=Number(t)-1;else if(t!=="-")break}return yield*this.pushUntil(t=>be(t)||t==="#")}*parseBlockScalar(){let e=this.pos-1,t=0,n;e:for(let i=this.pos;n=this.buffer[i];++i)switch(n){case" ":t+=1;break;case`
128
128
  `:e=i,t=0;break;case"\r":{const o=this.buffer[i+1];if(!o&&!this.atEnd)return this.setNext("block-scalar");if(o===`
@@ -132,39 +132,39 @@ ${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.pus
132
132
  `&&i>=this.pos&&i+1+t>a)e=i;else break}while(!0);return yield Ht,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(be(i)||e&&Zn.has(i))break;t=n}else if(be(r)){let i=this.buffer[n+1];if(r==="\r"&&(i===`
133
133
  `?(n+=1,r=`
134
134
  `,i=this.buffer[n+1]):t=n),i==="#"||e&&Zn.has(i))break;if(r===`
135
- `){const o=this.continueScalar(n+1);if(o===-1)break;n=Math.max(n,o-2)}}else{if(e&&Zn.has(r))break;t=n}return!r&&!this.atEnd?this.setNext("plain-scalar"):(yield Ht,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(yr))+(yield*this.pushSpaces(!0))+(yield*this.pushIndicators());case"-":case"?":case":":{const e=this.flowLevel>0,t=this.charAt(1);if(be(t)||e&&Zn.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(;!be(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(Tu.has(t))t=this.buffer[++e];else if(t==="%"&&Ko.has(this.buffer[e+1])&&Ko.has(this.buffer[e+2]))t=this.buffer[e+=3];else break;return yield*this.pushToIndex(e,!1)}}*pushNewline(){const e=this.buffer[this.pos];return e===`
135
+ `){const o=this.continueScalar(n+1);if(o===-1)break;n=Math.max(n,o-2)}}else{if(e&&Zn.has(r))break;t=n}return!r&&!this.atEnd?this.setNext("plain-scalar"):(yield Ht,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(wr))+(yield*this.pushSpaces(!0))+(yield*this.pushIndicators());case"-":case"?":case":":{const e=this.flowLevel>0,t=this.charAt(1);if(be(t)||e&&Zn.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(;!be(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(Au.has(t))t=this.buffer[++e];else if(t==="%"&&Bo.has(this.buffer[e+1])&&Bo.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===`
136
136
  `?yield*this.pushCount(1):e==="\r"&&this.charAt(1)===`
137
- `?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 qo{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 Be(s,e){for(let t=0;t<s.length;++t)if(s[t].type===e)return!0;return!1}c(Be,"includesToken");function Uo(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(Uo,"findNonEmptyIndex");function Wo(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(Wo,"isFlowToken");function es(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(es,"getPrevProps");function Tt(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(Tt,"getFirstKeyStartProps");function Jo(s){if(s.start.type==="flow-seq-start")for(const e of s.items)e.sep&&!e.value&&!Be(e.start,"explicit-key-ind")&&!Be(e.sep,"map-value-ind")&&(e.key&&(e.value=e.key),delete e.key,Wo(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(Jo,"fixFlowSeqItems");class wr{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 Bo,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=Fo(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"&&Jo(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&&Uo(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":{Uo(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=es(this.peek(2)),n=Tt(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(`
137
+ `?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 Uo{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 Be(s,e){for(let t=0;t<s.length;++t)if(s[t].type===e)return!0;return!1}c(Be,"includesToken");function Wo(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(Wo,"findNonEmptyIndex");function Jo(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(Jo,"isFlowToken");function es(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(es,"getPrevProps");function _t(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(_t,"getFirstKeyStartProps");function Ho(s){if(s.start.type==="flow-seq-start")for(const e of s.items)e.sep&&!e.value&&!Be(e.start,"explicit-key-ind")&&!Be(e.sep,"map-value-ind")&&(e.key&&(e.value=e.key),delete e.key,Jo(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(Ho,"fixFlowSeqItems");class br{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 qo,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=Ko(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"&&Ho(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&&Wo(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":{Wo(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=es(this.peek(2)),n=_t(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(`
138
138
  `)+1;for(;t!==0;)this.onNewLine(this.offset+t),t=this.source.indexOf(`
139
- `,t)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(e){const t=e.items[e.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,t.value){const n="end"in t.value?t.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type==="comment"?n?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"space":case"comment":if(t.value)e.items.push({start:[this.sourceToken]});else if(t.sep)t.sep.push(this.sourceToken);else{if(this.atIndentedComment(t.start,e.indent)){const r=e.items[e.items.length-2]?.value?.end;if(Array.isArray(r)){Array.prototype.push.apply(r,t.start),r.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return}if(this.indent>=e.indent){const n=!this.onKeyLine&&this.indent===e.indent,r=n&&(t.sep||t.explicitKey)&&this.type!=="seq-item-ind";let i=[];if(r&&t.sep&&!t.value){const o=[];for(let a=0;a<t.sep.length;++a){const l=t.sep[a];switch(l.type){case"newline":o.push(a);break;case"space":break;case"comment":l.indent>e.indent&&(o.length=0);break;default:o.length=0}}o.length>=2&&(i=t.sep.splice(o[1]))}switch(this.type){case"anchor":case"tag":r||t.value?(i.push(this.sourceToken),e.items.push({start:i}),this.onKeyLine=!0):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"explicit-key-ind":!t.sep&&!t.explicitKey?(t.start.push(this.sourceToken),t.explicitKey=!0):r||t.value?(i.push(this.sourceToken),e.items.push({start:i,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(t.explicitKey)if(t.sep)if(t.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(Be(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(Wo(t.key)&&!Be(t.sep,"newline")){const o=Tt(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(Be(t.start,"newline"))Object.assign(t,{key:null,sep:[this.sourceToken]});else{const o=Tt(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]}):Be(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&&!Be(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||Be(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=es(n),i=Tt(r);Jo(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(`
139
+ `,t)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(e){const t=e.items[e.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,t.value){const n="end"in t.value?t.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type==="comment"?n?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"space":case"comment":if(t.value)e.items.push({start:[this.sourceToken]});else if(t.sep)t.sep.push(this.sourceToken);else{if(this.atIndentedComment(t.start,e.indent)){const r=e.items[e.items.length-2]?.value?.end;if(Array.isArray(r)){Array.prototype.push.apply(r,t.start),r.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return}if(this.indent>=e.indent){const n=!this.onKeyLine&&this.indent===e.indent,r=n&&(t.sep||t.explicitKey)&&this.type!=="seq-item-ind";let i=[];if(r&&t.sep&&!t.value){const o=[];for(let a=0;a<t.sep.length;++a){const l=t.sep[a];switch(l.type){case"newline":o.push(a);break;case"space":break;case"comment":l.indent>e.indent&&(o.length=0);break;default:o.length=0}}o.length>=2&&(i=t.sep.splice(o[1]))}switch(this.type){case"anchor":case"tag":r||t.value?(i.push(this.sourceToken),e.items.push({start:i}),this.onKeyLine=!0):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"explicit-key-ind":!t.sep&&!t.explicitKey?(t.start.push(this.sourceToken),t.explicitKey=!0):r||t.value?(i.push(this.sourceToken),e.items.push({start:i,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(t.explicitKey)if(t.sep)if(t.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(Be(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(Jo(t.key)&&!Be(t.sep,"newline")){const o=_t(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(Be(t.start,"newline"))Object.assign(t,{key:null,sep:[this.sourceToken]});else{const o=_t(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]}):Be(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&&!Be(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||Be(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=es(n),i=_t(r);Ho(e);const o=e.end.splice(1,e.end.length);o.push(this.sourceToken);const a={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:i,key:e,sep:o}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=a}else yield*this.lineEnd(e)}}flowScalar(e){if(this.onNewLine){let t=this.source.indexOf(`
140
140
  `)+1;for(;t!==0;)this.onNewLine(this.offset+t),t=this.source.indexOf(`
141
- `,t)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;const t=es(e),n=Tt(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=es(e),n=Tt(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 Ho(s){const e=s.prettyErrors!==!1;return{lineCounter:s.lineCounter||e&&new qo||null,prettyErrors:e}}c(Ho,"parseOptions");function Ou(s,e={}){const{lineCounter:t,prettyErrors:n}=Ho(e),r=new wr(t?.addNewLine),i=new pr(e),o=Array.from(i.compose(r.parse(s)));if(n&&t)for(const a of o)a.errors.forEach(Vn(s,t)),a.warnings.forEach(Vn(s,t));return o.length>0?o:Object.assign([],{empty:!0},i.streamInfo())}c(Ou,"parseAllDocuments");function Vo(s,e={}){const{lineCounter:t,prettyErrors:n}=Ho(e),r=new wr(t?.addNewLine),i=new pr(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 Ze(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return n&&t&&(o.errors.forEach(Vn(s,t)),o.warnings.forEach(Vn(s,t))),o}c(Vo,"parseDocument");function Au(s,e,t){let n;typeof e=="function"?n=e:t===void 0&&e&&typeof e=="object"&&(t=e);const r=Vo(s,t);if(!r)return null;if(r.warnings.forEach(i=>so(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(Au,"parse");function Iu(s,e,t){let n=null;if(typeof e=="function"||Array.isArray(e)?n=e:t===void 0&&e&&(t=e),typeof t=="string"&&(t=t.length),typeof t=="number"){const r=Math.round(t);t=r<1?void 0:r>8?{indent:8}:{indent:r}}if(s===void 0){const{keepUndefined:r}=t??e??{};if(!r)return}return ze(s)&&!n?s.toString(t):new Pt(s,n,t).toString(t)}c(Iu,"stringify");var $u=Object.freeze({__proto__:null,Alias:$n,CST:_u,Composer:pr,Document:Pt,Lexer:Bo,LineCounter:qo,Pair:se,Parser:wr,Scalar:M,Schema:Es,YAMLError:cr,YAMLMap:ue,YAMLParseError:Ze,YAMLSeq:Ke,YAMLWarning:Oo,isAlias:Fe,isCollection:G,isDocument:ze,isMap:pt,isNode:z,isPair:H,isScalar:W,isSeq:mt,parse:Au,parseAllDocuments:Ou,parseDocument:Vo,stringify:Iu,visit:Ye,visitAsync:In});const he={Updated:"updated",Deleted:"deleted",Stopped:"stopped"},Nu={ignored:ll,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 xu extends qs{static{c(this,"LocalElementWatcher")}constructor(e){super(),this.options=e,this.membraneDir=ft(this.options.cwd),this.lockTimeoutMs=this.options.lockTimeoutMs??1e3}isWatching=!1;watcher;membraneDir;contentCache={};ignoredPaths=new Set;lockTimeoutMs;async start(){this.isWatching||(L.existsSync(this.membraneDir)||L.mkdirSync(this.membraneDir,{recursive:!0}),this.initializeContentCache(),this.watcher=Nc.watch(this.membraneDir,Nu),this.watcher.on("add",e=>this.handleFileSystemEvent(he.Updated,e)).on("change",e=>this.handleFileSystemEvent(he.Updated,e)).on("unlink",e=>this.handleFileSystemEvent(he.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(he.Stopped))}getCwd(){return this.options.cwd}async executeWithPathLock(e,t){const n=q.resolve(e);this.ignoredPaths.add(n);try{await t()}finally{setTimeout(()=>{this.ignoredPaths.delete(n)},this.lockTimeoutMs)}}isPathLocked(e){const t=q.resolve(e);if(this.ignoredPaths.has(t))return!0;for(const n of this.ignoredPaths)if(t.startsWith(n+q.sep))return!0;return!1}clearAllLocks(){this.ignoredPaths.clear()}handleFileSystemEvent(e,t){const n=q.relative(this.membraneDir,t);if(this.isPathLocked(t))return;if(e===he.Deleted){this.removeFromCache(n);const a={filePath:t,relativePath:n,data:void 0};b.info(`[local] ${e}: ${a.relativePath}`),this.emit(e,a);return}const r=this.readFileContent(t);if(!this.hasContentChanged(n,r))return;const o=this.processFileEvent(t,r);this.updateCache(n,r),o&&(b.info(`[local] ${e}: ${o.relativePath}`),this.emit(e,o))}readFileContent(e){return L.readFileSync(e,"utf8")}processFileEvent(e,t){const n=q.relative(this.membraneDir,e);let r;try{r=t?$u.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 Ic.createHash("sha256").update(e).digest("hex")}updateCache(e,t){if(!t){delete this.contentCache[e];return}this.contentCache[e]=this.getContentHash(t)}removeFromCache(e){delete this.contentCache[e]}clearCache(){Object.keys(this.contentCache).forEach(e=>{delete this.contentCache[e]})}initializeContentCache(){L.existsSync(this.membraneDir)&&this.scanDirectoryForCache(this.membraneDir)}scanDirectoryForCache(e){const t=L.readdirSync(e,{withFileTypes:!0});for(const n of t){const r=q.join(e,n.name);if(n.isDirectory())this.scanDirectoryForCache(r);else if(n.isFile())try{const i=L.readFileSync(r,"utf8"),o=q.relative(this.membraneDir,r);this.updateCache(o,i)}catch{}}}}var br=(s=>(s.Updated="updated",s.ConnectorFileUpdated="connector-file-updated",s.Connected="connected",s.Disconnected="disconnected",s.Error="error",s))(br||{});const Mu={debounceMs:2e3,reconnectIntervalMs:5e3,maxReconnectAttempts:5};class Ru extends qs{static{c(this,"RemoteElementWatcher")}constructor(e=Mu){super(),this.config=e}eventSource;debounceTimeouts=new Map;reconnectAttempts=0;reconnectTimeout;isStarted=!1;async start(){this.isStarted||(this.isStarted=!0,await this.connect())}async stop(){this.isStarted&&(this.isStarted=!1,this.clearReconnectTimeout(),this.clearAllDebounceTimeouts(),this.eventSource&&(this.eventSource.close(),this.eventSource=void 0))}async connect(){try{b.debug("[remote-events] Connecting to server");const e=await U.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 xc(n),this.setupEventSourceHandlers()}catch(e){b.error(`[remote-events] Failed to subscribe to workspace events: ${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.emit("connected",{})},this.eventSource.onmessage=e=>{try{const t=JSON.parse(e.data);this.handleElementUpdate(t)}catch(t){b.error(`[remote-events] Failed to parse workspace event: ${t}`)}},this.eventSource.onerror=e=>{b.error(`[remote-events] Connection error: ${JSON.stringify(e,null,2)}`),this.emit("disconnected",{}),this.isStarted&&this.scheduleReconnect()})}handleElementUpdate(e){if(e.type!==Sc.ElementUpdate)return;const{elementId:t,elementType:n,data:r={}}=e;if(!(!t||!n)){if(n===K.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){if(this.reconnectAttempts>=this.config.maxReconnectAttempts)throw new Error("Unable to re-connect to the server");return}this.reconnectAttempts++;const e=Math.min(this.config.reconnectIntervalMs*Math.pow(2,this.reconnectAttempts-1),3e4);b.debug(`[remote-watcher] Reconnecting in ${e}ms (attempt ${this.reconnectAttempts})`),this.reconnectTimeout=setTimeout(()=>{this.connect()},e)}clearReconnectTimeout(){this.reconnectTimeout&&(clearTimeout(this.reconnectTimeout),this.reconnectTimeout=void 0)}clearAllDebounceTimeouts(){this.debounceTimeouts.forEach(e=>clearTimeout(e)),this.debounceTimeouts.clear()}}class Go{static{c(this,"ElementsCache")}elements=new Map;typeIndex=new Map;internalIdIndex=new Map;constructor(e){e&&this.addAll(e)}add(e){const t=e.id;this.elements.set(t,e),this.typeIndex.has(e.type)||this.typeIndex.set(e.type,new Set),this.typeIndex.get(e.type).add(t),e.data?.id&&this.internalIdIndex.set(e.data.id,t)}remove(e){const t=e.id,n=this.elements.delete(t);if(n){const r=this.typeIndex.get(e.type);r&&(r.delete(t),r.size===0&&this.typeIndex.delete(e.type)),e.data?.id&&this.internalIdIndex.delete(e.data.id)}return n}put(e){this.elements.has(e.id)&&this.remove(e),this.add(e)}get(e){return this.elements.get(e)}getByInternalId(e){const t=this.internalIdIndex.get(e);if(t)return this.elements.get(t)}getElementsByType(e){const t=this.typeIndex.get(e);return t?Array.from(t).map(n=>this.elements.get(n)).filter(n=>n!==void 0):[]}getAll(){return Array.from(this.elements.values())??[]}getTypes(){return Array.from(this.typeIndex.keys())}addAll(e){for(const t of e)t&&this.add(t)}removeAll(e){for(const t of e)this.remove(t)}getElementIdsByType(e){return this.typeIndex.get(e)}clear(){this.elements.clear(),this.typeIndex.clear(),this.internalIdIndex.clear()}getAllIds(){return new Set(this.elements.keys())}}async function Pu(s="full"){const e={};b.info("[connectors] Getting remote workspace data");const t=await U.withClient(n=>n.integrations.findAll());e.integration=t.map(n=>Sr("integration",n));for(const n of Object.keys(le)){const r=le[n];if(r.exportable===!1)continue;const i=[];b.info(`[connectors] Reading ${r.elements} from remote workspace`);const o=await U.withClient(a=>a[r.elements].findAll());if(i.push(...o.map(a=>Sr(n,a))),r.integrationSpecific)for(const a of t){const l=await U.withClient(u=>u[r.elements].findAll({integrationId:a.id}));i.push(...l.map(u=>(u.integrationKey=a.key,Sr(n,u))))}i.length>0&&s=="full"&&(console.table(i.map(a=>({key:a.key,integrationKey:a.integrationKey,universal:!a.integrationKey})).reduce((a,l)=>(a||(a={}),a[l.key]||(a[l.key]={}),l.universal&&(a[l.key].universal=!0),l.integrationKey&&(a[l.key].integration?a[l.key].integration+=` ${l.integrationKey}`:a[l.key].integration=l.integrationKey),a),{})),console.groupEnd()),e[n]=i}return b.success("[connectors] Remote workspace data retrieved successfully"),e}c(Pu,"getWorkspaceData");function Sr(s,e){return e=al(e),le[s].exportCleanup?le[s].exportCleanup(e):e}c(Sr,"cleanUpForExport");const Et="connectors",Ne="development",vr={};async function Lu(){const s=await Pu("minified"),t=(await U.withClient(l=>l.get("org-workspace-id"))).id,n={};b.info("[connectors] Loading custom connectors");const r=await U.withClient(l=>l.get(`/connectors?workspaceId=${t}`));b.info("[connectors] Loading public connectors"),s.connector=r;const i=qe(),a=(P.existsSync(i)?P.readdirSync(i):[]).filter(l=>{if(l.startsWith("."))return!1;const u=B.join(i,l);try{return P.statSync(u).isDirectory()}catch{return!1}});for(const l of a){b.info(`[connectors] Loading connector from: ${l}`);const u=P.readdirSync(B.join(i,l)),h=await Cr(l);if(!h)continue;if("baseUri"in h&&delete h.baseUri,h.uuid&&s.connector?.find(p=>p.uuid==h.uuid))n[h.id]=s.connector.find(p=>p.uuid==h.uuid).id,b.info(`[connectors] Matched ${h.name} uuid: ${h.uuid}`);else if(!n[h.id]){let p=!1;try{const m=await kr({connectorId:h.id});m&&!m.workspaceId&&(p=!0)}catch{}if(!p){b.info(`[connectors] Creating custom connector ${h.name} (${h.key})`);const m=await U.withClient(y=>y.post("connectors",{...h,workspaceId:t}));n[h.id]=m.id}}const f=u.filter(p=>P.statSync(B.join(i,l,p)).isDirectory());for(const p of f)await Fu({connector:h,version:p,connectorId:n[h.id]})}return n}c(Lu,"pushConnectors");async function zo({connectorId:s,connectorVersion:e,allConnectors:t,pulledConnectors:n,pulledConnectorVersions:r}){if(!s||r[s]?.has(e))return;const i=Li(),o=await kr({connectorId:s});if(o.workspaceId||t){if(!o?.key){b.error(`[connectors] Connector ${s} has no key. Skipping..`);return}n.has(s)||(await Ku({basePath:i,connector:o}),n.add(s)),r[s]||(r[s]=new Set),r[s].has(e)||(await Bu({connector:o,connectorVersion:e,basePath:i}),r[s].add(e))}}c(zo,"pullRemoteConnector");function qe(){const s=Ws();return B.join(s.membraneDirPath,Et)}c(qe,"getConnectorsPath");async function Cr(s){const e=B.join(qe(),s,`${s}.yml`);if(P.existsSync(e))return Ge.load(P.readFileSync(e,"utf8"))}c(Cr,"readConnector");async function Du(s,e){return b.info(`[connectors] Zipping ${s} into ${e}`),new Promise((t,n)=>{const r=P.createWriteStream(e),i=Mc("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=P.readdirSync(s);for(const a of o){const l=B.join(s,a),u=P.statSync(l);u.isFile()?i.file(l,{name:a}):u.isDirectory()&&i.directory(l,a)}i.finalize()})}c(Du,"createZipArchive");async function ju(s,e){return b.info(`[connectors] Unzipping into ${e}`),new Promise((t,n)=>{const r=Pc.Parse();r.on("entry",i=>{const o=i.path;if(i.type==="Directory"){const l=B.join(e,o);P.mkdirSync(l,{recursive:!0}),i.autodrain()}else{const l=B.join(e,o),u=B.dirname(l);P.mkdirSync(u,{recursive:!0});const h=P.createWriteStream(l);i.pipe(h),h.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(ju,"extractZipArchive");async function Fu({connector:s,version:e,connectorId:t}){const n=B.join(qe(),xe(s),Yo(e)),r=B.join(n,"src"),i=B.join(n,"src.zip"),o=P.existsSync(i);if(P.existsSync(r)&&(b.info(`[connectors] Archiving source code for ${s.name} version ${e}`),await Du(r,i)),!P.existsSync(i)){b.warning(`[connectors] No source code found for ${s.name} version ${e}`);return}try{const a=new Rc;if(a.append("file",P.createReadStream(i),"file.zip"),b.info(`[connectors] Pushing connector version ${e} for ${s.name}`),e==Ne)b.info(`[connectors] Uploading connector ${t}`),await U.withClient(l=>l.post(`connectors/${t}/upload`,a,{headers:{...a.getHeaders()}}));else{if(a.append("version",e),a.append("changelog","Imported Version"),(await U.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 U.withClient(u=>u.post(`connectors/${t}/publish-version`,a,{headers:{...a.getHeaders()}}))}b.success(`Successfully pushed connector version ${e} for ${s.name}`)}catch(a){b.error(`Error pushing connector version ${e} for ${s.name}: ${a}`)}finally{!o&&P.existsSync(i)&&(b.info(`[connectors] Cleaning up temporary zip file for ${s.name} version ${e}`),P.unlinkSync(i))}}c(Fu,"pushConnectorVersion");async function kr({connectorId:s}){if(s){if(vr[s])return vr[s];try{const e=await U.withClient(t=>t.get(`connectors/${s}`));return vr[s]=e,e}catch(e){return b.error(`[connectors] Failed to get connector ${s}: ${e}`),null}}}c(kr,"getConnector");async function Ku({basePath:s,connector:e}){const t=xe(e),n=B.join(s,Et,t);P.mkdirSync(n,{recursive:!0});const r=B.join(n,`${xe(e)}.yml`);P.writeFileSync(r,Ge.dump(e)),b.info(`[connectors] Pulled connector ${e.name}`)}c(Ku,"pullConnector");async function Bu({connector:s,connectorVersion:e,basePath:t}){const n=xe(s),r=Yo(e),i=B.join(t,"connectors",n,r),o=await U.withClient(l=>l.get(`connectors/${s.id}/download`,{version:e},{responseType:"arraybuffer",headers:{Accept:"application/zip"},timeout:1e6}));P.mkdirSync(i,{recursive:!0});const a=B.join(i,"src.zip");if(P.writeFileSync(a,o),!e){const l=B.join(i,"src");P.mkdirSync(l,{recursive:!0}),await ju(o,l)}b.info(`[connectors] Pulled connector version: ${s.name} (${r})`)}c(Bu,"pullConnectorVersion");function xe(s){return s.key}c(xe,"getConnectorDirName");function Yo(s){return s??Ne}c(Yo,"getConnectorVersionDirName");function qu(s){const e=Li(),t=xe(s);return B.join(e,Et,t)}c(qu,"getConnectorDirPath");function Uu(s){return s.match(`${Et}/[^/]+/${Ne}/src/.*`)!==null}c(Uu,"isConnectorSourceFile");async function Wu(s){const e=s.match(`${Et}/([^/]+)/${Ne}/src/(.*)`);if(!e)return;const t=e[1],n=e[2],r=await Cr(t);if(!r){b.warning(`[connectors] Connector ${t} not found. Ignoring file change`);return}const i=r.id,o=P.readFileSync(s,"utf-8");await U.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(Wu,"putConnectorFile");async function Ju(s){const e=s.match(`${Et}/([^/]+)/${Ne}/src/(.*)`);if(!e)return;const t=e[1],n=e[2],r=await Cr(t);if(!r){b.warning(`[connectors] Connector ${t} not found. Ignoring file change`);return}const i=r.id;await U.withClient(o=>o.delete(`connectors/${i}/files/${n}`)),b.info(`[connectors] Deleted file ${n} for connector ${r.name}`)}c(Ju,"deleteConnectorFile");async function Hu(s,e){try{const t=await U.withClient(o=>o.get(`connectors/${s}`));if(!t){b.warning(`[connectors] Connector ${s} not found`);return}const n=await U.withClient(o=>o.get(`connectors/${s}/files/${e}`)),r=xe(t),i=B.join(qe(),r,Ne,"src",e);P.mkdirSync(B.dirname(i),{recursive:!0}),n!=null?(P.writeFileSync(i,n),b.info(`[connectors] Pulled file ${e} for connector ${t.name}`)):P.existsSync(i)&&(P.unlinkSync(i),b.info(`[connectors] Deleted file ${e} for connector ${t.name}`))}catch(t){b.error(`[connectors] Failed to pull connector file ${e} for connector ${s}: ${t}`)}}c(Hu,"pullConnectorFile");async function Vu(s,e){const t=await U.withClient(i=>i.get(`connectors/${s}`));if(!t){b.warning(`[connectors] Connector ${s} not found`);return}const n=xe(t),r=B.join(qe(),n,Ne,"src",e);P.existsSync(r)&&(P.unlinkSync(r),b.info(`[connectors] Deleted file ${e} for connector ${n}`))}c(Vu,"deleteLocalConnectorFile");async function Gu(s,e,t){if(t&&e!==t)try{const n=await U.withClient(l=>l.get(`connectors/${s}`));if(!n){b.warning(`[connectors] Connector ${s} not found`);return}const r=xe(n),i=B.join(qe(),r,Ne,"src"),o=B.join(i,e),a=B.join(i,t);P.existsSync(o)&&(P.mkdirSync(B.dirname(a),{recursive:!0}),P.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(Gu,"renameLocalConnectorDirectory");async function zu(s,e){try{const t=await U.withClient(i=>i.get(`connectors/${s}`));if(!t){b.warning(`[connectors] Connector ${s} not found`);return}const n=xe(t),r=B.join(qe(),n,Ne,"src",e);if(P.existsSync(r)){const i=B.resolve(qe());if(!B.resolve(r).startsWith(i))return;P.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(zu,"deleteLocalConnectorDirectory");const Xo=[K.DataSource,K.FieldMapping,K.Action,K.Flow];class mn{static{c(this,"ElementSyncService")}localWatcher=void 0;remoteWatcher=void 0;notifier;changes=[];localCache;remoteCache;localRepo;remoteRepo;pulledConnectors=new Set;pulledConnectorVersions={};constructor(){this.notifier=Ae,this.localCache=new Go,this.remoteCache=new Go,this.localRepo=new Sl(this.localCache),this.remoteRepo=new vl(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(K.Integration).map(n=>n.data);for(const n of t){const r=n.connectorId,i=n.connectorVersion;r&&await zo({connectorId:r,connectorVersion:i,allConnectors:e,pulledConnectors:this.pulledConnectors,pulledConnectorVersions:this.pulledConnectorVersions})}}async pushConnectors(){const e=await Lu();this.remoteRepo.setConnectorsMapping(e)}getHandler(e){return e===ae.INCOMING?this.localRepo:this.remoteRepo}getCache(e){return e===ae.INCOMING?this.localCache:this.remoteCache}async startWatching(){this.localWatcher=new xu({cwd:process.cwd(),lockTimeoutMs:1e3}),this.localWatcher.on(he.Updated,e=>this.handleLocalEvent(e,he.Updated)),this.localWatcher.on(he.Deleted,e=>this.handleLocalEvent(e,he.Deleted)),await this.localWatcher.start(),b.success("[local] Tracking changes.."),this.remoteWatcher=new Ru,this.remoteWatcher.on(br.Updated,({elementId:e,elementType:t})=>this.handleRemoteElementEvent(e,t)),this.remoteWatcher.on(br.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===K.Integration){const o=n.data.connectorId,a=n.data.connectorVersion,l=await kr({connectorId:o});if(!l?.key)return;const u=qu(l);await this.localWatcher?.executeWithPathLock(u,async()=>zo({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 Ms.ConnectorFileDeleted:await Vu(e,t);break;case Ms.ConnectorDirectoryRenamed:await Gu(e,t,r);break;case Ms.ConnectorDirectoryDeleted:await zu(e,t);break;default:await Hu(e,t);break}}catch(i){b.error(`[sync] Error handling remote connector file event: ${i}`)}}async handleLocalEvent(e,t){try{if(Uu(e.filePath))switch(t){case he.Updated:await Wu(e.filePath);break;case he.Deleted:await Ju(e.filePath);break}else{let n=Q.fromPathAndData(e.filePath,e.data);if(!n){const r=Q.idFromPath(e.filePath);if(!r||(n=this.remoteCache.get(r),!n))return}switch(b.info(`[${this.getDirectionLabel(ae.OUTGOING)}] ${ol.toSentenceCase(t)}: ${n.id}`),t){case he.Updated:await this.updateElement(n,ae.OUTGOING);break;case he.Deleted:await this.deleteElement(n,ae.OUTGOING);break}}}catch(n){b.error(`[sync] Error handling local event: ${n}`)}}detectIncomingChanges(){this.clearChanges();const e=mn.getChanges(ae.INCOMING,this.remoteCache,this.localCache);return this.updateChanges(e),e}detectOutgoingChanges(){this.clearChanges();const e=mn.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===K.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!==K.Integration)),b.info("[resolver] Resolving universal elements");const t=this.changes.filter(r=>!r.element.hasParent());for(const r of Xo){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 Xo){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 Oe.DELETE:return this.deleteElement(e.element,e.direction);case Oe.CREATE:return this.updateElement(e.element,e.direction);case Oe.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),h=n.get(l),f=mn.detectChangeForElement(u,h,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:Oe.CREATE,element:e,direction:n,isConflict:!1}:!e&&t?{type:Oe.DELETE,element:t,direction:n,isConflict:!0}:e&&t&&!e.isEqual(t)?{type:Oe.UPDATE,element:e,direction:n,isConflict:!0}:null}}const Ue=q.join(Lc.tmpdir(),"membrane-mcp-status"),Qo=3e4;class Yu{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=ts(void 0,e),n=Zo(e);t&&Ae.setMcpStatus(t),await Ae.setMcpServers(n)}catch{b.error("Failed to check MCP status")}}}function ts(s,e){try{const t=e||process.cwd();if(!s){const r=Zo(t);return r.length===0?null:r[0]}const n=Er(s,t);if(L.existsSync(n)){const r=L.statSync(n),i=new Date;if(i.getTime()-r.mtime.getTime()>Qo)return Vt(s,t),null;const a=L.readFileSync(n,"utf8"),l=JSON.parse(a);if(l.isRunning){const u=new Date(l.lastActivity).getTime();if(i.getTime()-u>Qo)return Vt(s,t),null}return l}}catch{s&&e&&Vt(s,e)}return null}c(ts,"getMcpStatus");function Zo(s){try{const e=s||process.cwd(),t=Tr(e);if(!L.existsSync(Ue))return[];const n=L.readdirSync(Ue),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=ts(a,e);l&&r.push(l)}}return r.sort((i,o)=>new Date(o.startTime).getTime()-new Date(i.startTime).getTime())}catch{return[]}}c(Zo,"getAllMcpStatusFiles");function _r(s){try{const t={...ts(s.processId,s.cwd)||{isRunning:!1,startTime:new Date().toISOString(),lastActivity:new Date().toISOString(),toolsCount:0,totalRequests:0,processId:s.processId,cwd:s.cwd,agentName:process.env.AGENT_NAME||"Unnamed Agent"},...s};L.existsSync(Ue)||L.mkdirSync(Ue,{recursive:!0});const n=Er(s.processId,s.cwd);L.writeFileSync(n,JSON.stringify(t,null,2))}catch{}}c(_r,"updateMcpStatus");function Vt(s,e){try{const t=e||process.cwd();if(s){const n=Er(s,t);L.existsSync(n)&&L.unlinkSync(n)}else{const n=Tr(t);if(L.existsSync(Ue)){const r=L.readdirSync(Ue);for(const i of r)i.match(new RegExp(`^mcp-${n}-\\d+\\.json$`))&&L.unlinkSync(q.join(Ue,i))}}}catch{}}c(Vt,"clearMcpStatus");function Xu(s,e){const t=ts(s,e);t&&_r({processId:s,cwd:e,totalRequests:t.totalRequests+1,lastRequestTime:new Date().toISOString(),lastActivity:new Date().toISOString()})}c(Xu,"trackToolExecution");function Tr(s){return $c("md5").update(s).digest("hex").slice(0,8)}c(Tr,"getCwdHash");function Er(s,e){const t=Tr(e);return q.join(Ue,`mcp-${t}-${s}.json`)}c(Er,"getStatusFilePath");const Gt={Agent:"agent",Cli:"cli"},x={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 ea{static{c(this,"MembraneCLIService")}constructor(e,t,n=()=>process.exit(0)){this.mode=e,this.cwd=t,this.onShutdown=n,this.notifier=Ae,this.mcpStatusService=new Yu,this.syncService=new mn,this.setupProcessCleanup()}initialized=!1;notifier;mcpStatusService;syncService;isShuttingDown=!1;currentConfig=null;get config(){return this.currentConfig}async pullWorkspace(e={}){try{if(b.setVerboseMode(!!e.verbose),await this.notifier.setState(x.PULLING),await this.syncService.fetchElements(),this.syncService.detectIncomingChanges(),this.syncService.needsForcedSync()&&!e.force)return this.notifier.setState(x.CONFLICTS);await this.syncService.pullConnectors(e.allConnectors),await this.syncWorkspaces(e)}catch(t){b.error(`Failed to pull workspace: ${t}`),await this.notifier.setState(x.ERROR),b.saveLogsToFile("error")}finally{return e.saveLogs&&b.saveLogsToFile(),e?.onComplete?.()}}async pushWorkspace(e={}){try{if(b.setVerboseMode(!!e.verbose),await this.notifier.setState(x.PUSHING),await this.syncService.fetchElements(),this.syncService.detectOutgoingChanges(),this.syncService.needsForcedSync()&&!e.force)return await this.notifier.setState(x.CONFLICTS);await this.syncService.pushConnectors(),await this.syncWorkspaces(e)}catch(t){b.error(`Failed to push workspace: ${t}`),await this.notifier.setState(x.ERROR),b.saveLogsToFile("error")}finally{return e.saveLogs&&b.saveLogsToFile(),e?.onComplete?.()}}async syncWorkspaces(e={}){try{e.verbose!==void 0&&b.setVerboseMode(!!e.verbose),await this.notifier.setState(x.RESOLVING),this.syncService.needsSync()&&await this.syncService.resolveChanges();const t=await this.syncService.getStats();this.notifier.setStats(t),await this.notifier.setState(x.SYNCED),e.watch&&(await this.notifier.setState(x.WATCHING),await this.syncService.startWatching())}catch(t){b.error(`Failed to sync local and remote workspaces: ${t}`),await this.notifier.setState(x.ERROR),b.saveLogsToFile("error")}}async init({force:e=!1}={}){if(!(this.initialized&&!e)){await this.notifier.setState(x.NOT_INITIALIZED);try{await this.loadConfig(),Dt.isCacheDefined()?(await this.initServices(),this.initialized=!0,await this.notifier.setState(x.INITIALIZED)):(this.initialized=!1,await this.notifier.setState(x.SETTING_UP))}catch(t){b.error(`Failed to initialize services: ${t}`),await this.notifier.setState(x.ERROR),b.saveLogsToFile("error"),this.onShutdown()}}}async loadConfig(){this.currentConfig=Dt.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=Dt.updateConfig(t);this.currentConfig=r,await this.init({force:!0})}async shutdown(){!this.initialized||this.isShuttingDown||(this.isShuttingDown=!0,this.mode===Gt.Agent&&(await this.notifier.cleanup(),await this.mcpStatusService.stop()),this.initialized=!1,this.onShutdown())}async initServices(){this.mode===Gt.Agent&&(await this.notifier.connectToRemote(),await this.mcpStatusService.start()),this.syncService.clear()}async stopServices(){this.mode===Gt.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=ii(null);function Qu({children:s,membraneCLIService:e}){const{data:t}=ai("/account"),[n,r]=J(x.NOT_INITIALIZED),[i,o]=J([]),[a,l]=J({}),[u,h]=J([]),[f,p]=J(null),y=t?.workspaces?.find(d=>d.workspaceKey===f?.workspaceKey)||null;return Ve(()=>{const d=c(({state:O})=>r(O),"handleStateChanged"),w=c(({stats:O})=>l(O),"handleStatsChanged"),k=c(({log:O})=>h($=>[...$,O]),"handleLogAdded"),_=c(({conflicts:O})=>o(O),"handleConflictsUpdated"),A=c(({config:O})=>p(O),"handleConfigChanged");return e.notifier.on(Y.StateChanged,d),e.notifier.on(Y.StatsChanged,w),e.notifier.on(Y.LogAdded,k),e.notifier.on(Y.ConflictsChanged,_),e.notifier.on(Y.ConfigChanged,A),e.init(),()=>{e.notifier.off(Y.StateChanged,d),e.notifier.off(Y.StatsChanged,w),e.notifier.off(Y.LogAdded,k),e.notifier.off(Y.ConflictsChanged,_),e.notifier.off(Y.ConfigChanged,A)}},[]),g(ta.Provider,{value:{state:n,stats:a,logs:u,currentWorkspace:y,conflicts:i,config:f,updateConfig:c(d=>e.updateConfig(d),"updateConfig"),resolveConflicts:c(d=>e.syncWorkspaces(d),"resolveConflicts"),pull:c(d=>e.pullWorkspace(d),"pull"),push:c(d=>e.pushWorkspace(d),"push"),exit:c(()=>e.shutdown(),"exit")},children:s})}c(Qu,"MembraneCLIServiceProvider");function Se(){const s=oi(ta);if(!s)throw new Error("useMembraneCLIService must be used within MembraneCLIServiceProvider");return s}c(Se,"useMembraneCLIService");const na=ii(process.cwd());function Zu({cwd:s,children:e}){return g(na.Provider,{value:s,children:e})}c(Zu,"CwdProvider");function eh(){return oi(na)}c(eh,"useCwd");function ns({cwd:s,children:e,membraneCLIService:t}){const n=s||process.cwd();return g(Zu,{cwd:n,children:g(mc,{value:{fetcher:ml()},children:g(Qu,{membraneCLIService:t,children:e})})})}c(ns,"Layout");const Or=[{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=q.join(process.cwd(),".mcp.json"),e={mcpServers:{membrane:{command:"membrane",args:["mcp"],env:{AGENT_NAME:"Claude Code"}}}};let t={};if(L.existsSync(s))try{t=JSON.parse(L.readFileSync(s,"utf8"))}catch{t={}}const n={...t,mcpServers:{...t.mcpServers,...e.mcpServers}};return L.writeFileSync(s,JSON.stringify(n,null,2)),`MCP server configuration added to ${s}`},"addConfig")},{id:"cursor",name:"Cursor",description:"Cursor AI editor",actionDescription:"Adding membrane MCP to .cursor/mcp.json in the current directory",addConfig:c(()=>{const s=q.join(process.cwd(),".cursor"),e=q.join(s,"mcp.json");L.existsSync(s)||L.mkdirSync(s);const t={mcpServers:{membrane:{command:"membrane",args:["mcp"],env:{AGENT_NAME:"Cursor"}}}};let n={};if(L.existsSync(e))try{n=JSON.parse(L.readFileSync(e,"utf8"))}catch{n={}}const r={...n,mcpServers:{...n.mcpServers,...t.mcpServers}};return L.writeFileSync(e,JSON.stringify(r,null,2)),`MCP server configuration added to ${e}`},"addConfig")}];function th({onExit:s,onComplete:e}){const[t,n]=J(0),[r,i]=J(!1),[o,a]=J(null),[l,u]=J(""),[h,f]=J("");st((y,d)=>{if(l||h){(d.escape||y==="q"||d.return)&&e();return}if(r)d.return||y===" "?p(o):d.escape&&(i(!1),a(null));else if(d.escape)s();else if(d.upArrow||y==="k")n(Math.max(0,t-1));else if(d.downArrow||y==="j")n(Math.min(Or.length-1,t+1));else if(d.return||y===" "){const w=Or[t];a(w),i(!0)}});const p=c(y=>{try{const d=y.addConfig();u(d)}catch(d){f(`Failed to write configuration: ${d.message||d}`)}},"addMcpConfiguration"),m=Math.min(80,process.stdout.columns||80);return l?E(v,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:m,children:[g(v,{marginTop:-1,marginBottom:1,children:E(C,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",g(C,{color:"green",children:"Success"})]})}),E(v,{flexDirection:"column",paddingLeft:2,children:[g(C,{color:"green",children:l}),g(v,{marginTop:1,children:g(C,{color:"grey",children:"The agent will now be able to use Membrane's integration capabilities."})})]}),g(v,{marginTop:1,paddingLeft:2,children:g(C,{color:"white",children:"[esc/q/enter: exit]"})})]}):h?E(v,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:m,children:[g(v,{marginTop:-1,marginBottom:1,children:E(C,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",g(C,{color:"red",children:"Error"})]})}),g(v,{flexDirection:"column",paddingLeft:2,children:g(C,{color:"red",children:h})}),g(v,{marginTop:1,children:g(C,{color:"grey",children:"[esc/q/enter: exit]"})})]}):r&&o?E(v,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:m,children:[g(v,{marginTop:-1,marginBottom:1,children:E(C,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",g(C,{color:"cyan",children:"Confirmation"})]})}),E(v,{flexDirection:"column",paddingLeft:2,children:[E(C,{children:["Connect ",g(C,{bold:!0,children:o.name})," to Membrane via MCP?"]}),g(v,{marginTop:1,children:g(C,{color:"grey",children:"This will add an MCP server configuration that allows the agent to use Membrane's integration capabilities."})}),g(v,{marginTop:1,children:g(C,{color:"yellow",bold:!0,children:o.actionDescription})}),g(v,{marginTop:2,marginBottom:1,children:E(C,{children:[g(C,{color:"white",bold:!0,children:"[Enter] Confirm"})," ",g(C,{color:"gray",children:"[Esc] Cancel"})]})})]})]}):E(v,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:m,children:[g(v,{marginTop:-1,marginBottom:1,children:E(C,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",g(C,{color:"cyan",children:"Select Agent"})]})}),E(v,{flexDirection:"column",paddingLeft:2,children:[g(C,{color:"grey",children:"Choose an agent to connect to Membrane via MCP:"}),g(v,{marginTop:1,children:g(C,{color:"grey",children:"This will add an MCP server configuration that allows the agent to use Membrane's integration capabilities."})}),g(v,{marginTop:1,flexDirection:"column",children:Or.map((y,d)=>E(v,{children:[E(C,{color:t===d?"cyan":"white",children:[t===d?"\u25B6 ":" ",y.name]}),E(C,{color:"grey",children:[" \u2014 ",y.description]})]},y.id))})]}),g(v,{marginTop:1,children:g(C,{color:"grey",children:"[\u2191\u2193: select] [enter: choose] [esc: exit]"})})]})}c(th,"AddMcpServerScreen");function nh(){const[s,e]=J(null),[t,n]=J([]),[r,i]=J(null);return Ve(()=>{const o=c(({status:l})=>{e(l),i(null)},"handleMcpStatusChanged"),a=c(({servers:l})=>{n(l),i(null)},"handleMcpServersChanged");return Ae.on(Y.McpStatusChanged,o),Ae.on(Y.McpServersChanged,a),()=>{Ae.off(Y.McpStatusChanged,o),Ae.off(Y.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(nh,"useMcpStatus");function sh(){const{error:s,serverCount:e,allMcpServers:t}=nh(),n=Math.min(100,process.stdout.columns||100);return E(v,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:n,children:[g(v,{marginTop:-1,marginBottom:0,flexDirection:"column",children:E(C,{bold:!0,children:["\u{1F916} Connected AI Agents:"," ",s?g(C,{color:"red",children:"error reading status"}):e===0?g(C,{color:"yellow",children:"none"}):g(C,{color:"green",children:e})]})}),!s&&e===0&&g(v,{marginTop:1,children:E(C,{color:"grey",children:["Connect your AI agents to Membrane.",g(dc,{}),"It will give them tools and context to build integrations."]})}),t.length>0&&g(v,{flexDirection:"column",paddingLeft:2,marginTop:1,children:t.map((r,i)=>g(v,{children:E(C,{color:"grey",children:["#",i+1," ",r.agentName,": ",r.totalRequests," calls"]})},r.processId))}),g(v,{marginTop:1,children:g(C,{color:"grey",children:"[a: connect an agent]"})})]})}c(sh,"Agent");const ss=c(s=>{switch(s){case"error":return"red";case"success":return"green";case"warning":return"yellow";default:return}},"getLogColor");function sa(s,e){return e<3?s.slice(0,Math.max(0,e)):s.length<=e?s:`${s.slice(0,e-3)}...`}c(sa,"truncateText");function Ar({children:s}){const{state:e,logs:t}=Se();return!e||e===x.NOT_INITIALIZED?E(v,{gap:1,flexDirection:"row",children:[g(jc,{type:"dots"}),g(C,{children:"Initializing..."})]}):e===x.SETTING_UP?g(v,{gap:1,flexDirection:"row",children:g(C,{children:"No workspace selected. Please run `membrane init` to select a workspace."})}):e===x.ERROR?g(v,{flexDirection:"column",children:t.slice().map((n,r)=>g(C,{color:ss(n.type),children:n.message},n.timestamp+r))}):s}c(Ar,"EnsureInitialized");function ra({onExit:s,showEscOption:e=!0}){const[t,n]=J(""),{data:r,error:i,isLoading:o}=ai("/account"),{updateConfig:a}=Se(),l=r?.workspaces,u=o;if(st((d,w)=>{w.escape&&s?.()}),u)return E(v,{children:[g(wn,{}),g(C,{children:" Fetching workspaces..."})]});if(i)return E(v,{flexDirection:"column",children:[E(C,{color:"red",children:["Error: ",i.message]}),g(v,{marginTop:1,children:g(C,{color:"grey",children:"Press ESC to go back"})})]});const h=l?.filter(d=>d.name.toLowerCase().includes(t.toLowerCase()))??[],f=h.map(d=>({label:d.name,value:d.id})),p=f.length,m=l?.length??0;async function y(d){const w=h.find(A=>A.id===d);if(!w)return;const{key:k,secret:_}=w;!k||!_||(await a({workspaceKey:k,workspaceSecret:_}),s?.())}return c(y,"handleSelect"),E(v,{flexDirection:"column",borderStyle:"round",borderTop:!0,width:70,paddingX:1,children:[g(v,{marginTop:-1,children:g(C,{bold:!0,children:"\u{1F4C1} Select your workspace"})}),E(v,{marginTop:1,children:[g(C,{children:"Search: "}),g(Fc,{placeholder:"Enter a search query...",onChange:n})]}),m>5&&E(C,{children:["Showing ",p," of ",m," workspaces."]}),g(v,{marginTop:1,children:g(Kc,{options:f,onChange:c(d=>{d&&y(d)},"onChange")})}),e&&g(v,{marginTop:1,children:g(C,{color:"grey",children:"Press ESC to go back"})})]})}c(ra,"SelectWorkspace");function rh({currentPat:s,onSubmit:e}){const[t,n]=J(""),[r,i]=J(!1),[o,a]=J(null);return E(v,{flexDirection:"column",borderStyle:"round",borderTop:!0,width:70,paddingX:1,children:[g(v,{marginTop:-1,marginBottom:1,children:g(C,{bold:!0,children:"\u{1F511} Enter your Personal Access Token"})}),g(C,{children:"Please provide your Personal Access Token. You can find it here:"}),g(v,{marginTop:1,marginBottom:1,children:g(C,{color:"yellow",children:"https://console.integration.app/w/0/manage-account/api-token"})}),s&&g(C,{dimColor:!0,children:"Press Enter to keep your current token or type a new one."}),g(Bc,{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&&g(v,{marginTop:1,children:E(C,{children:[g(wn,{type:"dots"})," Validating token..."]})}),o&&g(C,{color:"red",children:o})]})}c(rh,"PersonalAccessTokenInput");var zt=(s=>(s[s.Authenticate=0]="Authenticate",s[s.ConnectWorkspace=1]="ConnectWorkspace",s))(zt||{});const ih={0:"Authenticate in Membrane",1:"Connect a Membrane Workspace"},Ir=[zt.Authenticate,zt.ConnectWorkspace];function ia({onComplete:s}){const{config:e}=Se(),[t,n]=J(!1),[r,i]=J(0),o=!!(e?.workspaceKey&&e?.workspaceSecret),a=ji(),l=Ir[r],u=r+1,h=Ir.length,f=Ir.map((y,d)=>{let w="pending";return d<r?w="done":d===r&&(w="current"),{id:y,label:ih[y],status:w}});async function p(y){const d=a&&y===""?a:y,w=new Fi;try{await w.request("/account",{headers:{Authorization:`Bearer ${d}`}}),pl(d),i(k=>k+1)}catch(k){console.error(k)}}c(p,"handlePatSubmit");function m(){n(!0),s&&s()}return c(m,"handleWorkspaceSelected"),st((y,d)=>{o&&d.escape&&s&&s()}),t?g(v,{children:g(C,{children:"\u2705 Setup complete. You are ready to go!"})}):E(v,{flexDirection:"column",alignSelf:"flex-start",gap:1,children:[E(v,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:70,children:[g(v,{marginTop:-1,marginBottom:1,children:E(C,{bold:!0,children:["\u{1F6E0}\uFE0F Setup \u2014"," ",E(C,{color:"cyan",children:["Step ",u," of ",h]}),o&&g(C,{color:"grey",children:" [esc: go back]"})]})}),g(v,{flexDirection:"column",paddingLeft:2,children:f.map(y=>g(oh,{status:y.status,label:y.label},y.id))})]}),l===zt.Authenticate&&g(rh,{currentPat:a,onSubmit:p}),l===zt.ConnectWorkspace&&g(ra,{onExit:m,showEscOption:!1})]})}c(ia,"Setup");function oh({status:s,label:e}){return E(v,{children:[E(v,{width:2,children:[s==="current"&&g(wn,{type:"dots"}),s==="done"&&g(C,{children:"\u2705"})]}),g(C,{dimColor:s!=="current",children:e})]})}c(oh,"StepDisplay");function $r(){const{stats:s}=Se(),e=Object.entries(s).filter(([t,n])=>n>0);return e.length===0?null:E(v,{flexDirection:"column",children:[g(v,{children:g(v,{width:12,children:g(C,{color:"grey",children:"Elements:"})})}),g(v,{flexDirection:"column",marginLeft:1,children:e.map(([t,n])=>E(v,{children:[g(v,{width:20,children:E(C,{children:[t,":"]})}),g(C,{color:"green",children:n})]},t))})]})}c($r,"ElementStats");const Nr=5,ah=6;function ch(){const{logs:s}=Se(),[e,t]=J(0),n=Math.min(100,process.stdout.columns||100),r=Nr,i=Math.max(0,s.length-r-e),o=s.length-e,a=s.slice(i,o),l=n-ah,u=e<s.length-r,h=e>0;return st((f,p)=>{if(s.length!==0)if(p.upArrow){const m=Math.max(0,s.length-r);t(y=>Math.min(m,y+1))}else p.downArrow?t(m=>Math.max(0,m-1)):(f==="G"||f==="g")&&t(0)}),E(v,{flexDirection:"column",paddingTop:1,children:[E(C,{color:"grey",children:["Recent Activity (",i+1,"-",o," of ",s.length,"):",s.length>Nr&&g(C,{color:"grey",children:" [arrows: scroll] [g: end]"})]}),a.map((f,p)=>g(v,{marginLeft:1,children:g(C,{color:ss(f.type),children:sa(f.message,l)})},f.timestamp+p)),s.length>Nr&&E(v,{marginLeft:1,flexDirection:"row",children:[u&&g(C,{color:"grey",children:"\u2191 "}),h&&g(C,{color:"grey",children:"\u2193 "})]})]})}c(ch,"Logs");const rs=[{value:"sync",label:"Continue (overwrite/delete)",key:""},{value:"exit",label:"Cancel",key:""}];function lh(){const{state:s,resolveConflicts:e,exit:t}=Se(),[n,r]=J(0),[i,o]=J(!1),[a,l]=J(!1);return st((u,h)=>{if(!i){if(h.ctrl&&u.toLowerCase()==="r"){l(!a);return}h.upArrow?r(f=>f>0?f-1:rs.length-1):h.downArrow?r(f=>f<rs.length-1?f+1:0):u.toLowerCase()==="y"?r(0):u.toLowerCase()==="n"?r(1):(h.return||u===" ")&&(o(!0),rs[n].value==="sync"?e({watch:!0}):t())}}),Ve(()=>{s!==x.CONFLICTS&&i&&o(!1)},[s,i]),E(v,{flexDirection:"column",paddingTop:1,children:[g(v,{children:g(v,{flexDirection:"row",gap:2,children:g(C,{bold:!0,color:"white",children:"Conflicts with remote"})})}),g(v,{children:g(C,{color:"grey",children:"The remote workspace has changes that aren't in your local workspace:"})}),g(v,{marginTop:1,marginLeft:2,children:g(xr,{isExpanded:a})}),E(v,{marginTop:2,flexDirection:"row",gap:1,children:[g(C,{color:"white",bold:!0,children:"What would you like to do?"}),g(C,{color:"grey",children:"[up/down, enter]"})]}),g(v,{children:i?E(v,{flexDirection:"row",gap:1,children:[g(wn,{type:"dots"}),g(C,{color:"blue",bold:!0,children:"Syncing with remote..."})]}):g(v,{flexDirection:"column",children:rs.map((u,h)=>g(v,{flexDirection:"column",children:E(v,{flexDirection:"row",gap:1,children:[g(C,{color:n===h?"cyan":"grey",children:n===h?"\u25B6":" "}),g(C,{color:n===h?"cyan":"grey",bold:n===h,children:u.label})]})},u.value))})})]})}c(lh,"ResolveChangesUI");const uh={[Oe.UPDATE]:{incoming:{label:"Elements updated in remote",description:"(to be overwritten from remote)"},outgoing:{label:"Elements updated locally",description:"(to be pushed to remote)"}},[Oe.DELETE]:{incoming:{label:"Elements not existing in remote",description:"(to be deleted locally)"},outgoing:{label:"Elements deleted locally",description:"(to be deleted from remote)"}},[Oe.CREATE]:{incoming:{label:"Elements created in remote",description:"(to be created locally)"},outgoing:{label:"Elements created locally",description:"(to be created in remote)"}}};function xr({isExpanded:s}){const{conflicts:e}=Se(),t=5,n=gc(()=>{const r={};return e.forEach(i=>{const o=`${i.type}-${i.direction}`;r[o]||(r[o]=[]),r[o].push(i)}),r},[e]);return g(v,{flexDirection:"column",children:Object.entries(n).map(([r,i])=>{if(i.length===0)return null;const[o,a]=r.split("-"),l=uh[o][a];return E(v,{flexDirection:"column",children:[E(v,{flexDirection:"row",gap:1,children:[E(C,{color:"yellow",children:[l.label," (",i.length,")"]}),g(C,{color:"white",children:l.description})]}),(s?i:i.slice(0,t)).map(u=>g(v,{marginLeft:2,children:E(C,{color:"grey",children:["\u2022 ",u.element.id," (",u.element.relativePath,")"]})},u.element.id)),!s&&i.length>t&&g(v,{marginLeft:2,children:E(C,{color:"cyan",children:["... and ",i.length-t," more (press Ctrl+R to show all)"]})}),s&&i.length>t&&g(v,{marginLeft:2,children:g(C,{color:"cyan",children:"(press Ctrl+R to collapse)"})})]},r)})})}c(xr,"Conflicts");function hh(){const{config:s,state:e,logs:t,currentWorkspace:n,pull:r}=Se(),i=n?.name,o=i?sa(i,30):s?.workspaceKey,a=Math.min(100,process.stdout.columns||100);return Ve(()=>{r({watch:!0})},[]),E(v,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:a,children:[g(v,{marginTop:-1,marginBottom:1,children:E(v,{flexDirection:"row",gap:1,children:[g(C,{bold:!0,children:"\u{1F504} Workspace"}),E(C,{color:dh(e),children:[" [",fh(e),"] "]})]})}),E(v,{children:[g(v,{width:12,children:g(C,{color:"grey",children:"Local:"})}),g(C,{color:"grey",children:process.cwd()})]}),E(v,{children:[g(v,{width:12,children:g(C,{color:"grey",children:"Remote:"})}),s?.workspaceKey?E(C,{color:"grey",children:[o," [o: open in console] [w: change]"]}):E(C,{children:[g(C,{color:"yellow",children:"not selected"})," [w: select]"]})]}),e===x.CONFLICTS?g(lh,{}):E(Ns,{children:[g(v,{paddingTop:1,children:g($r,{})}),t.length>0&&g(ch,{})]})]})}c(hh,"Workspace");function fh(s){switch(s){case x.PULLING:return"pulling";case x.PUSHING:return"pushing";case x.CONFLICTS:return"conflicts";case x.SYNCED:return"synced";case x.ERROR:return"error";case x.WATCHING:return"tracking changes";case x.RESOLVING:return"resolving";case x.NOT_SYNCED:return"not synced";case x.INITIALIZED:return"initialized";case x.SETTING_UP:return"setup required";default:return"unknown"}}c(fh,"getStatusDisplay");function dh(s){switch(s){case x.PULLING:return"yellow";case x.PUSHING:return"yellow";case x.CONFLICTS:return"red";case x.SYNCED:return"green";case x.ERROR:return"red";case x.WATCHING:return"green";case x.RESOLVING:return"yellow";case x.NOT_SYNCED:return"grey";case x.SETTING_UP:return"yellow";default:return"grey"}}c(dh,"getStatusColor");const ph="https://console.integration.app/w";function mh(){const s=eh(),e=yc(!0),{exit:t,state:n}=Se(),[r,i]=J(null),o=r??(n===x.SETTING_UP?"setup":"main");st(l=>{o==="main"&&(l==="w"&&i("workspace-selection"),l==="a"&&i("add-mcp-server"),l==="o"&&n===x.INITIALIZED&&a(),l==="s"&&i("setup"))});async function a(){try{const l=await Ki(s),u=`${ph}/${l}`,h=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";Dc(`${h} "${u}"`)}catch(l){console.error("Failed to open workspace:",l),t()}}return c(a,"handleOpenWorkspace"),Ve(()=>(e.current=!0,()=>{e.current=!1}),[]),o==="workspace-selection"?g(ra,{onExit:c(()=>i(null),"onExit")}):o==="add-mcp-server"?g(th,{onExit:c(()=>i(null),"onExit"),onComplete:c(()=>i(null),"onComplete")}):o==="setup"?g(ia,{onComplete:c(()=>i(null),"onComplete")},Date.now()):g(Ar,{children:E(v,{flexDirection:"column",children:[g(v,{flexGrow:1,children:g(sh,{})}),g(hh,{}),g(v,{paddingLeft:2,children:g(C,{color:"grey",children:"[s: (re-)setup]"})})]})})}c(mh,"Main");const Mr=pc(process.argv.slice(2)),oa=Mr.cwd?hc(Mr.cwd):process.cwd(),gh=new ea(Gt.Agent,oa);Mr.verbose&&b.setVerboseMode(!0);const yh=c(()=>g(ns,{cwd:oa,membraneCLIService:gh,children:g(mh,{})}),"App");function wh(){gn(g(yh,{}))}c(wh,"runAgent");function bh(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(`
142
- `)).action(t=>{t.key&&t.secret?Dt.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)):gn(rt.createElement(ns,{membraneCLIService:e,children:rt.createElement(ia,{onComplete:c(()=>process.exit(0),"onComplete")})}))})}c(bh,"setupInitCommand");async function aa(s,e,t){const n={iss:s,exp:Math.floor(Date.now()/1e3)+600,isAdmin:!0};return t&&(n.id=t),Ds.sign(n,e)}c(aa,"generateAdminAccessToken");async function Sh(s,e){return(await js.get(`${s}/docs-json`,{headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}})).data}c(Sh,"fetchOpenApiSchema");function ca(s,e=!0){if(!s)return e?ne.string():ne.string().optional();let t;switch(s.type){case"integer":t=ne.coerce.number().int();break;case"number":t=ne.coerce.number();break;case"boolean":t=ne.coerce.boolean();break;case"string":default:t=ne.string();break}return s.format==="uuid"?t=ne.string().uuid():s.format==="email"?t=ne.string().email():s.format==="date"?t=ne.string().regex(/^\d{4}-\d{2}-\d{2}$/):s.format==="date-time"&&(t=ne.string().datetime()),s.enum&&(t=ne.enum(s.enum)),(s.type==="integer"||s.type==="number")&&(s.minimum!==void 0&&(t=t.min(s.minimum)),s.maximum!==void 0&&(t=t.max(s.maximum))),s.type==="string"&&(s.minLength!==void 0&&(t=t.min(s.minLength)),s.maxLength!==void 0&&(t=t.max(s.maxLength))),e?t:t.optional()}c(ca,"convertOpenApiSchemaToZod");function la(s){const e=s.match(/\{([^}]+)\}/g);return e?e.map(t=>t.slice(1,-1)):[]}c(la,"extractPathParameters");function vh(s,e,t,n,r,i,o){const a=s.operationId||`${t}_${e.replace(/[^a-zA-Z0-9]/g,"_")}`,l=s.description||s.summary||`${t.toUpperCase()} ${e}`,u={},h={},f={};if(s.parameters){for(const m of s.parameters)if(m.in==="path")h[m.name]=ca(m.schema,!0).describe(m.description||`Path parameter: ${m.name}`);else if(m.in==="query"){const y=m.required===!0;f[m.name]=ca(m.schema,y).describe(m.description||`Query parameter: ${m.name}`)}}Object.keys(h).length>0&&(u.params=ne.object(h).describe("Path parameters")),Object.keys(f).length>0&&(u.query=ne.object(f).describe("Query parameters")),s.requestBody&&s.requestBody.content&&s.requestBody.content["application/json"]&&(u.body=ne.any().describe("Request body"));const p=Object.keys(u).length>0?ne.object(u):ne.object({});return{name:a,description:l,parameters:p,async execute(m){try{const y=la(e);if(y.length>0){if(!m.params)throw new Error(`Missing required path parameters: ${y.join(", ")}`);const $=y.filter(N=>!(N in m.params));if($.length>0)throw new Error(`Missing required path parameters: ${$.join(", ")}`)}let d=`${n}${e}`;if(m.params)for(const[$,N]of Object.entries(m.params)){const F=`{${$}}`;d.includes(F)&&(d=d.replace(F,String(N)))}const w=la(d);if(w.length>0)throw new Error(`Unresolved path parameters: ${w.join(", ")}`);const k=new URLSearchParams;if(m.query)for(const[$,N]of Object.entries(m.query))N!=null&&k.append($,String(N));k.toString()&&(d+=`?${k.toString()}`);const _=await aa(r,i,o),A={method:t.toUpperCase(),headers:{Authorization:`Bearer ${_}`,"Content-Type":"application/json"}};m.body&&t.toLowerCase()!=="get"&&(A.data=m.body);const O=await js.request({url:d,...A});return{content:[{type:"text",text:JSON.stringify(O.data,null,2)}]}}catch(y){return js.isAxiosError(y)?{content:[{type:"text",text:`Error: ${y.response?.data?`HTTP ${y.response.status}: ${y.response.statusText} - ${JSON.stringify(y.response.data)}`:`HTTP ${y.response?.status||"unknown"}: ${y.message}`}`}],isError:!0}:y instanceof Error?{content:[{type:"text",text:`Error: API call failed: ${y.message}`}],isError:!0}:{content:[{type:"text",text:"Error: API call failed with unknown error"}],isError:!0}}}}}c(vh,"createApiTool");function Ch(s,e,t,n,r){const i=[];if(!s.paths)return i;for(const[o,a]of Object.entries(s.paths))if(typeof a=="object"&&a!==null){for(const[l,u]of Object.entries(a))if(["get","post","put","delete","patch"].includes(l)&&u&&typeof u=="object"){const h=vh(u,o,l,e,t,n,r);i.push(h)}}return i}c(Ch,"convertOpenApiToTools");function kh(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(`
143
- `)).action(async()=>{try{process.env.FASTMCP_SUPPRESS_WARNINGS="true";const e=An();e||(console.error("No configuration found. Please set MEMBRANE_WORKSPACE_KEY and MEMBRANE_WORKSPACE_SECRET environment variables, or run `membrane init` first."),process.exit(1)),(!e.workspaceKey||!e.workspaceSecret)&&(console.error("Missing workspace credentials"),process.exit(1));const t=e.apiUri||Us,n=await aa(e.workspaceKey,e.workspaceSecret,e.testCustomerId),r=await Sh(t,n),i=Ch(r,t,e.workspaceKey,e.workspaceSecret,e.testCustomerId),o=new Wc({name:"Membrane API",instructions:`This MCP server lets you interact with Membrane to configure, run, and troubleshoot integrations.
141
+ `,t)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;const t=es(e),n=_t(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=es(e),n=_t(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 Vo(s){const e=s.prettyErrors!==!1;return{lineCounter:s.lineCounter||e&&new Uo||null,prettyErrors:e}}c(Vo,"parseOptions");function Iu(s,e={}){const{lineCounter:t,prettyErrors:n}=Vo(e),r=new br(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(Vn(s,t)),a.warnings.forEach(Vn(s,t));return o.length>0?o:Object.assign([],{empty:!0},i.streamInfo())}c(Iu,"parseAllDocuments");function Go(s,e={}){const{lineCounter:t,prettyErrors:n}=Vo(e),r=new br(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 Qe(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return n&&t&&(o.errors.forEach(Vn(s,t)),o.warnings.forEach(Vn(s,t))),o}c(Go,"parseDocument");function $u(s,e,t){let n;typeof e=="function"?n=e:t===void 0&&e&&typeof e=="object"&&(t=e);const r=Go(s,t);if(!r)return null;if(r.warnings.forEach(i=>ro(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($u,"parse");function Nu(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 Ge(s)&&!n?s.toString(t):new Rt(s,n,t).toString(t)}c(Nu,"stringify");var xu=Object.freeze({__proto__:null,Alias:$n,CST:Eu,Composer:mr,Document:Rt,Lexer:qo,LineCounter:Uo,Pair:se,Parser:br,Scalar:M,Schema:Es,YAMLError:lr,YAMLMap:ue,YAMLParseError:Qe,YAMLSeq:Ke,YAMLWarning:Oo,isAlias:Fe,isCollection:G,isDocument:Ge,isMap:dt,isNode:z,isPair:H,isScalar:W,isSeq:pt,parse:$u,parseAllDocuments:Iu,parseDocument:Go,stringify:Nu,visit:ze,visitAsync:In});const he={Updated:"updated",Deleted:"deleted",Stopped:"stopped"},Mu={ignored:ul,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 Ru extends qs{static{c(this,"LocalElementWatcher")}constructor(e){super(),this.options=e,this.membraneDir=ht(this.options.cwd),this.lockTimeoutMs=this.options.lockTimeoutMs??1e3}isWatching=!1;watcher;membraneDir;contentCache={};ignoredPaths=new Set;lockTimeoutMs;async start(){this.isWatching||(P.existsSync(this.membraneDir)||P.mkdirSync(this.membraneDir,{recursive:!0}),this.initializeContentCache(),this.watcher=xc.watch(this.membraneDir,Mu),this.watcher.on("add",e=>this.handleFileSystemEvent(he.Updated,e)).on("change",e=>this.handleFileSystemEvent(he.Updated,e)).on("unlink",e=>this.handleFileSystemEvent(he.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(he.Stopped))}getCwd(){return this.options.cwd}async executeWithPathLock(e,t){const n=F.resolve(e);this.ignoredPaths.add(n);try{await t()}finally{setTimeout(()=>{this.ignoredPaths.delete(n)},this.lockTimeoutMs)}}isPathLocked(e){const t=F.resolve(e);if(this.ignoredPaths.has(t))return!0;for(const n of this.ignoredPaths)if(t.startsWith(n+F.sep))return!0;return!1}clearAllLocks(){this.ignoredPaths.clear()}handleFileSystemEvent(e,t){const n=F.relative(this.membraneDir,t);if(this.isPathLocked(t))return;if(e===he.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 P.readFileSync(e,"utf8")}processFileEvent(e,t){const n=F.relative(this.membraneDir,e);let r;try{r=t?xu.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 $c.createHash("sha256").update(e).digest("hex")}updateCache(e,t){if(!t){delete this.contentCache[e];return}this.contentCache[e]=this.getContentHash(t)}removeFromCache(e){delete this.contentCache[e]}clearCache(){Object.keys(this.contentCache).forEach(e=>{delete this.contentCache[e]})}initializeContentCache(){P.existsSync(this.membraneDir)&&this.scanDirectoryForCache(this.membraneDir)}scanDirectoryForCache(e){const t=P.readdirSync(e,{withFileTypes:!0});for(const n of t){const r=F.join(e,n.name);if(n.isDirectory())this.scanDirectoryForCache(r);else if(n.isFile())try{const i=P.readFileSync(r,"utf8"),o=F.relative(this.membraneDir,r);this.updateCache(o,i)}catch{}}}}var Sr=(s=>(s.Updated="updated",s.ConnectorFileUpdated="connector-file-updated",s.Connected="connected",s.Disconnected="disconnected",s.Error="error",s))(Sr||{});const Pu={debounceMs:2e3,reconnectIntervalMs:5e3,maxReconnectAttempts:5};class Lu extends qs{static{c(this,"RemoteElementWatcher")}constructor(e=Pu){super(),this.config=e}eventSource;debounceTimeouts=new Map;reconnectAttempts=0;reconnectTimeout;isStarted=!1;async start(){this.isStarted||(this.isStarted=!0,await this.connect())}async stop(){this.isStarted&&(this.isStarted=!1,this.clearReconnectTimeout(),this.clearAllDebounceTimeouts(),this.eventSource&&(this.eventSource.close(),this.eventSource=void 0))}async connect(){try{b.debug("[remote-events] Connecting to server");const e=await U.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 Mc(n),this.setupEventSourceHandlers()}catch(e){b.error(`[remote-events] Failed to subscribe to workspace events: ${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.emit("connected",{})},this.eventSource.onmessage=e=>{try{const t=JSON.parse(e.data);this.handleElementUpdate(t)}catch(t){b.error(`[remote-events] Failed to parse workspace event: ${t}`)}},this.eventSource.onerror=e=>{b.error(`[remote-events] Connection error: ${JSON.stringify(e,null,2)}`),this.emit("disconnected",{}),this.isStarted&&this.scheduleReconnect()})}handleElementUpdate(e){if(e.type!==vc.ElementUpdate)return;const{elementId:t,elementType:n,data:r={}}=e;if(!(!t||!n)){if(n===B.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){if(this.reconnectAttempts>=this.config.maxReconnectAttempts)throw new Error("Unable to re-connect to the server");return}this.reconnectAttempts++;const e=Math.min(this.config.reconnectIntervalMs*Math.pow(2,this.reconnectAttempts-1),3e4);b.debug(`[remote-watcher] Reconnecting in ${e}ms (attempt ${this.reconnectAttempts})`),this.reconnectTimeout=setTimeout(()=>{this.connect()},e)}clearReconnectTimeout(){this.reconnectTimeout&&(clearTimeout(this.reconnectTimeout),this.reconnectTimeout=void 0)}clearAllDebounceTimeouts(){this.debounceTimeouts.forEach(e=>clearTimeout(e)),this.debounceTimeouts.clear()}}class zo{static{c(this,"ElementsCache")}elements=new Map;typeIndex=new Map;internalIdIndex=new Map;constructor(e){e&&this.addAll(e)}add(e){const t=e.id;this.elements.set(t,e),this.typeIndex.has(e.type)||this.typeIndex.set(e.type,new Set),this.typeIndex.get(e.type).add(t),e.data?.id&&this.internalIdIndex.set(e.data.id,t)}remove(e){const t=e.id,n=this.elements.delete(t);if(n){const r=this.typeIndex.get(e.type);r&&(r.delete(t),r.size===0&&this.typeIndex.delete(e.type)),e.data?.id&&this.internalIdIndex.delete(e.data.id)}return n}put(e){this.elements.has(e.id)&&this.remove(e),this.add(e)}get(e){return this.elements.get(e)}getByInternalId(e){const t=this.internalIdIndex.get(e);if(t)return this.elements.get(t)}getElementsByType(e){const t=this.typeIndex.get(e);return t?Array.from(t).map(n=>this.elements.get(n)).filter(n=>n!==void 0):[]}getAll(){return Array.from(this.elements.values())??[]}getTypes(){return Array.from(this.typeIndex.keys())}addAll(e){for(const t of e)t&&this.add(t)}removeAll(e){for(const t of e)this.remove(t)}getElementIdsByType(e){return this.typeIndex.get(e)}clear(){this.elements.clear(),this.typeIndex.clear(),this.internalIdIndex.clear()}getAllIds(){return new Set(this.elements.keys())}}async function Du(s="full"){const e={};b.info("[connectors] Getting remote workspace data");const t=await U.withClient(n=>n.integrations.findAll());e.integration=t.map(n=>vr("integration",n));for(const n of Object.keys(le)){const r=le[n];if(r.exportable===!1)continue;const i=[];b.info(`[connectors] Reading ${r.elements} from remote workspace`);const o=await U.withClient(a=>a[r.elements].findAll());if(i.push(...o.map(a=>vr(n,a))),r.integrationSpecific)for(const a of t){const l=await U.withClient(u=>u[r.elements].findAll({integrationId:a.id}));i.push(...l.map(u=>(u.integrationKey=a.key,vr(n,u))))}i.length>0&&s=="full"&&(console.table(i.map(a=>({key:a.key,integrationKey:a.integrationKey,universal:!a.integrationKey})).reduce((a,l)=>(a||(a={}),a[l.key]||(a[l.key]={}),l.universal&&(a[l.key].universal=!0),l.integrationKey&&(a[l.key].integration?a[l.key].integration+=` ${l.integrationKey}`:a[l.key].integration=l.integrationKey),a),{})),console.groupEnd()),e[n]=i}return b.success("[connectors] Remote workspace data retrieved successfully"),e}c(Du,"getWorkspaceData");function vr(s,e){return e=cl(e),le[s].exportCleanup?le[s].exportCleanup(e):e}c(vr,"cleanUpForExport");const Tt="connectors",Ne="development",Cr={};async function ju(){const s=await Du("minified"),t=(await U.withClient(l=>l.get("org-workspace-id"))).id,n={};b.info("[connectors] Loading custom connectors");const r=await U.withClient(l=>l.get(`/connectors?workspaceId=${t}`));b.info("[connectors] Loading public connectors"),s.connector=r;const i=qe(),a=(D.existsSync(i)?D.readdirSync(i):[]).filter(l=>{if(l.startsWith("."))return!1;const u=q.join(i,l);try{return D.statSync(u).isDirectory()}catch{return!1}});for(const l of a){b.info(`[connectors] Loading connector from: ${l}`);const u=D.readdirSync(q.join(i,l)),h=await kr(l);if(!h)continue;if("baseUri"in h&&delete h.baseUri,h.uuid&&s.connector?.find(p=>p.uuid==h.uuid))n[h.id]=s.connector.find(p=>p.uuid==h.uuid).id,b.info(`[connectors] Matched ${h.name} uuid: ${h.uuid}`);else if(!n[h.id]){let p=!1;try{const m=await _r({connectorId:h.id});m&&!m.workspaceId&&(p=!0)}catch{}if(!p){b.info(`[connectors] Creating custom connector ${h.name} (${h.key})`);const m=await U.withClient(y=>y.post("connectors",{...h,workspaceId:t}));n[h.id]=m.id}}const f=u.filter(p=>D.statSync(q.join(i,l,p)).isDirectory());for(const p of f)await Bu({connector:h,version:p,connectorId:n[h.id]})}return n}c(ju,"pushConnectors");async function Yo({connectorId:s,connectorVersion:e,allConnectors:t,pulledConnectors:n,pulledConnectorVersions:r}){if(!s||r[s]?.has(e))return;const i=Di(),o=await _r({connectorId:s});if(o.workspaceId||t){if(!o?.key){b.error(`[connectors] Connector ${s} has no key. Skipping..`);return}n.has(s)||(await qu({basePath:i,connector:o}),n.add(s)),r[s]||(r[s]=new Set),r[s].has(e)||(await Uu({connector:o,connectorVersion:e,basePath:i}),r[s].add(e))}}c(Yo,"pullRemoteConnector");function qe(){const s=Ws();return q.join(s.membraneDirPath,Tt)}c(qe,"getConnectorsPath");async function kr(s){const e=q.join(qe(),s,`${s}.yml`);return Js(e,!1)}c(kr,"readConnector");async function Fu(s,e){return b.info(`[connectors] Zipping ${s} into ${e}`),new Promise((t,n)=>{const r=D.createWriteStream(e),i=Rc("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=D.readdirSync(s);for(const a of o){const l=q.join(s,a),u=D.statSync(l);u.isFile()?i.file(l,{name:a}):u.isDirectory()&&i.directory(l,a)}i.finalize()})}c(Fu,"createZipArchive");async function Ku(s,e){return b.info(`[connectors] Unzipping into ${e}`),new Promise((t,n)=>{const r=Lc.Parse();r.on("entry",i=>{const o=i.path;if(i.type==="Directory"){const l=q.join(e,o);D.mkdirSync(l,{recursive:!0}),i.autodrain()}else{const l=q.join(e,o),u=q.dirname(l);D.mkdirSync(u,{recursive:!0});const h=D.createWriteStream(l);i.pipe(h),h.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(Ku,"extractZipArchive");async function Bu({connector:s,version:e,connectorId:t}){const n=q.join(qe(),xe(s),Xo(e)),r=q.join(n,"src"),i=q.join(n,"src.zip"),o=D.existsSync(i);if(D.existsSync(r)&&(b.info(`[connectors] Archiving source code for ${s.name} version ${e}`),await Fu(r,i)),!D.existsSync(i)){b.warning(`[connectors] No source code found for ${s.name} version ${e}`);return}try{const a=new Pc;if(a.append("file",D.createReadStream(i),"file.zip"),b.info(`[connectors] Pushing connector version ${e} for ${s.name}`),e==Ne)b.info(`[connectors] Uploading connector ${t}`),await U.withClient(l=>l.post(`connectors/${t}/upload`,a,{headers:{...a.getHeaders()}}));else{if(a.append("version",e),a.append("changelog","Imported Version"),(await U.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 U.withClient(u=>u.post(`connectors/${t}/publish-version`,a,{headers:{...a.getHeaders()}}))}b.success(`Successfully pushed connector version ${e} for ${s.name}`)}catch(a){b.error(`Error pushing connector version ${e} for ${s.name}: ${a}`)}finally{!o&&D.existsSync(i)&&(b.info(`[connectors] Cleaning up temporary zip file for ${s.name} version ${e}`),D.unlinkSync(i))}}c(Bu,"pushConnectorVersion");async function _r({connectorId:s}){if(s){if(Cr[s])return Cr[s];try{const e=await U.withClient(t=>t.get(`connectors/${s}`));return Cr[s]=e,e}catch(e){return b.error(`[connectors] Failed to get connector ${s}: ${e}`),null}}}c(_r,"getConnector");async function qu({basePath:s,connector:e}){const t=xe(e),n=q.join(s,Tt,t);D.mkdirSync(n,{recursive:!0});const r=q.join(n,`${xe(e)}.yml`);D.writeFileSync(r,Pt.dump(e)),b.info(`[connectors] Pulled connector ${e.name}`)}c(qu,"pullConnector");async function Uu({connector:s,connectorVersion:e,basePath:t}){const n=xe(s),r=Xo(e),i=q.join(t,"connectors",n,r),o=await U.withClient(l=>l.get(`connectors/${s.id}/download`,{version:e},{responseType:"arraybuffer",headers:{Accept:"application/zip"},timeout:1e6}));D.mkdirSync(i,{recursive:!0});const a=q.join(i,"src.zip");if(D.writeFileSync(a,o),!e){const l=q.join(i,"src");D.mkdirSync(l,{recursive:!0}),await Ku(o,l)}b.info(`[connectors] Pulled connector version: ${s.name} (${r})`)}c(Uu,"pullConnectorVersion");function xe(s){return s.key}c(xe,"getConnectorDirName");function Xo(s){return s??Ne}c(Xo,"getConnectorVersionDirName");function Wu(s){const e=Di(),t=xe(s);return q.join(e,Tt,t)}c(Wu,"getConnectorDirPath");function Ju(s){return s.match(`${Tt}/[^/]+/${Ne}/src/.*`)!==null}c(Ju,"isConnectorSourceFile");async function Hu(s){const e=s.match(`${Tt}/([^/]+)/${Ne}/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=D.readFileSync(s,"utf-8");await U.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(Hu,"putConnectorFile");async function Vu(s){const e=s.match(`${Tt}/([^/]+)/${Ne}/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 U.withClient(o=>o.delete(`connectors/${i}/files/${n}`)),b.info(`[connectors] Deleted file ${n} for connector ${r.name}`)}c(Vu,"deleteConnectorFile");async function Gu(s,e){try{const t=await U.withClient(o=>o.get(`connectors/${s}`));if(!t){b.warning(`[connectors] Connector ${s} not found`);return}const n=await U.withClient(o=>o.get(`connectors/${s}/files/${e}`)),r=xe(t),i=q.join(qe(),r,Ne,"src",e);D.mkdirSync(q.dirname(i),{recursive:!0}),n!=null?(D.writeFileSync(i,n),b.info(`[connectors] Pulled file ${e} for connector ${t.name}`)):D.existsSync(i)&&(D.unlinkSync(i),b.info(`[connectors] Deleted file ${e} for connector ${t.name}`))}catch(t){b.error(`[connectors] Failed to pull connector file ${e} for connector ${s}: ${t}`)}}c(Gu,"pullConnectorFile");async function zu(s,e){const t=await U.withClient(i=>i.get(`connectors/${s}`));if(!t){b.warning(`[connectors] Connector ${s} not found`);return}const n=xe(t),r=q.join(qe(),n,Ne,"src",e);D.existsSync(r)&&(D.unlinkSync(r),b.info(`[connectors] Deleted file ${e} for connector ${n}`))}c(zu,"deleteLocalConnectorFile");async function Yu(s,e,t){if(t&&e!==t)try{const n=await U.withClient(l=>l.get(`connectors/${s}`));if(!n){b.warning(`[connectors] Connector ${s} not found`);return}const r=xe(n),i=q.join(qe(),r,Ne,"src"),o=q.join(i,e),a=q.join(i,t);D.existsSync(o)&&(D.mkdirSync(q.dirname(a),{recursive:!0}),D.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(Yu,"renameLocalConnectorDirectory");async function Xu(s,e){try{const t=await U.withClient(i=>i.get(`connectors/${s}`));if(!t){b.warning(`[connectors] Connector ${s} not found`);return}const n=xe(t),r=q.join(qe(),n,Ne,"src",e);if(D.existsSync(r)){const i=q.resolve(qe());if(!q.resolve(r).startsWith(i))return;D.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(Xu,"deleteLocalConnectorDirectory");const Qo=[B.DataSource,B.FieldMapping,B.Action,B.Flow];class mn{static{c(this,"ElementSyncService")}localWatcher=void 0;remoteWatcher=void 0;notifier;changes=[];localCache;remoteCache;localRepo;remoteRepo;pulledConnectors=new Set;pulledConnectorVersions={};constructor(){this.notifier=Oe,this.localCache=new zo,this.remoteCache=new zo,this.localRepo=new Cl(this.localCache),this.remoteRepo=new kl(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(B.Integration).map(n=>n.data);for(const n of t){const r=n.connectorId,i=n.connectorVersion;r&&await Yo({connectorId:r,connectorVersion:i,allConnectors:e,pulledConnectors:this.pulledConnectors,pulledConnectorVersions:this.pulledConnectorVersions})}}async pushConnectors(){const e=await ju();this.remoteRepo.setConnectorsMapping(e)}getHandler(e){return e===ae.INCOMING?this.localRepo:this.remoteRepo}getCache(e){return e===ae.INCOMING?this.localCache:this.remoteCache}async startWatching(){this.localWatcher=new Ru({cwd:process.cwd(),lockTimeoutMs:1e3}),this.localWatcher.on(he.Updated,e=>this.handleLocalEvent(e,he.Updated)),this.localWatcher.on(he.Deleted,e=>this.handleLocalEvent(e,he.Deleted)),await this.localWatcher.start(),b.success("[local] Tracking changes.."),this.remoteWatcher=new Lu,this.remoteWatcher.on(Sr.Updated,({elementId:e,elementType:t})=>this.handleRemoteElementEvent(e,t)),this.remoteWatcher.on(Sr.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===B.Integration){const o=n.data.connectorId,a=n.data.connectorVersion,l=await _r({connectorId:o});if(!l?.key)return;const u=Wu(l);await this.localWatcher?.executeWithPathLock(u,async()=>Yo({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 Ms.ConnectorFileDeleted:await zu(e,t);break;case Ms.ConnectorDirectoryRenamed:await Yu(e,t,r);break;case Ms.ConnectorDirectoryDeleted:await Xu(e,t);break;default:await Gu(e,t);break}}catch(i){b.error(`[sync] Error handling remote connector file event: ${i}`)}}async handleLocalEvent(e,t){try{if(Ju(e.filePath))switch(t){case he.Updated:await Hu(e.filePath);break;case he.Deleted:await Vu(e.filePath);break}else{let n=Q.fromPathAndData(e.filePath,e.data);if(!n){const r=Q.idFromPath(e.filePath);if(!r||(n=this.remoteCache.get(r),!n))return}switch(b.info(`[${this.getDirectionLabel(ae.OUTGOING)}] ${al.toSentenceCase(t)}: ${n.id}`),t){case he.Updated:await this.updateElement(n,ae.OUTGOING);break;case he.Deleted:await this.deleteElement(n,ae.OUTGOING);break}}}catch(n){b.error(`[sync] Error handling local event: ${n}`)}}detectIncomingChanges(){this.clearChanges();const e=mn.getChanges(ae.INCOMING,this.remoteCache,this.localCache);return this.updateChanges(e),e}detectOutgoingChanges(){this.clearChanges();const e=mn.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===B.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!==B.Integration)),b.info("[resolver] Resolving universal elements");const t=this.changes.filter(r=>!r.element.hasParent());for(const r of Qo){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 Qo){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 Ae.DELETE:return this.deleteElement(e.element,e.direction);case Ae.CREATE:return this.updateElement(e.element,e.direction);case Ae.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),h=n.get(l),f=mn.detectChangeForElement(u,h,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:Ae.CREATE,element:e,direction:n,isConflict:!1}:!e&&t?{type:Ae.DELETE,element:t,direction:n,isConflict:!0}:e&&t&&!e.isEqual(t)?{type:Ae.UPDATE,element:e,direction:n,isConflict:!0}:null}}const Ue=F.join(Dc.tmpdir(),"membrane-mcp-status"),Zo=3e4;class Qu{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=ts(void 0,e),n=ea(e);t&&Oe.setMcpStatus(t),await Oe.setMcpServers(n)}catch{b.error("Failed to check MCP status")}}}function ts(s,e){try{const t=e||process.cwd();if(!s){const r=ea(t);return r.length===0?null:r[0]}const n=Ar(s,t);if(P.existsSync(n)){const r=P.statSync(n),i=new Date;if(i.getTime()-r.mtime.getTime()>Zo)return Vt(s,t),null;const a=P.readFileSync(n,"utf8"),l=JSON.parse(a);if(l.isRunning){const u=new Date(l.lastActivity).getTime();if(i.getTime()-u>Zo)return Vt(s,t),null}return l}}catch{s&&e&&Vt(s,e)}return null}c(ts,"getMcpStatus");function ea(s){try{const e=s||process.cwd(),t=Er(e);if(!P.existsSync(Ue))return[];const n=P.readdirSync(Ue),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=ts(a,e);l&&r.push(l)}}return r.sort((i,o)=>new Date(o.startTime).getTime()-new Date(i.startTime).getTime())}catch{return[]}}c(ea,"getAllMcpStatusFiles");function Tr(s){try{const t={...ts(s.processId,s.cwd)||{isRunning:!1,startTime:new Date().toISOString(),lastActivity:new Date().toISOString(),toolsCount:0,totalRequests:0,processId:s.processId,cwd:s.cwd,agentName:process.env.AGENT_NAME||"Unnamed Agent"},...s};P.existsSync(Ue)||P.mkdirSync(Ue,{recursive:!0});const n=Ar(s.processId,s.cwd);P.writeFileSync(n,JSON.stringify(t,null,2))}catch{}}c(Tr,"updateMcpStatus");function Vt(s,e){try{const t=e||process.cwd();if(s){const n=Ar(s,t);P.existsSync(n)&&P.unlinkSync(n)}else{const n=Er(t);if(P.existsSync(Ue)){const r=P.readdirSync(Ue);for(const i of r)i.match(new RegExp(`^mcp-${n}-\\d+\\.json$`))&&P.unlinkSync(F.join(Ue,i))}}}catch{}}c(Vt,"clearMcpStatus");function Zu(s,e){const t=ts(s,e);t&&Tr({processId:s,cwd:e,totalRequests:t.totalRequests+1,lastRequestTime:new Date().toISOString(),lastActivity:new Date().toISOString()})}c(Zu,"trackToolExecution");function Er(s){return Nc("md5").update(s).digest("hex").slice(0,8)}c(Er,"getCwdHash");function Ar(s,e){const t=Er(e);return F.join(Ue,`mcp-${t}-${s}.json`)}c(Ar,"getStatusFilePath");const Gt={Agent:"agent",Cli:"cli"},x={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 ta{static{c(this,"MembraneCLIService")}constructor(e,t,n=()=>process.exit(0)){this.mode=e,this.cwd=t,this.onShutdown=n,this.notifier=Oe,this.mcpStatusService=new Qu,this.syncService=new mn,this.setupProcessCleanup()}initialized=!1;notifier;mcpStatusService;syncService;isShuttingDown=!1;currentConfig=null;get config(){return this.currentConfig}async pullWorkspace(e={}){try{if(b.setVerboseMode(!!e.verbose),await this.notifier.setState(x.PULLING),await this.syncService.fetchElements(),this.syncService.detectIncomingChanges(),this.syncService.needsForcedSync()&&!e.force)return this.notifier.setState(x.CONFLICTS);await this.syncService.pullConnectors(e.allConnectors),await this.syncWorkspaces(e)}catch(t){b.error(`Failed to pull workspace: ${t}`),await this.notifier.setState(x.ERROR),b.saveLogsToFile("error")}finally{return e.saveLogs&&b.saveLogsToFile(),e?.onComplete?.()}}async pushWorkspace(e={}){try{if(b.setVerboseMode(!!e.verbose),await this.notifier.setState(x.PUSHING),await this.syncService.fetchElements(),this.syncService.detectOutgoingChanges(),this.syncService.needsForcedSync()&&!e.force)return await this.notifier.setState(x.CONFLICTS);await this.syncService.pushConnectors(),await this.syncWorkspaces(e)}catch(t){b.error(`Failed to push workspace: ${t}`),await this.notifier.setState(x.ERROR),b.saveLogsToFile("error")}finally{return e.saveLogs&&b.saveLogsToFile(),e?.onComplete?.()}}async syncWorkspaces(e={}){try{e.verbose!==void 0&&b.setVerboseMode(!!e.verbose),await this.notifier.setState(x.RESOLVING),this.syncService.needsSync()&&await this.syncService.resolveChanges();const t=await this.syncService.getStats();this.notifier.setStats(t),await this.notifier.setState(x.SYNCED),e.watch&&(await this.notifier.setState(x.WATCHING),await this.syncService.startWatching())}catch(t){b.error(`Failed to sync local and remote workspaces: ${t}`),await this.notifier.setState(x.ERROR),b.saveLogsToFile("error")}}async init({force:e=!1}={}){if(!(this.initialized&&!e)){await this.notifier.setState(x.NOT_INITIALIZED);try{await this.loadConfig(),Dt.isCacheDefined()?(await this.initServices(),this.initialized=!0,await this.notifier.setState(x.INITIALIZED)):(this.initialized=!1,await this.notifier.setState(x.SETTING_UP))}catch(t){b.error(`Failed to initialize services: ${t}`),await this.notifier.setState(x.ERROR),b.saveLogsToFile("error"),this.onShutdown()}}}async loadConfig(){this.currentConfig=Dt.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=Dt.updateConfig(t);this.currentConfig=r,await this.init({force:!0})}async shutdown(){!this.initialized||this.isShuttingDown||(this.isShuttingDown=!0,this.mode===Gt.Agent&&(await this.notifier.cleanup(),await this.mcpStatusService.stop()),this.initialized=!1,this.onShutdown())}async initServices(){this.mode===Gt.Agent&&(await this.notifier.connectToRemote(),await this.mcpStatusService.start()),this.syncService.clear()}async stopServices(){this.mode===Gt.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 na=oi(null);function eh({children:s,membraneCLIService:e}){const{data:t}=ci("/account"),[n,r]=J(x.NOT_INITIALIZED),[i,o]=J([]),[a,l]=J({}),[u,h]=J([]),[f,p]=J(null),y=t?.workspaces?.find(d=>d.workspaceKey===f?.workspaceKey)||null;return Ve(()=>{const d=c(({state:A})=>r(A),"handleStateChanged"),w=c(({stats:A})=>l(A),"handleStatsChanged"),k=c(({log:A})=>h($=>[...$,A]),"handleLogAdded"),_=c(({conflicts:A})=>o(A),"handleConflictsUpdated"),O=c(({config:A})=>p(A),"handleConfigChanged");return e.notifier.on(Y.StateChanged,d),e.notifier.on(Y.StatsChanged,w),e.notifier.on(Y.LogAdded,k),e.notifier.on(Y.ConflictsChanged,_),e.notifier.on(Y.ConfigChanged,O),e.init(),()=>{e.notifier.off(Y.StateChanged,d),e.notifier.off(Y.StatsChanged,w),e.notifier.off(Y.LogAdded,k),e.notifier.off(Y.ConflictsChanged,_),e.notifier.off(Y.ConfigChanged,O)}},[]),g(na.Provider,{value:{state:n,stats:a,logs:u,currentWorkspace:y,conflicts:i,config:f,updateConfig:c(d=>e.updateConfig(d),"updateConfig"),resolveConflicts:c(d=>e.syncWorkspaces(d),"resolveConflicts"),pull:c(d=>e.pullWorkspace(d),"pull"),push:c(d=>e.pushWorkspace(d),"push"),exit:c(()=>e.shutdown(),"exit")},children:s})}c(eh,"MembraneCLIServiceProvider");function Se(){const s=ai(na);if(!s)throw new Error("useMembraneCLIService must be used within MembraneCLIServiceProvider");return s}c(Se,"useMembraneCLIService");const sa=oi(process.cwd());function th({cwd:s,children:e}){return g(sa.Provider,{value:s,children:e})}c(th,"CwdProvider");function nh(){return ai(sa)}c(nh,"useCwd");function ns({cwd:s,children:e,membraneCLIService:t}){const n=s||process.cwd();return g(th,{cwd:n,children:g(gc,{value:{fetcher:gl()},children:g(eh,{membraneCLIService:t,children:e})})})}c(ns,"Layout");const Or=[{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=F.join(process.cwd(),".mcp.json"),e={mcpServers:{membrane:{command:"membrane",args:["mcp"],env:{AGENT_NAME:"Claude Code"}}}};let t={};if(P.existsSync(s))try{t=JSON.parse(P.readFileSync(s,"utf8"))}catch{t={}}const n={...t,mcpServers:{...t.mcpServers,...e.mcpServers}};return P.writeFileSync(s,JSON.stringify(n,null,2)),`MCP server configuration added to ${s}`},"addConfig")},{id:"cursor",name:"Cursor",description:"Cursor AI editor",actionDescription:"Adding membrane MCP to .cursor/mcp.json in the current directory",addConfig:c(()=>{const s=F.join(process.cwd(),".cursor"),e=F.join(s,"mcp.json");P.existsSync(s)||P.mkdirSync(s);const t={mcpServers:{membrane:{command:"membrane",args:["mcp"],env:{AGENT_NAME:"Cursor"}}}};let n={};if(P.existsSync(e))try{n=JSON.parse(P.readFileSync(e,"utf8"))}catch{n={}}const r={...n,mcpServers:{...n.mcpServers,...t.mcpServers}};return P.writeFileSync(e,JSON.stringify(r,null,2)),`MCP server configuration added to ${e}`},"addConfig")}];function sh({onExit:s,onComplete:e}){const[t,n]=J(0),[r,i]=J(!1),[o,a]=J(null),[l,u]=J(""),[h,f]=J("");nt((y,d)=>{if(l||h){(d.escape||y==="q"||d.return)&&e();return}if(r)d.return||y===" "?p(o):d.escape&&(i(!1),a(null));else if(d.escape)s();else if(d.upArrow||y==="k")n(Math.max(0,t-1));else if(d.downArrow||y==="j")n(Math.min(Or.length-1,t+1));else if(d.return||y===" "){const w=Or[t];a(w),i(!0)}});const p=c(y=>{try{const d=y.addConfig();u(d)}catch(d){f(`Failed to write configuration: ${d.message||d}`)}},"addMcpConfiguration"),m=Math.min(80,process.stdout.columns||80);return l?E(v,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:m,children:[g(v,{marginTop:-1,marginBottom:1,children:E(C,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",g(C,{color:"green",children:"Success"})]})}),E(v,{flexDirection:"column",paddingLeft:2,children:[g(C,{color:"green",children:l}),g(v,{marginTop:1,children:g(C,{color:"grey",children:"The agent will now be able to use Membrane's integration capabilities."})})]}),g(v,{marginTop:1,paddingLeft:2,children:g(C,{color:"white",children:"[esc/q/enter: exit]"})})]}):h?E(v,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:m,children:[g(v,{marginTop:-1,marginBottom:1,children:E(C,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",g(C,{color:"red",children:"Error"})]})}),g(v,{flexDirection:"column",paddingLeft:2,children:g(C,{color:"red",children:h})}),g(v,{marginTop:1,children:g(C,{color:"grey",children:"[esc/q/enter: exit]"})})]}):r&&o?E(v,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:m,children:[g(v,{marginTop:-1,marginBottom:1,children:E(C,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",g(C,{color:"cyan",children:"Confirmation"})]})}),E(v,{flexDirection:"column",paddingLeft:2,children:[E(C,{children:["Connect ",g(C,{bold:!0,children:o.name})," to Membrane via MCP?"]}),g(v,{marginTop:1,children:g(C,{color:"grey",children:"This will add an MCP server configuration that allows the agent to use Membrane's integration capabilities."})}),g(v,{marginTop:1,children:g(C,{color:"yellow",bold:!0,children:o.actionDescription})}),g(v,{marginTop:2,marginBottom:1,children:E(C,{children:[g(C,{color:"white",bold:!0,children:"[Enter] Confirm"})," ",g(C,{color:"gray",children:"[Esc] Cancel"})]})})]})]}):E(v,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:m,children:[g(v,{marginTop:-1,marginBottom:1,children:E(C,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",g(C,{color:"cyan",children:"Select Agent"})]})}),E(v,{flexDirection:"column",paddingLeft:2,children:[g(C,{color:"grey",children:"Choose an agent to connect to Membrane via MCP:"}),g(v,{marginTop:1,children:g(C,{color:"grey",children:"This will add an MCP server configuration that allows the agent to use Membrane's integration capabilities."})}),g(v,{marginTop:1,flexDirection:"column",children:Or.map((y,d)=>E(v,{children:[E(C,{color:t===d?"cyan":"white",children:[t===d?"\u25B6 ":" ",y.name]}),E(C,{color:"grey",children:[" \u2014 ",y.description]})]},y.id))})]}),g(v,{marginTop:1,children:g(C,{color:"grey",children:"[\u2191\u2193: select] [enter: choose] [esc: exit]"})})]})}c(sh,"AddMcpServerScreen");function rh(){const[s,e]=J(null),[t,n]=J([]),[r,i]=J(null);return Ve(()=>{const o=c(({status:l})=>{e(l),i(null)},"handleMcpStatusChanged"),a=c(({servers:l})=>{n(l),i(null)},"handleMcpServersChanged");return Oe.on(Y.McpStatusChanged,o),Oe.on(Y.McpServersChanged,a),()=>{Oe.off(Y.McpStatusChanged,o),Oe.off(Y.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(rh,"useMcpStatus");function ih(){const{error:s,serverCount:e,allMcpServers:t}=rh(),n=Math.min(100,process.stdout.columns||100);return E(v,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:n,children:[g(v,{marginTop:-1,marginBottom:0,flexDirection:"column",children:E(C,{bold:!0,children:["\u{1F916} Connected AI Agents:"," ",s?g(C,{color:"red",children:"error reading status"}):e===0?g(C,{color:"yellow",children:"none"}):g(C,{color:"green",children:e})]})}),!s&&e===0&&g(v,{marginTop:1,children:E(C,{color:"grey",children:["Connect your AI agents to Membrane.",g(pc,{}),"It will give them tools and context to build integrations."]})}),t.length>0&&g(v,{flexDirection:"column",paddingLeft:2,marginTop:1,children:t.map((r,i)=>g(v,{children:E(C,{color:"grey",children:["#",i+1," ",r.agentName,": ",r.totalRequests," calls"]})},r.processId))}),g(v,{marginTop:1,children:g(C,{color:"grey",children:"[a: connect an agent]"})})]})}c(ih,"Agent");const ss=c(s=>{switch(s){case"error":return"red";case"success":return"green";case"warning":return"yellow";default:return}},"getLogColor");function ra(s,e){return e<3?s.slice(0,Math.max(0,e)):s.length<=e?s:`${s.slice(0,e-3)}...`}c(ra,"truncateText");function Ir({children:s}){const{state:e,logs:t}=Se();return!e||e===x.NOT_INITIALIZED?E(v,{gap:1,flexDirection:"row",children:[g(Fc,{type:"dots"}),g(C,{children:"Initializing..."})]}):e===x.SETTING_UP?g(v,{gap:1,flexDirection:"row",children:g(C,{children:"No workspace selected. Please run `membrane init` to select a workspace."})}):e===x.ERROR?g(v,{flexDirection:"column",children:t.slice().map((n,r)=>g(C,{color:ss(n.type),children:n.message},n.timestamp+r))}):s}c(Ir,"EnsureInitialized");function ia({onExit:s,showEscOption:e=!0}){const[t,n]=J(""),{data:r,error:i,isLoading:o}=ci("/account"),{updateConfig:a}=Se(),l=r?.workspaces,u=o;if(nt((d,w)=>{w.escape&&s?.()}),u)return E(v,{children:[g(wn,{}),g(C,{children:" Fetching workspaces..."})]});if(i)return E(v,{flexDirection:"column",children:[E(C,{color:"red",children:["Error: ",i.message]}),g(v,{marginTop:1,children:g(C,{color:"grey",children:"Press ESC to go back"})})]});const h=l?.filter(d=>d.name.toLowerCase().includes(t.toLowerCase()))??[],f=h.map(d=>({label:d.name,value:d.id})),p=f.length,m=l?.length??0;async function y(d){const w=h.find(O=>O.id===d);if(!w)return;const{key:k,secret:_}=w;!k||!_||(await a({workspaceKey:k,workspaceSecret:_}),s?.())}return c(y,"handleSelect"),E(v,{flexDirection:"column",borderStyle:"round",borderTop:!0,width:70,paddingX:1,children:[g(v,{marginTop:-1,children:g(C,{bold:!0,children:"\u{1F4C1} Select your workspace"})}),E(v,{marginTop:1,children:[g(C,{children:"Search: "}),g(Kc,{placeholder:"Enter a search query...",onChange:n})]}),m>5&&E(C,{children:["Showing ",p," of ",m," workspaces."]}),g(v,{marginTop:1,children:g(Bc,{options:f,onChange:c(d=>{d&&y(d)},"onChange")})}),e&&g(v,{marginTop:1,children:g(C,{color:"grey",children:"Press ESC to go back"})})]})}c(ia,"SelectWorkspace");function oh({currentPat:s,onSubmit:e}){const[t,n]=J(""),[r,i]=J(!1),[o,a]=J(null);return E(v,{flexDirection:"column",borderStyle:"round",borderTop:!0,width:70,paddingX:1,children:[g(v,{marginTop:-1,marginBottom:1,children:g(C,{bold:!0,children:"\u{1F511} Enter your Personal Access Token"})}),g(C,{children:"Please provide your Personal Access Token. You can find it here:"}),g(v,{marginTop:1,marginBottom:1,children:g(C,{color:"yellow",children:"https://console.integration.app/w/0/manage-account/api-token"})}),s&&g(C,{dimColor:!0,children:"Press Enter to keep your current token or type a new one."}),g(qc,{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&&g(v,{marginTop:1,children:E(C,{children:[g(wn,{type:"dots"})," Validating token..."]})}),o&&g(C,{color:"red",children:o})]})}c(oh,"PersonalAccessTokenInput");var zt=(s=>(s[s.Authenticate=0]="Authenticate",s[s.ConnectWorkspace=1]="ConnectWorkspace",s))(zt||{});const ah={0:"Authenticate in Membrane",1:"Connect a Membrane Workspace"},$r=[zt.Authenticate,zt.ConnectWorkspace];function oa({onComplete:s}){const{config:e}=Se(),[t,n]=J(!1),[r,i]=J(0),o=!!(e?.workspaceKey&&e?.workspaceSecret),a=Fi(),l=$r[r],u=r+1,h=$r.length,f=$r.map((y,d)=>{let w="pending";return d<r?w="done":d===r&&(w="current"),{id:y,label:ah[y],status:w}});async function p(y){const d=a&&y===""?a:y,w=new Ki;try{await w.request("/account",{headers:{Authorization:`Bearer ${d}`}}),ml(d),i(k=>k+1)}catch(k){console.error(k)}}c(p,"handlePatSubmit");function m(){n(!0),s&&s()}return c(m,"handleWorkspaceSelected"),nt((y,d)=>{o&&d.escape&&s&&s()}),t?g(v,{children:g(C,{children:"\u2705 Setup complete. You are ready to go!"})}):E(v,{flexDirection:"column",alignSelf:"flex-start",gap:1,children:[E(v,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:70,children:[g(v,{marginTop:-1,marginBottom:1,children:E(C,{bold:!0,children:["\u{1F6E0}\uFE0F Setup \u2014"," ",E(C,{color:"cyan",children:["Step ",u," of ",h]}),o&&g(C,{color:"grey",children:" [esc: go back]"})]})}),g(v,{flexDirection:"column",paddingLeft:2,children:f.map(y=>g(ch,{status:y.status,label:y.label},y.id))})]}),l===zt.Authenticate&&g(oh,{currentPat:a,onSubmit:p}),l===zt.ConnectWorkspace&&g(ia,{onExit:m,showEscOption:!1})]})}c(oa,"Setup");function ch({status:s,label:e}){return E(v,{children:[E(v,{width:2,children:[s==="current"&&g(wn,{type:"dots"}),s==="done"&&g(C,{children:"\u2705"})]}),g(C,{dimColor:s!=="current",children:e})]})}c(ch,"StepDisplay");function Nr(){const{stats:s}=Se(),e=Object.entries(s).filter(([t,n])=>n>0);return e.length===0?null:E(v,{flexDirection:"column",children:[g(v,{children:g(v,{width:12,children:g(C,{color:"grey",children:"Elements:"})})}),g(v,{flexDirection:"column",marginLeft:1,children:e.map(([t,n])=>E(v,{children:[g(v,{width:20,children:E(C,{children:[t,":"]})}),g(C,{color:"green",children:n})]},t))})]})}c(Nr,"ElementStats");const xr=5,lh=6;function uh(){const{logs:s}=Se(),[e,t]=J(0),n=Math.min(100,process.stdout.columns||100),r=xr,i=Math.max(0,s.length-r-e),o=s.length-e,a=s.slice(i,o),l=n-lh,u=e<s.length-r,h=e>0;return nt((f,p)=>{if(s.length!==0)if(p.upArrow){const m=Math.max(0,s.length-r);t(y=>Math.min(m,y+1))}else p.downArrow?t(m=>Math.max(0,m-1)):(f==="G"||f==="g")&&t(0)}),E(v,{flexDirection:"column",paddingTop:1,children:[E(C,{color:"grey",children:["Recent Activity (",i+1,"-",o," of ",s.length,"):",s.length>xr&&g(C,{color:"grey",children:" [arrows: scroll] [g: end]"})]}),a.map((f,p)=>g(v,{marginLeft:1,children:g(C,{color:ss(f.type),children:ra(f.message,l)})},f.timestamp+p)),s.length>xr&&E(v,{marginLeft:1,flexDirection:"row",children:[u&&g(C,{color:"grey",children:"\u2191 "}),h&&g(C,{color:"grey",children:"\u2193 "})]})]})}c(uh,"Logs");const rs=[{value:"sync",label:"Continue (overwrite/delete)",key:""},{value:"exit",label:"Cancel",key:""}];function hh(){const{state:s,resolveConflicts:e,exit:t}=Se(),[n,r]=J(0),[i,o]=J(!1),[a,l]=J(!1);return nt((u,h)=>{if(!i){if(h.ctrl&&u.toLowerCase()==="r"){l(!a);return}h.upArrow?r(f=>f>0?f-1:rs.length-1):h.downArrow?r(f=>f<rs.length-1?f+1:0):u.toLowerCase()==="y"?r(0):u.toLowerCase()==="n"?r(1):(h.return||u===" ")&&(o(!0),rs[n].value==="sync"?e({watch:!0}):t())}}),Ve(()=>{s!==x.CONFLICTS&&i&&o(!1)},[s,i]),E(v,{flexDirection:"column",paddingTop:1,children:[g(v,{children:g(v,{flexDirection:"row",gap:2,children:g(C,{bold:!0,color:"white",children:"Conflicts with remote"})})}),g(v,{children:g(C,{color:"grey",children:"The remote workspace has changes that aren't in your local workspace:"})}),g(v,{marginTop:1,marginLeft:2,children:g(Mr,{isExpanded:a})}),E(v,{marginTop:2,flexDirection:"row",gap:1,children:[g(C,{color:"white",bold:!0,children:"What would you like to do?"}),g(C,{color:"grey",children:"[up/down, enter]"})]}),g(v,{children:i?E(v,{flexDirection:"row",gap:1,children:[g(wn,{type:"dots"}),g(C,{color:"blue",bold:!0,children:"Syncing with remote..."})]}):g(v,{flexDirection:"column",children:rs.map((u,h)=>g(v,{flexDirection:"column",children:E(v,{flexDirection:"row",gap:1,children:[g(C,{color:n===h?"cyan":"grey",children:n===h?"\u25B6":" "}),g(C,{color:n===h?"cyan":"grey",bold:n===h,children:u.label})]})},u.value))})})]})}c(hh,"ResolveChangesUI");const fh={[Ae.UPDATE]:{incoming:{label:"Elements updated in remote",description:"(to be overwritten from remote)"},outgoing:{label:"Elements updated locally",description:"(to be pushed to remote)"}},[Ae.DELETE]:{incoming:{label:"Elements not existing in remote",description:"(to be deleted locally)"},outgoing:{label:"Elements deleted locally",description:"(to be deleted from remote)"}},[Ae.CREATE]:{incoming:{label:"Elements created in remote",description:"(to be created locally)"},outgoing:{label:"Elements created locally",description:"(to be created in remote)"}}};function Mr({isExpanded:s}){const{conflicts:e}=Se(),t=5,n=yc(()=>{const r={};return e.forEach(i=>{const o=`${i.type}-${i.direction}`;r[o]||(r[o]=[]),r[o].push(i)}),r},[e]);return g(v,{flexDirection:"column",children:Object.entries(n).map(([r,i])=>{if(i.length===0)return null;const[o,a]=r.split("-"),l=fh[o][a];return E(v,{flexDirection:"column",children:[E(v,{flexDirection:"row",gap:1,children:[E(C,{color:"yellow",children:[l.label," (",i.length,")"]}),g(C,{color:"white",children:l.description})]}),(s?i:i.slice(0,t)).map(u=>g(v,{marginLeft:2,children:E(C,{color:"grey",children:["\u2022 ",u.element.id," (",u.element.relativePath,")"]})},u.element.id)),!s&&i.length>t&&g(v,{marginLeft:2,children:E(C,{color:"cyan",children:["... and ",i.length-t," more (press Ctrl+R to show all)"]})}),s&&i.length>t&&g(v,{marginLeft:2,children:g(C,{color:"cyan",children:"(press Ctrl+R to collapse)"})})]},r)})})}c(Mr,"Conflicts");function dh(){const{config:s,state:e,logs:t,currentWorkspace:n,pull:r}=Se(),i=n?.name,o=i?ra(i,30):s?.workspaceKey,a=Math.min(100,process.stdout.columns||100);return Ve(()=>{r({watch:!0})},[]),E(v,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:a,children:[g(v,{marginTop:-1,marginBottom:1,children:E(v,{flexDirection:"row",gap:1,children:[g(C,{bold:!0,children:"\u{1F504} Workspace"}),E(C,{color:mh(e),children:[" [",ph(e),"] "]})]})}),E(v,{children:[g(v,{width:12,children:g(C,{color:"grey",children:"Local:"})}),g(C,{color:"grey",children:process.cwd()})]}),E(v,{children:[g(v,{width:12,children:g(C,{color:"grey",children:"Remote:"})}),s?.workspaceKey?E(C,{color:"grey",children:[o," [o: open in console] [w: change]"]}):E(C,{children:[g(C,{color:"yellow",children:"not selected"})," [w: select]"]})]}),e===x.CONFLICTS?g(hh,{}):E(Ns,{children:[g(v,{paddingTop:1,children:g(Nr,{})}),t.length>0&&g(uh,{})]})]})}c(dh,"Workspace");function ph(s){switch(s){case x.PULLING:return"pulling";case x.PUSHING:return"pushing";case x.CONFLICTS:return"conflicts";case x.SYNCED:return"synced";case x.ERROR:return"error";case x.WATCHING:return"tracking changes";case x.RESOLVING:return"resolving";case x.NOT_SYNCED:return"not synced";case x.INITIALIZED:return"initialized";case x.SETTING_UP:return"setup required";default:return"unknown"}}c(ph,"getStatusDisplay");function mh(s){switch(s){case x.PULLING:return"yellow";case x.PUSHING:return"yellow";case x.CONFLICTS:return"red";case x.SYNCED:return"green";case x.ERROR:return"red";case x.WATCHING:return"green";case x.RESOLVING:return"yellow";case x.NOT_SYNCED:return"grey";case x.SETTING_UP:return"yellow";default:return"grey"}}c(mh,"getStatusColor");const gh="https://console.integration.app/w";function yh(){const s=nh(),e=wc(!0),{exit:t,state:n}=Se(),[r,i]=J(null),o=r??(n===x.SETTING_UP?"setup":"main");nt(l=>{o==="main"&&(l==="w"&&i("workspace-selection"),l==="a"&&i("add-mcp-server"),l==="o"&&n===x.INITIALIZED&&a(),l==="s"&&i("setup"))});async function a(){try{const l=await Bi(s),u=`${gh}/${l}`,h=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";jc(`${h} "${u}"`)}catch(l){console.error("Failed to open workspace:",l),t()}}return c(a,"handleOpenWorkspace"),Ve(()=>(e.current=!0,()=>{e.current=!1}),[]),o==="workspace-selection"?g(ia,{onExit:c(()=>i(null),"onExit")}):o==="add-mcp-server"?g(sh,{onExit:c(()=>i(null),"onExit"),onComplete:c(()=>i(null),"onComplete")}):o==="setup"?g(oa,{onComplete:c(()=>i(null),"onComplete")},Date.now()):g(Ir,{children:E(v,{flexDirection:"column",children:[g(v,{flexGrow:1,children:g(ih,{})}),g(dh,{}),g(v,{paddingLeft:2,children:g(C,{color:"grey",children:"[s: (re-)setup]"})})]})})}c(yh,"Main");const Rr=mc(process.argv.slice(2)),aa=Rr.cwd?fc(Rr.cwd):process.cwd(),wh=new ta(Gt.Agent,aa);Rr.verbose&&b.setVerboseMode(!0);const bh=c(()=>g(ns,{cwd:aa,membraneCLIService:wh,children:g(yh,{})}),"App");function Sh(){gn(g(bh,{}))}c(Sh,"runAgent");function vh(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(`
142
+ `)).action(t=>{t.key&&t.secret?Dt.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)):gn(st.createElement(ns,{membraneCLIService:e,children:st.createElement(oa,{onComplete:c(()=>process.exit(0),"onComplete")})}))})}c(vh,"setupInitCommand");async function ca(s,e,t){const n={iss:s,exp:Math.floor(Date.now()/1e3)+600,isAdmin:!0};return t&&(n.id=t),Ds.sign(n,e)}c(ca,"generateAdminAccessToken");async function Ch(s,e){return(await js.get(`${s}/docs-json`,{headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}})).data}c(Ch,"fetchOpenApiSchema");function la(s,e=!0){if(!s)return e?ne.string():ne.string().optional();let t;switch(s.type){case"integer":t=ne.coerce.number().int();break;case"number":t=ne.coerce.number();break;case"boolean":t=ne.coerce.boolean();break;case"string":default:t=ne.string();break}return s.format==="uuid"?t=ne.string().uuid():s.format==="email"?t=ne.string().email():s.format==="date"?t=ne.string().regex(/^\d{4}-\d{2}-\d{2}$/):s.format==="date-time"&&(t=ne.string().datetime()),s.enum&&(t=ne.enum(s.enum)),(s.type==="integer"||s.type==="number")&&(s.minimum!==void 0&&(t=t.min(s.minimum)),s.maximum!==void 0&&(t=t.max(s.maximum))),s.type==="string"&&(s.minLength!==void 0&&(t=t.min(s.minLength)),s.maxLength!==void 0&&(t=t.max(s.maxLength))),e?t:t.optional()}c(la,"convertOpenApiSchemaToZod");function ua(s){const e=s.match(/\{([^}]+)\}/g);return e?e.map(t=>t.slice(1,-1)):[]}c(ua,"extractPathParameters");function kh(s,e,t,n,r,i,o){const a=s.operationId||`${t}_${e.replace(/[^a-zA-Z0-9]/g,"_")}`,l=s.description||s.summary||`${t.toUpperCase()} ${e}`,u={},h={},f={};if(s.parameters){for(const m of s.parameters)if(m.in==="path")h[m.name]=la(m.schema,!0).describe(m.description||`Path parameter: ${m.name}`);else if(m.in==="query"){const y=m.required===!0;f[m.name]=la(m.schema,y).describe(m.description||`Query parameter: ${m.name}`)}}Object.keys(h).length>0&&(u.params=ne.object(h).describe("Path parameters")),Object.keys(f).length>0&&(u.query=ne.object(f).describe("Query parameters")),s.requestBody&&s.requestBody.content&&s.requestBody.content["application/json"]&&(u.body=ne.any().describe("Request body"));const p=Object.keys(u).length>0?ne.object(u):ne.object({});return{name:a,description:l,parameters:p,async execute(m){try{const y=ua(e);if(y.length>0){if(!m.params)throw new Error(`Missing required path parameters: ${y.join(", ")}`);const $=y.filter(N=>!(N in m.params));if($.length>0)throw new Error(`Missing required path parameters: ${$.join(", ")}`)}let d=`${n}${e}`;if(m.params)for(const[$,N]of Object.entries(m.params)){const K=`{${$}}`;d.includes(K)&&(d=d.replace(K,String(N)))}const w=ua(d);if(w.length>0)throw new Error(`Unresolved path parameters: ${w.join(", ")}`);const k=new URLSearchParams;if(m.query)for(const[$,N]of Object.entries(m.query))N!=null&&k.append($,String(N));k.toString()&&(d+=`?${k.toString()}`);const _=await ca(r,i,o),O={method:t.toUpperCase(),headers:{Authorization:`Bearer ${_}`,"Content-Type":"application/json"}};m.body&&t.toLowerCase()!=="get"&&(O.data=m.body);const A=await js.request({url:d,...O});return{content:[{type:"text",text:JSON.stringify(A.data,null,2)}]}}catch(y){return js.isAxiosError(y)?{content:[{type:"text",text:`Error: ${y.response?.data?`HTTP ${y.response.status}: ${y.response.statusText} - ${JSON.stringify(y.response.data)}`:`HTTP ${y.response?.status||"unknown"}: ${y.message}`}`}],isError:!0}:y instanceof Error?{content:[{type:"text",text:`Error: API call failed: ${y.message}`}],isError:!0}:{content:[{type:"text",text:"Error: API call failed with unknown error"}],isError:!0}}}}}c(kh,"createApiTool");function _h(s,e,t,n,r){const i=[];if(!s.paths)return i;for(const[o,a]of Object.entries(s.paths))if(typeof a=="object"&&a!==null){for(const[l,u]of Object.entries(a))if(["get","post","put","delete","patch"].includes(l)&&u&&typeof u=="object"){const h=kh(u,o,l,e,t,n,r);i.push(h)}}return i}c(_h,"convertOpenApiToTools");function Th(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(`
143
+ `)).action(async()=>{try{process.env.FASTMCP_SUPPRESS_WARNINGS="true";const e=On();e||(console.error("No configuration found. Please set MEMBRANE_WORKSPACE_KEY and MEMBRANE_WORKSPACE_SECRET environment variables, or run `membrane init` first."),process.exit(1)),(!e.workspaceKey||!e.workspaceSecret)&&(console.error("Missing workspace credentials"),process.exit(1));const t=e.apiUri||Us,n=await ca(e.workspaceKey,e.workspaceSecret,e.testCustomerId),r=await Ch(t,n),i=_h(r,t,e.workspaceKey,e.workspaceSecret,e.testCustomerId),o=new Jc({name:"Membrane API",instructions:`This MCP server lets you interact with Membrane to configure, run, and troubleshoot integrations.
144
144
  Use it for anything related to Membrane or integrations.
145
- `,version:"1.0.0"});for(const u of i){const h=u.execute;u.execute=async f=>(Xu(process.pid,process.cwd()),h(f)),o.addTool(u)}_r({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(()=>{_r({processId:process.pid,cwd:process.cwd(),lastActivity:new Date().toISOString()})},5e3),l=c(async()=>{clearInterval(a),Vt(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",()=>{Vt(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(kh,"setupMcpCommand");const _h={info:"\u{1F4DD}",success:"\u2728",warning:"\u26A0\uFE0F",error:"\u274C",debug:"\u{1F50D}"},Th={info:T.blue,success:T.green,warning:T.yellow,error:T.red,debug:T.gray};class X{static{c(this,"Logger")}static formatMessage(e,t,n={}){const r=n.timestamp?`${T.gray(new Date().toISOString())} `:"",i=n.prefix?`${T.gray(n.prefix)} `:"",o=n.suffix?` ${T.gray(n.suffix)}`:"",a=_h[t],l=Th[t];return`${r}${a} ${i}${l(e)}${o}`}static info(e,t){let n=T.blue;if(t?.color&&(n=T[t.color.toLowerCase()]||T.blue),t?.timestamp){const r=new Date().toLocaleTimeString();console.debug(`${T.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(T.gray(`[${t.prefix}] ${e}`),t.error?`
145
+ `,version:"1.0.0"});for(const u of i){const h=u.execute;u.execute=async f=>(Zu(process.pid,process.cwd()),h(f)),o.addTool(u)}Tr({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(()=>{Tr({processId:process.pid,cwd:process.cwd(),lastActivity:new Date().toISOString()})},5e3),l=c(async()=>{clearInterval(a),Vt(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",()=>{Vt(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(Th,"setupMcpCommand");const Eh={info:"\u{1F4DD}",success:"\u2728",warning:"\u26A0\uFE0F",error:"\u274C",debug:"\u{1F50D}"},Ah={info:T.blue,success:T.green,warning:T.yellow,error:T.red,debug:T.gray};class X{static{c(this,"Logger")}static formatMessage(e,t,n={}){const r=n.timestamp?`${T.gray(new Date().toISOString())} `:"",i=n.prefix?`${T.gray(n.prefix)} `:"",o=n.suffix?` ${T.gray(n.suffix)}`:"",a=Eh[t],l=Ah[t];return`${r}${a} ${i}${l(e)}${o}`}static info(e,t){let n=T.blue;if(t?.color&&(n=T[t.color.toLowerCase()]||T.blue),t?.timestamp){const r=new Date().toLocaleTimeString();console.debug(`${T.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(T.gray(`[${t.prefix}] ${e}`),t.error?`
146
146
  ${T.red(t.error)}`:""):console.debug(T.gray(e),t?.error?`
147
- ${T.red(t.error)}`:"")}static step(e,t){}static header(e){console.debug(),console.debug(T.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 Eh(s){s.command("open").description("Open the workspace in the browser").addHelpText("after",["","Examples:"," membrane open # Open workspace in browser",""].join(`
148
- `)).action(async()=>{try{X.header("Opening Workspace in Browser"),X.info("Loading configuration...");const e=An();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");X.info("Retrieving workspace ID...");const n=`https://console.integration.app/w/${await Ki(process.cwd())}`;X.info(`Opening ${n}...`);const{default:r}=await import("open");await r(n),X.success("Browser opened successfully")}catch(e){e instanceof Error&&(X.error(e.message),process.exit(1)),X.error("An unknown error occurred"),process.exit(1)}})}c(Eh,"setupOpenCommand");function Oh(s){return g(Ar,{children:g(Ah,{options:s})})}c(Oh,"Pull");function Ah({options:s}){const{logs:e,state:t,conflicts:n,pull:r}=Se();Ve(()=>{r(s)},[]);const i=t===x.CONFLICTS;return E(v,{flexDirection:"column",children:[e.slice().map((o,a)=>g(C,{color:ss(o.type),children:o.message},o.timestamp+a)),i&&E(Ns,{children:[E(C,{color:"yellow",bold:!0,children:["Found ",n.length," conflicts with remote:"]}),g(xr,{isExpanded:!1}),g(C,{color:"red",children:"Out of sync with remote, use --force to overwrite conflict changes"})]}),t===x.SYNCED&&g($r,{})]})}c(Ah,"PullActivity");function ua(){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(ua,"getWatchModeCallback");function Ih(s,e){s.command("pull").description("Pull workspace data from specified workspace").option("--force","Overwrite conflicts with remote data",!1).option("--watch","Watch for changes and pull automatically",!1).option("--all-connectors","Include public connectors in export - to push to the self-hosted instance",!1).option("--save-logs","Save logs to a file",!1).option("--verbose","Show verbose debug logs",!1).addHelpText("after",["","Examples:"," membrane pull # Pull from default workspace"," membrane pull --force # Overwrite conflicts with remote data"," membrane pull --all-connectors # Pull all connectors"," membrane pull --watch # Watch for changes and pull automatically",""].join(`
149
- `)).action(async t=>{const n=t.watch?ua():()=>process.exit(0);gn(rt.createElement(ns,{membraneCLIService:e,children:rt.createElement(Oh,{...t,onComplete:n})}))})}c(Ih,"setupPullCommand");function $h(s){return g(Ar,{children:g(Nh,{options:s})})}c($h,"Push");function Nh({options:s}){const{logs:e,state:t,conflicts:n,push:r}=Se();Ve(()=>{r(s)},[]);const i=t===x.CONFLICTS;return E(v,{flexDirection:"column",children:[e.slice().map((o,a)=>g(C,{color:ss(o.type),children:o.message},o.timestamp+a)),i&&E(Ns,{children:[E(C,{color:"yellow",bold:!0,children:["Found ",n.length," conflicts with remote:"]}),g(xr,{isExpanded:!1}),g(C,{color:"red",children:"Out of sync with remote, use --force to overwrite conflict changes"})]}),t===x.SYNCED&&g($r,{})]})}c(Nh,"PushActivity");function xh(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).addHelpText("after",["","Examples:"," membrane push # Push to default workspace"," membrane push --force # Overwrite conflicts with local data",""].join(`
150
- `)).action(async t=>{const n=t.watch?ua():()=>process.exit(0);gn(rt.createElement(ns,{membraneCLIService:e,children:rt.createElement($h,{...t,onComplete:n})}))})}c(xh,"setupPushCommand");class Mh{static{c(this,"BaseRunner")}constructor(e){if(this.options=e,this.fsPaths=Ws(),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 R(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(R,"__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 ha=c(function(){const{crypto:s}=globalThis;if(s?.randomUUID)return ha=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 Yt(s){return typeof s=="object"&&s!==null&&("name"in s&&s.name==="AbortError"||"message"in s&&String(s.message).includes("FetchRequestCanceledException"))}c(Yt,"isAbortError");const Rr=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 D extends Error{static{c(this,"AnthropicError")}}class re extends D{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 is({message:n,cause:Rr(t)});const i=t;return e===400?new da(e,i,n,r):e===401?new pa(e,i,n,r):e===403?new ma(e,i,n,r):e===404?new ga(e,i,n,r):e===409?new ya(e,i,n,r):e===422?new wa(e,i,n,r):e===429?new ba(e,i,n,r):e>=500?new Sa(e,i,n,r):new re(e,i,n,r)}}class ve extends re{static{c(this,"APIUserAbortError")}constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}}class is 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 fa extends is{static{c(this,"APIConnectionTimeoutError")}constructor({message:e}={}){super({message:e??"Request timed out."})}}class da extends re{static{c(this,"BadRequestError")}}class pa extends re{static{c(this,"AuthenticationError")}}class ma extends re{static{c(this,"PermissionDeniedError")}}class ga extends re{static{c(this,"NotFoundError")}}class ya extends re{static{c(this,"ConflictError")}}class wa extends re{static{c(this,"UnprocessableEntityError")}}class ba extends re{static{c(this,"RateLimitError")}}class Sa extends re{static{c(this,"InternalServerError")}}const Rh=/^[a-z][a-z0-9+.-]*:/i,Ph=c(s=>Rh.test(s),"isAbsoluteURL");let Pr=c(s=>(Pr=Array.isArray,Pr(s)),"isArray"),va=Pr;function Ca(s){return typeof s!="object"?{}:s??{}}c(Ca,"maybeObj");function Lh(s){if(!s)return!0;for(const e in s)return!1;return!0}c(Lh,"isEmptyObj");function Dh(s,e){return Object.prototype.hasOwnProperty.call(s,e)}c(Dh,"hasOwn");const jh=c((s,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new D(`${s} must be an integer`);if(e<0)throw new D(`${s} must be a positive integer`);return e},"validatePositiveInteger"),ka=c(s=>{try{return JSON.parse(s)}catch{return}},"safeJSON"),Fh=c(s=>new Promise(e=>setTimeout(e,s)),"sleep"),Ot="0.62.0",Kh=c(()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u","isRunningInBrowser");function Bh(){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(Bh,"getDetectedPlatform");const qh=c(()=>{const s=Bh();if(s==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Ot,"X-Stainless-OS":Ta(Deno.build.os),"X-Stainless-Arch":_a(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":Ot,"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":Ot,"X-Stainless-OS":Ta(globalThis.process.platform??"unknown"),"X-Stainless-Arch":_a(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};const e=Uh();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Ot,"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":Ot,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}},"getPlatformProperties");function Uh(){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(Uh,"getBrowserInfo");const _a=c(s=>s==="x32"?"x32":s==="x86_64"||s==="x64"?"x64":s==="arm"?"arm":s==="aarch64"||s==="arm64"?"arm64":s?`other:${s}`:"unknown","normalizeArch"),Ta=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 Ea;const Wh=c(()=>Ea??(Ea=qh()),"getPlatformHeaders");function Jh(){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(Jh,"getDefaultFetch");function Oa(...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(Oa,"makeReadableStream");function Aa(s){let e=Symbol.asyncIterator in s?s[Symbol.asyncIterator]():s[Symbol.iterator]();return Oa({start(){},async pull(t){const{done:n,value:r}=await e.next();n?t.close():t.enqueue(r)},async cancel(){await e.return?.()}})}c(Aa,"ReadableStreamFrom");function Lr(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(Lr,"ReadableStreamToAsyncIterable");async function Hh(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(Hh,"CancelReadableStream");const Vh=c(({headers:s,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)}),"FallbackEncoder");function Gh(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(Gh,"concatBytes");let Ia;function Dr(s){let e;return(Ia??(e=new globalThis.TextEncoder,Ia=e.encode.bind(e)))(s)}c(Dr,"encodeUTF8");let $a;function Na(s){let e;return($a??(e=new globalThis.TextDecoder,$a=e.decode.bind(e)))(s)}c(Na,"decodeUTF8");var fe,de;class Xt{static{c(this,"LineDecoder")}constructor(){fe.set(this,void 0),de.set(this,void 0),R(this,fe,new Uint8Array),R(this,de,null)}decode(e){if(e==null)return[];const t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?Dr(e):e;R(this,fe,Gh([S(this,fe,"f"),t]));const n=[];let r;for(;(r=zh(S(this,fe,"f"),S(this,de,"f")))!=null;){if(r.carriage&&S(this,de,"f")==null){R(this,de,r.index);continue}if(S(this,de,"f")!=null&&(r.index!==S(this,de,"f")+1||r.carriage)){n.push(Na(S(this,fe,"f").subarray(0,S(this,de,"f")-1))),R(this,fe,S(this,fe,"f").subarray(S(this,de,"f"))),R(this,de,null);continue}const i=S(this,de,"f")!==null?r.preceding-1:r.preceding,o=Na(S(this,fe,"f").subarray(0,i));n.push(o),R(this,fe,S(this,fe,"f").subarray(r.index)),R(this,de,null)}return n}flush(){return S(this,fe,"f").length?this.decode(`
147
+ ${T.red(t.error)}`:"")}static step(e,t){}static header(e){console.debug(),console.debug(T.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 Oh(s){s.command("open").description("Open the workspace in the browser").addHelpText("after",["","Examples:"," membrane open # Open workspace in browser",""].join(`
148
+ `)).action(async()=>{try{X.header("Opening Workspace in Browser"),X.info("Loading configuration...");const e=On();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");X.info("Retrieving workspace ID...");const n=`https://console.integration.app/w/${await Bi(process.cwd())}`;X.info(`Opening ${n}...`);const{default:r}=await import("open");await r(n),X.success("Browser opened successfully")}catch(e){e instanceof Error&&(X.error(e.message),process.exit(1)),X.error("An unknown error occurred"),process.exit(1)}})}c(Oh,"setupOpenCommand");function Ih(s){return g(Ir,{children:g($h,{options:s})})}c(Ih,"Pull");function $h({options:s}){const{logs:e,state:t,conflicts:n,pull:r}=Se();Ve(()=>{r(s)},[]);const i=t===x.CONFLICTS;return E(v,{flexDirection:"column",children:[e.slice().map((o,a)=>g(C,{color:ss(o.type),children:o.message},o.timestamp+a)),i&&E(Ns,{children:[E(C,{color:"yellow",bold:!0,children:["Found ",n.length," conflicts with remote:"]}),g(Mr,{isExpanded:!1}),g(C,{color:"red",children:"Out of sync with remote, use --force to overwrite conflict changes"})]}),t===x.SYNCED&&g(Nr,{})]})}c($h,"PullActivity");function ha(){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(ha,"getWatchModeCallback");function Nh(s,e){s.command("pull").description("Pull workspace data from specified workspace").option("--force","Overwrite conflicts with remote data",!1).option("--watch","Watch for changes and pull automatically",!1).option("--all-connectors","Include public connectors in export - to push to the self-hosted instance",!1).option("--save-logs","Save logs to a file",!1).option("--verbose","Show verbose debug logs",!1).addHelpText("after",["","Examples:"," membrane pull # Pull from default workspace"," membrane pull --force # Overwrite conflicts with remote data"," membrane pull --all-connectors # Pull all connectors"," membrane pull --watch # Watch for changes and pull automatically",""].join(`
149
+ `)).action(async t=>{const n=t.watch?ha():()=>process.exit(0);gn(st.createElement(ns,{membraneCLIService:e,children:st.createElement(Ih,{...t,onComplete:n})}))})}c(Nh,"setupPullCommand");function xh(s){return g(Ir,{children:g(Mh,{options:s})})}c(xh,"Push");function Mh({options:s}){const{logs:e,state:t,conflicts:n,push:r}=Se();Ve(()=>{r(s)},[]);const i=t===x.CONFLICTS;return E(v,{flexDirection:"column",children:[e.slice().map((o,a)=>g(C,{color:ss(o.type),children:o.message},o.timestamp+a)),i&&E(Ns,{children:[E(C,{color:"yellow",bold:!0,children:["Found ",n.length," conflicts with remote:"]}),g(Mr,{isExpanded:!1}),g(C,{color:"red",children:"Out of sync with remote, use --force to overwrite conflict changes"})]}),t===x.SYNCED&&g(Nr,{})]})}c(Mh,"PushActivity");function Rh(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).addHelpText("after",["","Examples:"," membrane push # Push to default workspace"," membrane push --force # Overwrite conflicts with local data",""].join(`
150
+ `)).action(async t=>{const n=t.watch?ha():()=>process.exit(0);gn(st.createElement(ns,{membraneCLIService:e,children:st.createElement(xh,{...t,onComplete:n})}))})}c(Rh,"setupPushCommand");class Ph{static{c(this,"BaseRunner")}constructor(e){if(this.options=e,this.fsPaths=Ws(),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 R(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(R,"__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 fa=c(function(){const{crypto:s}=globalThis;if(s?.randomUUID)return fa=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 Yt(s){return typeof s=="object"&&s!==null&&("name"in s&&s.name==="AbortError"||"message"in s&&String(s.message).includes("FetchRequestCanceledException"))}c(Yt,"isAbortError");const Pr=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 L extends Error{static{c(this,"AnthropicError")}}class re extends L{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 is({message:n,cause:Pr(t)});const i=t;return e===400?new pa(e,i,n,r):e===401?new ma(e,i,n,r):e===403?new ga(e,i,n,r):e===404?new ya(e,i,n,r):e===409?new wa(e,i,n,r):e===422?new ba(e,i,n,r):e===429?new Sa(e,i,n,r):e>=500?new va(e,i,n,r):new re(e,i,n,r)}}class ve extends re{static{c(this,"APIUserAbortError")}constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}}class is 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 da extends is{static{c(this,"APIConnectionTimeoutError")}constructor({message:e}={}){super({message:e??"Request timed out."})}}class pa extends re{static{c(this,"BadRequestError")}}class ma extends re{static{c(this,"AuthenticationError")}}class ga extends re{static{c(this,"PermissionDeniedError")}}class ya extends re{static{c(this,"NotFoundError")}}class wa extends re{static{c(this,"ConflictError")}}class ba extends re{static{c(this,"UnprocessableEntityError")}}class Sa extends re{static{c(this,"RateLimitError")}}class va extends re{static{c(this,"InternalServerError")}}const Lh=/^[a-z][a-z0-9+.-]*:/i,Dh=c(s=>Lh.test(s),"isAbsoluteURL");let Lr=c(s=>(Lr=Array.isArray,Lr(s)),"isArray"),Ca=Lr;function ka(s){return typeof s!="object"?{}:s??{}}c(ka,"maybeObj");function jh(s){if(!s)return!0;for(const e in s)return!1;return!0}c(jh,"isEmptyObj");function Fh(s,e){return Object.prototype.hasOwnProperty.call(s,e)}c(Fh,"hasOwn");const Kh=c((s,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new L(`${s} must be an integer`);if(e<0)throw new L(`${s} must be a positive integer`);return e},"validatePositiveInteger"),_a=c(s=>{try{return JSON.parse(s)}catch{return}},"safeJSON"),Bh=c(s=>new Promise(e=>setTimeout(e,s)),"sleep"),Et="0.62.0",qh=c(()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u","isRunningInBrowser");function Uh(){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(Uh,"getDetectedPlatform");const Wh=c(()=>{const s=Uh();if(s==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Et,"X-Stainless-OS":Ea(Deno.build.os),"X-Stainless-Arch":Ta(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":Et,"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":Et,"X-Stainless-OS":Ea(globalThis.process.platform??"unknown"),"X-Stainless-Arch":Ta(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};const e=Jh();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Et,"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":Et,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}},"getPlatformProperties");function Jh(){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(Jh,"getBrowserInfo");const Ta=c(s=>s==="x32"?"x32":s==="x86_64"||s==="x64"?"x64":s==="arm"?"arm":s==="aarch64"||s==="arm64"?"arm64":s?`other:${s}`:"unknown","normalizeArch"),Ea=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 Aa;const Hh=c(()=>Aa??(Aa=Wh()),"getPlatformHeaders");function Vh(){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(Vh,"getDefaultFetch");function Oa(...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(Oa,"makeReadableStream");function Ia(s){let e=Symbol.asyncIterator in s?s[Symbol.asyncIterator]():s[Symbol.iterator]();return Oa({start(){},async pull(t){const{done:n,value:r}=await e.next();n?t.close():t.enqueue(r)},async cancel(){await e.return?.()}})}c(Ia,"ReadableStreamFrom");function Dr(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(Dr,"ReadableStreamToAsyncIterable");async function Gh(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(Gh,"CancelReadableStream");const zh=c(({headers:s,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)}),"FallbackEncoder");function Yh(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(Yh,"concatBytes");let $a;function jr(s){let e;return($a??(e=new globalThis.TextEncoder,$a=e.encode.bind(e)))(s)}c(jr,"encodeUTF8");let Na;function xa(s){let e;return(Na??(e=new globalThis.TextDecoder,Na=e.decode.bind(e)))(s)}c(xa,"decodeUTF8");var fe,de;class Xt{static{c(this,"LineDecoder")}constructor(){fe.set(this,void 0),de.set(this,void 0),R(this,fe,new Uint8Array),R(this,de,null)}decode(e){if(e==null)return[];const t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?jr(e):e;R(this,fe,Yh([S(this,fe,"f"),t]));const n=[];let r;for(;(r=Xh(S(this,fe,"f"),S(this,de,"f")))!=null;){if(r.carriage&&S(this,de,"f")==null){R(this,de,r.index);continue}if(S(this,de,"f")!=null&&(r.index!==S(this,de,"f")+1||r.carriage)){n.push(xa(S(this,fe,"f").subarray(0,S(this,de,"f")-1))),R(this,fe,S(this,fe,"f").subarray(S(this,de,"f"))),R(this,de,null);continue}const i=S(this,de,"f")!==null?r.preceding-1:r.preceding,o=xa(S(this,fe,"f").subarray(0,i));n.push(o),R(this,fe,S(this,fe,"f").subarray(r.index)),R(this,de,null)}return n}flush(){return S(this,fe,"f").length?this.decode(`
151
151
  `):[]}}fe=new WeakMap,de=new WeakMap,Xt.NEWLINE_CHARS=new Set([`
152
- `,"\r"]),Xt.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function zh(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(zh,"findNewlineIndex");function Yh(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(Yh,"findDoubleNewlineIndex");const os={off:0,error:200,warn:300,info:400,debug:500},xa=c((s,e,t)=>{if(s){if(Dh(os,s))return s;ie(t).warn(`${e} was set to ${JSON.stringify(s)}, expected one of ${JSON.stringify(Object.keys(os))}`)}},"parseLogLevel");function Qt(){}c(Qt,"noop");function as(s,e,t){return!e||os[s]>os[t]?Qt:e[s].bind(e)}c(as,"makeLogFn");const Xh={error:Qt,warn:Qt,info:Qt,debug:Qt};let Ma=new WeakMap;function ie(s){const e=s.logger,t=s.logLevel??"off";if(!e)return Xh;const n=Ma.get(e);if(n&&n[0]===t)return n[1];const r={error:as("error",e,t),warn:as("warn",e,t),info:as("info",e,t),debug:as("debug",e,t)};return Ma.set(e,[t,r]),r}c(ie,"loggerFor");const tt=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 Zt;class Ee{static{c(this,"Stream")}constructor(e,t,n){this.iterator=e,Zt.set(this,void 0),this.controller=t,R(this,Zt,n)}static fromSSEResponse(e,t,n){let r=!1;const i=n?ie(n):console;async function*o(){if(r)throw new D("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");r=!0;let a=!1;try{for await(const l of Qh(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,ka(l.data)??l.data,void 0,e.headers)}a=!0}catch(l){if(Yt(l))return;throw l}finally{a||t.abort()}}return c(o,"iterator"),new Ee(o,t,n)}static fromReadableStream(e,t,n){let r=!1;async function*i(){const a=new Xt,l=Lr(e);for await(const u of l)for(const h of a.decode(u))yield h;for(const u of a.flush())yield u}c(i,"iterLines");async function*o(){if(r)throw new D("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(Yt(l))return;throw l}finally{a||t.abort()}}return c(o,"iterator"),new Ee(o,t,n)}[(Zt=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 Ee(()=>r(e),this.controller,S(this,Zt,"f")),new Ee(()=>r(t),this.controller,S(this,Zt,"f"))]}toReadableStream(){const e=this;let t;return Oa({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=Dr(JSON.stringify(r)+`
153
- `);n.enqueue(o)}catch(r){n.error(r)}},async cancel(){await t.return?.()}})}}async function*Qh(s,e){if(!s.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new D("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 D("Attempted to iterate over a response with no body");const t=new ef,n=new Xt,r=Lr(s.body);for await(const i of Zh(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(Qh,"_iterSSEMessages");async function*Zh(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"?Dr(t):t;let r=new Uint8Array(e.length+n.length);r.set(e),r.set(n,e.length),e=r;let i;for(;(i=Yh(e))!==-1;)yield e.slice(0,i),e=e.slice(i)}e.length>0&&(yield e)}c(Zh,"iterSSEChunks");class ef{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(`
154
- `),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]=tf(e,":");return r.startsWith(" ")&&(r=r.substring(1)),t==="event"?this.event=r:t==="data"&&this.data.push(r),null}}function tf(s,e){const t=s.indexOf(e);return t!==-1?[s.substring(0,t),e,s.substring(t+e.length)]:[s,"",""]}c(tf,"partition");async function Ra(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):Ee.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 Pa(f,t)}return await t.text()})();return ie(s).debug(`[${n}] response parsed`,tt({retryOfRequestLogID:r,url:t.url,status:t.status,body:o,durationMs:Date.now()-i})),o}c(Ra,"defaultParseResponse");function Pa(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(Pa,"addRequestID");var en;class Os extends Promise{static{c(this,"APIPromise")}constructor(e,t,n=Ra){super(r=>{r(null)}),this.responsePromise=t,this.parseResponse=n,en.set(this,void 0),R(this,en,e)}_thenUnwrap(e){return new Os(S(this,en,"f"),this.responsePromise,async(t,n)=>Pa(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,en,"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)}}en=new WeakMap;var cs;class nf{static{c(this,"AbstractPage")}constructor(e,t,n,r){cs.set(this,void 0),R(this,cs,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 D("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await S(this,cs,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(cs=new WeakMap,Symbol.asyncIterator)](){for await(const e of this.iterPages())for(const t of e.getPaginatedItems())yield t}}class sf extends Os{static{c(this,"PagePromise")}constructor(e,t,n){super(e,t,async(r,i)=>new n(r,i.response,await Ra(r,i),i.options))}async*[Symbol.asyncIterator](){const e=await this;for await(const t of e)yield t}}class tn extends nf{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:{...Ca(this.options.query),before_id:t}}:null}const e=this.last_id;return e?{...this.options,query:{...Ca(this.options.query),after_id:e}}:null}}const La=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 At(s,e,t){return La(),new File(s,e??"unknown_file",t)}c(At,"makeFile");function ls(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(ls,"getName");const Da=c(s=>s!=null&&typeof s=="object"&&typeof s[Symbol.asyncIterator]=="function","isAsyncIterable"),rf=c(async(s,e)=>({...s,body:await af(s.body,e)}),"multipartFormRequestOptions"),ja=new WeakMap;function of(s){const e=typeof s=="function"?s:s.fetch,t=ja.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 ja.set(e,n),n}c(of,"supportsFormData");const af=c(async(s,e)=>{if(!await of(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])=>jr(t,n,r))),t},"createForm"),cf=c(s=>s instanceof Blob&&"name"in s,"isNamedBlob"),jr=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,At([await t.blob()],ls(t),n))}else if(Da(t))s.append(e,At([await new Response(Aa(t)).blob()],ls(t)));else if(cf(t))s.append(e,At([t],ls(t),{type:t.type}));else if(Array.isArray(t))await Promise.all(t.map(n=>jr(s,e+"[]",n)));else if(typeof t=="object")await Promise.all(Object.entries(t).map(([n,r])=>jr(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"),Fa=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"),lf=c(s=>s!=null&&typeof s=="object"&&typeof s.name=="string"&&typeof s.lastModified=="number"&&Fa(s),"isFileLike"),uf=c(s=>s!=null&&typeof s=="object"&&typeof s.url=="string"&&typeof s.blob=="function","isResponseLike");async function hf(s,e,t){if(La(),s=await s,e||(e=ls(s)),lf(s))return s instanceof File&&e==null&&t==null?s:At([await s.arrayBuffer()],e??s.name,{type:s.type,lastModified:s.lastModified,...t});if(uf(s)){const r=await s.blob();return e||(e=new URL(s.url).pathname.split(/[\\/]/).pop()),At(await Fr(r),e,t)}const n=await Fr(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 At(n,e,t)}c(hf,"toFile");async function Fr(s){let e=[];if(typeof s=="string"||ArrayBuffer.isView(s)||s instanceof ArrayBuffer)e.push(s);else if(Fa(s))e.push(s instanceof Blob?s:await s.arrayBuffer());else if(Da(s))for await(const t of s)e.push(...await Fr(t));else{const t=s?.constructor?.name;throw new Error(`Unexpected data type: ${typeof s}${t?`; constructor: ${t}`:""}${ff(s)}`)}return e}c(Fr,"getBytes");function ff(s){return typeof s!="object"||s===null?"":`; props: [${Object.getOwnPropertyNames(s).map(t=>`"${t}"`).join(", ")}]`}c(ff,"propsForError");class Me{static{c(this,"APIResource")}constructor(e){this._client=e}}const Ka=Symbol.for("brand.privateNullableHeaders");function*df(s){if(!s)return;if(Ka 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():va(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=va(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(df,"iterateHeaders");const V=c(s=>{const e=new Headers,t=new Set;for(const n of s){const r=new Set;for(const[i,o]of df(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{[Ka]:!0,values:e,nulls:t}},"buildHeaders");function Ba(s){return s.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}c(Ba,"encodeURIPath");const qa=Object.freeze(Object.create(null)),pf=c((s=Ba)=>c(function(t,...n){if(t.length===1)return t[0];let r=!1;const i=[],o=t.reduce((h,f,p)=>{/[?#]/.test(f)&&(r=!0);const m=n[p];let y=(r?encodeURIComponent:s)(""+m);return p!==n.length&&(m==null||typeof m=="object"&&m.toString===Object.getPrototypeOf(Object.getPrototypeOf(m.hasOwnProperty??qa)??qa)?.toString)&&(y=m+"",i.push({start:h.length+f.length,length:y.length,error:`Value of type ${Object.prototype.toString.call(m).slice(8,-1)} is not a valid path parameter`})),h+f+(p===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((h,f)=>h.start-f.start),i.length>0){let h=0;const f=i.reduce((p,m)=>{const y=" ".repeat(m.start-h),d="^".repeat(m.length);return h=m.start+m.length,p+y+d},"");throw new D(`Path parameters result in path with invalid segments:
152
+ `,"\r"]),Xt.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function Xh(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(Xh,"findNewlineIndex");function Qh(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(Qh,"findDoubleNewlineIndex");const os={off:0,error:200,warn:300,info:400,debug:500},Ma=c((s,e,t)=>{if(s){if(Fh(os,s))return s;ie(t).warn(`${e} was set to ${JSON.stringify(s)}, expected one of ${JSON.stringify(Object.keys(os))}`)}},"parseLogLevel");function Qt(){}c(Qt,"noop");function as(s,e,t){return!e||os[s]>os[t]?Qt:e[s].bind(e)}c(as,"makeLogFn");const Zh={error:Qt,warn:Qt,info:Qt,debug:Qt};let Ra=new WeakMap;function ie(s){const e=s.logger,t=s.logLevel??"off";if(!e)return Zh;const n=Ra.get(e);if(n&&n[0]===t)return n[1];const r={error:as("error",e,t),warn:as("warn",e,t),info:as("info",e,t),debug:as("debug",e,t)};return Ra.set(e,[t,r]),r}c(ie,"loggerFor");const et=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 Zt;class Ee{static{c(this,"Stream")}constructor(e,t,n){this.iterator=e,Zt.set(this,void 0),this.controller=t,R(this,Zt,n)}static fromSSEResponse(e,t,n){let r=!1;const i=n?ie(n):console;async function*o(){if(r)throw new L("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");r=!0;let a=!1;try{for await(const l of ef(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,_a(l.data)??l.data,void 0,e.headers)}a=!0}catch(l){if(Yt(l))return;throw l}finally{a||t.abort()}}return c(o,"iterator"),new Ee(o,t,n)}static fromReadableStream(e,t,n){let r=!1;async function*i(){const a=new Xt,l=Dr(e);for await(const u of l)for(const h of a.decode(u))yield h;for(const u of a.flush())yield u}c(i,"iterLines");async function*o(){if(r)throw new L("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(Yt(l))return;throw l}finally{a||t.abort()}}return c(o,"iterator"),new Ee(o,t,n)}[(Zt=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 Ee(()=>r(e),this.controller,S(this,Zt,"f")),new Ee(()=>r(t),this.controller,S(this,Zt,"f"))]}toReadableStream(){const e=this;let t;return Oa({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=jr(JSON.stringify(r)+`
153
+ `);n.enqueue(o)}catch(r){n.error(r)}},async cancel(){await t.return?.()}})}}async function*ef(s,e){if(!s.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new L("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 L("Attempted to iterate over a response with no body");const t=new nf,n=new Xt,r=Dr(s.body);for await(const i of tf(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(ef,"_iterSSEMessages");async function*tf(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"?jr(t):t;let r=new Uint8Array(e.length+n.length);r.set(e),r.set(n,e.length),e=r;let i;for(;(i=Qh(e))!==-1;)yield e.slice(0,i),e=e.slice(i)}e.length>0&&(yield e)}c(tf,"iterSSEChunks");class nf{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(`
154
+ `),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]=sf(e,":");return r.startsWith(" ")&&(r=r.substring(1)),t==="event"?this.event=r:t==="data"&&this.data.push(r),null}}function sf(s,e){const t=s.indexOf(e);return t!==-1?[s.substring(0,t),e,s.substring(t+e.length)]:[s,"",""]}c(sf,"partition");async function Pa(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):Ee.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 La(f,t)}return await t.text()})();return ie(s).debug(`[${n}] response parsed`,et({retryOfRequestLogID:r,url:t.url,status:t.status,body:o,durationMs:Date.now()-i})),o}c(Pa,"defaultParseResponse");function La(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(La,"addRequestID");var en;class As extends Promise{static{c(this,"APIPromise")}constructor(e,t,n=Pa){super(r=>{r(null)}),this.responsePromise=t,this.parseResponse=n,en.set(this,void 0),R(this,en,e)}_thenUnwrap(e){return new As(S(this,en,"f"),this.responsePromise,async(t,n)=>La(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,en,"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)}}en=new WeakMap;var cs;class rf{static{c(this,"AbstractPage")}constructor(e,t,n,r){cs.set(this,void 0),R(this,cs,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 L("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await S(this,cs,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(cs=new WeakMap,Symbol.asyncIterator)](){for await(const e of this.iterPages())for(const t of e.getPaginatedItems())yield t}}class of extends As{static{c(this,"PagePromise")}constructor(e,t,n){super(e,t,async(r,i)=>new n(r,i.response,await Pa(r,i),i.options))}async*[Symbol.asyncIterator](){const e=await this;for await(const t of e)yield t}}class tn extends rf{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:{...ka(this.options.query),before_id:t}}:null}const e=this.last_id;return e?{...this.options,query:{...ka(this.options.query),after_id:e}}:null}}const Da=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 At(s,e,t){return Da(),new File(s,e??"unknown_file",t)}c(At,"makeFile");function ls(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(ls,"getName");const ja=c(s=>s!=null&&typeof s=="object"&&typeof s[Symbol.asyncIterator]=="function","isAsyncIterable"),af=c(async(s,e)=>({...s,body:await lf(s.body,e)}),"multipartFormRequestOptions"),Fa=new WeakMap;function cf(s){const e=typeof s=="function"?s:s.fetch,t=Fa.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 Fa.set(e,n),n}c(cf,"supportsFormData");const lf=c(async(s,e)=>{if(!await cf(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])=>Fr(t,n,r))),t},"createForm"),uf=c(s=>s instanceof Blob&&"name"in s,"isNamedBlob"),Fr=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,At([await t.blob()],ls(t),n))}else if(ja(t))s.append(e,At([await new Response(Ia(t)).blob()],ls(t)));else if(uf(t))s.append(e,At([t],ls(t),{type:t.type}));else if(Array.isArray(t))await Promise.all(t.map(n=>Fr(s,e+"[]",n)));else if(typeof t=="object")await Promise.all(Object.entries(t).map(([n,r])=>Fr(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"),Ka=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"),hf=c(s=>s!=null&&typeof s=="object"&&typeof s.name=="string"&&typeof s.lastModified=="number"&&Ka(s),"isFileLike"),ff=c(s=>s!=null&&typeof s=="object"&&typeof s.url=="string"&&typeof s.blob=="function","isResponseLike");async function df(s,e,t){if(Da(),s=await s,e||(e=ls(s)),hf(s))return s instanceof File&&e==null&&t==null?s:At([await s.arrayBuffer()],e??s.name,{type:s.type,lastModified:s.lastModified,...t});if(ff(s)){const r=await s.blob();return e||(e=new URL(s.url).pathname.split(/[\\/]/).pop()),At(await Kr(r),e,t)}const n=await Kr(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 At(n,e,t)}c(df,"toFile");async function Kr(s){let e=[];if(typeof s=="string"||ArrayBuffer.isView(s)||s instanceof ArrayBuffer)e.push(s);else if(Ka(s))e.push(s instanceof Blob?s:await s.arrayBuffer());else if(ja(s))for await(const t of s)e.push(...await Kr(t));else{const t=s?.constructor?.name;throw new Error(`Unexpected data type: ${typeof s}${t?`; constructor: ${t}`:""}${pf(s)}`)}return e}c(Kr,"getBytes");function pf(s){return typeof s!="object"||s===null?"":`; props: [${Object.getOwnPropertyNames(s).map(t=>`"${t}"`).join(", ")}]`}c(pf,"propsForError");class Me{static{c(this,"APIResource")}constructor(e){this._client=e}}const Ba=Symbol.for("brand.privateNullableHeaders");function*mf(s){if(!s)return;if(Ba 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():Ca(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=Ca(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(mf,"iterateHeaders");const V=c(s=>{const e=new Headers,t=new Set;for(const n of s){const r=new Set;for(const[i,o]of mf(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{[Ba]:!0,values:e,nulls:t}},"buildHeaders");function qa(s){return s.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}c(qa,"encodeURIPath");const Ua=Object.freeze(Object.create(null)),gf=c((s=qa)=>c(function(t,...n){if(t.length===1)return t[0];let r=!1;const i=[],o=t.reduce((h,f,p)=>{/[?#]/.test(f)&&(r=!0);const m=n[p];let y=(r?encodeURIComponent:s)(""+m);return p!==n.length&&(m==null||typeof m=="object"&&m.toString===Object.getPrototypeOf(Object.getPrototypeOf(m.hasOwnProperty??Ua)??Ua)?.toString)&&(y=m+"",i.push({start:h.length+f.length,length:y.length,error:`Value of type ${Object.prototype.toString.call(m).slice(8,-1)} is not a valid path parameter`})),h+f+(p===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((h,f)=>h.start-f.start),i.length>0){let h=0;const f=i.reduce((p,m)=>{const y=" ".repeat(m.start-h),d="^".repeat(m.length);return h=m.start+m.length,p+y+d},"");throw new L(`Path parameters result in path with invalid segments:
155
155
  ${i.map(p=>p.error).join(`
156
156
  `)}
157
157
  ${o}
158
- ${f}`)}return o},"path2"),"createPathTagFunction"),Ce=pf(Ba);class Ua extends Me{static{c(this,"Files")}list(e={},t){const{betas:n,...r}=e??{};return this._client.getAPIList("/v1/files",tn,{query:r,...t,headers:V([{"anthropic-beta":[...n??[],"files-api-2025-04-14"].toString()},t?.headers])})}delete(e,t={},n){const{betas:r}=t??{};return this._client.delete(Ce`/v1/files/${e}`,{...n,headers:V([{"anthropic-beta":[...r??[],"files-api-2025-04-14"].toString()},n?.headers])})}download(e,t={},n){const{betas:r}=t??{};return this._client.get(Ce`/v1/files/${e}/content`,{...n,headers:V([{"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(Ce`/v1/files/${e}`,{...n,headers:V([{"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",rf({body:r,...t,headers:V([{"anthropic-beta":[...n??[],"files-api-2025-04-14"].toString()},t?.headers])},this._client))}}let Wa=class extends Me{static{c(this,"Models")}retrieve(e,t={},n){const{betas:r}=t??{};return this._client.get(Ce`/v1/models/${e}?beta=true`,{...n,headers:V([{...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",tn,{query:r,...t,headers:V([{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void 0},t?.headers])})}};class As{static{c(this,"JSONLDecoder")}constructor(e,t){this.iterator=e,this.controller=t}async*decoder(){const e=new Xt;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 D("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 D("Attempted to iterate over a response with no body");return new As(Lr(e.body),t)}}let Ja=class extends Me{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:V([{"anthropic-beta":[...n??[],"message-batches-2024-09-24"].toString()},t?.headers])})}retrieve(e,t={},n){const{betas:r}=t??{};return this._client.get(Ce`/v1/messages/batches/${e}?beta=true`,{...n,headers:V([{"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",tn,{query:r,...t,headers:V([{"anthropic-beta":[...n??[],"message-batches-2024-09-24"].toString()},t?.headers])})}delete(e,t={},n){const{betas:r}=t??{};return this._client.delete(Ce`/v1/messages/batches/${e}?beta=true`,{...n,headers:V([{"anthropic-beta":[...r??[],"message-batches-2024-09-24"].toString()},n?.headers])})}cancel(e,t={},n){const{betas:r}=t??{};return this._client.post(Ce`/v1/messages/batches/${e}/cancel?beta=true`,{...n,headers:V([{"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 D(`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:V([{"anthropic-beta":[...i??[],"message-batches-2024-09-24"].toString(),Accept:"application/binary"},n?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((o,a)=>As.fromResponse(a.response,a.controller))}};const mf=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"),It=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),It(s);case"number":let t=e.value[e.value.length-1];if(t==="."||t==="-")return s=s.slice(0,s.length-1),It(s);case"string":let n=s[s.length-2];if(n?.type==="delimiter")return s=s.slice(0,s.length-1),It(s);if(n?.type==="brace"&&n.value==="{")return s=s.slice(0,s.length-1),It(s);break;case"delimiter":return s=s.slice(0,s.length-1),It(s)}return s},"strip"),gf=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"),yf=c(s=>{let e="";return s.map(t=>{switch(t.type){case"string":e+='"'+t.value+'"';break;default:e+=t.value;break}}),e},"generate"),Ha=c(s=>JSON.parse(yf(gf(It(mf(s))))),"partialParse");var ge,We,nn,us,sn,rn,hs,on,Re,an,fs,ds,$t,ps,ms,Kr,Va,gs,Br,qr,Ur,Ga;const za="__json_buf";function Ya(s){return s.type==="tool_use"||s.type==="server_tool_use"||s.type==="mcp_tool_use"}c(Ya,"tracksToolInput$1");class Is{static{c(this,"BetaMessageStream")}constructor(){ge.add(this),this.messages=[],this.receivedMessages=[],We.set(this,void 0),this.controller=new AbortController,nn.set(this,void 0),us.set(this,()=>{}),sn.set(this,()=>{}),rn.set(this,void 0),hs.set(this,()=>{}),on.set(this,()=>{}),Re.set(this,{}),an.set(this,!1),fs.set(this,!1),ds.set(this,!1),$t.set(this,!1),ps.set(this,void 0),ms.set(this,void 0),gs.set(this,e=>{if(R(this,fs,!0),Yt(e)&&(e=new ve),e instanceof ve)return R(this,ds,!0),this._emit("abort",e);if(e instanceof D)return this._emit("error",e);if(e instanceof Error){const t=new D(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new D(String(e)))}),R(this,nn,new Promise((e,t)=>{R(this,us,e,"f"),R(this,sn,t,"f")})),R(this,rn,new Promise((e,t)=>{R(this,hs,e,"f"),R(this,on,t,"f")})),S(this,nn,"f").catch(()=>{}),S(this,rn,"f").catch(()=>{})}get response(){return S(this,ps,"f")}get request_id(){return S(this,ms,"f")}async withResponse(){const e=await S(this,nn,"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 Is;return t._run(()=>t._fromReadableStream(e)),t}static createMessage(e,t,n){const r=new Is;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,gs,"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,ge,"m",Br).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,ge,"m",qr).call(this,l);if(a.controller.signal?.aborted)throw new ve;S(this,ge,"m",Ur).call(this)}finally{r&&i&&r.removeEventListener("abort",i)}}_connected(e){this.ended||(R(this,ps,e),R(this,ms,e?.headers.get("request-id")),S(this,us,"f").call(this,e),this._emit("connect"))}get ended(){return S(this,an,"f")}get errored(){return S(this,fs,"f")}get aborted(){return S(this,ds,"f")}abort(){this.controller.abort()}on(e,t){return(S(this,Re,"f")[e]||(S(this,Re,"f")[e]=[])).push({listener:t}),this}off(e,t){const n=S(this,Re,"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,Re,"f")[e]||(S(this,Re,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,n)=>{R(this,$t,!0),e!=="error"&&this.once("error",n),this.once(e,t)})}async done(){R(this,$t,!0),await S(this,rn,"f")}get currentMessage(){return S(this,We,"f")}async finalMessage(){return await this.done(),S(this,ge,"m",Kr).call(this)}async finalText(){return await this.done(),S(this,ge,"m",Va).call(this)}_emit(e,...t){if(S(this,an,"f"))return;e==="end"&&(R(this,an,!0),S(this,hs,"f").call(this));const n=S(this,Re,"f")[e];if(n&&(S(this,Re,"f")[e]=n.filter(r=>!r.once),n.forEach(({listener:r})=>r(...t))),e==="abort"){const r=t[0];!S(this,$t,"f")&&!n?.length&&Promise.reject(r),S(this,sn,"f").call(this,r),S(this,on,"f").call(this,r),this._emit("end");return}if(e==="error"){const r=t[0];!S(this,$t,"f")&&!n?.length&&Promise.reject(r),S(this,sn,"f").call(this,r),S(this,on,"f").call(this,r),this._emit("end")}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit("finalMessage",S(this,ge,"m",Kr).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,ge,"m",Br).call(this),this._connected(null);const i=Ee.fromReadableStream(e,this.controller);for await(const o of i)S(this,ge,"m",qr).call(this,o);if(i.controller.signal?.aborted)throw new ve;S(this,ge,"m",Ur).call(this)}finally{n&&r&&n.removeEventListener("abort",r)}}[(We=new WeakMap,nn=new WeakMap,us=new WeakMap,sn=new WeakMap,rn=new WeakMap,hs=new WeakMap,on=new WeakMap,Re=new WeakMap,an=new WeakMap,fs=new WeakMap,ds=new WeakMap,$t=new WeakMap,ps=new WeakMap,ms=new WeakMap,gs=new WeakMap,ge=new WeakSet,Kr=c(function(){if(this.receivedMessages.length===0)throw new D("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},"_BetaMessageStream_getFinalMessage2"),Va=c(function(){if(this.receivedMessages.length===0)throw new D("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 D("stream ended without producing a content block with type=text");return t.join(" ")},"_BetaMessageStream_getFinalText2"),Br=c(function(){this.ended||R(this,We,void 0)},"_BetaMessageStream_beginRequest2"),qr=c(function(t){if(this.ended)return;const n=S(this,ge,"m",Ga).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":{Ya(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":{R(this,We,n);break}}},"_BetaMessageStream_addStreamEvent2"),Ur=c(function(){if(this.ended)throw new D("stream has ended, this shouldn't happen");const t=S(this,We,"f");if(!t)throw new D("request ended without sending any chunks");return R(this,We,void 0),t},"_BetaMessageStream_endRequest2"),Ga=c(function(t){let n=S(this,We,"f");if(t.type==="message_start"){if(n)throw new D(`Unexpected event order, got ${t.type} before receiving "message_stop"`);return t.message}if(!n)throw new D(`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&&Ya(r)){let i=r[za]||"";i+=t.delta.partial_json;const o={...r};if(Object.defineProperty(o,za,{value:i,enumerable:!1,writable:!0}),i)try{o.input=Ha(i)}catch(a){const l=new D(`Unable to parse tool parameter JSON from model. Please retry your request or adjust your prompt. Error: ${a}. JSON: ${i}`);S(this,gs,"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 Ee(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function kd(s){}c(kd,"checkNever$1");const Xa={"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},Qa={"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 Wr=class extends Me{static{c(this,"Messages")}constructor(){super(...arguments),this.batches=new Ja(this._client)}create(e,t){const{betas:n,...r}=e;r.model in Qa&&console.warn(`The model '${r.model}' is deprecated and will reach end-of-life on ${Qa[r.model]}
159
- 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=Xa[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:V([{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void 0},t?.headers]),stream:e.stream??!1})}stream(e,t){return Is.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:V([{"anthropic-beta":[...n??[],"token-counting-2024-11-01"].toString()},t?.headers])})}};Wr.Batches=Ja;class cn extends Me{static{c(this,"Beta")}constructor(){super(...arguments),this.models=new Wa(this._client),this.messages=new Wr(this._client),this.files=new Ua(this._client)}}cn.Models=Wa,cn.Messages=Wr,cn.Files=Ua;class Za extends Me{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:V([{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void 0},t?.headers]),stream:e.stream??!1})}}var ye,Je,ln,ys,un,hn,ws,fn,Pe,dn,bs,Ss,Nt,vs,Cs,Jr,ec,Hr,Vr,Gr,zr,tc;const nc="__json_buf";function sc(s){return s.type==="tool_use"||s.type==="server_tool_use"}c(sc,"tracksToolInput");class $s{static{c(this,"MessageStream")}constructor(){ye.add(this),this.messages=[],this.receivedMessages=[],Je.set(this,void 0),this.controller=new AbortController,ln.set(this,void 0),ys.set(this,()=>{}),un.set(this,()=>{}),hn.set(this,void 0),ws.set(this,()=>{}),fn.set(this,()=>{}),Pe.set(this,{}),dn.set(this,!1),bs.set(this,!1),Ss.set(this,!1),Nt.set(this,!1),vs.set(this,void 0),Cs.set(this,void 0),Hr.set(this,e=>{if(R(this,bs,!0),Yt(e)&&(e=new ve),e instanceof ve)return R(this,Ss,!0),this._emit("abort",e);if(e instanceof D)return this._emit("error",e);if(e instanceof Error){const t=new D(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new D(String(e)))}),R(this,ln,new Promise((e,t)=>{R(this,ys,e,"f"),R(this,un,t,"f")})),R(this,hn,new Promise((e,t)=>{R(this,ws,e,"f"),R(this,fn,t,"f")})),S(this,ln,"f").catch(()=>{}),S(this,hn,"f").catch(()=>{})}get response(){return S(this,vs,"f")}get request_id(){return S(this,Cs,"f")}async withResponse(){const e=await S(this,ln,"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 $s;return t._run(()=>t._fromReadableStream(e)),t}static createMessage(e,t,n){const r=new $s;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,Hr,"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,ye,"m",Vr).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,ye,"m",Gr).call(this,l);if(a.controller.signal?.aborted)throw new ve;S(this,ye,"m",zr).call(this)}finally{r&&i&&r.removeEventListener("abort",i)}}_connected(e){this.ended||(R(this,vs,e),R(this,Cs,e?.headers.get("request-id")),S(this,ys,"f").call(this,e),this._emit("connect"))}get ended(){return S(this,dn,"f")}get errored(){return S(this,bs,"f")}get aborted(){return S(this,Ss,"f")}abort(){this.controller.abort()}on(e,t){return(S(this,Pe,"f")[e]||(S(this,Pe,"f")[e]=[])).push({listener:t}),this}off(e,t){const n=S(this,Pe,"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,Pe,"f")[e]||(S(this,Pe,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,n)=>{R(this,Nt,!0),e!=="error"&&this.once("error",n),this.once(e,t)})}async done(){R(this,Nt,!0),await S(this,hn,"f")}get currentMessage(){return S(this,Je,"f")}async finalMessage(){return await this.done(),S(this,ye,"m",Jr).call(this)}async finalText(){return await this.done(),S(this,ye,"m",ec).call(this)}_emit(e,...t){if(S(this,dn,"f"))return;e==="end"&&(R(this,dn,!0),S(this,ws,"f").call(this));const n=S(this,Pe,"f")[e];if(n&&(S(this,Pe,"f")[e]=n.filter(r=>!r.once),n.forEach(({listener:r})=>r(...t))),e==="abort"){const r=t[0];!S(this,Nt,"f")&&!n?.length&&Promise.reject(r),S(this,un,"f").call(this,r),S(this,fn,"f").call(this,r),this._emit("end");return}if(e==="error"){const r=t[0];!S(this,Nt,"f")&&!n?.length&&Promise.reject(r),S(this,un,"f").call(this,r),S(this,fn,"f").call(this,r),this._emit("end")}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit("finalMessage",S(this,ye,"m",Jr).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,ye,"m",Vr).call(this),this._connected(null);const i=Ee.fromReadableStream(e,this.controller);for await(const o of i)S(this,ye,"m",Gr).call(this,o);if(i.controller.signal?.aborted)throw new ve;S(this,ye,"m",zr).call(this)}finally{n&&r&&n.removeEventListener("abort",r)}}[(Je=new WeakMap,ln=new WeakMap,ys=new WeakMap,un=new WeakMap,hn=new WeakMap,ws=new WeakMap,fn=new WeakMap,Pe=new WeakMap,dn=new WeakMap,bs=new WeakMap,Ss=new WeakMap,Nt=new WeakMap,vs=new WeakMap,Cs=new WeakMap,Hr=new WeakMap,ye=new WeakSet,Jr=c(function(){if(this.receivedMessages.length===0)throw new D("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},"_MessageStream_getFinalMessage2"),ec=c(function(){if(this.receivedMessages.length===0)throw new D("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 D("stream ended without producing a content block with type=text");return t.join(" ")},"_MessageStream_getFinalText2"),Vr=c(function(){this.ended||R(this,Je,void 0)},"_MessageStream_beginRequest2"),Gr=c(function(t){if(this.ended)return;const n=S(this,ye,"m",tc).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":{sc(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":{R(this,Je,n);break}}},"_MessageStream_addStreamEvent2"),zr=c(function(){if(this.ended)throw new D("stream has ended, this shouldn't happen");const t=S(this,Je,"f");if(!t)throw new D("request ended without sending any chunks");return R(this,Je,void 0),t},"_MessageStream_endRequest2"),tc=c(function(t){let n=S(this,Je,"f");if(t.type==="message_start"){if(n)throw new D(`Unexpected event order, got ${t.type} before receiving "message_stop"`);return t.message}if(!n)throw new D(`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&&sc(r)){let i=r[nc]||"";i+=t.delta.partial_json;const o={...r};Object.defineProperty(o,nc,{value:i,enumerable:!1,writable:!0}),i&&(o.input=Ha(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 Ee(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function Td(s){}c(Td,"checkNever");class rc extends Me{static{c(this,"Batches")}create(e,t){return this._client.post("/v1/messages/batches",{body:e,...t})}retrieve(e,t){return this._client.get(Ce`/v1/messages/batches/${e}`,t)}list(e={},t){return this._client.getAPIList("/v1/messages/batches",tn,{query:e,...t})}delete(e,t){return this._client.delete(Ce`/v1/messages/batches/${e}`,t)}cancel(e,t){return this._client.post(Ce`/v1/messages/batches/${e}/cancel`,t)}async results(e,t){const n=await this.retrieve(e);if(!n.results_url)throw new D(`No batch \`results_url\`; Has it finished processing? ${n.processing_status} - ${n.id}`);return this._client.get(n.results_url,{...t,headers:V([{Accept:"application/binary"},t?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((r,i)=>As.fromResponse(i.response,i.controller))}}class Yr extends Me{static{c(this,"Messages")}constructor(){super(...arguments),this.batches=new rc(this._client)}create(e,t){e.model in ic&&console.warn(`The model '${e.model}' is deprecated and will reach end-of-life on ${ic[e.model]}
160
- 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=Xa[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 $s.createMessage(this,e,t)}countTokens(e,t){return this._client.post("/v1/messages/count_tokens",{body:e,...t})}}const ic={"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"};Yr.Batches=rc;class oc extends Me{static{c(this,"Models")}retrieve(e,t={},n){const{betas:r}=t??{};return this._client.get(Ce`/v1/models/${e}`,{...n,headers:V([{...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",tn,{query:r,...t,headers:V([{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void 0},t?.headers])})}}const ks=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 Xr,Qr,_s,ac;const wf="\\n\\nHuman:",bf="\\n\\nAssistant:";class Z{static{c(this,"BaseAnthropic")}constructor({baseURL:e=ks("ANTHROPIC_BASE_URL"),apiKey:t=ks("ANTHROPIC_API_KEY")??null,authToken:n=ks("ANTHROPIC_AUTH_TOKEN")??null,...r}={}){Xr.add(this),_s.set(this,void 0);const i={apiKey:t,authToken:n,...r,baseURL:e||"https://api.anthropic.com"};if(!i.dangerouslyAllowBrowser&&Kh())throw new D(`It looks like you're running in a browser-like environment.
158
+ ${f}`)}return o},"path2"),"createPathTagFunction"),Ce=gf(qa);class Wa extends Me{static{c(this,"Files")}list(e={},t){const{betas:n,...r}=e??{};return this._client.getAPIList("/v1/files",tn,{query:r,...t,headers:V([{"anthropic-beta":[...n??[],"files-api-2025-04-14"].toString()},t?.headers])})}delete(e,t={},n){const{betas:r}=t??{};return this._client.delete(Ce`/v1/files/${e}`,{...n,headers:V([{"anthropic-beta":[...r??[],"files-api-2025-04-14"].toString()},n?.headers])})}download(e,t={},n){const{betas:r}=t??{};return this._client.get(Ce`/v1/files/${e}/content`,{...n,headers:V([{"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(Ce`/v1/files/${e}`,{...n,headers:V([{"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",af({body:r,...t,headers:V([{"anthropic-beta":[...n??[],"files-api-2025-04-14"].toString()},t?.headers])},this._client))}}let Ja=class extends Me{static{c(this,"Models")}retrieve(e,t={},n){const{betas:r}=t??{};return this._client.get(Ce`/v1/models/${e}?beta=true`,{...n,headers:V([{...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",tn,{query:r,...t,headers:V([{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void 0},t?.headers])})}};class Os{static{c(this,"JSONLDecoder")}constructor(e,t){this.iterator=e,this.controller=t}async*decoder(){const e=new Xt;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 L("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 L("Attempted to iterate over a response with no body");return new Os(Dr(e.body),t)}}let Ha=class extends Me{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:V([{"anthropic-beta":[...n??[],"message-batches-2024-09-24"].toString()},t?.headers])})}retrieve(e,t={},n){const{betas:r}=t??{};return this._client.get(Ce`/v1/messages/batches/${e}?beta=true`,{...n,headers:V([{"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",tn,{query:r,...t,headers:V([{"anthropic-beta":[...n??[],"message-batches-2024-09-24"].toString()},t?.headers])})}delete(e,t={},n){const{betas:r}=t??{};return this._client.delete(Ce`/v1/messages/batches/${e}?beta=true`,{...n,headers:V([{"anthropic-beta":[...r??[],"message-batches-2024-09-24"].toString()},n?.headers])})}cancel(e,t={},n){const{betas:r}=t??{};return this._client.post(Ce`/v1/messages/batches/${e}/cancel?beta=true`,{...n,headers:V([{"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 L(`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:V([{"anthropic-beta":[...i??[],"message-batches-2024-09-24"].toString(),Accept:"application/binary"},n?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((o,a)=>Os.fromResponse(a.response,a.controller))}};const yf=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"),Ot=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),Ot(s);case"number":let t=e.value[e.value.length-1];if(t==="."||t==="-")return s=s.slice(0,s.length-1),Ot(s);case"string":let n=s[s.length-2];if(n?.type==="delimiter")return s=s.slice(0,s.length-1),Ot(s);if(n?.type==="brace"&&n.value==="{")return s=s.slice(0,s.length-1),Ot(s);break;case"delimiter":return s=s.slice(0,s.length-1),Ot(s)}return s},"strip"),wf=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"),bf=c(s=>{let e="";return s.map(t=>{switch(t.type){case"string":e+='"'+t.value+'"';break;default:e+=t.value;break}}),e},"generate"),Va=c(s=>JSON.parse(bf(wf(Ot(yf(s))))),"partialParse");var ge,We,nn,us,sn,rn,hs,on,Re,an,fs,ds,It,ps,ms,Br,Ga,gs,qr,Ur,Wr,za;const Ya="__json_buf";function Xa(s){return s.type==="tool_use"||s.type==="server_tool_use"||s.type==="mcp_tool_use"}c(Xa,"tracksToolInput$1");class Is{static{c(this,"BetaMessageStream")}constructor(){ge.add(this),this.messages=[],this.receivedMessages=[],We.set(this,void 0),this.controller=new AbortController,nn.set(this,void 0),us.set(this,()=>{}),sn.set(this,()=>{}),rn.set(this,void 0),hs.set(this,()=>{}),on.set(this,()=>{}),Re.set(this,{}),an.set(this,!1),fs.set(this,!1),ds.set(this,!1),It.set(this,!1),ps.set(this,void 0),ms.set(this,void 0),gs.set(this,e=>{if(R(this,fs,!0),Yt(e)&&(e=new ve),e instanceof ve)return R(this,ds,!0),this._emit("abort",e);if(e instanceof L)return this._emit("error",e);if(e instanceof Error){const t=new L(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new L(String(e)))}),R(this,nn,new Promise((e,t)=>{R(this,us,e,"f"),R(this,sn,t,"f")})),R(this,rn,new Promise((e,t)=>{R(this,hs,e,"f"),R(this,on,t,"f")})),S(this,nn,"f").catch(()=>{}),S(this,rn,"f").catch(()=>{})}get response(){return S(this,ps,"f")}get request_id(){return S(this,ms,"f")}async withResponse(){const e=await S(this,nn,"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 Is;return t._run(()=>t._fromReadableStream(e)),t}static createMessage(e,t,n){const r=new Is;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,gs,"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,ge,"m",qr).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,ge,"m",Ur).call(this,l);if(a.controller.signal?.aborted)throw new ve;S(this,ge,"m",Wr).call(this)}finally{r&&i&&r.removeEventListener("abort",i)}}_connected(e){this.ended||(R(this,ps,e),R(this,ms,e?.headers.get("request-id")),S(this,us,"f").call(this,e),this._emit("connect"))}get ended(){return S(this,an,"f")}get errored(){return S(this,fs,"f")}get aborted(){return S(this,ds,"f")}abort(){this.controller.abort()}on(e,t){return(S(this,Re,"f")[e]||(S(this,Re,"f")[e]=[])).push({listener:t}),this}off(e,t){const n=S(this,Re,"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,Re,"f")[e]||(S(this,Re,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,n)=>{R(this,It,!0),e!=="error"&&this.once("error",n),this.once(e,t)})}async done(){R(this,It,!0),await S(this,rn,"f")}get currentMessage(){return S(this,We,"f")}async finalMessage(){return await this.done(),S(this,ge,"m",Br).call(this)}async finalText(){return await this.done(),S(this,ge,"m",Ga).call(this)}_emit(e,...t){if(S(this,an,"f"))return;e==="end"&&(R(this,an,!0),S(this,hs,"f").call(this));const n=S(this,Re,"f")[e];if(n&&(S(this,Re,"f")[e]=n.filter(r=>!r.once),n.forEach(({listener:r})=>r(...t))),e==="abort"){const r=t[0];!S(this,It,"f")&&!n?.length&&Promise.reject(r),S(this,sn,"f").call(this,r),S(this,on,"f").call(this,r),this._emit("end");return}if(e==="error"){const r=t[0];!S(this,It,"f")&&!n?.length&&Promise.reject(r),S(this,sn,"f").call(this,r),S(this,on,"f").call(this,r),this._emit("end")}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit("finalMessage",S(this,ge,"m",Br).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,ge,"m",qr).call(this),this._connected(null);const i=Ee.fromReadableStream(e,this.controller);for await(const o of i)S(this,ge,"m",Ur).call(this,o);if(i.controller.signal?.aborted)throw new ve;S(this,ge,"m",Wr).call(this)}finally{n&&r&&n.removeEventListener("abort",r)}}[(We=new WeakMap,nn=new WeakMap,us=new WeakMap,sn=new WeakMap,rn=new WeakMap,hs=new WeakMap,on=new WeakMap,Re=new WeakMap,an=new WeakMap,fs=new WeakMap,ds=new WeakMap,It=new WeakMap,ps=new WeakMap,ms=new WeakMap,gs=new WeakMap,ge=new WeakSet,Br=c(function(){if(this.receivedMessages.length===0)throw new L("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},"_BetaMessageStream_getFinalMessage2"),Ga=c(function(){if(this.receivedMessages.length===0)throw new L("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 L("stream ended without producing a content block with type=text");return t.join(" ")},"_BetaMessageStream_getFinalText2"),qr=c(function(){this.ended||R(this,We,void 0)},"_BetaMessageStream_beginRequest2"),Ur=c(function(t){if(this.ended)return;const n=S(this,ge,"m",za).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":{Xa(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":{R(this,We,n);break}}},"_BetaMessageStream_addStreamEvent2"),Wr=c(function(){if(this.ended)throw new L("stream has ended, this shouldn't happen");const t=S(this,We,"f");if(!t)throw new L("request ended without sending any chunks");return R(this,We,void 0),t},"_BetaMessageStream_endRequest2"),za=c(function(t){let n=S(this,We,"f");if(t.type==="message_start"){if(n)throw new L(`Unexpected event order, got ${t.type} before receiving "message_stop"`);return t.message}if(!n)throw new L(`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&&Xa(r)){let i=r[Ya]||"";i+=t.delta.partial_json;const o={...r};if(Object.defineProperty(o,Ya,{value:i,enumerable:!1,writable:!0}),i)try{o.input=Va(i)}catch(a){const l=new L(`Unable to parse tool parameter JSON from model. Please retry your request or adjust your prompt. Error: ${a}. JSON: ${i}`);S(this,gs,"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 Ee(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function Td(s){}c(Td,"checkNever$1");const Qa={"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},Za={"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 Jr=class extends Me{static{c(this,"Messages")}constructor(){super(...arguments),this.batches=new Ha(this._client)}create(e,t){const{betas:n,...r}=e;r.model in Za&&console.warn(`The model '${r.model}' is deprecated and will reach end-of-life on ${Za[r.model]}
159
+ 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=Qa[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:V([{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void 0},t?.headers]),stream:e.stream??!1})}stream(e,t){return Is.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:V([{"anthropic-beta":[...n??[],"token-counting-2024-11-01"].toString()},t?.headers])})}};Jr.Batches=Ha;class cn extends Me{static{c(this,"Beta")}constructor(){super(...arguments),this.models=new Ja(this._client),this.messages=new Jr(this._client),this.files=new Wa(this._client)}}cn.Models=Ja,cn.Messages=Jr,cn.Files=Wa;class ec extends Me{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:V([{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void 0},t?.headers]),stream:e.stream??!1})}}var ye,Je,ln,ys,un,hn,ws,fn,Pe,dn,bs,Ss,$t,vs,Cs,Hr,tc,Vr,Gr,zr,Yr,nc;const sc="__json_buf";function rc(s){return s.type==="tool_use"||s.type==="server_tool_use"}c(rc,"tracksToolInput");class $s{static{c(this,"MessageStream")}constructor(){ye.add(this),this.messages=[],this.receivedMessages=[],Je.set(this,void 0),this.controller=new AbortController,ln.set(this,void 0),ys.set(this,()=>{}),un.set(this,()=>{}),hn.set(this,void 0),ws.set(this,()=>{}),fn.set(this,()=>{}),Pe.set(this,{}),dn.set(this,!1),bs.set(this,!1),Ss.set(this,!1),$t.set(this,!1),vs.set(this,void 0),Cs.set(this,void 0),Vr.set(this,e=>{if(R(this,bs,!0),Yt(e)&&(e=new ve),e instanceof ve)return R(this,Ss,!0),this._emit("abort",e);if(e instanceof L)return this._emit("error",e);if(e instanceof Error){const t=new L(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new L(String(e)))}),R(this,ln,new Promise((e,t)=>{R(this,ys,e,"f"),R(this,un,t,"f")})),R(this,hn,new Promise((e,t)=>{R(this,ws,e,"f"),R(this,fn,t,"f")})),S(this,ln,"f").catch(()=>{}),S(this,hn,"f").catch(()=>{})}get response(){return S(this,vs,"f")}get request_id(){return S(this,Cs,"f")}async withResponse(){const e=await S(this,ln,"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 $s;return t._run(()=>t._fromReadableStream(e)),t}static createMessage(e,t,n){const r=new $s;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,Vr,"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,ye,"m",Gr).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,ye,"m",zr).call(this,l);if(a.controller.signal?.aborted)throw new ve;S(this,ye,"m",Yr).call(this)}finally{r&&i&&r.removeEventListener("abort",i)}}_connected(e){this.ended||(R(this,vs,e),R(this,Cs,e?.headers.get("request-id")),S(this,ys,"f").call(this,e),this._emit("connect"))}get ended(){return S(this,dn,"f")}get errored(){return S(this,bs,"f")}get aborted(){return S(this,Ss,"f")}abort(){this.controller.abort()}on(e,t){return(S(this,Pe,"f")[e]||(S(this,Pe,"f")[e]=[])).push({listener:t}),this}off(e,t){const n=S(this,Pe,"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,Pe,"f")[e]||(S(this,Pe,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,n)=>{R(this,$t,!0),e!=="error"&&this.once("error",n),this.once(e,t)})}async done(){R(this,$t,!0),await S(this,hn,"f")}get currentMessage(){return S(this,Je,"f")}async finalMessage(){return await this.done(),S(this,ye,"m",Hr).call(this)}async finalText(){return await this.done(),S(this,ye,"m",tc).call(this)}_emit(e,...t){if(S(this,dn,"f"))return;e==="end"&&(R(this,dn,!0),S(this,ws,"f").call(this));const n=S(this,Pe,"f")[e];if(n&&(S(this,Pe,"f")[e]=n.filter(r=>!r.once),n.forEach(({listener:r})=>r(...t))),e==="abort"){const r=t[0];!S(this,$t,"f")&&!n?.length&&Promise.reject(r),S(this,un,"f").call(this,r),S(this,fn,"f").call(this,r),this._emit("end");return}if(e==="error"){const r=t[0];!S(this,$t,"f")&&!n?.length&&Promise.reject(r),S(this,un,"f").call(this,r),S(this,fn,"f").call(this,r),this._emit("end")}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit("finalMessage",S(this,ye,"m",Hr).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,ye,"m",Gr).call(this),this._connected(null);const i=Ee.fromReadableStream(e,this.controller);for await(const o of i)S(this,ye,"m",zr).call(this,o);if(i.controller.signal?.aborted)throw new ve;S(this,ye,"m",Yr).call(this)}finally{n&&r&&n.removeEventListener("abort",r)}}[(Je=new WeakMap,ln=new WeakMap,ys=new WeakMap,un=new WeakMap,hn=new WeakMap,ws=new WeakMap,fn=new WeakMap,Pe=new WeakMap,dn=new WeakMap,bs=new WeakMap,Ss=new WeakMap,$t=new WeakMap,vs=new WeakMap,Cs=new WeakMap,Vr=new WeakMap,ye=new WeakSet,Hr=c(function(){if(this.receivedMessages.length===0)throw new L("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},"_MessageStream_getFinalMessage2"),tc=c(function(){if(this.receivedMessages.length===0)throw new L("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 L("stream ended without producing a content block with type=text");return t.join(" ")},"_MessageStream_getFinalText2"),Gr=c(function(){this.ended||R(this,Je,void 0)},"_MessageStream_beginRequest2"),zr=c(function(t){if(this.ended)return;const n=S(this,ye,"m",nc).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":{rc(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":{R(this,Je,n);break}}},"_MessageStream_addStreamEvent2"),Yr=c(function(){if(this.ended)throw new L("stream has ended, this shouldn't happen");const t=S(this,Je,"f");if(!t)throw new L("request ended without sending any chunks");return R(this,Je,void 0),t},"_MessageStream_endRequest2"),nc=c(function(t){let n=S(this,Je,"f");if(t.type==="message_start"){if(n)throw new L(`Unexpected event order, got ${t.type} before receiving "message_stop"`);return t.message}if(!n)throw new L(`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&&rc(r)){let i=r[sc]||"";i+=t.delta.partial_json;const o={...r};Object.defineProperty(o,sc,{value:i,enumerable:!1,writable:!0}),i&&(o.input=Va(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 Ee(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function Ad(s){}c(Ad,"checkNever");class ic extends Me{static{c(this,"Batches")}create(e,t){return this._client.post("/v1/messages/batches",{body:e,...t})}retrieve(e,t){return this._client.get(Ce`/v1/messages/batches/${e}`,t)}list(e={},t){return this._client.getAPIList("/v1/messages/batches",tn,{query:e,...t})}delete(e,t){return this._client.delete(Ce`/v1/messages/batches/${e}`,t)}cancel(e,t){return this._client.post(Ce`/v1/messages/batches/${e}/cancel`,t)}async results(e,t){const n=await this.retrieve(e);if(!n.results_url)throw new L(`No batch \`results_url\`; Has it finished processing? ${n.processing_status} - ${n.id}`);return this._client.get(n.results_url,{...t,headers:V([{Accept:"application/binary"},t?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((r,i)=>Os.fromResponse(i.response,i.controller))}}class Xr extends Me{static{c(this,"Messages")}constructor(){super(...arguments),this.batches=new ic(this._client)}create(e,t){e.model in oc&&console.warn(`The model '${e.model}' is deprecated and will reach end-of-life on ${oc[e.model]}
160
+ 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=Qa[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 $s.createMessage(this,e,t)}countTokens(e,t){return this._client.post("/v1/messages/count_tokens",{body:e,...t})}}const oc={"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"};Xr.Batches=ic;class ac extends Me{static{c(this,"Models")}retrieve(e,t={},n){const{betas:r}=t??{};return this._client.get(Ce`/v1/models/${e}`,{...n,headers:V([{...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",tn,{query:r,...t,headers:V([{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void 0},t?.headers])})}}const ks=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 Qr,Zr,_s,cc;const Sf="\\n\\nHuman:",vf="\\n\\nAssistant:";class Z{static{c(this,"BaseAnthropic")}constructor({baseURL:e=ks("ANTHROPIC_BASE_URL"),apiKey:t=ks("ANTHROPIC_API_KEY")??null,authToken:n=ks("ANTHROPIC_AUTH_TOKEN")??null,...r}={}){Qr.add(this),_s.set(this,void 0);const i={apiKey:t,authToken:n,...r,baseURL:e||"https://api.anthropic.com"};if(!i.dangerouslyAllowBrowser&&qh())throw new L(`It looks like you're running in a browser-like environment.
161
161
 
162
162
  This is disabled by default, as it risks exposing your secret API credentials to attackers.
163
163
  If you understand the risks and have appropriate mitigations in place,
164
164
  you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
165
165
 
166
166
  new Anthropic({ apiKey, dangerouslyAllowBrowser: true });
167
- `);this.baseURL=i.baseURL,this.timeout=i.timeout??Qr.DEFAULT_TIMEOUT,this.logger=i.logger??console;const o="warn";this.logLevel=o,this.logLevel=xa(i.logLevel,"ClientOptions.logLevel",this)??xa(ks("ANTHROPIC_LOG"),"process.env['ANTHROPIC_LOG']",this)??o,this.fetchOptions=i.fetchOptions,this.maxRetries=i.maxRetries??2,this.fetch=i.fetch??Jh(),R(this,_s,Vh),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 V([await this.apiKeyAuth(e),await this.bearerAuth(e)])}async apiKeyAuth(e){if(this.apiKey!=null)return V([{"X-Api-Key":this.apiKey}])}async bearerAuth(e){if(this.authToken!=null)return V([{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 D(`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 ${Ot}`}defaultIdempotencyKey(){return`stainless-node-retry-${ha()}`}makeStatusError(e,t,n,r){return re.generate(e,t,n,r)}buildURL(e,t,n){const r=!S(this,Xr,"m",ac).call(this)&&n||this.baseURL,i=Ph(e)?new URL(e):new URL(r+(r.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),o=this.defaultQuery();return Lh(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 D("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 Os(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"),h=n===void 0?"":`, retryOf: ${n}`,f=Date.now();if(ie(this).debug(`[${u}] sending request`,tt({retryOfRequestLogID:n,method:r.method,url:a,options:r,headers:o.headers})),r.signal?.aborted)throw new ve;const p=new AbortController,m=await this.fetchWithTimeout(a,o,l,p).catch(Rr),y=Date.now();if(m instanceof globalThis.Error){const k=`retrying, ${t} attempts remaining`;if(r.signal?.aborted)throw new ve;const _=Yt(m)||/timed? ?out/i.test(String(m)+("cause"in m?String(m.cause):""));if(t)return ie(this).info(`[${u}] connection ${_?"timed out":"failed"} - ${k}`),ie(this).debug(`[${u}] connection ${_?"timed out":"failed"} (${k})`,tt({retryOfRequestLogID:n,url:a,durationMs:y-f,message:m.message})),this.retryRequest(r,t,n??u);throw ie(this).info(`[${u}] connection ${_?"timed out":"failed"} - error; no more retries left`),ie(this).debug(`[${u}] connection ${_?"timed out":"failed"} (error; no more retries left)`,tt({retryOfRequestLogID:n,url:a,durationMs:y-f,message:m.message})),_?new fa:new is({cause:m})}const d=[...m.headers.entries()].filter(([k])=>k==="request-id").map(([k,_])=>", "+k+": "+JSON.stringify(_)).join(""),w=`[${u}${h}${d}] ${o.method} ${a} ${m.ok?"succeeded":"failed"} with status ${m.status} in ${y-f}ms`;if(!m.ok){const k=await this.shouldRetry(m);if(t&&k){const F=`retrying, ${t} attempts remaining`;return await Hh(m.body),ie(this).info(`${w} - ${F}`),ie(this).debug(`[${u}] response error (${F})`,tt({retryOfRequestLogID:n,url:m.url,status:m.status,headers:m.headers,durationMs:y-f})),this.retryRequest(r,t,n??u,m.headers)}const _=k?"error; no more retries left":"error; not retryable";ie(this).info(`${w} - ${_}`);const A=await m.text().catch(F=>Rr(F).message),O=ka(A),$=O?void 0:A;throw ie(this).debug(`[${u}] response error (${_})`,tt({retryOfRequestLogID:n,url:m.url,status:m.status,headers:m.headers,message:$,durationMs:Date.now()-f})),this.makeStatusError(m.status,O,$,m.headers)}return ie(this).info(w),ie(this).debug(`[${u}] response start`,tt({retryOfRequestLogID:n,url:m.url,status:m.status,headers:m.headers,durationMs:y-f})),{response:m,options:r,controller:p,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 sf(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,h={signal:r.signal,...u?{duplex:"half"}:{},method:"GET",...a};o&&(h.method=o.toUpperCase());try{return await this.fetch.call(void 0,e,h)}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 Fh(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 D("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&&jh("timeout",n.timeout),n.timeout=n.timeout??this.timeout;const{bodyHeaders:u,body:h}=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&&h instanceof globalThis.ReadableStream&&{duplex:"half"},...h&&{body:h},...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=V([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))}:{},...Wh(),...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=V([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:Aa(e)}:S(this,_s,"f").call(this,{body:e,headers:n})}}Qr=Z,_s=new WeakMap,Xr=new WeakSet,ac=c(function(){return this.baseURL!=="https://api.anthropic.com"},"_BaseAnthropic_baseURLOverridden2"),Z.Anthropic=Qr,Z.HUMAN_PROMPT=wf,Z.AI_PROMPT=bf,Z.DEFAULT_TIMEOUT=6e5,Z.AnthropicError=D,Z.APIError=re,Z.APIConnectionError=is,Z.APIConnectionTimeoutError=fa,Z.APIUserAbortError=ve,Z.NotFoundError=ga,Z.ConflictError=ya,Z.RateLimitError=ba,Z.BadRequestError=da,Z.AuthenticationError=pa,Z.InternalServerError=Sa,Z.PermissionDeniedError=ma,Z.UnprocessableEntityError=wa,Z.toFile=hf;class pn extends Z{static{c(this,"Anthropic")}constructor(){super(...arguments),this.completions=new Za(this),this.messages=new Yr(this),this.models=new oc(this),this.beta=new cn(this)}}pn.Completions=Za,pn.Messages=Yr,pn.Models=oc,pn.Beta=cn;const Sf="claude-sonnet-4-20250514";class si{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=An();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 ci({token:await this.createMembraneToken(r),apiUri:r.apiUri}),o=new pn({apiKey:r.anthropicApiKey}),a={complete:c(async({prompt:l,maxTokens:u})=>{const h=await o.messages.create({model:Sf,max_tokens:u,messages:[{role:"user",content:l}]});return h.content[0].type==="text"?h.content[0].text:""},"complete")};return new si({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(),Fs(t,n.getResult());this.writeResults(t)}async readYaml(e){const t=B.join(this.testsDir,this.testBasePath,this.connectionId,e);if(P.existsSync(t))return Ge.load(P.readFileSync(t,"utf8"))}async writeYaml(e,t){const n=B.join(this.testsDir,this.testBasePath,this.connectionId,e);P.mkdirSync(B.dirname(n),{recursive:!0}),P.writeFileSync(n,Ge.dump(t,{noRefs:!0}))}writeResults(e){const t=B.join(this.testsDir,this.testBasePath,this.connectionId);P.mkdirSync(t,{recursive:!0});const n=B.join(t,"test-results.yaml");P.writeFileSync(n,Ge.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 Ds.sign(n,e.workspaceSecret,r)}}Hc.interpolate=/{{([\s\S]+?)}}/g;function Zr(s,e){if(typeof s=="string"){const t=Jc(s),n={state:e,random:{number:c(()=>Lt.number.int(),"number"),alphaNumeric:c(i=>Lt.string.alphanumeric(i),"alphaNumeric")},faker:{company:{name:c(()=>Lt.company.name(),"name"),catchPhrase:c(()=>Lt.company.catchPhrase(),"catchPhrase")},internet:{email:c(()=>Lt.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=>Zr(t,e)):typeof s=="object"&&s!==null?Object.fromEntries(Object.entries(s).map(([t,n])=>[t,Zr(n,e)])):s}c(Zr,"processNode");function vf(s,e){return Zr(s,e)}c(vf,"handleTemplate");class Cf{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(`${T.bold.cyan("[start]")} ${T.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(`${T.bold.yellow("[initialized]")} ${T.yellow(e.path)}`)),o=vf(i,this.environment.state),await e.run(o),console.debug(`${T.bold.green("[success]")} ${T.yellow(e.path)}`),t=!0,r=e.getResult(),Rs(this.result,e.path,r)}catch(l){if(console.error(`${T.bold.red("[error]")} ${T.yellow(e.path)}: ${l}`),this.environment.options.fix&&!n){n=!0;try{await e.fix(l);continue}catch(u){console.error(`${T.bold.red("[fix fail]")} ${T.yellow(e.path)}: ${u}`)}}Rs(this.result,e.path,{error:ke(l)}),t=!0,r={error:ke(l)}}const a={...o,result:r};await this.environment.writeYaml(e.getTestCasePath(),a)}async runTestSuite(e){await e.run(),Fs(this.result,e.getResult())}}class He{static{c(this,"BaseTester")}environment;level;logs;assertions;resultsLocator;path;constructor({environment:e,path:t}){this.environment=e,this.logs=[],this.assertions=[],this.path=t,this.level=0}async fix(e){const t=await this.readTestCase();if(!t)throw new Error(`No config found for test ${this.path}`);const n=await this.fixTestCase({config:t,error:e});console.debug(T.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:ke(r)}),this.logMsg(`\u274C ${t}: ${r.message}`)}}logMsg(e){console.debug(`${" ".repeat(this.level*2)}${e}`)}getTestCasePath(){return`${this.path}.test.yml`}}function ei(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)||!ti(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=ei(r,i);o!==null&&(t[n]=o)}else t[n]=i;continue}ti(r,i)||(t[n]=i)}return Object.keys(t).length===0?null:t}c(ei,"getNotMatchingSubFields");function ti(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(ti,"softCompare");class kf extends He{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=Ps(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=li(n),a=yn(e.input.fields,o,{skipUnknownFields:!0}),l=yn(i.record.fields,o),u=ei(l,a);await this.assert(()=>!u,"Returned fields match created fields",{difference:u,sentFields:a,receivedFields:l})}const r=vc(n);if(r.length>0){const i={};r.forEach(a=>{const l=Cc(e.input.fields,a);typeof l<"u"&&Rs(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=Ps(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=ke(t),r=Ps(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:
167
+ `);this.baseURL=i.baseURL,this.timeout=i.timeout??Zr.DEFAULT_TIMEOUT,this.logger=i.logger??console;const o="warn";this.logLevel=o,this.logLevel=Ma(i.logLevel,"ClientOptions.logLevel",this)??Ma(ks("ANTHROPIC_LOG"),"process.env['ANTHROPIC_LOG']",this)??o,this.fetchOptions=i.fetchOptions,this.maxRetries=i.maxRetries??2,this.fetch=i.fetch??Vh(),R(this,_s,zh),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 V([await this.apiKeyAuth(e),await this.bearerAuth(e)])}async apiKeyAuth(e){if(this.apiKey!=null)return V([{"X-Api-Key":this.apiKey}])}async bearerAuth(e){if(this.authToken!=null)return V([{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 L(`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 ${Et}`}defaultIdempotencyKey(){return`stainless-node-retry-${fa()}`}makeStatusError(e,t,n,r){return re.generate(e,t,n,r)}buildURL(e,t,n){const r=!S(this,Qr,"m",cc).call(this)&&n||this.baseURL,i=Dh(e)?new URL(e):new URL(r+(r.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),o=this.defaultQuery();return jh(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 L("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 As(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"),h=n===void 0?"":`, retryOf: ${n}`,f=Date.now();if(ie(this).debug(`[${u}] sending request`,et({retryOfRequestLogID:n,method:r.method,url:a,options:r,headers:o.headers})),r.signal?.aborted)throw new ve;const p=new AbortController,m=await this.fetchWithTimeout(a,o,l,p).catch(Pr),y=Date.now();if(m instanceof globalThis.Error){const k=`retrying, ${t} attempts remaining`;if(r.signal?.aborted)throw new ve;const _=Yt(m)||/timed? ?out/i.test(String(m)+("cause"in m?String(m.cause):""));if(t)return ie(this).info(`[${u}] connection ${_?"timed out":"failed"} - ${k}`),ie(this).debug(`[${u}] connection ${_?"timed out":"failed"} (${k})`,et({retryOfRequestLogID:n,url:a,durationMs:y-f,message:m.message})),this.retryRequest(r,t,n??u);throw ie(this).info(`[${u}] connection ${_?"timed out":"failed"} - error; no more retries left`),ie(this).debug(`[${u}] connection ${_?"timed out":"failed"} (error; no more retries left)`,et({retryOfRequestLogID:n,url:a,durationMs:y-f,message:m.message})),_?new da:new is({cause:m})}const d=[...m.headers.entries()].filter(([k])=>k==="request-id").map(([k,_])=>", "+k+": "+JSON.stringify(_)).join(""),w=`[${u}${h}${d}] ${o.method} ${a} ${m.ok?"succeeded":"failed"} with status ${m.status} in ${y-f}ms`;if(!m.ok){const k=await this.shouldRetry(m);if(t&&k){const K=`retrying, ${t} attempts remaining`;return await Gh(m.body),ie(this).info(`${w} - ${K}`),ie(this).debug(`[${u}] response error (${K})`,et({retryOfRequestLogID:n,url:m.url,status:m.status,headers:m.headers,durationMs:y-f})),this.retryRequest(r,t,n??u,m.headers)}const _=k?"error; no more retries left":"error; not retryable";ie(this).info(`${w} - ${_}`);const O=await m.text().catch(K=>Pr(K).message),A=_a(O),$=A?void 0:O;throw ie(this).debug(`[${u}] response error (${_})`,et({retryOfRequestLogID:n,url:m.url,status:m.status,headers:m.headers,message:$,durationMs:Date.now()-f})),this.makeStatusError(m.status,A,$,m.headers)}return ie(this).info(w),ie(this).debug(`[${u}] response start`,et({retryOfRequestLogID:n,url:m.url,status:m.status,headers:m.headers,durationMs:y-f})),{response:m,options:r,controller:p,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 of(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,h={signal:r.signal,...u?{duplex:"half"}:{},method:"GET",...a};o&&(h.method=o.toUpperCase());try{return await this.fetch.call(void 0,e,h)}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 Bh(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 L("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&&Kh("timeout",n.timeout),n.timeout=n.timeout??this.timeout;const{bodyHeaders:u,body:h}=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&&h instanceof globalThis.ReadableStream&&{duplex:"half"},...h&&{body:h},...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=V([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))}:{},...Hh(),...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=V([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:Ia(e)}:S(this,_s,"f").call(this,{body:e,headers:n})}}Zr=Z,_s=new WeakMap,Qr=new WeakSet,cc=c(function(){return this.baseURL!=="https://api.anthropic.com"},"_BaseAnthropic_baseURLOverridden2"),Z.Anthropic=Zr,Z.HUMAN_PROMPT=Sf,Z.AI_PROMPT=vf,Z.DEFAULT_TIMEOUT=6e5,Z.AnthropicError=L,Z.APIError=re,Z.APIConnectionError=is,Z.APIConnectionTimeoutError=da,Z.APIUserAbortError=ve,Z.NotFoundError=ya,Z.ConflictError=wa,Z.RateLimitError=Sa,Z.BadRequestError=pa,Z.AuthenticationError=ma,Z.InternalServerError=va,Z.PermissionDeniedError=ga,Z.UnprocessableEntityError=ba,Z.toFile=df;class pn extends Z{static{c(this,"Anthropic")}constructor(){super(...arguments),this.completions=new ec(this),this.messages=new Xr(this),this.models=new ac(this),this.beta=new cn(this)}}pn.Completions=ec,pn.Messages=Xr,pn.Models=ac,pn.Beta=cn;const Cf="claude-sonnet-4-20250514";class ri{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=On();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 li({token:await this.createMembraneToken(r),apiUri:r.apiUri}),o=new pn({apiKey:r.anthropicApiKey}),a={complete:c(async({prompt:l,maxTokens:u})=>{const h=await o.messages.create({model:Cf,max_tokens:u,messages:[{role:"user",content:l}]});return h.content[0].type==="text"?h.content[0].text:""},"complete")};return new ri({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(),Fs(t,n.getResult());this.writeResults(t)}async readYaml(e){const t=q.join(this.testsDir,this.testBasePath,this.connectionId,e);return Js(t)}async writeYaml(e,t){const n=q.join(this.testsDir,this.testBasePath,this.connectionId,e);D.mkdirSync(q.dirname(n),{recursive:!0}),D.writeFileSync(n,Pt.dump(t,{noRefs:!0}))}writeResults(e){const t=q.join(this.testsDir,this.testBasePath,this.connectionId);D.mkdirSync(t,{recursive:!0});const n=q.join(t,"test-results.yaml");D.writeFileSync(n,Pt.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 Ds.sign(n,e.workspaceSecret,r)}}Vc.interpolate=/{{([\s\S]+?)}}/g;function ei(s,e){if(typeof s=="string"){const t=Hc(s),n={state:e,random:{number:c(()=>Lt.number.int(),"number"),alphaNumeric:c(i=>Lt.string.alphanumeric(i),"alphaNumeric")},faker:{company:{name:c(()=>Lt.company.name(),"name"),catchPhrase:c(()=>Lt.company.catchPhrase(),"catchPhrase")},internet:{email:c(()=>Lt.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=>ei(t,e)):typeof s=="object"&&s!==null?Object.fromEntries(Object.entries(s).map(([t,n])=>[t,ei(n,e)])):s}c(ei,"processNode");function kf(s,e){return ei(s,e)}c(kf,"handleTemplate");class _f{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(`${T.bold.cyan("[start]")} ${T.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(`${T.bold.yellow("[initialized]")} ${T.yellow(e.path)}`)),o=kf(i,this.environment.state),await e.run(o),console.debug(`${T.bold.green("[success]")} ${T.yellow(e.path)}`),t=!0,r=e.getResult(),Rs(this.result,e.path,r)}catch(l){if(console.error(`${T.bold.red("[error]")} ${T.yellow(e.path)}: ${l}`),this.environment.options.fix&&!n){n=!0;try{await e.fix(l);continue}catch(u){console.error(`${T.bold.red("[fix fail]")} ${T.yellow(e.path)}: ${u}`)}}Rs(this.result,e.path,{error:ke(l)}),t=!0,r={error:ke(l)}}const a={...o,result:r};await this.environment.writeYaml(e.getTestCasePath(),a)}async runTestSuite(e){await e.run(),Fs(this.result,e.getResult())}}class He{static{c(this,"BaseTester")}environment;level;logs;assertions;resultsLocator;path;constructor({environment:e,path:t}){this.environment=e,this.logs=[],this.assertions=[],this.path=t,this.level=0}async fix(e){const t=await this.readTestCase();if(!t)throw new Error(`No config found for test ${this.path}`);const n=await this.fixTestCase({config:t,error:e});console.debug(T.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:ke(r)}),this.logMsg(`\u274C ${t}: ${r.message}`)}}logMsg(e){console.debug(`${" ".repeat(this.level*2)}${e}`)}getTestCasePath(){return`${this.path}.test.yml`}}function ti(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)||!ni(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=ti(r,i);o!==null&&(t[n]=o)}else t[n]=i;continue}ni(r,i)||(t[n]=i)}return Object.keys(t).length===0?null:t}c(ti,"getNotMatchingSubFields");function ni(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(ni,"softCompare");class Tf extends He{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=Ps(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=ui(n),a=yn(e.input.fields,o,{skipUnknownFields:!0}),l=yn(i.record.fields,o),u=ti(l,a);await this.assert(()=>!u,"Returned fields match created fields",{difference:u,sentFields:a,receivedFields:l})}const r=Cc(n);if(r.length>0){const i={};r.forEach(a=>{const l=kc(e.input.fields,a);typeof l<"u"&&Rs(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=Ps(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=ke(t),r=Ps(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:
168
168
 
169
169
  ${JSON.stringify(r,null,2)}
170
170
 
@@ -204,7 +204,7 @@ ${JSON.stringify(r,null,2)}`).join(`
204
204
 
205
205
  `)}.
206
206
 
207
- 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 ui(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=hi(r);n[i]=await this.fetchExampleRecords(r)}return n}}class _f extends He{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=ke(t),r=`I'm trying to delete a record from a data collection.
207
+ 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 hi(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=fi(r);n[i]=await this.fetchExampleRecords(r)}return n}}class Ef extends He{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=ke(t),r=`I'm trying to delete a record from a data collection.
208
208
 
209
209
  I tried to delete a record with this ID:
210
210
 
@@ -224,7 +224,7 @@ Format your response as a JSON object with two fields:
224
224
  "id": "fixed id"
225
225
  }.
226
226
 
227
- 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(T.bold.yellow("[auto-fix]"),`${this.path}:`,o.explanation),{input:{id:o.id}}}}class Tf extends He{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=ke(t),r=`I'm trying to find a record by ID in a data collection.
227
+ 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(T.bold.yellow("[auto-fix]"),`${this.path}:`,o.explanation),{input:{id:o.id}}}}class Af extends He{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=ke(t),r=`I'm trying to find a record by ID in a data collection.
228
228
 
229
229
  I tried to find a record with this ID:
230
230
 
@@ -244,7 +244,7 @@ Format your response as a JSON object with two fields:
244
244
  "id": "fixed id"
245
245
  }.
246
246
 
247
- 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(T.bold.yellow("[auto-fix]"),`${this.path}:`,o.explanation),{input:{id:o.id}}}}class Ef extends He{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=ke(t),r=`I'm trying to list records from a data collection.
247
+ 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(T.bold.yellow("[auto-fix]"),`${this.path}:`,o.explanation),{input:{id:o.id}}}}class Of extends He{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=ke(t),r=`I'm trying to list records from a data collection.
248
248
 
249
249
  I tried to list records with these parameters:
250
250
 
@@ -264,7 +264,7 @@ Format your response as a JSON object with two fields:
264
264
  "input": { ... fixed parameters ... }
265
265
  }.
266
266
 
267
- 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(T.bold.yellow("[auto-fix]"),`${this.path}:`,o.explanation),{input:o.input}}}class Of extends He{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(()=>ti(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=ke(t),r=`I'm trying to match a record in a data collection.
267
+ 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(T.bold.yellow("[auto-fix]"),`${this.path}:`,o.explanation),{input:o.input}}}class If extends He{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(()=>ni(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=ke(t),r=`I'm trying to match a record in a data collection.
268
268
 
269
269
  I tried to match a record with this query:
270
270
 
@@ -284,7 +284,7 @@ Format your response as a JSON object with two fields:
284
284
  "query": { ... fixed query ... }
285
285
  }.
286
286
 
287
- 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(T.bold.yellow("[auto-fix]"),`${this.path}:`,o.explanation),{input:{query:o.query}}}}class Af extends He{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(T.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.
287
+ 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(T.bold.yellow("[auto-fix]"),`${this.path}:`,o.explanation),{input:{query:o.query}}}}class $f extends He{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(T.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.
288
288
 
289
289
  Record fields:
290
290
  ${JSON.stringify(e,null,2)}
@@ -309,7 +309,7 @@ Format your response as a JSON object with two fields:
309
309
  "input": { ... fixed parameters ... }
310
310
  }.
311
311
 
312
- 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(T.bold.yellow("[auto-fix]"),`${this.path}:`,o.explanation),{input:o.input,expectedRecordId:e.expectedRecordId}}}class If extends He{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 $f extends He{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=Ls(this.dataCollection),o=li(i),a=yn(e.input.fields,o,{skipUnknownFields:!0}),l=yn(r.record.fields,o),u=ei(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=Ls(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=ke(t),r=Ls(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:
312
+ 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(T.bold.yellow("[auto-fix]"),`${this.path}:`,o.explanation),{input:o.input,expectedRecordId:e.expectedRecordId}}}class Nf extends He{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 xf extends He{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=Ls(this.dataCollection),o=ui(i),a=yn(e.input.fields,o,{skipUnknownFields:!0}),l=yn(r.record.fields,o),u=ti(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=Ls(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=ke(t),r=Ls(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:
313
313
 
314
314
  ${JSON.stringify(r,null,2)}
315
315
 
@@ -349,9 +349,9 @@ ${JSON.stringify(r,null,2)}`).join(`
349
349
 
350
350
  `)}.
351
351
 
352
- 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 ui(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=hi(r);n[i]=await this.fetchExampleRecords(r)}return n}}const ni={spec:{testerClass:If},create:{testerClass:kf,operationKey:"create"},"find-by-id":{testerClass:Tf,operationKey:"findById"},list:{testerClass:Ef,operationKey:"list"},match:{testerClass:Of,operationKey:"match"},search:{testerClass:Af,operationKey:"search"},update:{testerClass:$f,operationKey:"update"},delete:{testerClass:_f,operationKey:"delete"}};class Nf extends Cf{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);X.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=ni[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(ni).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(ni).filter(([,t])=>{const n="operationKey"in t?t.operationKey:void 0;return this.isOperationAvailable(e,n)}).map(([t])=>t)}displayTestSummary(e){X.info(`\u{1F4CA} ${e} test${e===1?"":"s"} executed`)}}class xf extends Mh{static{c(this,"TestRunner")}constructor(e){super(e)}async initialize(){X.debug("Initializing test runner",{prefix:"TestRunner"})}async run(){try{const{testPath:e,path:t,fix:n}=this.options,r=e.split("/");r.length<2&&(X.error("Invalid test path. Expected format: <type>/<name>[/additional/path][/method]"),process.exit(1));const[i,o,...a]=r;i!=="connectors"&&(X.error(`Test type "${i}" is not yet fully implemented. Currently only "connectors" is fully supported.`),X.error("Supported test types: connectors"),process.exit(1));const l=o,u=i,h=[...a,...t?t.split("/"):[]].join("/"),f=await si.create({connectionId:l,testBasePath:u,options:{fix:n}}),m=await f.client.get(`connections/${l}/data`),y=[],d=h?h.split("/"):[];if(d.length===0||d[0]==="data"){d[0]==="data"&&d.shift();let k,_;d.length>=1&&(_=d[0],d.length>=2&&d[1].trim()!==""&&(k=d[1]));for(const A of m){if(_&&_!==A.key)continue;const O=new Nf({environment:f,dataCollectionKey:A.key,testMethod:k});y.push(O)}}y.length===0&&(X.error(`No test suites found for path: ${e}${h?"/"+h:""}`),process.exit(1));const w={};for(const k of y){await k.run();const _=k.getResult();X.debug(`Suite ${k.constructor.name} result:`,{prefix:"TestRunner"}),Fs(w,_)}console.debug("[TestRunner] All results collected:",Object.keys(w)),f.writeResults(w)}catch(e){throw console.error("Error in TestRunner.run():",e),e}}}const Ts=c(()=>[T.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"),T.yellow("\u2502 \u26A0\uFE0F EXPERIMENTAL FEATURE WARNING \u2502"),T.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"),T.yellow("\u2502 The test command is experimental and subject to rapid changes. \u2502"),T.yellow("\u2502 Features, APIs, and file structures may change without notice. \u2502"),T.yellow("\u2502 Use in production environments is not recommended. \u2502"),T.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(`
353
- `),"createExperimentalWarning");function Mf(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",Ts()).action(async()=>{console.warn(Ts()),X.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",["",T.bold("Examples:"),` ${T.gray("\u25B8")} ${T.cyan("membrane test run connectors/netsuite")} # Test all data collections for netsuite connector`,` ${T.gray("\u25B8")} ${T.cyan("membrane test run connectors/netsuite/data/contacts")} # Test specific data collection`,` ${T.gray("\u25B8")} ${T.cyan("membrane test run connectors/netsuite/data/contacts/create")} # Test specific method for data collection`,` ${T.gray("\u25B8")} ${T.cyan("membrane test run connectors/netsuite/data/contacts/delete")} # Test delete method for data collection`,` ${T.gray("\u25B8")} ${T.cyan("membrane test run actions/create-contact")} # Test specific action`,` ${T.gray("\u25B8")} ${T.cyan("membrane test run connectors/hubspot/events")} # Test events for hubspot`,` ${T.gray("\u25B8")} ${T.cyan("membrane test run connectors/salesforce --fix")} # Run tests with auto-fix enabled`,"",T.gray("For more information, visit:"),T.blue(" https://docs.integration.app/cli"),"",Ts()].join(`
354
- `)).action(async(t,n)=>{try{console.warn(Ts()),t||(X.error("Test path is required"),process.exit(1)),X.header(`Testing: ${t}`);const r=new xf({testPath:t,path:n.path,fix:n.fix});await r.initialize(),await r.run(),X.success("Tests completed")}catch(r){r instanceof Error&&(X.error(r.message),process.exit(1)),X.error("An unknown error occurred"),process.exit(1)}})}c(Mf,"setupTestCommand");const Rf=c(()=>{try{const s=qc(import.meta.url),e=fc(s),t=xs(e,"..","package.json");return JSON.parse(Ec(t,"utf-8")).version}catch{return"1.0.0"}},"getPackageVersion"),cc=Rf();function Pf(){const s=new Uc().name("membrane").description("Command-line interface for Membrane Agent").version(cc,"-v, --version","Output the version number").option("--verbose","Enable verbose logging (shows debug messages)");s.configureHelp({sortSubcommands:!0,subcommandTerm:c(n=>T.cyan(n.name()),"subcommandTerm"),commandUsage:c(n=>n.name()==="membrane"?`${T.cyan(n.name())} ${T.gray("[options]")} ${T.cyan("[command]")}`:n.usage(),"commandUsage"),optionTerm:c(n=>{const r=n.flags;return`${T.gray("\u25B8")} ${T.cyan(r)}`},"optionTerm"),subcommandDescription:c(n=>T.gray(n.description()),"subcommandDescription"),optionDescription:c(n=>T.gray(n.description),"optionDescription"),commandDescription:c(n=>T.gray(n.description()),"commandDescription")}),s.addHelpText("beforeAll",`
355
- ${T.bold.cyan("Membrane Agent CLI")} ${T.gray(`v${cc}`)}
352
+ 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 hi(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=fi(r);n[i]=await this.fetchExampleRecords(r)}return n}}const si={spec:{testerClass:Nf},create:{testerClass:Tf,operationKey:"create"},"find-by-id":{testerClass:Af,operationKey:"findById"},list:{testerClass:Of,operationKey:"list"},match:{testerClass:If,operationKey:"match"},search:{testerClass:$f,operationKey:"search"},update:{testerClass:xf,operationKey:"update"},delete:{testerClass:Ef,operationKey:"delete"}};class Mf extends _f{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);X.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=si[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(si).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(si).filter(([,t])=>{const n="operationKey"in t?t.operationKey:void 0;return this.isOperationAvailable(e,n)}).map(([t])=>t)}displayTestSummary(e){X.info(`\u{1F4CA} ${e} test${e===1?"":"s"} executed`)}}class Rf extends Ph{static{c(this,"TestRunner")}constructor(e){super(e)}async initialize(){X.debug("Initializing test runner",{prefix:"TestRunner"})}async run(){try{const{testPath:e,path:t,fix:n}=this.options,r=e.split("/");r.length<2&&(X.error("Invalid test path. Expected format: <type>/<name>[/additional/path][/method]"),process.exit(1));const[i,o,...a]=r;i!=="connectors"&&(X.error(`Test type "${i}" is not yet fully implemented. Currently only "connectors" is fully supported.`),X.error("Supported test types: connectors"),process.exit(1));const l=o,u=i,h=[...a,...t?t.split("/"):[]].join("/"),f=await ri.create({connectionId:l,testBasePath:u,options:{fix:n}}),m=await f.client.get(`connections/${l}/data`),y=[],d=h?h.split("/"):[];if(d.length===0||d[0]==="data"){d[0]==="data"&&d.shift();let k,_;d.length>=1&&(_=d[0],d.length>=2&&d[1].trim()!==""&&(k=d[1]));for(const O of m){if(_&&_!==O.key)continue;const A=new Mf({environment:f,dataCollectionKey:O.key,testMethod:k});y.push(A)}}y.length===0&&(X.error(`No test suites found for path: ${e}${h?"/"+h:""}`),process.exit(1));const w={};for(const k of y){await k.run();const _=k.getResult();X.debug(`Suite ${k.constructor.name} result:`,{prefix:"TestRunner"}),Fs(w,_)}console.debug("[TestRunner] All results collected:",Object.keys(w)),f.writeResults(w)}catch(e){throw console.error("Error in TestRunner.run():",e),e}}}const Ts=c(()=>[T.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"),T.yellow("\u2502 \u26A0\uFE0F EXPERIMENTAL FEATURE WARNING \u2502"),T.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"),T.yellow("\u2502 The test command is experimental and subject to rapid changes. \u2502"),T.yellow("\u2502 Features, APIs, and file structures may change without notice. \u2502"),T.yellow("\u2502 Use in production environments is not recommended. \u2502"),T.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(`
353
+ `),"createExperimentalWarning");function Pf(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",Ts()).action(async()=>{console.warn(Ts()),X.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",["",T.bold("Examples:"),` ${T.gray("\u25B8")} ${T.cyan("membrane test run connectors/netsuite")} # Test all data collections for netsuite connector`,` ${T.gray("\u25B8")} ${T.cyan("membrane test run connectors/netsuite/data/contacts")} # Test specific data collection`,` ${T.gray("\u25B8")} ${T.cyan("membrane test run connectors/netsuite/data/contacts/create")} # Test specific method for data collection`,` ${T.gray("\u25B8")} ${T.cyan("membrane test run connectors/netsuite/data/contacts/delete")} # Test delete method for data collection`,` ${T.gray("\u25B8")} ${T.cyan("membrane test run actions/create-contact")} # Test specific action`,` ${T.gray("\u25B8")} ${T.cyan("membrane test run connectors/hubspot/events")} # Test events for hubspot`,` ${T.gray("\u25B8")} ${T.cyan("membrane test run connectors/salesforce --fix")} # Run tests with auto-fix enabled`,"",T.gray("For more information, visit:"),T.blue(" https://docs.integration.app/cli"),"",Ts()].join(`
354
+ `)).action(async(t,n)=>{try{console.warn(Ts()),t||(X.error("Test path is required"),process.exit(1)),X.header(`Testing: ${t}`);const r=new Rf({testPath:t,path:n.path,fix:n.fix});await r.initialize(),await r.run(),X.success("Tests completed")}catch(r){r instanceof Error&&(X.error(r.message),process.exit(1)),X.error("An unknown error occurred"),process.exit(1)}})}c(Pf,"setupTestCommand");const Lf=c(()=>{try{const s=Uc(import.meta.url),e=dc(s),t=xs(e,"..","package.json");return JSON.parse(Ac(t,"utf-8")).version}catch{return"1.0.0"}},"getPackageVersion"),lc=Lf();function Df(){const s=new Wc().name("membrane").description("Command-line interface for Membrane Agent").version(lc,"-v, --version","Output the version number").option("--verbose","Enable verbose logging (shows debug messages)");s.configureHelp({sortSubcommands:!0,subcommandTerm:c(n=>T.cyan(n.name()),"subcommandTerm"),commandUsage:c(n=>n.name()==="membrane"?`${T.cyan(n.name())} ${T.gray("[options]")} ${T.cyan("[command]")}`:n.usage(),"commandUsage"),optionTerm:c(n=>{const r=n.flags;return`${T.gray("\u25B8")} ${T.cyan(r)}`},"optionTerm"),subcommandDescription:c(n=>T.gray(n.description()),"subcommandDescription"),optionDescription:c(n=>T.gray(n.description),"optionDescription"),commandDescription:c(n=>T.gray(n.description()),"commandDescription")}),s.addHelpText("beforeAll",`
355
+ ${T.bold.cyan("Membrane Agent CLI")} ${T.gray(`v${lc}`)}
356
356
 
357
- `);const e=new ea(Gt.Cli,process.cwd());Ih(s,e),xh(s,e),bh(s,e),Eh(s),Mf(s),kh(s),process.argv.length===2&&(s.outputHelp(),process.exit(0)),s.parse(),s.opts().verbose&&b.setVerboseMode(!0)}c(Pf,"runCLI");const lc=["--cwd","--verbose"];function Lf(){const s=process.argv.slice(2);return s.some((e,t)=>t>0&&lc.includes(s[t-1])?!1:!lc.includes(e))}c(Lf,"hasCLIArguments"),Lf()?Pf():wh();
357
+ `);const e=new ta(Gt.Cli,process.cwd());Nh(s,e),Rh(s,e),vh(s,e),Oh(s),Pf(s),Th(s),process.argv.length===2&&(s.outputHelp(),process.exit(0)),s.parse(),s.opts().verbose&&b.setVerboseMode(!0)}c(Df,"runCLI");const uc=["--cwd","--verbose"];function jf(){const s=process.argv.slice(2);return s.some((e,t)=>t>0&&uc.includes(s[t-1])?!1:!uc.includes(e))}c(jf,"hasCLIArguments"),jf()?Df():Sh();